_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
|
---|---|---|---|---|---|---|---|---|
90e1e411be23e779e409016d7b460244c02b83f4e50c20572a4600cfde29e557 | OCamlPro/ocp-ocamlres | oCamlResSubFormats.mli | (** Formatters for resource leaves in the tree structure *)
This file is part of ocp - ocamlres - subformats
* ( C ) 2013 OCamlPro - Benjamin CANOU
*
* ocp - ocamlres 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.0 of the License , or ( at your option ) any later
* version , with linking exception .
*
* ocp - ocamlres 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 LICENSE file for more details
* (C) 2013 OCamlPro - Benjamin CANOU
*
* ocp-ocamlres 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.0 of the License, or (at your option) any later
* version, with linking exception.
*
* ocp-ocamlres 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 LICENSE file for more details *)
* The type of subformats , as passed to format functors .
This is basically an abstract type equipped with the functions
that work on it as required by the formats . This type is the
intermediate representation of resources at generation time . It
can be the same as the run - time type of the resources , but is not
necessarily so . For instance , a subformat could parse a CSV file
using a CSV library at generation time but produce OCaml arrays or
records as output . See { ! Int } for a simple sample instance .
All functions take two extra parameters specifying the path and
data of the processed resource . They are added for building
decorator / dispatch and should be ignored for most
formats .
This is basically an abstract type equipped with the functions
that work on it as required by the formats. This type is the
intermediate representation of resources at generation time. It
can be the same as the run-time type of the resources, but is not
necessarily so. For instance, a subformat could parse a CSV file
using a CSV library at generation time but produce OCaml arrays or
records as output. See {!Int} for a simple sample instance.
All functions take two extra parameters specifying the path and
data of the processed resource. They are added for building
decorator / dispatch subformats and should be ignored for most
formats. *)
module type SubFormat = sig
(** The generation-time intermediate representation of data. *)
type t
(** A parser as used by the scanner to obtain the in-memory
resources from files. *)
val from_raw : OCamlRes.Path.t -> string -> t
(** A dumper to reconstitute the files from the in-memory
resources. *)
val to_raw : OCamlRes.Path.t -> t -> string
(** Takes the path to the resource in the resource tree, and its
value to pretty print. Returns the OCaml representation of the
value. *)
val pprint : OCamlRes.Path.t -> t -> PPrint.document
(** Provides an optional piece of OCaml code to put before the
resource store definition, for instance a type definition. *)
val pprint_header : OCamlRes.Path.t -> t -> PPrint.document option
(** Provides an optional piece of OCaml code to put after the
resource store definition, for instance a type definition. *)
val pprint_footer : OCamlRes.Path.t -> t -> PPrint.document option
(** A name used to identify the subformat. *)
val name : OCamlRes.Path.t -> t -> string
(** The run-time OCaml type name (that describes the type of
values generated by {!pprint}). Used to annotate the generated
source where needed. The common usecase is when this function
returns the same type as the static {!t} type. *)
val type_name : OCamlRes.Path.t -> t -> string
(** The name of the subformat module at run-time. If the static type
{!t} is the same as the runtime type returned by {!type_abbrv},
this is simply the path to the module used for generation.*)
val mod_name : OCamlRes.Path.t -> t -> string
end
(** A probably useless subformat, for demonstration purposes *)
module Int : SubFormat with type t = int
(** The default format (raw contents as a string) *)
module Raw : SubFormat with type t = string
(** Splits the input into lines *)
module Lines : SubFormat with type t = string list
| null | https://raw.githubusercontent.com/OCamlPro/ocp-ocamlres/8ec8bce4afb55dd13f6df30eccda60ca1f6f0d6b/src/oCamlResSubFormats.mli | ocaml | * Formatters for resource leaves in the tree structure
* The generation-time intermediate representation of data.
* A parser as used by the scanner to obtain the in-memory
resources from files.
* A dumper to reconstitute the files from the in-memory
resources.
* Takes the path to the resource in the resource tree, and its
value to pretty print. Returns the OCaml representation of the
value.
* Provides an optional piece of OCaml code to put before the
resource store definition, for instance a type definition.
* Provides an optional piece of OCaml code to put after the
resource store definition, for instance a type definition.
* A name used to identify the subformat.
* The run-time OCaml type name (that describes the type of
values generated by {!pprint}). Used to annotate the generated
source where needed. The common usecase is when this function
returns the same type as the static {!t} type.
* The name of the subformat module at run-time. If the static type
{!t} is the same as the runtime type returned by {!type_abbrv},
this is simply the path to the module used for generation.
* A probably useless subformat, for demonstration purposes
* The default format (raw contents as a string)
* Splits the input into lines |
This file is part of ocp - ocamlres - subformats
* ( C ) 2013 OCamlPro - Benjamin CANOU
*
* ocp - ocamlres 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.0 of the License , or ( at your option ) any later
* version , with linking exception .
*
* ocp - ocamlres 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 LICENSE file for more details
* (C) 2013 OCamlPro - Benjamin CANOU
*
* ocp-ocamlres 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.0 of the License, or (at your option) any later
* version, with linking exception.
*
* ocp-ocamlres 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 LICENSE file for more details *)
* The type of subformats , as passed to format functors .
This is basically an abstract type equipped with the functions
that work on it as required by the formats . This type is the
intermediate representation of resources at generation time . It
can be the same as the run - time type of the resources , but is not
necessarily so . For instance , a subformat could parse a CSV file
using a CSV library at generation time but produce OCaml arrays or
records as output . See { ! Int } for a simple sample instance .
All functions take two extra parameters specifying the path and
data of the processed resource . They are added for building
decorator / dispatch and should be ignored for most
formats .
This is basically an abstract type equipped with the functions
that work on it as required by the formats. This type is the
intermediate representation of resources at generation time. It
can be the same as the run-time type of the resources, but is not
necessarily so. For instance, a subformat could parse a CSV file
using a CSV library at generation time but produce OCaml arrays or
records as output. See {!Int} for a simple sample instance.
All functions take two extra parameters specifying the path and
data of the processed resource. They are added for building
decorator / dispatch subformats and should be ignored for most
formats. *)
module type SubFormat = sig
type t
val from_raw : OCamlRes.Path.t -> string -> t
val to_raw : OCamlRes.Path.t -> t -> string
val pprint : OCamlRes.Path.t -> t -> PPrint.document
val pprint_header : OCamlRes.Path.t -> t -> PPrint.document option
val pprint_footer : OCamlRes.Path.t -> t -> PPrint.document option
val name : OCamlRes.Path.t -> t -> string
val type_name : OCamlRes.Path.t -> t -> string
val mod_name : OCamlRes.Path.t -> t -> string
end
module Int : SubFormat with type t = int
module Raw : SubFormat with type t = string
module Lines : SubFormat with type t = string list
|
77bcf5492d30b4d4e041cd3239a46d730b60bf084723422fc34e57b12ad26e29 | mcdejonge/rs | rs-util.rkt | #lang racket/base
(require racket/bool
racket/contract/base
racket/contract/region)
;; Utility functions for use in rs
(provide
rs-util-rtsleep
rs-util-diag
rs-util-set-diag-mode
rs-util-loop-and-wait
rs-util-run-timed-ms
rs-util-calc-time-corrected
)
;; Diagnosis mode. When turned on it prints diagnostic messages.
(define rs-util-diag-mode #f)
(define (rs-util-set-diag-mode true-or-false)
(set! rs-util-diag-mode true-or-false))
(define (rs-util-diag message . args)
;; Print a diagnostic message (using printf) but only if
rs - util - diag - mode is # t.
;;
;; NOTE: if you need to perform a function call in one of your args,
;; make sure it only happens when diag-mode is #t, in other words
;; supply a procedure object rather than the result of a procedure
;; call. If you do not do this, performance will suffer greatly as
;; your procedure calls will also be executed if they don't need to
;; be (namely when diag-mode is #f).
(when rs-util-diag-mode
(apply printf (cons message
(map (lambda (item)
(cond [(procedure? item) (item)]
[else item]))
args)))))
(define/contract (rs-util-rtsleep ms)
;; Sleep for the given number of milliseconds. More accurate than
;; (sleep) because it checks every millisecond if it should wake up.
(-> positive? void)
(let ([end (+ (current-inexact-milliseconds) ms)])
(let loop ()
(when (< (current-inexact-milliseconds) end)
(sleep 0.001)
(loop)))))
(define (rs-util-run-timed-ms proc)
;; Run a procedure and return the time it took.
(define now (current-inexact-milliseconds))
(proc)
(- (current-inexact-milliseconds) now))
(define/contract (rs-util-calc-time-corrected pref-length last-diff [max-diff-ratio 1/20])
(->* (positive? number?)
(positive?) positive?)
;; Calculate the corrected length of something (a step or a loop)
;; taking into account the last time it ran. max-diff-ratio is the
;; limit to how much correction will take place (as a ratio of the
;; preferred length).
(define max-diff (* pref-length max-diff-ratio))
(define min-length (- pref-length max-diff))
(define max-length (+ pref-length max-diff))
(max min-length (min (- pref-length last-diff) max-length)))
(define/contract (rs-util-loop-and-wait procedure loop-length [max-difference 1/10])
;; Loop the supplied procedure for the given number of ms.
;; Attempts to correct the time to wait based on the duration of the
;; last iteration. The correction will not, however, be more than
;; max-difference * loop-length more or less than loop-length.
;;
;; If supplied a procedure this procedure MUST return true or
;; false. If it returns false the loop stops.
(->* (procedure? positive?)
(positive?)
any)
(let loop ([last-diff 0])
(define corrected-loop-length (rs-util-calc-time-corrected loop-length last-diff))
(rs-util-diag "Starting new iteration of a loop with proper length ~s that will have length ~s\n"
loop-length corrected-loop-length)
(define start-time (current-inexact-milliseconds))
(define result (procedure))
(rs-util-rtsleep corrected-loop-length)
(when result
(loop (- (- (current-inexact-milliseconds) start-time) corrected-loop-length)))))
| null | https://raw.githubusercontent.com/mcdejonge/rs/d9cb3a15e7416df7c2a0a29748cb2f07f1dace32/rs-util.rkt | racket | Utility functions for use in rs
Diagnosis mode. When turned on it prints diagnostic messages.
Print a diagnostic message (using printf) but only if
NOTE: if you need to perform a function call in one of your args,
make sure it only happens when diag-mode is #t, in other words
supply a procedure object rather than the result of a procedure
call. If you do not do this, performance will suffer greatly as
your procedure calls will also be executed if they don't need to
be (namely when diag-mode is #f).
Sleep for the given number of milliseconds. More accurate than
(sleep) because it checks every millisecond if it should wake up.
Run a procedure and return the time it took.
Calculate the corrected length of something (a step or a loop)
taking into account the last time it ran. max-diff-ratio is the
limit to how much correction will take place (as a ratio of the
preferred length).
Loop the supplied procedure for the given number of ms.
Attempts to correct the time to wait based on the duration of the
last iteration. The correction will not, however, be more than
max-difference * loop-length more or less than loop-length.
If supplied a procedure this procedure MUST return true or
false. If it returns false the loop stops. | #lang racket/base
(require racket/bool
racket/contract/base
racket/contract/region)
(provide
rs-util-rtsleep
rs-util-diag
rs-util-set-diag-mode
rs-util-loop-and-wait
rs-util-run-timed-ms
rs-util-calc-time-corrected
)
(define rs-util-diag-mode #f)
(define (rs-util-set-diag-mode true-or-false)
(set! rs-util-diag-mode true-or-false))
(define (rs-util-diag message . args)
rs - util - diag - mode is # t.
(when rs-util-diag-mode
(apply printf (cons message
(map (lambda (item)
(cond [(procedure? item) (item)]
[else item]))
args)))))
(define/contract (rs-util-rtsleep ms)
(-> positive? void)
(let ([end (+ (current-inexact-milliseconds) ms)])
(let loop ()
(when (< (current-inexact-milliseconds) end)
(sleep 0.001)
(loop)))))
(define (rs-util-run-timed-ms proc)
(define now (current-inexact-milliseconds))
(proc)
(- (current-inexact-milliseconds) now))
(define/contract (rs-util-calc-time-corrected pref-length last-diff [max-diff-ratio 1/20])
(->* (positive? number?)
(positive?) positive?)
(define max-diff (* pref-length max-diff-ratio))
(define min-length (- pref-length max-diff))
(define max-length (+ pref-length max-diff))
(max min-length (min (- pref-length last-diff) max-length)))
(define/contract (rs-util-loop-and-wait procedure loop-length [max-difference 1/10])
(->* (procedure? positive?)
(positive?)
any)
(let loop ([last-diff 0])
(define corrected-loop-length (rs-util-calc-time-corrected loop-length last-diff))
(rs-util-diag "Starting new iteration of a loop with proper length ~s that will have length ~s\n"
loop-length corrected-loop-length)
(define start-time (current-inexact-milliseconds))
(define result (procedure))
(rs-util-rtsleep corrected-loop-length)
(when result
(loop (- (- (current-inexact-milliseconds) start-time) corrected-loop-length)))))
|
84c4c9bfd391a9cf2947a0987fd371b9db0a39ebb9ab694262b5b91c3fd1c8d6 | rodrigosetti/messagepack | Main.hs | # LANGUAGE TemplateHaskell #
module Main where
import Control.Applicative
import Data.MessagePack
import Data.Serialize
import Test.QuickCheck
import qualified Data.ByteString as BS
import qualified Data.Map as M
instance Arbitrary Object where
arbitrary = sized $ \n -> oneof [ return ObjectNil
, ObjectUInt <$> arbitrary
, ObjectInt <$> arbitrary
, ObjectBool <$> arbitrary
, ObjectFloat <$> arbitrary
, ObjectDouble <$> arbitrary
, ObjectString <$> arbitrary
, ObjectBinary <$> arbitrary
, ObjectArray <$> resize (3 * n `quot` 4) arbitrary
, ObjectMap <$> resize (3 * n `quot` 4) arbitrary
, ObjectExt <$> arbitrary <*> arbitrary ]
shrink (ObjectString s) = map ObjectString $ shrink s
shrink (ObjectBinary b) = map ObjectBinary $ shrink b
shrink (ObjectArray a) = map ObjectArray (shrink a) ++ a
shrink (ObjectMap m) = map ObjectMap (shrink m) ++ M.keys m ++ M.elems m
shrink (ObjectExt t s) = map (ObjectExt t) $ shrink s
shrink _ = []
instance Arbitrary BS.ByteString where
arbitrary = BS.pack <$> arbitrary
shrink = map BS.pack . shrink . BS.unpack
prop_encodeDecodeIsIdentity :: Object -> Bool
prop_encodeDecodeIsIdentity o = either error (== o) $ decode $ encode o
return []
main :: IO Bool
main = $quickCheckAll
| null | https://raw.githubusercontent.com/rodrigosetti/messagepack/c84a93ebc260837eecaca0182a8626d1615a14c4/tests/Main.hs | haskell | # LANGUAGE TemplateHaskell #
module Main where
import Control.Applicative
import Data.MessagePack
import Data.Serialize
import Test.QuickCheck
import qualified Data.ByteString as BS
import qualified Data.Map as M
instance Arbitrary Object where
arbitrary = sized $ \n -> oneof [ return ObjectNil
, ObjectUInt <$> arbitrary
, ObjectInt <$> arbitrary
, ObjectBool <$> arbitrary
, ObjectFloat <$> arbitrary
, ObjectDouble <$> arbitrary
, ObjectString <$> arbitrary
, ObjectBinary <$> arbitrary
, ObjectArray <$> resize (3 * n `quot` 4) arbitrary
, ObjectMap <$> resize (3 * n `quot` 4) arbitrary
, ObjectExt <$> arbitrary <*> arbitrary ]
shrink (ObjectString s) = map ObjectString $ shrink s
shrink (ObjectBinary b) = map ObjectBinary $ shrink b
shrink (ObjectArray a) = map ObjectArray (shrink a) ++ a
shrink (ObjectMap m) = map ObjectMap (shrink m) ++ M.keys m ++ M.elems m
shrink (ObjectExt t s) = map (ObjectExt t) $ shrink s
shrink _ = []
instance Arbitrary BS.ByteString where
arbitrary = BS.pack <$> arbitrary
shrink = map BS.pack . shrink . BS.unpack
prop_encodeDecodeIsIdentity :: Object -> Bool
prop_encodeDecodeIsIdentity o = either error (== o) $ decode $ encode o
return []
main :: IO Bool
main = $quickCheckAll
|
|
6a4fc237fe176d87b2fb5279d9829beeac1f80d7f55f86a66b9d45196ccbf244 | vkz/PLAI | type-unify.rkt | #lang plai-typed
(require "type-constraints.rkt")
(define-type-alias Subst (listof Substitution))
(define-type Substitution
[sub (var : Term) (is : Term)])
(define (unify [cs : (listof Constraints)]) : Subst
(unify/theta cs empty))
(define (lookup [t : Term] [in : Subst]) : (optionof Term)
(cond
[(empty? in) (none)]
[(cons? in)
(type-case Substitution (first in)
[sub (var is) (if (eq? var t)
(some is)
(lookup t (rest in)))])]))
(define (extend+replace [l : Term]
[r : Term]
[s : Subst]) : Subst
(local ([define (l-occurs-in? [rhs : Term]) : boolean
(type-case Term r
[tArrow (dom rng) (or (l-occurs-in? dom)
(l-occurs-in? rng))]
[else (eq? l rhs)])]
[define (l-replace-in [s : Subst]) : Subst
(cond
[(empty? s) empty]
[(cons? s)
(let ([var (sub-var (first s))]
[is (replace (sub-is (first s)))])
(cons (sub var is)
(l-replace-in (rest s))))])]
[define (replace [t : Term]) : Term
(type-case Term t
[tArrow (dom rng) (tArrow (replace dom)
(replace rng))]
[else (if (eq? t l)
r
t)])])
(cond
[(not (l-occurs-in? r)) (cons (sub l r)
(l-replace-in s))]
[else (error 'extend+replace "cycle in substitution")])))
(define (unify/theta [cs : (listof Constraints)] [theta : Subst]) : Subst
(begin
(display "\nNew cs\n")
(display cs)
(display "\n\n")
(cond
[(empty? cs) theta]
[(cons? cs)
(let ([l (eqCon-lhs (first cs))]
[r (eqCon-rhs (first cs))])
(type-case Term l
[tVar (s) (type-case (optionof Term) (lookup l theta)
[some (bound)
(unify/theta (cons (eqCon bound r)
(rest cs))
theta)]
[none () (unify/theta (rest cs)
(extend+replace l r theta))])]
[tExp (e) (type-case (optionof Term) (lookup l theta)
[some (bound)
(unify/theta (cons (eqCon bound r)
(rest cs))
theta)]
[none () (unify/theta (rest cs)
(extend+replace l r theta))])]
[tNum () (type-case Term r
[tNum () (unify/theta (rest cs) theta)]
[else (error 'unify "number and something else")])]
[tArrow (d1 r1) (type-case Term r
[tArrow (d2 r2)
(unify/theta (cons (eqCon d1 d2)
(cons (eqCon r1 r2)
(rest cs)))
theta)]
[else (error 'unify "arrow and something else")])]))])))
( unify ( cg ( appC ( lamC ' x ( appC ( idC ' x ) ( numC 1 ) ) ) ( lamC ' y ( plusC ( idC ' y ) ( numC 0 ) ) ) ) ) )
(unify (cg (lamC 'x (idC 'x)))) | null | https://raw.githubusercontent.com/vkz/PLAI/3a7dc604dab78f4ebcfa6f88d03242cb3f7f1113/type-unify.rkt | racket | #lang plai-typed
(require "type-constraints.rkt")
(define-type-alias Subst (listof Substitution))
(define-type Substitution
[sub (var : Term) (is : Term)])
(define (unify [cs : (listof Constraints)]) : Subst
(unify/theta cs empty))
(define (lookup [t : Term] [in : Subst]) : (optionof Term)
(cond
[(empty? in) (none)]
[(cons? in)
(type-case Substitution (first in)
[sub (var is) (if (eq? var t)
(some is)
(lookup t (rest in)))])]))
(define (extend+replace [l : Term]
[r : Term]
[s : Subst]) : Subst
(local ([define (l-occurs-in? [rhs : Term]) : boolean
(type-case Term r
[tArrow (dom rng) (or (l-occurs-in? dom)
(l-occurs-in? rng))]
[else (eq? l rhs)])]
[define (l-replace-in [s : Subst]) : Subst
(cond
[(empty? s) empty]
[(cons? s)
(let ([var (sub-var (first s))]
[is (replace (sub-is (first s)))])
(cons (sub var is)
(l-replace-in (rest s))))])]
[define (replace [t : Term]) : Term
(type-case Term t
[tArrow (dom rng) (tArrow (replace dom)
(replace rng))]
[else (if (eq? t l)
r
t)])])
(cond
[(not (l-occurs-in? r)) (cons (sub l r)
(l-replace-in s))]
[else (error 'extend+replace "cycle in substitution")])))
(define (unify/theta [cs : (listof Constraints)] [theta : Subst]) : Subst
(begin
(display "\nNew cs\n")
(display cs)
(display "\n\n")
(cond
[(empty? cs) theta]
[(cons? cs)
(let ([l (eqCon-lhs (first cs))]
[r (eqCon-rhs (first cs))])
(type-case Term l
[tVar (s) (type-case (optionof Term) (lookup l theta)
[some (bound)
(unify/theta (cons (eqCon bound r)
(rest cs))
theta)]
[none () (unify/theta (rest cs)
(extend+replace l r theta))])]
[tExp (e) (type-case (optionof Term) (lookup l theta)
[some (bound)
(unify/theta (cons (eqCon bound r)
(rest cs))
theta)]
[none () (unify/theta (rest cs)
(extend+replace l r theta))])]
[tNum () (type-case Term r
[tNum () (unify/theta (rest cs) theta)]
[else (error 'unify "number and something else")])]
[tArrow (d1 r1) (type-case Term r
[tArrow (d2 r2)
(unify/theta (cons (eqCon d1 d2)
(cons (eqCon r1 r2)
(rest cs)))
theta)]
[else (error 'unify "arrow and something else")])]))])))
( unify ( cg ( appC ( lamC ' x ( appC ( idC ' x ) ( numC 1 ) ) ) ( lamC ' y ( plusC ( idC ' y ) ( numC 0 ) ) ) ) ) )
(unify (cg (lamC 'x (idC 'x)))) |
|
d0fba302cb53460caecbfbcf0b04a3d1a0420223619426ae25c65fe6fee40ec9 | khotyn/4clojure-answer | 138-squares-squared.clj | (fn [i j]
(let [num-str (apply str (take-while #(<= % j) (iterate #(* % %) i)))
str-size (first (drop-while #(< (* % %) (count num-str)) (range)))
s (concat num-str (repeat (- (* str-size str-size) (count num-str)) \*))
board-size (dec (* 2 str-size))
init-board (vec (repeat board-size (vec (repeat board-size \space))))]
(println init-board)
(letfn [(step [board current gap str-seq]
(if (seq str-seq)
(let [next-board (assoc-in board current (first str-seq))
f-next-gap (if (zero? (first current))
[1 -1]
(if (= (dec board-size) (first current))
[-1 1]
(if (zero? (second current))
[1 1]
(if (= (dec board-size) (second current))
[-1 -1]
gap))))
f-next-current (map #(+ %1 %2) current f-next-gap)
next-gap (if (= \space (get-in board f-next-current))
f-next-gap
(case f-next-gap
[1 -1] [1 1]
[1 1] [-1 1]
[-1 1] [-1 -1]
[-1 -1] [1 -1]))]
(step next-board (map #(+ %1 %2) current next-gap) next-gap (next str-seq)))
board))]
(mapv #(apply str %) (step init-board (if (odd? str-size) [(dec str-size) (dec board-size)] [(dec str-size) 0]) [1 1] (reverse s))))))
| null | https://raw.githubusercontent.com/khotyn/4clojure-answer/3de82d732faedceafac4f1585a72d0712fe5d3c6/138-squares-squared.clj | clojure | (fn [i j]
(let [num-str (apply str (take-while #(<= % j) (iterate #(* % %) i)))
str-size (first (drop-while #(< (* % %) (count num-str)) (range)))
s (concat num-str (repeat (- (* str-size str-size) (count num-str)) \*))
board-size (dec (* 2 str-size))
init-board (vec (repeat board-size (vec (repeat board-size \space))))]
(println init-board)
(letfn [(step [board current gap str-seq]
(if (seq str-seq)
(let [next-board (assoc-in board current (first str-seq))
f-next-gap (if (zero? (first current))
[1 -1]
(if (= (dec board-size) (first current))
[-1 1]
(if (zero? (second current))
[1 1]
(if (= (dec board-size) (second current))
[-1 -1]
gap))))
f-next-current (map #(+ %1 %2) current f-next-gap)
next-gap (if (= \space (get-in board f-next-current))
f-next-gap
(case f-next-gap
[1 -1] [1 1]
[1 1] [-1 1]
[-1 1] [-1 -1]
[-1 -1] [1 -1]))]
(step next-board (map #(+ %1 %2) current next-gap) next-gap (next str-seq)))
board))]
(mapv #(apply str %) (step init-board (if (odd? str-size) [(dec str-size) (dec board-size)] [(dec str-size) 0]) [1 1] (reverse s))))))
|
|
d8d32f2b4e572953967a03cb8eeea34a9b734c4b2438ea2ed8ed3924f7d60c19 | AccelerateHS/accelerate-examples | MatrixMarket.hs | {-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module MatrixMarket (Matrix(..), readMatrix) where
import Control.Applicative hiding ( many )
import Data.Int
import Data.Complex
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Lex.Fractional
import qualified Data.Attoparsec.Lazy as L
import qualified Data.ByteString.Lazy as L
-- | Specifies the element type. Pattern matrices do not have any elements,
-- only indices, and only make sense for coordinate matrices and vectors.
--
data Field = Real | Complex | Integer | Pattern
deriving (Eq, Show)
-- | Specifies either sparse or dense storage. In sparse (\"coordinate\")
-- storage, elements are given in (i,j,x) triplets for matrices (or (i,x) for
vectors ) . Indices are 1 - based , so that A(1,1 ) is the first element of a
matrix , and x(1 ) is the first element of a vector .
--
In dense ( \"array\ " ) storage , elements are given in column - major order .
--
-- In both cases, each element is given on a separate line.
--
data Format = Coordinate | Array
deriving (Eq, Show)
-- | Specifies any special structure in the matrix. For symmetric and hermition
-- matrices, only the lower-triangular part of the matrix is given. For skew
-- matrices, only the entries below the diagonal are stored.
--
data Structure = General | Symmetric | Hermitian | Skew
deriving (Eq, Show)
We really want a type parameter to Matrix , but I think that requires some
-- kind of dynamic typing so that we can determine (a ~ Integral) or (a ~
-- RealFloat), and so forth, depending on the file being read. This will do for
-- our purposes...
--
Format is : ( rows , columns ) [ ( row , column , value ) ]
--
data Matrix
= PatternMatrix (Int,Int) Int [(Int32,Int32)]
| IntMatrix (Int,Int) Int [(Int32,Int32,Int)]
| RealMatrix (Int,Int) Int [(Int32,Int32,Float)]
| ComplexMatrix (Int,Int) Int [(Int32,Int32,Complex Float)]
deriving Show
--------------------------------------------------------------------------------
-- Combinators
--------------------------------------------------------------------------------
comment :: Parser ()
comment = char '%' *> skipWhile (not . eol) *> endOfLine
where
eol w = w `elem` ("\n\r" :: String)
floating :: Fractional a => Parser a
floating = do
mv <- readDecimal <$> (skipSpace *> takeTill isSpace) -- readDecimal does the fancy stuff
case mv of
Just (v,_) -> return v
Nothing -> fail "floating-point number"
integral :: Integral a => Parser a
integral = skipSpace *> decimal
format :: Parser Format
format = string "coordinate" *> pure Coordinate
<|> string "array" *> pure Array
<?> "matrix format"
field :: Parser Field
field = string "real" *> pure Real
<|> string "complex" *> pure Complex
<|> string "integer" *> pure Integer
<|> string "pattern" *> pure Pattern
<?> "matrix field"
structure :: Parser Structure
structure = string "general" *> pure General
<|> string "symmetric" *> pure Symmetric
<|> string "hermitian" *> pure Hermitian
<|> string "skew-symmetric" *> pure Skew
<?> "matrix structure"
header :: Parser (Format,Field,Structure)
header = string "%%MatrixMarket matrix"
>> (,,) <$> (skipSpace *> format)
<*> (skipSpace *> field)
<*> (skipSpace *> structure)
<* endOfLine
<?> "MatrixMarket header"
extent :: Parser (Int,Int,Int)
extent = do
[m,n,l] <- skipWhile isSpace *> count 3 integral <* endOfLine
return (m,n,l)
line :: Integral i => Parser a -> Parser (i,i,a)
line f = (,,) <$> integral
<*> integral
<*> f
<* endOfLine
--------------------------------------------------------------------------------
Matrix Market
--------------------------------------------------------------------------------
matrix :: Parser Matrix
matrix = do
(_,t,_) <- header
(m,n,l) <- skipMany comment *> extent
case t of
Real -> RealMatrix (m,n) l `fmap` many1 (line floating)
Complex -> ComplexMatrix (m,n) l `fmap` many1 (line ((:+) <$> floating <*> floating))
Integer -> IntMatrix (m,n) l `fmap` many1 (line integral)
Pattern -> PatternMatrix (m,n) l `fmap` many1 ((,) <$> integral <*> integral)
readMatrix :: FilePath -> IO Matrix
readMatrix file = do
chunks <- L.readFile file
case L.parse matrix chunks of
L.Fail _ _ msg -> error $ file ++ ": " ++ msg
L.Done _ mtx -> return mtx
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/smvm/icebox/MatrixMarket.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
| Specifies the element type. Pattern matrices do not have any elements,
only indices, and only make sense for coordinate matrices and vectors.
| Specifies either sparse or dense storage. In sparse (\"coordinate\")
storage, elements are given in (i,j,x) triplets for matrices (or (i,x) for
In both cases, each element is given on a separate line.
| Specifies any special structure in the matrix. For symmetric and hermition
matrices, only the lower-triangular part of the matrix is given. For skew
matrices, only the entries below the diagonal are stored.
kind of dynamic typing so that we can determine (a ~ Integral) or (a ~
RealFloat), and so forth, depending on the file being read. This will do for
our purposes...
------------------------------------------------------------------------------
Combinators
------------------------------------------------------------------------------
readDecimal does the fancy stuff
------------------------------------------------------------------------------
------------------------------------------------------------------------------ |
module MatrixMarket (Matrix(..), readMatrix) where
import Control.Applicative hiding ( many )
import Data.Int
import Data.Complex
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Lex.Fractional
import qualified Data.Attoparsec.Lazy as L
import qualified Data.ByteString.Lazy as L
data Field = Real | Complex | Integer | Pattern
deriving (Eq, Show)
vectors ) . Indices are 1 - based , so that A(1,1 ) is the first element of a
matrix , and x(1 ) is the first element of a vector .
In dense ( \"array\ " ) storage , elements are given in column - major order .
data Format = Coordinate | Array
deriving (Eq, Show)
data Structure = General | Symmetric | Hermitian | Skew
deriving (Eq, Show)
We really want a type parameter to Matrix , but I think that requires some
Format is : ( rows , columns ) [ ( row , column , value ) ]
data Matrix
= PatternMatrix (Int,Int) Int [(Int32,Int32)]
| IntMatrix (Int,Int) Int [(Int32,Int32,Int)]
| RealMatrix (Int,Int) Int [(Int32,Int32,Float)]
| ComplexMatrix (Int,Int) Int [(Int32,Int32,Complex Float)]
deriving Show
comment :: Parser ()
comment = char '%' *> skipWhile (not . eol) *> endOfLine
where
eol w = w `elem` ("\n\r" :: String)
floating :: Fractional a => Parser a
floating = do
case mv of
Just (v,_) -> return v
Nothing -> fail "floating-point number"
integral :: Integral a => Parser a
integral = skipSpace *> decimal
format :: Parser Format
format = string "coordinate" *> pure Coordinate
<|> string "array" *> pure Array
<?> "matrix format"
field :: Parser Field
field = string "real" *> pure Real
<|> string "complex" *> pure Complex
<|> string "integer" *> pure Integer
<|> string "pattern" *> pure Pattern
<?> "matrix field"
structure :: Parser Structure
structure = string "general" *> pure General
<|> string "symmetric" *> pure Symmetric
<|> string "hermitian" *> pure Hermitian
<|> string "skew-symmetric" *> pure Skew
<?> "matrix structure"
header :: Parser (Format,Field,Structure)
header = string "%%MatrixMarket matrix"
>> (,,) <$> (skipSpace *> format)
<*> (skipSpace *> field)
<*> (skipSpace *> structure)
<* endOfLine
<?> "MatrixMarket header"
extent :: Parser (Int,Int,Int)
extent = do
[m,n,l] <- skipWhile isSpace *> count 3 integral <* endOfLine
return (m,n,l)
line :: Integral i => Parser a -> Parser (i,i,a)
line f = (,,) <$> integral
<*> integral
<*> f
<* endOfLine
Matrix Market
matrix :: Parser Matrix
matrix = do
(_,t,_) <- header
(m,n,l) <- skipMany comment *> extent
case t of
Real -> RealMatrix (m,n) l `fmap` many1 (line floating)
Complex -> ComplexMatrix (m,n) l `fmap` many1 (line ((:+) <$> floating <*> floating))
Integer -> IntMatrix (m,n) l `fmap` many1 (line integral)
Pattern -> PatternMatrix (m,n) l `fmap` many1 ((,) <$> integral <*> integral)
readMatrix :: FilePath -> IO Matrix
readMatrix file = do
chunks <- L.readFile file
case L.parse matrix chunks of
L.Fail _ _ msg -> error $ file ++ ": " ++ msg
L.Done _ mtx -> return mtx
|
88396af7054e64daf6a0fc41289b538a33f52f12248f72ac6eddd89c115599d3 | huangz1990/real-world-haskell-cn | foldA.hs | -- file: ch12/Barcode.hs
-- | Strict left fold, similar to foldl' on lists.
foldA :: Ix k => (a -> b -> a) -> a -> Array k b -> a
foldA f s a = go s (indices a)
where go s (j:js) = let s' = f s (a ! j)
in s' `seq` go s' js
go s _ = s
| Strict left fold using the first element of the array as its
starting value , similar to foldl1 on lists .
foldA1 :: Ix k => (a -> a -> a) -> Array k a -> a
foldA1 f a = foldA f (a ! fst (bounds a)) a
| null | https://raw.githubusercontent.com/huangz1990/real-world-haskell-cn/f67b07dd846b1950d17ff941d650089fcbbe9586/code/ch12/foldA.hs | haskell | file: ch12/Barcode.hs
| Strict left fold, similar to foldl' on lists. | foldA :: Ix k => (a -> b -> a) -> a -> Array k b -> a
foldA f s a = go s (indices a)
where go s (j:js) = let s' = f s (a ! j)
in s' `seq` go s' js
go s _ = s
| Strict left fold using the first element of the array as its
starting value , similar to foldl1 on lists .
foldA1 :: Ix k => (a -> a -> a) -> Array k a -> a
foldA1 f a = foldA f (a ! fst (bounds a)) a
|
1010c7496ed3065f12660862855cde1c29f669fb12ebd404d3f5feb42dfc285b | chicken-mobile/chicken-sdl2-android-builder | window.scm | ;;
chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
;;
Copyright © 2013 , 2015 - 2016 .
;; 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR 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.
(export SDL_CreateWindow
SDL_GetWindowFromID
SDL_DestroyWindow
SDL_UpdateWindowSurface
SDL_UpdateWindowSurfaceRects
SDL_ShowWindow
SDL_HideWindow
SDL_MaximizeWindow
SDL_MinimizeWindow
SDL_RaiseWindow
SDL_RestoreWindow
SDL_GetWindowBrightness
SDL_GetWindowData
SDL_GetWindowDisplayIndex
SDL_GetWindowDisplayMode
SDL_GetWindowFlags
SDL_GetWindowGammaRamp
SDL_GetWindowGrab
SDL_GetWindowID
SDL_GetWindowMaximumSize
SDL_GetWindowMinimumSize
SDL_GetWindowPixelFormat
SDL_GetWindowPosition
SDL_GetWindowSize
SDL_GetWindowSurface
SDL_GetWindowTitle
SDL_SetWindowBordered
SDL_SetWindowBrightness
SDL_SetWindowData
SDL_SetWindowDisplayMode
SDL_SetWindowFullscreen
SDL_SetWindowGammaRamp
SDL_SetWindowGrab
SDL_SetWindowIcon
SDL_SetWindowMaximumSize
SDL_SetWindowMinimumSize
SDL_SetWindowPosition
SDL_SetWindowSize
SDL_SetWindowTitle
SDL_WINDOWPOS_UNDEFINED_DISPLAY
SDL_WINDOWPOS_ISUNDEFINED
SDL_WINDOWPOS_CENTERED_DISPLAY
SDL_WINDOWPOS_ISCENTERED)
#+libSDL-2.0.4+
(export SDL_GetGrabbedWindow)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; CREATE / DESTROY WINDOW
(define-function-binding SDL_CreateWindow
return: (SDL_Window* new-window)
args: ((c-string title)
(Sint32 x) (Sint32 y)
(Sint32 w) (Sint32 h)
(Uint32 flags)))
;;; TODO?: SDL_CreateWindowAndRenderer
TODO ? : SDL_CreateWindowFrom
(define-function-binding SDL_GetWindowFromID
return: (SDL_Window* window-or-null)
args: ((Uint32 id)))
(define-function-binding SDL_DestroyWindow
args: ((SDL_Window* window)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; UPDATE WINDOW SURFACE
(define-function-binding SDL_UpdateWindowSurface
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)))
(define-function-binding SDL_UpdateWindowSurfaceRects
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(c-pointer rects)
(Sint32 numrects)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; WINDOW MANAGEMENT
(define-function-binding SDL_ShowWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_HideWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_MaximizeWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_MinimizeWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_RaiseWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_RestoreWindow
args: ((SDL_Window* window)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; GET WINDOW PROPERTIES
(define-function-binding SDL_GetWindowBrightness
return: (float brightness)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowData
return: (c-pointer data-value)
args: ((SDL_Window* window)
(c-string data-key)))
(define-function-binding SDL_GetWindowDisplayIndex
return: (Sint32 display-index)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowDisplayMode
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(SDL_DisplayMode* mode-out)))
(define-function-binding SDL_GetWindowFlags
return: (Uint32 flags)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowGammaRamp
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(Uint16* red-array-out)
(Uint16* green-array-out)
(Uint16* blue-array-out)))
(define-function-binding SDL_GetWindowGrab
return: (bool grabbed?)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowID
return: (Uint32 id)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowMaximumSize
args: ((SDL_Window* window)
(Sint32* w-out)
(Sint32* h-out)))
(define-function-binding SDL_GetWindowMinimumSize
args: ((SDL_Window* window)
(Sint32* w-out)
(Sint32* h-out)))
(define-function-binding SDL_GetWindowPixelFormat
return: (Uint32 format)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowPosition
args: ((SDL_Window* window)
(Sint32* x-out)
(Sint32* y-out)))
(define-function-binding SDL_GetWindowSize
args: ((SDL_Window* window)
(Sint32* w-out)
(Sint32* h-out)))
(define-function-binding SDL_GetWindowSurface
return: (SDL_Surface* surface-or-null)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowTitle
return: (c-string title)
args: ((SDL_Window* window)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SET WINDOW PROPERTIES
(define-function-binding SDL_SetWindowBordered
args: ((SDL_Window* window)
(bool bordered?)))
(define-function-binding SDL_SetWindowBrightness
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(float brightness)))
(define-function-binding SDL_SetWindowData
return: (c-pointer previous-data-value)
args: ((SDL_Window* window)
(c-string data-key)
(c-pointer data-value)))
(define-function-binding SDL_SetWindowDisplayMode
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(SDL_DisplayMode* mode)))
(define-function-binding SDL_SetWindowFullscreen
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(Uint32 fullscreen-flags)))
(define-function-binding SDL_SetWindowGammaRamp
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(Uint16* red-array)
(Uint16* green-array)
(Uint16* blue-array)))
(define-function-binding SDL_SetWindowGrab
args: ((SDL_Window* window)
(bool grabbed?)))
(define-function-binding SDL_SetWindowIcon
args: ((SDL_Window* window)
(SDL_Surface* surface)))
(define-function-binding SDL_SetWindowMaximumSize
args: ((SDL_Window* window)
(Sint32 max_w)
(Sint32 max_h)))
(define-function-binding SDL_SetWindowMinimumSize
args: ((SDL_Window* window)
(Sint32 min_w)
(Sint32 min_h)))
(define-function-binding SDL_SetWindowPosition
args: ((SDL_Window* window)
(Sint32 x)
(Sint32 y)))
(define-function-binding SDL_SetWindowSize
args: ((SDL_Window* window)
(Sint32 w)
(Sint32 h)))
(define-function-binding SDL_SetWindowTitle
args: ((SDL_Window* window)
(c-string title)))
#+libSDL-2.0.4+
(define-function-binding SDL_GetGrabbedWindow
return: (SDL_Window* window))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; WINDOW POSITION C-MACROS
(define-function-binding* SDL_WINDOWPOS_UNDEFINED_DISPLAY
return: (Uint32 value)
args: ((Uint32 displayNum))
body: "C_return(SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayNum));")
(define-function-binding* SDL_WINDOWPOS_ISUNDEFINED
return: (bool is-undefined?)
args: ((Uint32 value))
body: "C_return(SDL_WINDOWPOS_ISUNDEFINED(value));")
(define-function-binding* SDL_WINDOWPOS_CENTERED_DISPLAY
return: (Uint32 value)
args: ((Uint32 displayNum))
body: "C_return(SDL_WINDOWPOS_CENTERED_DISPLAY(displayNum));")
(define-function-binding* SDL_WINDOWPOS_ISCENTERED
return: (bool is-undefined?)
args: ((Uint32 value))
body: "C_return(SDL_WINDOWPOS_ISCENTERED(value));")
| null | https://raw.githubusercontent.com/chicken-mobile/chicken-sdl2-android-builder/90ef1f0ff667737736f1932e204d29ae615a00c4/eggs/sdl2/lib/sdl2-internals/functions/window.scm | scheme |
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 COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
CREATE / DESTROY WINDOW
TODO?: SDL_CreateWindowAndRenderer
UPDATE WINDOW SURFACE
WINDOW MANAGEMENT
GET WINDOW PROPERTIES
SET WINDOW PROPERTIES
WINDOW POSITION C-MACROS | chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2
Copyright © 2013 , 2015 - 2016 .
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDER OR FOR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
(export SDL_CreateWindow
SDL_GetWindowFromID
SDL_DestroyWindow
SDL_UpdateWindowSurface
SDL_UpdateWindowSurfaceRects
SDL_ShowWindow
SDL_HideWindow
SDL_MaximizeWindow
SDL_MinimizeWindow
SDL_RaiseWindow
SDL_RestoreWindow
SDL_GetWindowBrightness
SDL_GetWindowData
SDL_GetWindowDisplayIndex
SDL_GetWindowDisplayMode
SDL_GetWindowFlags
SDL_GetWindowGammaRamp
SDL_GetWindowGrab
SDL_GetWindowID
SDL_GetWindowMaximumSize
SDL_GetWindowMinimumSize
SDL_GetWindowPixelFormat
SDL_GetWindowPosition
SDL_GetWindowSize
SDL_GetWindowSurface
SDL_GetWindowTitle
SDL_SetWindowBordered
SDL_SetWindowBrightness
SDL_SetWindowData
SDL_SetWindowDisplayMode
SDL_SetWindowFullscreen
SDL_SetWindowGammaRamp
SDL_SetWindowGrab
SDL_SetWindowIcon
SDL_SetWindowMaximumSize
SDL_SetWindowMinimumSize
SDL_SetWindowPosition
SDL_SetWindowSize
SDL_SetWindowTitle
SDL_WINDOWPOS_UNDEFINED_DISPLAY
SDL_WINDOWPOS_ISUNDEFINED
SDL_WINDOWPOS_CENTERED_DISPLAY
SDL_WINDOWPOS_ISCENTERED)
#+libSDL-2.0.4+
(export SDL_GetGrabbedWindow)
(define-function-binding SDL_CreateWindow
return: (SDL_Window* new-window)
args: ((c-string title)
(Sint32 x) (Sint32 y)
(Sint32 w) (Sint32 h)
(Uint32 flags)))
TODO ? : SDL_CreateWindowFrom
(define-function-binding SDL_GetWindowFromID
return: (SDL_Window* window-or-null)
args: ((Uint32 id)))
(define-function-binding SDL_DestroyWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_UpdateWindowSurface
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)))
(define-function-binding SDL_UpdateWindowSurfaceRects
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(c-pointer rects)
(Sint32 numrects)))
(define-function-binding SDL_ShowWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_HideWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_MaximizeWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_MinimizeWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_RaiseWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_RestoreWindow
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowBrightness
return: (float brightness)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowData
return: (c-pointer data-value)
args: ((SDL_Window* window)
(c-string data-key)))
(define-function-binding SDL_GetWindowDisplayIndex
return: (Sint32 display-index)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowDisplayMode
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(SDL_DisplayMode* mode-out)))
(define-function-binding SDL_GetWindowFlags
return: (Uint32 flags)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowGammaRamp
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(Uint16* red-array-out)
(Uint16* green-array-out)
(Uint16* blue-array-out)))
(define-function-binding SDL_GetWindowGrab
return: (bool grabbed?)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowID
return: (Uint32 id)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowMaximumSize
args: ((SDL_Window* window)
(Sint32* w-out)
(Sint32* h-out)))
(define-function-binding SDL_GetWindowMinimumSize
args: ((SDL_Window* window)
(Sint32* w-out)
(Sint32* h-out)))
(define-function-binding SDL_GetWindowPixelFormat
return: (Uint32 format)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowPosition
args: ((SDL_Window* window)
(Sint32* x-out)
(Sint32* y-out)))
(define-function-binding SDL_GetWindowSize
args: ((SDL_Window* window)
(Sint32* w-out)
(Sint32* h-out)))
(define-function-binding SDL_GetWindowSurface
return: (SDL_Surface* surface-or-null)
args: ((SDL_Window* window)))
(define-function-binding SDL_GetWindowTitle
return: (c-string title)
args: ((SDL_Window* window)))
(define-function-binding SDL_SetWindowBordered
args: ((SDL_Window* window)
(bool bordered?)))
(define-function-binding SDL_SetWindowBrightness
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(float brightness)))
(define-function-binding SDL_SetWindowData
return: (c-pointer previous-data-value)
args: ((SDL_Window* window)
(c-string data-key)
(c-pointer data-value)))
(define-function-binding SDL_SetWindowDisplayMode
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(SDL_DisplayMode* mode)))
(define-function-binding SDL_SetWindowFullscreen
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(Uint32 fullscreen-flags)))
(define-function-binding SDL_SetWindowGammaRamp
return: (Sint32 zero-if-success)
args: ((SDL_Window* window)
(Uint16* red-array)
(Uint16* green-array)
(Uint16* blue-array)))
(define-function-binding SDL_SetWindowGrab
args: ((SDL_Window* window)
(bool grabbed?)))
(define-function-binding SDL_SetWindowIcon
args: ((SDL_Window* window)
(SDL_Surface* surface)))
(define-function-binding SDL_SetWindowMaximumSize
args: ((SDL_Window* window)
(Sint32 max_w)
(Sint32 max_h)))
(define-function-binding SDL_SetWindowMinimumSize
args: ((SDL_Window* window)
(Sint32 min_w)
(Sint32 min_h)))
(define-function-binding SDL_SetWindowPosition
args: ((SDL_Window* window)
(Sint32 x)
(Sint32 y)))
(define-function-binding SDL_SetWindowSize
args: ((SDL_Window* window)
(Sint32 w)
(Sint32 h)))
(define-function-binding SDL_SetWindowTitle
args: ((SDL_Window* window)
(c-string title)))
#+libSDL-2.0.4+
(define-function-binding SDL_GetGrabbedWindow
return: (SDL_Window* window))
(define-function-binding* SDL_WINDOWPOS_UNDEFINED_DISPLAY
return: (Uint32 value)
args: ((Uint32 displayNum))
body: "C_return(SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayNum));")
(define-function-binding* SDL_WINDOWPOS_ISUNDEFINED
return: (bool is-undefined?)
args: ((Uint32 value))
body: "C_return(SDL_WINDOWPOS_ISUNDEFINED(value));")
(define-function-binding* SDL_WINDOWPOS_CENTERED_DISPLAY
return: (Uint32 value)
args: ((Uint32 displayNum))
body: "C_return(SDL_WINDOWPOS_CENTERED_DISPLAY(displayNum));")
(define-function-binding* SDL_WINDOWPOS_ISCENTERED
return: (bool is-undefined?)
args: ((Uint32 value))
body: "C_return(SDL_WINDOWPOS_ISCENTERED(value));")
|
084bafae9f5d0276d83cdc9626eff71d8e9e00ec5a9b9566a502d9a08b808139 | rm-hull/project-euler | euler069.clj | EULER # 069
;; ==========
Euler 's Totient function , ) [ sometimes called the phi function ] , is
;; used to determine the number of numbers less than n which are relatively
prime to n. For example , as 1 , 2 , 4 , 5 , 7 , and 8 , are all less than nine
and relatively prime to nine , φ(9)=6 .
;;
n Relatively Prime φ(n ) n / φ(n )
2 1 1 2
3 1,2 2 1.5
4 1,3 2 2
5 1,2,3,4 4 1.25
6 1,5 2 3
7 1,2,3,4,5,6 6 1.1666 ...
8 1,3,5,7 4 2
9 1,2,4,5,7,8 6 1.5
10 1,3,7,9 4 2.5
;;
It can be seen that n=6 produces a maximum n / φ(n ) for n < = 10 .
;;
Find the value of n < = 1,000,000 for which n / φ(n ) is a maximum .
;;
(ns euler069
(:use [util.primes]))
(defn solve [n]
(->>
(range 2 (inc n))
(map (fn [a] (vector a (/ a (phi a)))))
(reduce (fn [a b] (if (> (second a) (second b)) a b)))))
(time (solve 1000000))
| null | https://raw.githubusercontent.com/rm-hull/project-euler/04e689e87a1844cfd83229bb4628051e3ac6a325/src/euler069.clj | clojure | ==========
used to determine the number of numbers less than n which are relatively
| EULER # 069
Euler 's Totient function , ) [ sometimes called the phi function ] , is
prime to n. For example , as 1 , 2 , 4 , 5 , 7 , and 8 , are all less than nine
and relatively prime to nine , φ(9)=6 .
n Relatively Prime φ(n ) n / φ(n )
2 1 1 2
3 1,2 2 1.5
4 1,3 2 2
5 1,2,3,4 4 1.25
6 1,5 2 3
7 1,2,3,4,5,6 6 1.1666 ...
8 1,3,5,7 4 2
9 1,2,4,5,7,8 6 1.5
10 1,3,7,9 4 2.5
It can be seen that n=6 produces a maximum n / φ(n ) for n < = 10 .
Find the value of n < = 1,000,000 for which n / φ(n ) is a maximum .
(ns euler069
(:use [util.primes]))
(defn solve [n]
(->>
(range 2 (inc n))
(map (fn [a] (vector a (/ a (phi a)))))
(reduce (fn [a b] (if (> (second a) (second b)) a b)))))
(time (solve 1000000))
|
d6898ff05a6206f100d4be871e7101aba995b1ae4dee14f68ccef4921fa5ef0c | byorgey/haxr | validate.hs | -- Implements the validation suite from /
This has not been tested as the XML - RPC validator does not seem to
-- be working at the moment.
import System.Time
import Network.XmlRpc.Internals
import Network.XmlRpc.Server
get :: String -> [(String,a)] -> IO a
get f xs = maybeToM ("No such field: '" ++ f ++ "'") (lookup f xs)
arrayOfStructsTest :: [[(String,Int)]] -> IO Int
arrayOfStructsTest xs = return $ sum [ i | Just i <- map (lookup "curly") xs]
countTheEntities :: String -> IO [(String,Int)]
countTheEntities xs = return [
("ctLeftAngleBrackets", count '<'),
("ctRightAngleBrackets", count '>'),
("ctAmpersands", count '&'),
("ctApostrophes", count '\''),
("ctQuotes", count '"')
]
where count c = length (filter (==c) xs)
easyStructTest :: [(String,Int)] -> IO Int
easyStructTest xs = do
m <- get "moe" xs
l <- get "larry" xs
c <- get "curly" xs
return (m+l+c)
-- FIXME: should be able to get it as a struct
echoStructTest :: Value -> IO Value
echoStructTest xs = return xs
manyTypesTest :: Int -> Bool -> String -> Double -> CalendarTime -> String
-> IO [Value]
manyTypesTest i b s d t b64 = return [toValue i, toValue b, toValue s,
toValue d, toValue t, toValue b64]
moderateSizeArrayCheck :: [String] -> IO String
moderateSizeArrayCheck [] = fail "empty array"
moderateSizeArrayCheck xs = return (head xs ++ last xs)
nestedStructTest :: [(String,[(String,[(String,[(String,Int)])])])] -> IO Int
nestedStructTest c = do
y <- get "2000" c
m <- get "04" y
d <- get "01" m
easyStructTest d
simpleStructReturnTest :: Int -> IO [(String, Int)]
simpleStructReturnTest x = return [
("times10",10*x),
("times100",100*x),
("times1000",1000*x)
]
main = cgiXmlRpcServer
[
("validator1.arrayOfStructsTest", fun arrayOfStructsTest),
("validator1.countTheEntities", fun countTheEntities),
("validator1.easyStructTest", fun easyStructTest),
("validator1.echoStructTest", fun echoStructTest),
("validator1.manyTypesTest", fun manyTypesTest),
("validator1.moderateSizeArrayCheck", fun moderateSizeArrayCheck),
("validator1.nestedStructTest", fun nestedStructTest),
("validator1.simpleStructReturnTest", fun simpleStructReturnTest)
]
| null | https://raw.githubusercontent.com/byorgey/haxr/0a643b9b8ce1265736b1bc454d7df47c57bd9f50/examples/validate.hs | haskell | Implements the validation suite from /
be working at the moment.
FIXME: should be able to get it as a struct | This has not been tested as the XML - RPC validator does not seem to
import System.Time
import Network.XmlRpc.Internals
import Network.XmlRpc.Server
get :: String -> [(String,a)] -> IO a
get f xs = maybeToM ("No such field: '" ++ f ++ "'") (lookup f xs)
arrayOfStructsTest :: [[(String,Int)]] -> IO Int
arrayOfStructsTest xs = return $ sum [ i | Just i <- map (lookup "curly") xs]
countTheEntities :: String -> IO [(String,Int)]
countTheEntities xs = return [
("ctLeftAngleBrackets", count '<'),
("ctRightAngleBrackets", count '>'),
("ctAmpersands", count '&'),
("ctApostrophes", count '\''),
("ctQuotes", count '"')
]
where count c = length (filter (==c) xs)
easyStructTest :: [(String,Int)] -> IO Int
easyStructTest xs = do
m <- get "moe" xs
l <- get "larry" xs
c <- get "curly" xs
return (m+l+c)
echoStructTest :: Value -> IO Value
echoStructTest xs = return xs
manyTypesTest :: Int -> Bool -> String -> Double -> CalendarTime -> String
-> IO [Value]
manyTypesTest i b s d t b64 = return [toValue i, toValue b, toValue s,
toValue d, toValue t, toValue b64]
moderateSizeArrayCheck :: [String] -> IO String
moderateSizeArrayCheck [] = fail "empty array"
moderateSizeArrayCheck xs = return (head xs ++ last xs)
nestedStructTest :: [(String,[(String,[(String,[(String,Int)])])])] -> IO Int
nestedStructTest c = do
y <- get "2000" c
m <- get "04" y
d <- get "01" m
easyStructTest d
simpleStructReturnTest :: Int -> IO [(String, Int)]
simpleStructReturnTest x = return [
("times10",10*x),
("times100",100*x),
("times1000",1000*x)
]
main = cgiXmlRpcServer
[
("validator1.arrayOfStructsTest", fun arrayOfStructsTest),
("validator1.countTheEntities", fun countTheEntities),
("validator1.easyStructTest", fun easyStructTest),
("validator1.echoStructTest", fun echoStructTest),
("validator1.manyTypesTest", fun manyTypesTest),
("validator1.moderateSizeArrayCheck", fun moderateSizeArrayCheck),
("validator1.nestedStructTest", fun nestedStructTest),
("validator1.simpleStructReturnTest", fun simpleStructReturnTest)
]
|
a4ff2fff5a3e2cca32b96655f88ac88f13c37af984a5fef317dfe2d93cd74c3a | webyrd/n-grams-for-synthesis | recnum.scm | ; This file is part of the reference implementation of the R6RS Arithmetic SRFI.
; See file COPYING.
; Exact complex arithmetic built on rational arithmetic
from Scheme 48
; By structuring the complex numbers this way---instead of using just
one representation using tuples of arbitrary reals --- we avoid having
; to implement full generic arithmetic below the complex numbers, or
; having to resort to confusing recursion in the generic arithmetic.
; But suit yourself.
Note that , unlike the COMPNUMS operations , these can return
; ratnums.
(define-record-type :recnum
(make-recnum real imag)
recnum?
(real recnum-real)
(imag recnum-imag))
(define-record-discloser :recnum
(lambda (r)
(list 'recnum
(recnum-real r)
(recnum-imag r))))
(define (r5rs->recnum n)
(make-recnum (r5rs->integer (r5rs:real-part n))
(r5rs->integer (r5rs:imag-part n))))
(define (rectangulate x y)
(if (rational= y (r5rs->integer 0))
x
(make-recnum x y)))
(define (recnum+ a b)
(rectangulate (rational+ (recnum-real a) (recnum-real b))
(rational+ (recnum-imag a) (recnum-imag b))))
(define (recnum- a b)
(rectangulate (rational- (recnum-real a) (recnum-real b))
(rational- (recnum-imag a) (recnum-imag b))))
(define (recnum* a b)
(let ((a1 (recnum-real a))
(a2 (recnum-imag a))
(b1 (recnum-real b))
(b2 (recnum-imag b)))
(rectangulate (rational- (rational* a1 b1) (rational* a2 b2))
(rational+ (rational* a1 b2) (rational* a2 b1)))))
(define (recnum/ a b)
(let ((a1 (recnum-real a))
(a2 (recnum-imag a))
(b1 (recnum-real b))
(b2 (recnum-imag b)))
(let ((d (rational+ (rational* b1 b1) (rational* b2 b2))))
(rectangulate (rational/ (rational+ (rational* a1 b1) (rational* a2 b2)) d)
(rational/ (rational- (rational* a2 b1) (rational* a1 b2)) d)))))
(define (recnum= a b)
(let ((a1 (recnum-real a))
(a2 (recnum-imag a))
(b1 (recnum-real b))
(b2 (recnum-imag b)))
(and (rational= a1 b1) (rational= a2 b2))))
(define (recnum->string r radix)
(if (rational-negative? (recnum-imag r))
(string-append (rational->string (recnum-real r) radix)
"-"
(rational->string (rational- (recnum-imag r)) radix)
"i")
(string-append (rational->string (recnum-real r) radix)
"+"
(rational->string (recnum-imag r) radix)
"i")))
| null | https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-77/arithmetic-reference/recnum.scm | scheme | This file is part of the reference implementation of the R6RS Arithmetic SRFI.
See file COPYING.
Exact complex arithmetic built on rational arithmetic
By structuring the complex numbers this way---instead of using just
to implement full generic arithmetic below the complex numbers, or
having to resort to confusing recursion in the generic arithmetic.
But suit yourself.
ratnums. |
from Scheme 48
one representation using tuples of arbitrary reals --- we avoid having
Note that , unlike the COMPNUMS operations , these can return
(define-record-type :recnum
(make-recnum real imag)
recnum?
(real recnum-real)
(imag recnum-imag))
(define-record-discloser :recnum
(lambda (r)
(list 'recnum
(recnum-real r)
(recnum-imag r))))
(define (r5rs->recnum n)
(make-recnum (r5rs->integer (r5rs:real-part n))
(r5rs->integer (r5rs:imag-part n))))
(define (rectangulate x y)
(if (rational= y (r5rs->integer 0))
x
(make-recnum x y)))
(define (recnum+ a b)
(rectangulate (rational+ (recnum-real a) (recnum-real b))
(rational+ (recnum-imag a) (recnum-imag b))))
(define (recnum- a b)
(rectangulate (rational- (recnum-real a) (recnum-real b))
(rational- (recnum-imag a) (recnum-imag b))))
(define (recnum* a b)
(let ((a1 (recnum-real a))
(a2 (recnum-imag a))
(b1 (recnum-real b))
(b2 (recnum-imag b)))
(rectangulate (rational- (rational* a1 b1) (rational* a2 b2))
(rational+ (rational* a1 b2) (rational* a2 b1)))))
(define (recnum/ a b)
(let ((a1 (recnum-real a))
(a2 (recnum-imag a))
(b1 (recnum-real b))
(b2 (recnum-imag b)))
(let ((d (rational+ (rational* b1 b1) (rational* b2 b2))))
(rectangulate (rational/ (rational+ (rational* a1 b1) (rational* a2 b2)) d)
(rational/ (rational- (rational* a2 b1) (rational* a1 b2)) d)))))
(define (recnum= a b)
(let ((a1 (recnum-real a))
(a2 (recnum-imag a))
(b1 (recnum-real b))
(b2 (recnum-imag b)))
(and (rational= a1 b1) (rational= a2 b2))))
(define (recnum->string r radix)
(if (rational-negative? (recnum-imag r))
(string-append (rational->string (recnum-real r) radix)
"-"
(rational->string (rational- (recnum-imag r)) radix)
"i")
(string-append (rational->string (recnum-real r) radix)
"+"
(rational->string (recnum-imag r) radix)
"i")))
|
a663e4790a89ef781061be5aec4ff6fbeed2c50a8639c66c8d005c840c07952d | IUCompilerCourse/public-student-support-code | interp-Lvecof.rkt | #lang racket
(require racket/fixnum)
(require "utilities.rkt")
(require "interp-Lvec.rkt")
(provide interp-Lvecof interp-Lvecof-class)
;; Note to maintainers of this code:
;; A copy of this interpreter is in the book and should be
;; kept in sync with this code.
(define interp-Lvecof-class
(class interp-Lvec-class
(super-new)
(define/override (interp-op op)
(verbose "Lvecof/interp-op" op)
(match op
['make-vector make-vector]
['vectorof-length vector-length]
['vectorof-ref
(lambda (v i)
(if (< i (vector-length v))
(vector-ref v i)
(error 'trapped-error "vectorof-ref: index ~a out of bounds\nin ~v" i v)))]
['vectorof-set!
(lambda (v i e)
(if (< i (vector-length v))
(vector-set! v i e)
(error 'trapped-error "vectorof-set!: index ~a out of bounds\nin ~v" i v)))]
['* fx*]
['exit (lambda () (error 'interp "exiting"))]
[else (super interp-op op)]))
))
(define (interp-Lvecof p)
(send (new interp-Lvecof-class) interp-program p))
| null | https://raw.githubusercontent.com/IUCompilerCourse/public-student-support-code/fe5f4a657f4622eba596454c14bc8f72765004d9/interp-Lvecof.rkt | racket | Note to maintainers of this code:
A copy of this interpreter is in the book and should be
kept in sync with this code. | #lang racket
(require racket/fixnum)
(require "utilities.rkt")
(require "interp-Lvec.rkt")
(provide interp-Lvecof interp-Lvecof-class)
(define interp-Lvecof-class
(class interp-Lvec-class
(super-new)
(define/override (interp-op op)
(verbose "Lvecof/interp-op" op)
(match op
['make-vector make-vector]
['vectorof-length vector-length]
['vectorof-ref
(lambda (v i)
(if (< i (vector-length v))
(vector-ref v i)
(error 'trapped-error "vectorof-ref: index ~a out of bounds\nin ~v" i v)))]
['vectorof-set!
(lambda (v i e)
(if (< i (vector-length v))
(vector-set! v i e)
(error 'trapped-error "vectorof-set!: index ~a out of bounds\nin ~v" i v)))]
['* fx*]
['exit (lambda () (error 'interp "exiting"))]
[else (super interp-op op)]))
))
(define (interp-Lvecof p)
(send (new interp-Lvecof-class) interp-program p))
|
5595fa62ce45e33dafdf61aac37b4fe36075732177ad469f339b7a2380959ef8 | privet-kitty/cl-competitive | eulerian-polynomial.lisp | (defpackage :cp/eulerian-polynomial
(:use :cl
:cp/ntt :cp/fps :cp/perfect-kth-powers :cp/binom-mod-prime :cp/static-mod)
(:export #:make-eulerian-polynomial #:make-eulerian-polynomial*))
(in-package :cp/eulerian-polynomial)
(defun make-eulerian-polynomial (n minfactor-table)
"Returns a sequence A(n, 0), A(n, 1), ..., A(n, n-1), where A(n, m) is the
number of permutations of the length n which contains exactly m descent (or
ascent). Note that the 0-th eulerian polynomial is 1 by definition."
(declare (optimize (speed 3))
((mod #.array-dimension-limit) n)
(vector minfactor-table))
(when (zerop n)
(return-from make-eulerian-polynomial
(make-array 1 :element-type 'mint :initial-element 1)))
(let* ((len (ceiling n 2))
(poly1 (make-array len :element-type 'mint :initial-element 0))
(poly2 (subseq (make-perfect-kth-powers minfactor-table (+ len 1) n +mod+) 1)))
(dotimes (k len)
(let ((val (mod (* (aref *fact-inv* k)
(aref *fact-inv* (- (+ n 1) k)))
+mod+)))
(setf (aref poly1 k)
(if (evenp k) val (mod (- val) +mod+)))))
(let ((res (adjust-array (poly-prod poly1 poly2) n))
(coef (aref *fact* (+ n 1))))
(declare (mint-vector res))
(dotimes (i len)
(setf (aref res i) (mod (* (aref res i) coef) +mod+)))
(loop for i from len below n
do (setf (aref res i) (aref res (- n i 1))))
res)))
(defun make-eulerian-polynomial* (n minfactor-table)
"Returns a sequence A'(n, 0), A'(n, 1), ..., A'(n, n), where A'(n, m) is the
number of permutations of the length n which contains exactly m runs.
Note: Run is a maximal contiguous increasing subsequence. It holds A'(n, m) =
A'(n, m-1) for almost all args. This variant will be more useful when we deal
with FPS of n-th powers and assume 0^0 = 1."
(declare (optimize (speed 3))
((mod #.array-dimension-limit) n)
(vector minfactor-table))
(if (= n 0)
(make-array 1 :element-type 'mint :initial-element 1)
(concatenate 'mint-vector
#(0)
(make-eulerian-polynomial n minfactor-table))))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/a2e4156e66417c051404ade181ce6305cb0c2824/module/eulerian-polynomial.lisp | lisp | (defpackage :cp/eulerian-polynomial
(:use :cl
:cp/ntt :cp/fps :cp/perfect-kth-powers :cp/binom-mod-prime :cp/static-mod)
(:export #:make-eulerian-polynomial #:make-eulerian-polynomial*))
(in-package :cp/eulerian-polynomial)
(defun make-eulerian-polynomial (n minfactor-table)
"Returns a sequence A(n, 0), A(n, 1), ..., A(n, n-1), where A(n, m) is the
number of permutations of the length n which contains exactly m descent (or
ascent). Note that the 0-th eulerian polynomial is 1 by definition."
(declare (optimize (speed 3))
((mod #.array-dimension-limit) n)
(vector minfactor-table))
(when (zerop n)
(return-from make-eulerian-polynomial
(make-array 1 :element-type 'mint :initial-element 1)))
(let* ((len (ceiling n 2))
(poly1 (make-array len :element-type 'mint :initial-element 0))
(poly2 (subseq (make-perfect-kth-powers minfactor-table (+ len 1) n +mod+) 1)))
(dotimes (k len)
(let ((val (mod (* (aref *fact-inv* k)
(aref *fact-inv* (- (+ n 1) k)))
+mod+)))
(setf (aref poly1 k)
(if (evenp k) val (mod (- val) +mod+)))))
(let ((res (adjust-array (poly-prod poly1 poly2) n))
(coef (aref *fact* (+ n 1))))
(declare (mint-vector res))
(dotimes (i len)
(setf (aref res i) (mod (* (aref res i) coef) +mod+)))
(loop for i from len below n
do (setf (aref res i) (aref res (- n i 1))))
res)))
(defun make-eulerian-polynomial* (n minfactor-table)
"Returns a sequence A'(n, 0), A'(n, 1), ..., A'(n, n), where A'(n, m) is the
number of permutations of the length n which contains exactly m runs.
Note: Run is a maximal contiguous increasing subsequence. It holds A'(n, m) =
A'(n, m-1) for almost all args. This variant will be more useful when we deal
with FPS of n-th powers and assume 0^0 = 1."
(declare (optimize (speed 3))
((mod #.array-dimension-limit) n)
(vector minfactor-table))
(if (= n 0)
(make-array 1 :element-type 'mint :initial-element 1)
(concatenate 'mint-vector
#(0)
(make-eulerian-polynomial n minfactor-table))))
|
|
8f305442899e362a4619502bde420fac8ec04156e54b03434e10a2bf484af68f | funcool/cats | core_spec.cljc | (ns cats.core-spec
#?(:cljs
(:require [cljs.test :as t]
[cats.builtin :as b]
[cats.monad.maybe :as maybe]
[cats.core :as m :include-macros true]
[cats.context :as ctx :include-macros true])
:clj
(:require [clojure.test :as t]
[cats.builtin :as b]
[cats.monad.maybe :as maybe]
[cats.core :as m]
[cats.context :as ctx])))
(defn add2 [x y]
(+ x y))
(t/deftest fmap-test
(t/testing "Sets the context."
(t/is (= [[1] [2] [3] [4]]
(m/fmap #(m/return %) [1 2 3 4])))))
(t/deftest fapply-test
(t/testing "Simple fapply run."
(t/is (= 2 @(m/fapply (maybe/just inc) (maybe/just 1)))))
(t/testing "Variadic fapply run."
(t/is (= 3 @(m/fapply (maybe/just #(partial + %))
(maybe/just 1)
(maybe/just 2))))))
(t/deftest mlet-tests
(t/testing "Support regular let bindings inside mlet"
(t/is (= (maybe/just 2)
(m/mlet [i (maybe/just 1)
:let [i (inc i)]]
(m/return i)))))
(t/testing "Support :when guards inside its bindings"
(t/is (= (maybe/nothing)
(m/mlet [i (maybe/just 2)
:when (> i 2)]
(m/return i))))
(t/is (= [3 4 5]
(m/mlet [i [1 2 3 4 5]
:when (> i 2)]
(m/return i)))))
(t/testing "The body runs in an implicit do"
(t/is (= (maybe/just 3)
(m/mlet [i (maybe/just 2)
:let [x (inc i)]]
(assert (= x 3))
(m/return x))))))
(t/deftest alet-tests
(t/testing "It works with just one applicative binding"
(t/is (= (maybe/just 3)
(m/alet [x (maybe/just 2)]
(inc x)))))
(t/testing "The body runs in an implicit do"
(t/is (= (maybe/just 3)
(m/alet [x (maybe/just 2)]
nil
42
(inc x)))))
(t/testing "It works with no dependencies between applicative values"
(t/is (= (maybe/just 3)
(m/alet [x (maybe/just 1)
y (maybe/just 2)]
(add2 x y)))))
(t/testing "It works with one level of dependencies between applicative values"
(t/is (= (maybe/just [42])
split 1
y (maybe/just 2)
split 2
(vector z)))))
(t/testing "It works with more than one level of dependencies between applicative values"
(t/is (= (maybe/just [45])
split 1
y (maybe/just 2)
split 2
split 3
(vector z)))))
(t/testing "It works with more than one level of dependencies, with distinct split sizes"
(t/is (= (maybe/just 66)
split 1
y (maybe/just 2)
split 2
a (maybe/just (* 3 x))
split 3
c (maybe/just 2)
split 4
d))))
(t/testing "It renames the body symbols correctly"
(t/is (= (maybe/just 42)
(m/alet [x (maybe/just 5)
y (maybe/just 6)
x (maybe/just (inc x))
y (maybe/just (inc y))]
(* x y))))))
(t/deftest sequence-tests
(t/testing "It works with vectors"
(t/is (= (m/sequence [[1 2] [3 4]])
[[1 3] [1 4] [2 3] [2 4]])))
(t/testing "It works with lazy seqs"
(t/is (= (m/sequence [(lazy-seq [1 2]) (lazy-seq [3 4])])
[[1 3] [1 4] [2 3] [2 4]])))
(t/testing "It works with sets"
(t/is (= (m/sequence [#{1 2} #{3 4}])
#{[1 3] [1 4] [2 3] [2 4]})))
(t/testing "It works with Maybe values"
(t/is (= (maybe/just [2 3])
(m/sequence [(maybe/just 2) (maybe/just 3)])))
(t/is (= (maybe/nothing)
(m/sequence [(maybe/just 2) (maybe/nothing)]))))
(t/testing "It works with an empty collection"
(t/is (= (maybe/just ())
(ctx/with-context maybe/context
(m/sequence ()))))))
(t/deftest mapseq-tests
(t/testing "It works with Maybe values"
(t/is (= (maybe/just [1 2 3 4 5])
(m/mapseq maybe/just [1 2 3 4 5])))
(t/is (= (maybe/nothing)
(m/mapseq (fn [v]
(if (odd? v)
(maybe/just v)
(maybe/nothing)))
[1 2 3 4 5]))))
(t/testing "It works with an empty collection"
(t/is (= (maybe/just ())
(ctx/with-context maybe/context
(m/mapseq maybe/just []))))))
(t/deftest lift-a-tests
(let [app+ (m/lift-a 2 +)]
(t/testing "It can lift a function to the vector applicative"
(t/is (= [1 2 3 4 5 6]
(app+ [0 2 4] [1 2]))))
(t/testing "It can lift a function to the Maybe applicative"
(t/is (= (maybe/just 6)
(app+ (maybe/just 2) (maybe/just 4))))
(t/is (= (maybe/nothing)
(app+ (maybe/just 1) (maybe/nothing)))))))
(t/deftest lift-m-tests
(let [monad+ (m/lift-m 2 +)]
(t/testing "It can lift a function to the vector monad"
(t/is (= [1 2 3 4 5 6]
(monad+ [0 2 4] [1 2]))))
(t/testing "It can lift a function to the Maybe monad"
(t/is (= (maybe/just 6)
(monad+ (maybe/just 2) (maybe/just 4))))
(t/is (= (maybe/nothing)
(monad+ (maybe/just 1) (maybe/nothing)))))))
(t/deftest fixed-arity-lift-m-tests
#?(:clj
(let [monad+ (m/lift-m add2)]
(t/testing "It can lift a function to the vector monad"
(t/is (= [1 2 3 4 5 6]
(monad+ [0 2 4] [1 2]))))))
(t/testing "It can lift a function to the Maybe monad"
(let [monad+ (m/lift-m 2 add2)]
(t/is (= (maybe/just 6)
(monad+ (maybe/just 2) (maybe/just 4))))
(t/is (= (maybe/nothing)
(monad+ (maybe/just 1) (maybe/nothing))))))
(t/testing "Currying and lifting can be combined"
(let [curry-monad+ (m/curry-lift-m 2 add2)]
(t/is (= (maybe/just 6)
((curry-monad+ (maybe/just 1)) (maybe/just 5)))))))
(t/deftest filter-tests
(t/testing "It can filter Maybe monadic values"
(let [bigger-than-4 (partial < 4)]
(t/is (= (maybe/just 6)
(m/filter bigger-than-4 (maybe/just 6))))
(t/is (= (maybe/nothing)
(m/filter bigger-than-4 (maybe/just 3))))))
(t/testing "It can filter vectors"
(t/is (= [1 3 5]
(m/filter odd? [1 2 3 4 5 6])))))
(t/deftest when-tests
(t/testing "It returns the monadic value unchanged when the condition is true"
(t/is (= (maybe/just 3)
(m/when true (maybe/just 3))))
(t/is (= (maybe/just 3)
(m/when maybe/context true (maybe/just 3)))))
(t/testing "It returns nil in the monadic context when the condition is false"
(ctx/with-context b/sequence-context
(t/is (= [nil]
(m/when false []))))
(t/is (= [nil]
(m/when b/sequence-context false []))))
(t/testing "it doesn't evaluate the mv when the conditions is false"
(t/is (= [nil]
(m/when b/sequence-context false (throw (ex-info "bang" {})))))))
(t/deftest unless-tests
(t/testing "It returns the monadic value unchanged when the condition is false"
(t/is (= (maybe/just 3)
(m/unless false (maybe/just 3))))
(t/is (= (maybe/just 3)
(m/unless maybe/context false (maybe/just 3)))))
(t/testing "It returns nil in the monadic context when the condition is true"
(ctx/with-context b/sequence-context
(t/is (= [nil]
(m/unless true []))))
(t/is (= [nil]
(m/unless b/sequence-context true []))))
(t/testing "it doesn't evaluate the mv when the condition is true"
(t/is (= [nil]
(m/unless b/sequence-context true (throw (ex-info "bang" {})))))))
(t/deftest curry-tests
#?(:clj
(t/testing "It can curry single and fixed arity functions automatically"
(let [cadd2 (m/curry add2)]
(t/is (= ((cadd2 1) 2)
3))
(t/is (= (cadd2)
cadd2))
(t/is (= (cadd2 1 2)
3)))))
(t/testing "It can curry anonymous functions when providing an arity"
(let [csum (m/curry 3 (fn [x y z] (+ x y z)))]
(t/is (= (((csum 1) 2) 3)
6))
(t/is (= ((csum 1 2) 3)
6))
(t/is (= (((csum) 1 2) 3)
6))
(t/is (= (csum 1 2 3)
6))))
(t/testing "It can curry variadic functions when providing an arity"
(let [csum (m/curry 3 +)]
(t/is (= (((csum 1) 2) 3)
6))
(t/is (= ((csum 1 2) 3)
6))
(t/is (= (((csum) 1 2) 3)
6))
(t/is (= (csum 1 2 3)
6)))))
(t/deftest foldm-tests
(letfn [(m-div [x y]
(if (zero? y)
(maybe/nothing)
(maybe/just (/ x y))))]
(t/testing "It can fold a non-empty collection without an explicit context"
(t/is (= (maybe/just #?(:clj 1/6 :cljs (/ 1 6)))
(m/foldm m-div 1 [1 2 3])))
(t/is (= (maybe/nothing)
(m/foldm m-div 1 [1 0 3]))))
(t/testing "It cannot fold an empty collection without an explicit context"
(t/is (thrown? #?(:clj IllegalArgumentException, :cljs js/Error)
(with-redefs [cats.context/get-current (constantly nil)]
(m/foldm m-div 1 [])))))
(t/testing "It can fold a non-empty collection, given an explicit context"
(t/is (= (maybe/just #?(:clj 1/6, :cljs (/ 1 6)))
(m/foldm maybe/context m-div 1 [1 2 3])))
(t/is (= (maybe/nothing)
(m/foldm maybe/context m-div 1 [1 0 3]))))
(t/testing "It can fold an empty collection, given an explicit context"
(t/is (= (maybe/just 1)
(m/foldm maybe/context m-div 1 [])))
(t/is (= (maybe/just 1)
(ctx/with-context maybe/context
(m/foldm m-div 1 [])))))))
(t/deftest do-let-tests
(t/testing "Support regular let bindings inside do-let"
(t/is (= (maybe/just 2)
(m/do-let [i (maybe/just 1)
:let [i (inc i)]]
(m/return i)))))
(t/testing "Support :when guards inside its bindings"
(t/is (= (maybe/nothing)
(m/do-let [i (maybe/just 2)
:when (> i 2)]
(m/return i))))
(t/is (= [3 4 5]
(m/do-let [i [1 2 3 4 5]
:when (> i 2)]
(m/return i)))))
(t/testing "Support one single form"
(t/is (= (maybe/just 2)
(m/do-let (maybe/just 2)))))
(t/testing "Support multiple single form"
(t/is (= (maybe/just 3)
(m/do-let (maybe/just 2)
(maybe/just 3)))))
(t/testing "Bound variables are always in scope"
(t/is (= (maybe/just 6)
(m/do-let [x (maybe/just 2)]
(maybe/just x)
[y (maybe/just (+ 2 x))]
(maybe/just (+ 2 y)))))))
(t/deftest for-tests
(t/testing "m/for works like (m/sequence (clojure.core/for))"
(t/is (= (maybe/just [2 3])
(m/sequence [(maybe/just 2) (maybe/just 3)])
(m/sequence (for [x [2 3]] (maybe/just x)))
(m/for [x [2 3]] (maybe/just x))))))
| null | https://raw.githubusercontent.com/funcool/cats/120c8f99afff9d9d92f4f690392a1ce1dc68e0b6/test/cats/core_spec.cljc | clojure | (ns cats.core-spec
#?(:cljs
(:require [cljs.test :as t]
[cats.builtin :as b]
[cats.monad.maybe :as maybe]
[cats.core :as m :include-macros true]
[cats.context :as ctx :include-macros true])
:clj
(:require [clojure.test :as t]
[cats.builtin :as b]
[cats.monad.maybe :as maybe]
[cats.core :as m]
[cats.context :as ctx])))
(defn add2 [x y]
(+ x y))
(t/deftest fmap-test
(t/testing "Sets the context."
(t/is (= [[1] [2] [3] [4]]
(m/fmap #(m/return %) [1 2 3 4])))))
(t/deftest fapply-test
(t/testing "Simple fapply run."
(t/is (= 2 @(m/fapply (maybe/just inc) (maybe/just 1)))))
(t/testing "Variadic fapply run."
(t/is (= 3 @(m/fapply (maybe/just #(partial + %))
(maybe/just 1)
(maybe/just 2))))))
(t/deftest mlet-tests
(t/testing "Support regular let bindings inside mlet"
(t/is (= (maybe/just 2)
(m/mlet [i (maybe/just 1)
:let [i (inc i)]]
(m/return i)))))
(t/testing "Support :when guards inside its bindings"
(t/is (= (maybe/nothing)
(m/mlet [i (maybe/just 2)
:when (> i 2)]
(m/return i))))
(t/is (= [3 4 5]
(m/mlet [i [1 2 3 4 5]
:when (> i 2)]
(m/return i)))))
(t/testing "The body runs in an implicit do"
(t/is (= (maybe/just 3)
(m/mlet [i (maybe/just 2)
:let [x (inc i)]]
(assert (= x 3))
(m/return x))))))
(t/deftest alet-tests
(t/testing "It works with just one applicative binding"
(t/is (= (maybe/just 3)
(m/alet [x (maybe/just 2)]
(inc x)))))
(t/testing "The body runs in an implicit do"
(t/is (= (maybe/just 3)
(m/alet [x (maybe/just 2)]
nil
42
(inc x)))))
(t/testing "It works with no dependencies between applicative values"
(t/is (= (maybe/just 3)
(m/alet [x (maybe/just 1)
y (maybe/just 2)]
(add2 x y)))))
(t/testing "It works with one level of dependencies between applicative values"
(t/is (= (maybe/just [42])
split 1
y (maybe/just 2)
split 2
(vector z)))))
(t/testing "It works with more than one level of dependencies between applicative values"
(t/is (= (maybe/just [45])
split 1
y (maybe/just 2)
split 2
split 3
(vector z)))))
(t/testing "It works with more than one level of dependencies, with distinct split sizes"
(t/is (= (maybe/just 66)
split 1
y (maybe/just 2)
split 2
a (maybe/just (* 3 x))
split 3
c (maybe/just 2)
split 4
d))))
(t/testing "It renames the body symbols correctly"
(t/is (= (maybe/just 42)
(m/alet [x (maybe/just 5)
y (maybe/just 6)
x (maybe/just (inc x))
y (maybe/just (inc y))]
(* x y))))))
(t/deftest sequence-tests
(t/testing "It works with vectors"
(t/is (= (m/sequence [[1 2] [3 4]])
[[1 3] [1 4] [2 3] [2 4]])))
(t/testing "It works with lazy seqs"
(t/is (= (m/sequence [(lazy-seq [1 2]) (lazy-seq [3 4])])
[[1 3] [1 4] [2 3] [2 4]])))
(t/testing "It works with sets"
(t/is (= (m/sequence [#{1 2} #{3 4}])
#{[1 3] [1 4] [2 3] [2 4]})))
(t/testing "It works with Maybe values"
(t/is (= (maybe/just [2 3])
(m/sequence [(maybe/just 2) (maybe/just 3)])))
(t/is (= (maybe/nothing)
(m/sequence [(maybe/just 2) (maybe/nothing)]))))
(t/testing "It works with an empty collection"
(t/is (= (maybe/just ())
(ctx/with-context maybe/context
(m/sequence ()))))))
(t/deftest mapseq-tests
(t/testing "It works with Maybe values"
(t/is (= (maybe/just [1 2 3 4 5])
(m/mapseq maybe/just [1 2 3 4 5])))
(t/is (= (maybe/nothing)
(m/mapseq (fn [v]
(if (odd? v)
(maybe/just v)
(maybe/nothing)))
[1 2 3 4 5]))))
(t/testing "It works with an empty collection"
(t/is (= (maybe/just ())
(ctx/with-context maybe/context
(m/mapseq maybe/just []))))))
(t/deftest lift-a-tests
(let [app+ (m/lift-a 2 +)]
(t/testing "It can lift a function to the vector applicative"
(t/is (= [1 2 3 4 5 6]
(app+ [0 2 4] [1 2]))))
(t/testing "It can lift a function to the Maybe applicative"
(t/is (= (maybe/just 6)
(app+ (maybe/just 2) (maybe/just 4))))
(t/is (= (maybe/nothing)
(app+ (maybe/just 1) (maybe/nothing)))))))
(t/deftest lift-m-tests
(let [monad+ (m/lift-m 2 +)]
(t/testing "It can lift a function to the vector monad"
(t/is (= [1 2 3 4 5 6]
(monad+ [0 2 4] [1 2]))))
(t/testing "It can lift a function to the Maybe monad"
(t/is (= (maybe/just 6)
(monad+ (maybe/just 2) (maybe/just 4))))
(t/is (= (maybe/nothing)
(monad+ (maybe/just 1) (maybe/nothing)))))))
(t/deftest fixed-arity-lift-m-tests
#?(:clj
(let [monad+ (m/lift-m add2)]
(t/testing "It can lift a function to the vector monad"
(t/is (= [1 2 3 4 5 6]
(monad+ [0 2 4] [1 2]))))))
(t/testing "It can lift a function to the Maybe monad"
(let [monad+ (m/lift-m 2 add2)]
(t/is (= (maybe/just 6)
(monad+ (maybe/just 2) (maybe/just 4))))
(t/is (= (maybe/nothing)
(monad+ (maybe/just 1) (maybe/nothing))))))
(t/testing "Currying and lifting can be combined"
(let [curry-monad+ (m/curry-lift-m 2 add2)]
(t/is (= (maybe/just 6)
((curry-monad+ (maybe/just 1)) (maybe/just 5)))))))
(t/deftest filter-tests
(t/testing "It can filter Maybe monadic values"
(let [bigger-than-4 (partial < 4)]
(t/is (= (maybe/just 6)
(m/filter bigger-than-4 (maybe/just 6))))
(t/is (= (maybe/nothing)
(m/filter bigger-than-4 (maybe/just 3))))))
(t/testing "It can filter vectors"
(t/is (= [1 3 5]
(m/filter odd? [1 2 3 4 5 6])))))
(t/deftest when-tests
(t/testing "It returns the monadic value unchanged when the condition is true"
(t/is (= (maybe/just 3)
(m/when true (maybe/just 3))))
(t/is (= (maybe/just 3)
(m/when maybe/context true (maybe/just 3)))))
(t/testing "It returns nil in the monadic context when the condition is false"
(ctx/with-context b/sequence-context
(t/is (= [nil]
(m/when false []))))
(t/is (= [nil]
(m/when b/sequence-context false []))))
(t/testing "it doesn't evaluate the mv when the conditions is false"
(t/is (= [nil]
(m/when b/sequence-context false (throw (ex-info "bang" {})))))))
(t/deftest unless-tests
(t/testing "It returns the monadic value unchanged when the condition is false"
(t/is (= (maybe/just 3)
(m/unless false (maybe/just 3))))
(t/is (= (maybe/just 3)
(m/unless maybe/context false (maybe/just 3)))))
(t/testing "It returns nil in the monadic context when the condition is true"
(ctx/with-context b/sequence-context
(t/is (= [nil]
(m/unless true []))))
(t/is (= [nil]
(m/unless b/sequence-context true []))))
(t/testing "it doesn't evaluate the mv when the condition is true"
(t/is (= [nil]
(m/unless b/sequence-context true (throw (ex-info "bang" {})))))))
(t/deftest curry-tests
#?(:clj
(t/testing "It can curry single and fixed arity functions automatically"
(let [cadd2 (m/curry add2)]
(t/is (= ((cadd2 1) 2)
3))
(t/is (= (cadd2)
cadd2))
(t/is (= (cadd2 1 2)
3)))))
(t/testing "It can curry anonymous functions when providing an arity"
(let [csum (m/curry 3 (fn [x y z] (+ x y z)))]
(t/is (= (((csum 1) 2) 3)
6))
(t/is (= ((csum 1 2) 3)
6))
(t/is (= (((csum) 1 2) 3)
6))
(t/is (= (csum 1 2 3)
6))))
(t/testing "It can curry variadic functions when providing an arity"
(let [csum (m/curry 3 +)]
(t/is (= (((csum 1) 2) 3)
6))
(t/is (= ((csum 1 2) 3)
6))
(t/is (= (((csum) 1 2) 3)
6))
(t/is (= (csum 1 2 3)
6)))))
(t/deftest foldm-tests
(letfn [(m-div [x y]
(if (zero? y)
(maybe/nothing)
(maybe/just (/ x y))))]
(t/testing "It can fold a non-empty collection without an explicit context"
(t/is (= (maybe/just #?(:clj 1/6 :cljs (/ 1 6)))
(m/foldm m-div 1 [1 2 3])))
(t/is (= (maybe/nothing)
(m/foldm m-div 1 [1 0 3]))))
(t/testing "It cannot fold an empty collection without an explicit context"
(t/is (thrown? #?(:clj IllegalArgumentException, :cljs js/Error)
(with-redefs [cats.context/get-current (constantly nil)]
(m/foldm m-div 1 [])))))
(t/testing "It can fold a non-empty collection, given an explicit context"
(t/is (= (maybe/just #?(:clj 1/6, :cljs (/ 1 6)))
(m/foldm maybe/context m-div 1 [1 2 3])))
(t/is (= (maybe/nothing)
(m/foldm maybe/context m-div 1 [1 0 3]))))
(t/testing "It can fold an empty collection, given an explicit context"
(t/is (= (maybe/just 1)
(m/foldm maybe/context m-div 1 [])))
(t/is (= (maybe/just 1)
(ctx/with-context maybe/context
(m/foldm m-div 1 [])))))))
(t/deftest do-let-tests
(t/testing "Support regular let bindings inside do-let"
(t/is (= (maybe/just 2)
(m/do-let [i (maybe/just 1)
:let [i (inc i)]]
(m/return i)))))
(t/testing "Support :when guards inside its bindings"
(t/is (= (maybe/nothing)
(m/do-let [i (maybe/just 2)
:when (> i 2)]
(m/return i))))
(t/is (= [3 4 5]
(m/do-let [i [1 2 3 4 5]
:when (> i 2)]
(m/return i)))))
(t/testing "Support one single form"
(t/is (= (maybe/just 2)
(m/do-let (maybe/just 2)))))
(t/testing "Support multiple single form"
(t/is (= (maybe/just 3)
(m/do-let (maybe/just 2)
(maybe/just 3)))))
(t/testing "Bound variables are always in scope"
(t/is (= (maybe/just 6)
(m/do-let [x (maybe/just 2)]
(maybe/just x)
[y (maybe/just (+ 2 x))]
(maybe/just (+ 2 y)))))))
(t/deftest for-tests
(t/testing "m/for works like (m/sequence (clojure.core/for))"
(t/is (= (maybe/just [2 3])
(m/sequence [(maybe/just 2) (maybe/just 3)])
(m/sequence (for [x [2 3]] (maybe/just x)))
(m/for [x [2 3]] (maybe/just x))))))
|
|
d60d032b919fe90a7850b67ec3f9f474ad9cd03a19ed394ac5ca91a7b1bc62a1 | jackfirth/lens | test-lens.rkt | #lang racket/base
(require racket/contract
rackunit
fancy-app
lens/private/base/base
"../base/view-set.rkt")
(provide
(contract-out
[check-lens-view (-> lens? any/c any/c void?)]
[check-lens-set (-> lens? any/c any/c any/c void?)]
[check-lens-view-set (-> lens? any/c void?)]
[check-lens-set-view (-> lens? any/c any/c void?)]
[check-lens-set-set (-> lens? any/c any/c any/c void?)]
[test-lens-laws (-> lens? any/c any/c any/c void?)]))
(define-check (check-lens-view lens target expected-view)
(check-equal? (lens-view lens target) expected-view))
(define-check (check-lens-set lens target new-view expected-new-target)
(check-equal? (lens-set lens target new-view) expected-new-target))
(define-check (check-lens-view-set lens target)
(check-lens-set lens target (lens-view lens target)
target
"setting target's view to its own view not equal? to itself"))
(define-check (check-lens-set-view lens target new-view)
(check-lens-view lens (lens-set lens target new-view)
new-view
"view of target after setting it's view not equal? to the set view"))
(define-check (check-lens-set-set lens target new-view1 new-view2)
(let* ([target/1 (lens-set lens target new-view1)]
[target/12 (lens-set lens target/1 new-view2)]
[target/2 (lens-set lens target new-view2)])
(check-equal? target/12 target/2
"target after setting view twice not equal? to setting to second view")))
(define (test-lens-laws lens test-target test-view1 test-view2)
(check-lens-view-set lens test-target)
(check-lens-set-view lens test-target test-view1)
(check-lens-set-view lens test-target test-view2)
(check-lens-set-set lens test-target test-view1 test-view2))
| null | https://raw.githubusercontent.com/jackfirth/lens/733db7744921409b69ddc78ae5b23ffaa6b91e37/lens-common/lens/private/test-util/test-lens.rkt | racket | #lang racket/base
(require racket/contract
rackunit
fancy-app
lens/private/base/base
"../base/view-set.rkt")
(provide
(contract-out
[check-lens-view (-> lens? any/c any/c void?)]
[check-lens-set (-> lens? any/c any/c any/c void?)]
[check-lens-view-set (-> lens? any/c void?)]
[check-lens-set-view (-> lens? any/c any/c void?)]
[check-lens-set-set (-> lens? any/c any/c any/c void?)]
[test-lens-laws (-> lens? any/c any/c any/c void?)]))
(define-check (check-lens-view lens target expected-view)
(check-equal? (lens-view lens target) expected-view))
(define-check (check-lens-set lens target new-view expected-new-target)
(check-equal? (lens-set lens target new-view) expected-new-target))
(define-check (check-lens-view-set lens target)
(check-lens-set lens target (lens-view lens target)
target
"setting target's view to its own view not equal? to itself"))
(define-check (check-lens-set-view lens target new-view)
(check-lens-view lens (lens-set lens target new-view)
new-view
"view of target after setting it's view not equal? to the set view"))
(define-check (check-lens-set-set lens target new-view1 new-view2)
(let* ([target/1 (lens-set lens target new-view1)]
[target/12 (lens-set lens target/1 new-view2)]
[target/2 (lens-set lens target new-view2)])
(check-equal? target/12 target/2
"target after setting view twice not equal? to setting to second view")))
(define (test-lens-laws lens test-target test-view1 test-view2)
(check-lens-view-set lens test-target)
(check-lens-set-view lens test-target test-view1)
(check-lens-set-view lens test-target test-view2)
(check-lens-set-set lens test-target test-view1 test-view2))
|
|
85ad09b0729cb0a4174b82f0a50b9e765a0d4a929551bb4d9d0c3389b3d1fa51 | mswift42/themecreator | components.cljs | (ns app.components
(:require [reagent.core :as r]
[app.db :as db]
[app.colors :as colors]
[app.previews :as prev]))
(def active-preview
(r/atom
prev/preview-javascript))
(defn toggle-preview
[lang]
(reset! active-preview lang))
(defn select-component
[compid title linklist]
[:div.btn-group.themedrop {:id compid}
[:button.btn.btn-default.dropdown-toggle
{:type "button" :data-toggle "dropdown"}
(str title " ")
[:span.caret]
[:span.sr-only]]
[:ul.dropdown-menu {:aria-labelledby compid}
(for [[linkhandler linktitle] linklist]
^{:key linkhandler}
[:li [:a {:href "#" :on-click linkhandler} linktitle]])]])
(defn theme-select
[]
[select-component "themedrop" "Theme Samples"
[[#(db/switch-theme db/black) "black"]
[#(db/switch-theme db/white) "white"]
[#(db/switch-theme db/warm-night) "warm-night"]
[#(db/switch-theme db/white-sand) "white-sand"]
[#(db/switch-theme db/munich) "munich"]
[#(db/switch-theme db/greymatters) "greymatters"]
[#(db/switch-theme db/reykjavik) "reykjavik"]
[#(db/switch-theme db/oldlace) "oldlace"]
[#(db/switch-theme db/soft-charcoal) "soft-charcoal"]
[#(db/switch-theme db/bergen) "bergen"]
[#(db/switch-theme db/madrid) "madrid"]
[#(db/switch-theme db/soft-morning) "soft-morning"]
[#(db/switch-theme db/magonyx) "magonyx"]
[#(db/switch-theme db/light-kiss) "light-kiss"]
[#(db/switch-theme db/foggy-night) "foggy-night"]
[#(db/switch-theme db/silkworm) "silkworm"]
[#(db/switch-theme db/metalheart) "metalheart"]
[#(db/switch-theme db/breezy-fall) "breezy-fall"]
[#(db/switch-theme db/thursday) "thursday"]]])
(defn language-select
[]
[select-component "langdrop" "Languages"
[[#(toggle-preview prev/preview-javascript) "Javascript"]
[#(toggle-preview prev/preview-ruby) "Ruby"]
[#(toggle-preview prev/preview-typescript) "Typescript"]
[#(toggle-preview prev/preview-python) "Python"]
[#(toggle-preview prev/preview-c) "C"]]])
(defn button-component
"button-component returns the markup for a bootstrap default button"
[text handler]
[:button.btn.btn-default
{:type "button" :on-click handler}
text])
(defn inc-contrast-component
[]
[:button.btn.btn-default
{:on-click #(colors/inc-contrast)} [:span.conticons [:i.fa.fa-adjust] [:i.fa.fa-plus]]])
(defn red-contrast-component
[]
[:button.btn.btn-default
{:type "button" :on-click #(colors/red-contrast)} [:span.conticons [:i.fa.fa-adjust] [:i.fa.fa-minus]]])
(defn adjustbg-component
[]
[:div.adbggroup
[:input#adbg.adbgcheckbox
{:type "checkbox" :value @db/adjustbg :on-change
#(db/toggle-adjust)}]
[:label {:for "adbg"} "Adjust Bg"]])
(defn random-button-component
[text handler]
[:button.btn.btn-default
{:type "button" :on-click handler}
[:span.randicons [:i.fa.fa-random] text]])
(defn random-colors-component
[]
[:div.randbuttons.row
[random-button-component "Warm"
#(colors/set-random-palette (colors/warm-palette))]
[random-button-component "Soft"
#(colors/set-random-palette (colors/soft-palette))]
[random-button-component "Pop"
#(colors/set-random-palette (colors/pop-palette))]
[random-button-component "Muted"
#(colors/set-random-palette (colors/muted-palette))]])
(defn custom-color-input-component
[value title]
[:span.custominputlabel (str title)
[:input.custominput {:id (str (name value) "id") :type "number"
:step "0.1" :min "0" :max "100"
:default-value (.toFixed (value @db/custom-palette-db) 2)}]])
(defn custom-colors-component
[]
[:div.randbuttons.row.custombutton
[random-button-component "Custom"
#(do
(let [sat (.-value (.getElementById js/document "saturationid"))
light (.-value (.getElementById js/document "lightnessid"))]
(reset! db/custom-palette-db {:saturation (js/parseFloat sat)
:lightness (js/parseFloat light)}))
(colors/set-random-palette (colors/custom-palette
(:lightness @db/custom-palette-db)
(:saturation @db/custom-palette-db))))]
[custom-color-input-component :lightness "L: "]
[custom-color-input-component :saturation "S: "]])
(defn color-component [facename]
[:div.colorcomponent
[:div.row.themeface
[:label.colortitle.col-xs-4 (name facename)]
[:input.col-xs-3.colorinput.col-xs-offset-1
{:type "color" :value (facename @db/app-db)
:on-change
#(swap! db/app-db assoc facename (->
% .-target .-value))}]
[:input.col-xs-3.textinput
{:type "text" :value (facename @db/app-db)
:on-change
#(swap! db/app-db assoc facename (->
% .-target .-value))}]]])
(defn name-component []
[:div.themename
[:div.row
[:label.colortitle.col-xs-5 (str "Themename")]
[:input.col-xs-4.textinput.col-xs-offset-1.nameinput
{:type "text" :value (:themename @db/app-db)
:on-change #(swap! db/app-db assoc :themename (-> % .-target .-value))}]]])
(defn author-component []
[:div.themename
[:div.row
[:label.colortitle.col-xs-5 (str "Author")]
[:input.col-xs-4.textinput.col-xs-offset-1.nameinput
{:type "text" :value (:themeauthor @db/app-db)
:on-change #(swap! db/app-db assoc :themeauthor (-> % .-target .-value))}]]])
| null | https://raw.githubusercontent.com/mswift42/themecreator/b2b5d2e9b24572122aa43688d4376b62d6dda638/app.core/src/app/components.cljs | clojure | (ns app.components
(:require [reagent.core :as r]
[app.db :as db]
[app.colors :as colors]
[app.previews :as prev]))
(def active-preview
(r/atom
prev/preview-javascript))
(defn toggle-preview
[lang]
(reset! active-preview lang))
(defn select-component
[compid title linklist]
[:div.btn-group.themedrop {:id compid}
[:button.btn.btn-default.dropdown-toggle
{:type "button" :data-toggle "dropdown"}
(str title " ")
[:span.caret]
[:span.sr-only]]
[:ul.dropdown-menu {:aria-labelledby compid}
(for [[linkhandler linktitle] linklist]
^{:key linkhandler}
[:li [:a {:href "#" :on-click linkhandler} linktitle]])]])
(defn theme-select
[]
[select-component "themedrop" "Theme Samples"
[[#(db/switch-theme db/black) "black"]
[#(db/switch-theme db/white) "white"]
[#(db/switch-theme db/warm-night) "warm-night"]
[#(db/switch-theme db/white-sand) "white-sand"]
[#(db/switch-theme db/munich) "munich"]
[#(db/switch-theme db/greymatters) "greymatters"]
[#(db/switch-theme db/reykjavik) "reykjavik"]
[#(db/switch-theme db/oldlace) "oldlace"]
[#(db/switch-theme db/soft-charcoal) "soft-charcoal"]
[#(db/switch-theme db/bergen) "bergen"]
[#(db/switch-theme db/madrid) "madrid"]
[#(db/switch-theme db/soft-morning) "soft-morning"]
[#(db/switch-theme db/magonyx) "magonyx"]
[#(db/switch-theme db/light-kiss) "light-kiss"]
[#(db/switch-theme db/foggy-night) "foggy-night"]
[#(db/switch-theme db/silkworm) "silkworm"]
[#(db/switch-theme db/metalheart) "metalheart"]
[#(db/switch-theme db/breezy-fall) "breezy-fall"]
[#(db/switch-theme db/thursday) "thursday"]]])
(defn language-select
[]
[select-component "langdrop" "Languages"
[[#(toggle-preview prev/preview-javascript) "Javascript"]
[#(toggle-preview prev/preview-ruby) "Ruby"]
[#(toggle-preview prev/preview-typescript) "Typescript"]
[#(toggle-preview prev/preview-python) "Python"]
[#(toggle-preview prev/preview-c) "C"]]])
(defn button-component
"button-component returns the markup for a bootstrap default button"
[text handler]
[:button.btn.btn-default
{:type "button" :on-click handler}
text])
(defn inc-contrast-component
[]
[:button.btn.btn-default
{:on-click #(colors/inc-contrast)} [:span.conticons [:i.fa.fa-adjust] [:i.fa.fa-plus]]])
(defn red-contrast-component
[]
[:button.btn.btn-default
{:type "button" :on-click #(colors/red-contrast)} [:span.conticons [:i.fa.fa-adjust] [:i.fa.fa-minus]]])
(defn adjustbg-component
[]
[:div.adbggroup
[:input#adbg.adbgcheckbox
{:type "checkbox" :value @db/adjustbg :on-change
#(db/toggle-adjust)}]
[:label {:for "adbg"} "Adjust Bg"]])
(defn random-button-component
[text handler]
[:button.btn.btn-default
{:type "button" :on-click handler}
[:span.randicons [:i.fa.fa-random] text]])
(defn random-colors-component
[]
[:div.randbuttons.row
[random-button-component "Warm"
#(colors/set-random-palette (colors/warm-palette))]
[random-button-component "Soft"
#(colors/set-random-palette (colors/soft-palette))]
[random-button-component "Pop"
#(colors/set-random-palette (colors/pop-palette))]
[random-button-component "Muted"
#(colors/set-random-palette (colors/muted-palette))]])
(defn custom-color-input-component
[value title]
[:span.custominputlabel (str title)
[:input.custominput {:id (str (name value) "id") :type "number"
:step "0.1" :min "0" :max "100"
:default-value (.toFixed (value @db/custom-palette-db) 2)}]])
(defn custom-colors-component
[]
[:div.randbuttons.row.custombutton
[random-button-component "Custom"
#(do
(let [sat (.-value (.getElementById js/document "saturationid"))
light (.-value (.getElementById js/document "lightnessid"))]
(reset! db/custom-palette-db {:saturation (js/parseFloat sat)
:lightness (js/parseFloat light)}))
(colors/set-random-palette (colors/custom-palette
(:lightness @db/custom-palette-db)
(:saturation @db/custom-palette-db))))]
[custom-color-input-component :lightness "L: "]
[custom-color-input-component :saturation "S: "]])
(defn color-component [facename]
[:div.colorcomponent
[:div.row.themeface
[:label.colortitle.col-xs-4 (name facename)]
[:input.col-xs-3.colorinput.col-xs-offset-1
{:type "color" :value (facename @db/app-db)
:on-change
#(swap! db/app-db assoc facename (->
% .-target .-value))}]
[:input.col-xs-3.textinput
{:type "text" :value (facename @db/app-db)
:on-change
#(swap! db/app-db assoc facename (->
% .-target .-value))}]]])
(defn name-component []
[:div.themename
[:div.row
[:label.colortitle.col-xs-5 (str "Themename")]
[:input.col-xs-4.textinput.col-xs-offset-1.nameinput
{:type "text" :value (:themename @db/app-db)
:on-change #(swap! db/app-db assoc :themename (-> % .-target .-value))}]]])
(defn author-component []
[:div.themename
[:div.row
[:label.colortitle.col-xs-5 (str "Author")]
[:input.col-xs-4.textinput.col-xs-offset-1.nameinput
{:type "text" :value (:themeauthor @db/app-db)
:on-change #(swap! db/app-db assoc :themeauthor (-> % .-target .-value))}]]])
|
|
36cf68f1f2ddc464583ffc7c0b6af9a3d8044852b09d838c1895cfbdc9f6fc84 | rizo/snowflake-os | sys.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ I d : sys.mlp , v 1.1.2.1 2007 - 03 - 16 13:28:57 frisch Exp $
WARNING : sys.ml is generated from sys.mlp . DO NOT EDIT sys.ml or
your changes will be lost .
your changes will be lost.
*)
(* System interface *)
(*external get_config: unit -> string * int = "caml_sys_get_config"
external get_argv: unit -> string * string array = "caml_sys_get_argv"*)
let (executable_name, argv) = "snowflake", [| |] (*get_argv()*)
get_config ( )
let max_array_length = (1 lsl (word_size - 10)) - 1;;
let max_string_length = word_size / 8 * max_array_length - 1;;
external file_exists : string - > bool = " caml_sys_file_exists "
external is_directory : string - > bool = " caml_sys_is_directory "
external remove : string - > unit = " caml_sys_remove "
external rename : string - > string - > unit = " caml_sys_rename "
external getenv : string - > string = " caml_sys_getenv "
external command : string - > int = " caml_sys_system_command "
external time : unit - > float = " caml_sys_time "
external chdir : string - > unit = " caml_sys_chdir "
external getcwd : unit - > string = " caml_sys_getcwd "
external readdir : string - > string array = " caml_sys_read_directory "
external is_directory : string -> bool = "caml_sys_is_directory"
external remove: string -> unit = "caml_sys_remove"
external rename : string -> string -> unit = "caml_sys_rename"
external getenv: string -> string = "caml_sys_getenv"
external command: string -> int = "caml_sys_system_command"
external time: unit -> float = "caml_sys_time"
external chdir: string -> unit = "caml_sys_chdir"
external getcwd: unit -> string = "caml_sys_getcwd"
external readdir : string -> string array = "caml_sys_read_directory"*)
let interactive = ref false
type signal_behavior =
Signal_default
| Signal_ignore
| Signal_handle of (int -> unit)
external signal : int -> signal_behavior -> signal_behavior
= "caml_install_signal_handler"
let set_signal sig_num sig_beh = ignore(signal sig_num sig_beh)
let sigabrt = -1
let sigalrm = -2
let sigfpe = -3
let sighup = -4
let sigill = -5
let sigint = -6
let sigkill = -7
let sigpipe = -8
let sigquit = -9
let sigsegv = -10
let sigterm = -11
let sigusr1 = -12
let sigusr2 = -13
let sigchld = -14
let sigcont = -15
let sigstop = -16
let sigtstp = -17
let sigttin = -18
let sigttou = -19
let sigvtalrm = 20
let sigprof = -21
exception Break
let catch_break on =
if on then
set_signal sigint (Signal_handle(fun _ -> raise Break))
else
set_signal sigint Signal_default
(* The version string is found in file ../VERSION *)
let ocaml_version = "ocaml-3.12.0+dev-snowflake";;
| null | https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/libraries/stdlib/sys.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
System interface
external get_config: unit -> string * int = "caml_sys_get_config"
external get_argv: unit -> string * string array = "caml_sys_get_argv"
get_argv()
The version string is found in file ../VERSION | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ I d : sys.mlp , v 1.1.2.1 2007 - 03 - 16 13:28:57 frisch Exp $
WARNING : sys.ml is generated from sys.mlp . DO NOT EDIT sys.ml or
your changes will be lost .
your changes will be lost.
*)
get_config ( )
let max_array_length = (1 lsl (word_size - 10)) - 1;;
let max_string_length = word_size / 8 * max_array_length - 1;;
external file_exists : string - > bool = " caml_sys_file_exists "
external is_directory : string - > bool = " caml_sys_is_directory "
external remove : string - > unit = " caml_sys_remove "
external rename : string - > string - > unit = " caml_sys_rename "
external getenv : string - > string = " caml_sys_getenv "
external command : string - > int = " caml_sys_system_command "
external time : unit - > float = " caml_sys_time "
external chdir : string - > unit = " caml_sys_chdir "
external getcwd : unit - > string = " caml_sys_getcwd "
external readdir : string - > string array = " caml_sys_read_directory "
external is_directory : string -> bool = "caml_sys_is_directory"
external remove: string -> unit = "caml_sys_remove"
external rename : string -> string -> unit = "caml_sys_rename"
external getenv: string -> string = "caml_sys_getenv"
external command: string -> int = "caml_sys_system_command"
external time: unit -> float = "caml_sys_time"
external chdir: string -> unit = "caml_sys_chdir"
external getcwd: unit -> string = "caml_sys_getcwd"
external readdir : string -> string array = "caml_sys_read_directory"*)
let interactive = ref false
type signal_behavior =
Signal_default
| Signal_ignore
| Signal_handle of (int -> unit)
external signal : int -> signal_behavior -> signal_behavior
= "caml_install_signal_handler"
let set_signal sig_num sig_beh = ignore(signal sig_num sig_beh)
let sigabrt = -1
let sigalrm = -2
let sigfpe = -3
let sighup = -4
let sigill = -5
let sigint = -6
let sigkill = -7
let sigpipe = -8
let sigquit = -9
let sigsegv = -10
let sigterm = -11
let sigusr1 = -12
let sigusr2 = -13
let sigchld = -14
let sigcont = -15
let sigstop = -16
let sigtstp = -17
let sigttin = -18
let sigttou = -19
let sigvtalrm = 20
let sigprof = -21
exception Break
let catch_break on =
if on then
set_signal sigint (Signal_handle(fun _ -> raise Break))
else
set_signal sigint Signal_default
let ocaml_version = "ocaml-3.12.0+dev-snowflake";;
|
b0c3bf84b52dced6165d3b07e0944ee86d826ca77b18727a54d90977f9a056a7 | remyoudompheng/hs-language-go | Operators.hs | module Language.Go.Parser.Operators (
goOpExpr,
goUnaryOp
) where
import Text.Parsec.Expr
import Text.Parsec.Prim (try, token)
import Text.Parsec.Combinator (anyToken)
import Language.Go.Parser.Tokens (GoParser,GoToken(..),GoTokenPos(..))
import Language.Go.Syntax.AST
-- | @goOpExpr p@ returns a parser for expressions with
binary operators whose terms are parsed by @p@.
goOpExpr :: GoParser GoExpr -> GoParser GoExpr
goOpExpr p = buildExpressionParser goOpTable p
Unary operators can not be stacked when using
-- buildExpressionParser so we parse them separately
-- in goUnaryExpr.
goOpTable =
[ [ Infix (goBinaryOp mul_op) AssocLeft ]
, [ Infix (goBinaryOp add_op) AssocLeft ]
, [ Infix (goBinaryOp rel_op) AssocLeft ]
, [ Infix (goBinaryOp and_op) AssocLeft ]
, [ Infix (goBinaryOp or_op) AssocLeft ]
]
-- | @goUnaryOp@ parse a unary (prefix) operator.
--
goUnaryOp :: GoParser GoOp
goUnaryOp = do
-- unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-"
GoTokenPos _ tok <- anyToken
case tok of
GoTokPlus -> return $ GoOp "+"
GoTokMinus -> return $ GoOp "-"
GoTokExclaim -> return $ GoOp "!"
GoTokXOR -> return $ GoOp "^"
GoTokAsterisk-> return $ GoOp "*"
GoTokAND -> return $ GoOp "&"
GoTokArrow -> return $ GoOp "<-"
_ -> fail "not a unary operator"
goBinaryOp :: (GoToken -> Maybe String) -> GoParser (GoExpr -> GoExpr -> GoExpr)
goBinaryOp want = try $ do
-- binary_op = "||" | "&&" | rel_op | add_op | mul_op .
-- rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" .
-- add_op = "+" | "-" | "|" | "^" .
-- mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .
let s (GoTokenPos _ t) = show t
pos (GoTokenPos pos _) = pos
match (GoTokenPos _ t) = want t
op <- token s pos match
return (Go2Op $ GoOp op)
mul_op :: GoToken -> Maybe String
mul_op op = case op of
GoTokAsterisk -> Just "*"
GoTokSolidus -> Just "/"
GoTokPercent -> Just "%"
GoTokSHL -> Just "<<"
GoTokSHR -> Just ">>"
GoTokAND -> Just "&"
GoTokBUT -> Just "&^"
_ -> Nothing
add_op :: GoToken -> Maybe String
add_op op = case op of
GoTokPlus -> Just "+"
GoTokMinus -> Just "-"
GoTokIOR -> Just "|"
GoTokXOR -> Just "^"
_ -> Nothing
rel_op :: GoToken -> Maybe String
rel_op op = case op of
GoTokEQ -> Just "=="
GoTokNE -> Just "!="
GoTokLT -> Just "<"
GoTokLE -> Just "<="
GoTokGT -> Just ">"
GoTokGE -> Just ">="
_ -> Nothing
or_op op = if op == GoTokLOR then Just "||" else Nothing
and_op op = if op == GoTokLAND then Just "&&" else Nothing
| null | https://raw.githubusercontent.com/remyoudompheng/hs-language-go/5440485f6404356892eab4832cff4f1378c11670/Language/Go/Parser/Operators.hs | haskell | | @goOpExpr p@ returns a parser for expressions with
buildExpressionParser so we parse them separately
in goUnaryExpr.
| @goUnaryOp@ parse a unary (prefix) operator.
unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-"
binary_op = "||" | "&&" | rel_op | add_op | mul_op .
rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" .
add_op = "+" | "-" | "|" | "^" .
mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" . | module Language.Go.Parser.Operators (
goOpExpr,
goUnaryOp
) where
import Text.Parsec.Expr
import Text.Parsec.Prim (try, token)
import Text.Parsec.Combinator (anyToken)
import Language.Go.Parser.Tokens (GoParser,GoToken(..),GoTokenPos(..))
import Language.Go.Syntax.AST
binary operators whose terms are parsed by @p@.
goOpExpr :: GoParser GoExpr -> GoParser GoExpr
goOpExpr p = buildExpressionParser goOpTable p
Unary operators can not be stacked when using
goOpTable =
[ [ Infix (goBinaryOp mul_op) AssocLeft ]
, [ Infix (goBinaryOp add_op) AssocLeft ]
, [ Infix (goBinaryOp rel_op) AssocLeft ]
, [ Infix (goBinaryOp and_op) AssocLeft ]
, [ Infix (goBinaryOp or_op) AssocLeft ]
]
goUnaryOp :: GoParser GoOp
goUnaryOp = do
GoTokenPos _ tok <- anyToken
case tok of
GoTokPlus -> return $ GoOp "+"
GoTokMinus -> return $ GoOp "-"
GoTokExclaim -> return $ GoOp "!"
GoTokXOR -> return $ GoOp "^"
GoTokAsterisk-> return $ GoOp "*"
GoTokAND -> return $ GoOp "&"
GoTokArrow -> return $ GoOp "<-"
_ -> fail "not a unary operator"
goBinaryOp :: (GoToken -> Maybe String) -> GoParser (GoExpr -> GoExpr -> GoExpr)
goBinaryOp want = try $ do
let s (GoTokenPos _ t) = show t
pos (GoTokenPos pos _) = pos
match (GoTokenPos _ t) = want t
op <- token s pos match
return (Go2Op $ GoOp op)
mul_op :: GoToken -> Maybe String
mul_op op = case op of
GoTokAsterisk -> Just "*"
GoTokSolidus -> Just "/"
GoTokPercent -> Just "%"
GoTokSHL -> Just "<<"
GoTokSHR -> Just ">>"
GoTokAND -> Just "&"
GoTokBUT -> Just "&^"
_ -> Nothing
add_op :: GoToken -> Maybe String
add_op op = case op of
GoTokPlus -> Just "+"
GoTokMinus -> Just "-"
GoTokIOR -> Just "|"
GoTokXOR -> Just "^"
_ -> Nothing
rel_op :: GoToken -> Maybe String
rel_op op = case op of
GoTokEQ -> Just "=="
GoTokNE -> Just "!="
GoTokLT -> Just "<"
GoTokLE -> Just "<="
GoTokGT -> Just ">"
GoTokGE -> Just ">="
_ -> Nothing
or_op op = if op == GoTokLOR then Just "||" else Nothing
and_op op = if op == GoTokLAND then Just "&&" else Nothing
|
21f5cd4ae88560e2458790d7644b2d1c80e29f7b1e9c930c8e443223f2cccba5 | blindglobe/clocc | typedvar.lisp | ;;; Typed variable syntax for Common Lisp
2004 - 08 - 05
;;; This file is put in the public domain by its authors.
;;; A typed variable is a variable whose value at any time is guaranteed
;;; by the programmer to belong to a given type. It is assumed that the
;;; type's semantics doesn't change during the dynamic extent of the variable.
;;;
Common Lisp supports typed variables in various situations , but the
;;; syntax to declare a typed variable is different each time:
- In LAMBDA , LET , LET * , MULTIPLE - VALUE - BIND :
;;; (lambda (x ...) (declare (integer x)) ...)
;;; (lambda (x ...) (declare (type integer x)) ...)
;;; (let ((x ...)) (declare (integer x)) ...)
;;; (let ((x ...)) (declare (type integer x)) ...)
- In DEFMETHOD , :
;;; (defmethod foo ((x integer) ...) ...)
;;; - In LOOP:
;;; (loop for x integer across v ...)
;;; (loop for x of-type integer across v ...)
;;; - Type declarations in function returns:
;;; (declaim (ftype (function (t) integer) foo))
;;; (defun foo (x) ...)
;;;
;;; This file supports typed variables and typed function returns through
;;; a simple common syntax: [variable type] and [type].
;;; Examples:
- In LAMBDA , LET , LET * , MULTIPLE - VALUE - BIND :
;;; (lambda ([x integer] ...) ...)
;;; (let (([x integer] ...) ...)
- In DEFMETHOD , :
( defmethod foo ( [ x integer ] ... ) ... )
;;; - In LOOP:
;;; (loop for [x integer] across v ...)
;;; - Type declarations in function returns:
;;; (defun foo (x) [integer] ...)
;;;
;;; The variable name always comes before the type, because (assuming decent
;;; coding style) it carries more information than the type.
;;; Example:
;;; (defun scale-long-float (x exp)
;;; (declare (long-float x) (fixnum exp))
;;; ...)
;;; -> (defun scale-long-float ([x long-float] [exp fixnum])
;;; ...)
;;;
Note : Specialized lambda lists in DEFMETHOD , can contain an
;;; an evaluated form, whereas type specifiers cannot. Therefore
;;; (defmethod foo ([x (eql a)]) ...)
;;; is equivalent to
( defmethod foo ( ( x ( eql ' a ) ) ) ... ) ,
;;; and there is no typed-variable syntax for
;;; (defmethod foo ((x (eql a))) ...).
;;;
Note : Another difference with specialized lambda lists in DEFMETHOD is
;;; that the typed variable syntax not only defines a specializer, but also
;;; a declaration for the entire scope of variable. I.e.
;;; (defmethod foo ([x integer]) ...)
;;; is equivalent to
;;; (defmethod foo ((x integer)) (declare (type integer x)) ...)
;;; It would be bad style anyway to assign a non-integer value to x inside
;;; the method.
;;;
;;; Note: When a return type declaration and documentation string are both
specified together , the type declaration should come first :
;;; (defun foo (x) [integer] "comment" ...)
;; ============================ Package Setup ============================
(defpackage "TYPEDVAR-COMMON-LISP"
(:use "COMMON-LISP")
(:export . #1=("DEFCONSTANT"
"DEFGENERIC"
"DEFMETHOD"
"DEFPARAMETER"
"DEFUN"
"DEFVAR"
;"DESTRUCTURING-BIND"
"DO"
"DO*"
"DO-ALL-SYMBOLS"
"DO-EXTERNAL-SYMBOLS"
"DO-SYMBOLS"
#+CLISP "DOHASH"
"DOLIST"
#+CLISP "DOSEQ"
"DOTIMES"
"FLET"
"FUNCTION"
;"HANDLER-CASE"
"LABELS"
"LAMBDA"
"LET"
"LET*"
;"LOOP"
"MULTIPLE-VALUE-BIND"
"PROG"
"PROG*"
;"RESTART-CASE"
"WITH-ACCESSORS"
"WITH-INPUT-FROM-STRING"
"WITH-OPEN-FILE"
"WITH-OPEN-STREAM"
"WITH-OUTPUT-TO-STRING"
"WITH-SLOTS"))
(:shadow . #1#))
(in-package "TYPEDVAR-COMMON-LISP")
(cl:do-external-symbols (s "COMMON-LISP")
(unless (member (nth-value 1 (find-symbol (symbol-name s))) '(:internal :external))
(import (list s))
(export (list s))))
;; ============================ Basic definitions ============================
;; In-memory representation of syntax [type]: `(type-decl ,type).
(defmacro type-decl (type)
(error "misplaced type declaration: [~S]" type))
(cl:defun type-decl-p (form)
(and (consp form) (eq (car form) 'type-decl)
(consp (cdr form))
(null (cddr form))))
(cl:defun type-decl-type (x) (second x))
;; In-memory representation of syntax [var type]: `(typed-var ,var ,type).
(defmacro typed-var (var type)
(error "misplaced typed variable declaration: [~S ~S]" var type))
(cl:defun typed-var-p (form)
(and (consp form) (eq (car form) 'typed-var)
(consp (cdr form))
(consp (cddr form))
(null (cdddr form))))
(cl:defun typed-var-variable (x) (second x))
(cl:defun typed-var-type (x) (third x))
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(set-macro-character #\[
#'(cl:lambda (stream char)
(declare (ignore char))
(cl:let ((contents (read-delimited-list #\] stream t)))
(when (null contents)
(error "invalid syntax: []"))
(case (length contents)
(1 `(type-decl ,(first contents)))
(2 (unless (symbolp (first contents))
(error "invalid syntax, variable should be a symbol: [~S ~S]"
(first contents) (second contents)))
`(typed-var ,(first contents) ,(second contents)))))))
(set-syntax-from-char #\] #\))
;; =================== Subroutines for the extended macros ===================
(cl:defun variable-to-keyword (variable)
(if (symbolp variable)
(intern (symbol-name variable) (find-package "KEYWORD"))
nil))
(cl:defun analyze-typed-lambdalist (lambdalist)
(cl:let ((pure-lambdalist '())
(typelist '())
(declspecs '())
(seen-&key nil)
(seen-&aux nil))
(cl:dolist (item lambdalist)
(if (typed-var-p item)
(progn
(push (typed-var-variable item) pure-lambdalist)
(push `(type ,(typed-var-type item) ,(typed-var-variable item)) declspecs)
(unless seen-&aux
(push (if seen-&key
(list (variable-to-keyword (typed-var-variable item)) (typed-var-type item))
(typed-var-type item))
typelist)))
(if (atom item)
(progn
(push item pure-lambdalist)
(if (member item lambda-list-keywords)
(progn
(when (eq item '&key)
(setq seen-&key t))
(when (eq item '&aux)
(setq seen-&aux t))
(when (member item '(&optional &rest &key))
(push item typelist)))
(unless seen-&aux
(push (if seen-&key
(list (variable-to-keyword item) 't)
't)
typelist))))
(cl:multiple-value-bind (var1 type1 keyword)
(if (typed-var-p (first item))
(progn
(push `(type ,(typed-var-type (first item)) ,(typed-var-variable (first item))) declspecs)
(values (typed-var-variable (first item))
(typed-var-type (first item))
(if (and seen-&key (not seen-&aux))
(variable-to-keyword (typed-var-variable (first item)))
nil)))
(if (atom (first item))
(values (first item)
't
(if (and seen-&key (not seen-&aux))
(variable-to-keyword (first item))
nil))
(if (and (consp (cdr (first item)))
(null (cddr (first item))))
(if (typed-var-p (second (first item)))
(progn
(push `(type ,(typed-var-type (second (first item))) ,(typed-var-variable (second (first item)))) declspecs)
(values (list (first (first item))
(typed-var-variable (second (first item))))
(typed-var-type (second (first item)))
(first (first item))))
(values (first item)
't
(first (first item))))
(values (first item)
't
nil))))
(unless seen-&aux
(push (if seen-&key (list keyword type1) type1) typelist))
(push (cons var1
(if (and (consp (cdr item)) (consp (cddr item)))
(cl:let ((var3
(if (typed-var-p (third item))
(progn
(push `(type ,(typed-var-type (third item)) ,(typed-var-variable (third item))) declspecs)
(typed-var-variable (third item)))
(third item))))
(list* (second item) var3 (cdddr item)))
(cdr item)))
pure-lambdalist)))))
(values (nreverse pure-lambdalist)
(nreverse typelist)
(nreverse declspecs))))
(cl:defun analyze-typed-lambdabody (lambdalist body)
(cl:multiple-value-bind (pure-lambdalist typelist declspecs)
(analyze-typed-lambdalist lambdalist)
(if (or declspecs (and (consp body) (type-decl-p (car body))))
(cl:multiple-value-bind (resulttype rbody)
(if (and (consp body) (type-decl-p (car body)))
(values (type-decl-type (car body)) (cdr body))
(values 't body))
(values `(,pure-lambdalist
,@(if declspecs `((declare ,@declspecs)))
,@rbody)
`(cl:function ,typelist ,resulttype)))
(values `(,lambdalist ,@body) nil))))
(cl:defun untyped-flet-bindings (bindings)
(cl:let ((declspecs '())
(pure-bindings '()))
(cl:dolist (binding bindings)
(cl:let ((funname (car binding)))
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody (cadr binding) (cddr binding))
(when ftype (push `(ftype ,ftype ,funname) declspecs))
(push (cons funname pure-lambdabody) pure-bindings))))
(values (nreverse pure-bindings) (nreverse declspecs))))
(cl:defun untyped-variable-bindings (bindings)
(cl:let ((declspecs '())
(pure-bindings '()))
(cl:dolist (binding bindings)
(if (atom binding)
(if (typed-var-p binding)
(progn
(push (typed-var-variable binding) pure-bindings)
(push `(type ,(typed-var-type binding) ,(typed-var-variable binding)) declspecs))
(push binding pure-bindings))
(cl:let ((var (first binding)))
(if (typed-var-p var)
(progn
(push (cons (typed-var-variable var) (rest binding)) pure-bindings)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push binding pure-bindings)))))
(values (nreverse pure-bindings) (nreverse declspecs))))
(cl:defun untyped-method-body (method-body)
(cl:let* ((lambdalist-position (position-if #'listp method-body))
(qualifiers (subseq method-body 0 lambdalist-position))
(lambdalist (nth lambdalist-position method-body))
(body (nthcdr (+ lambdalist-position 1) method-body))
(req-num (or (position-if #'(cl:lambda (x) (member x lambda-list-keywords)) lambdalist)
(length lambdalist))))
(cl:multiple-value-bind (pure-lambdalist typelist declspecs)
(analyze-typed-lambdalist lambdalist)
(declare (ignore typelist))
`(,@qualifiers
(,@(mapcar #'(cl:lambda (specialized-argument)
(if (typed-var-p specialized-argument)
(list (typed-var-variable specialized-argument)
(cl:let ((type (typed-var-type specialized-argument)))
(if (and (consp type) (eq (car type) 'eql)
(consp (cdr type)) (null (cddr type))
(cl:let ((singleton (second type)))
;; not self-evaluating?
(or (symbolp singleton) (consp singleton))))
`(eql ',(second type))
type)))
specialized-argument))
(subseq lambdalist 0 req-num))
,@(nthcdr req-num pure-lambdalist))
,@(if declspecs `((declare ,@declspecs)))
,@body))))
;; ============ Extended Common Lisp special operators and macros ============
;; TODO: Review the declaration scope in macros that establish several
;; bindings, like LET, LET*, LAMBDA, DO, DO*.
(defmacro defconstant (&whole whole
name initial-value &optional documentation)
(declare (ignore initial-value documentation))
(if (typed-var-p name)
`(progn
(declaim (type ,(typed-var-type name) ,(typed-var-variable name)))
(cl:defconstant ,(typed-var-variable name) ,@(cddr whole)))
`(cl:defconstant ,@(cdr whole))))
(defmacro defgeneric (funname gf-lambda-list &rest options)
`(cl:defgeneric ,funname ,gf-lambda-list
,@(mapcar #'(cl:lambda (option)
(if (and (consp option) (eq (car option) ':method))
`(:method ,@(untyped-method-body (cdr option)))
option))
options)))
(defmacro defmethod (funname &rest method-body)
`(cl:defmethod ,funname ,@(untyped-method-body method-body)))
(defmacro defparameter (&whole whole
name initial-value &optional documentation)
(declare (ignore initial-value documentation))
(if (typed-var-p name)
`(progn
(declaim (type ,(typed-var-type name) ,(typed-var-variable name)))
(cl:defparameter ,(typed-var-variable name) ,@(cddr whole)))
`(cl:defparameter ,@(cdr whole))))
(defmacro defun (&whole whole
funname lambdalist &body body)
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody lambdalist body)
(if ftype
`(progn
(declaim (ftype ,ftype ,funname))
(cl:defun ,funname ,@pure-lambdabody))
`(cl:defun ,@(cdr whole)))))
(defmacro defvar (&whole whole
name &optional initial-value documentation)
(declare (ignore initial-value documentation))
(if (typed-var-p name)
`(progn
(declaim (type ,(typed-var-type name) ,(typed-var-variable name)))
(cl:defvar ,(typed-var-variable name) ,@(cddr whole)))
`(cl:defvar ,@(cdr whole))))
#| TODO: destructuring-bind |#
(defmacro do (&whole whole
bindings endtest &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:do ,pure-bindings ,endtest (declare ,@declspecs) ,@body)
`(cl:do ,@(cdr whole)))))
(defmacro do* (&whole whole
bindings endtest &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:do* ,pure-bindings ,endtest (declare ,@declspecs) ,@body)
`(cl:do* ,@(cdr whole)))))
(defmacro do-all-symbols (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:do-all-symbols (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:do-all-symbols ,@(cdr whole))))
(defmacro do-external-symbols (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:do-external-symbols (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:do-external-symbols ,@(cdr whole))))
(defmacro do-symbols (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:do-symbols (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:do-symbols ,@(cdr whole))))
#+CLISP
(defmacro dohash (&whole whole
(var1 var2 &rest options) &body body)
(if (or (typed-var-p var1) (typed-var-p var2))
`(ext:dohash (,(if (typed-var-p var1) (typed-var-variable var1) var1)
,(if (typed-var-p var2) (typed-var-variable var2) var2)
,@options)
(declare
,@(if (typed-var-p var1)
`((type ,(typed-var-type var1) ,(typed-var-variable var1))))
,@(if (typed-var-p var2)
`((type ,(typed-var-type var2) ,(typed-var-variable var2)))))
,@body)
`(ext:dohash ,@(cdr whole))))
(defmacro dolist (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:dolist (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:dolist ,@(cdr whole))))
#+CLISP
(defmacro doseq (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(ext:doseq (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(ext:doseq ,@(cdr whole))))
(defmacro dotimes (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:dotimes (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:dotimes ,@(cdr whole))))
(defmacro flet (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-flet-bindings bindings)
(if declspecs
`(cl:flet ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:flet ,@(cdr whole)))))
#-CLISP
(defmacro function (arg)
(if (and (consp arg) (member (first arg) '(cl:lambda lambda)))
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody (cadr arg) (cddr arg))
(if ftype
`(the ,ftype (cl:function (cl:lambda ,@pure-lambdabody)))
`(cl:function (cl:lambda ,@(cdr arg)))))
`(cl:function ,arg)))
#+CLISP
(defmacro function (&whole whole arg1 &optional (arg2 nil arg2-p))
(cl:let ((named (if arg2-p (list arg1) '()))
(arg (if arg2-p arg2 arg1)))
(if (and (consp arg) (member (first arg) '(cl:lambda lambda)))
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody (cadr arg) (cddr arg))
(if ftype
`(the ,ftype (cl:function ,@named (cl:lambda ,@pure-lambdabody)))
`(cl:function ,@named (cl:lambda ,@(cdr arg)))))
`(cl:function ,@(cdr whole)))))
(setf (find-class 'function) (find-class 'cl:function))
(deftype function (&rest args) `(cl:function ,@args))
(cl:defmethod documentation (x (doc-type (eql 'function)))
(documentation x 'cl:function))
(cl:defmethod (setf documentation) (new-value x (doc-type (eql 'function)))
(funcall #'(setf documentation) new-value x 'cl:function))
(set-dispatch-macro-character #\# #\'
(cl:function
(cl:lambda (stream sub-char n)
(when (and n (not *read-suppress*))
(error "no number allowed between # and '"))
(list 'function (read stream t nil t)))))
TODO : ( - case
(defmacro labels (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-flet-bindings bindings)
(if declspecs
`(cl:labels ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:labels ,@(cdr whole)))))
(defmacro lambda (&whole whole
lambdalist &body body)
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody lambdalist body)
(if ftype
`(the ,ftype (cl:function (cl:lambda ,@pure-lambdabody)))
`(cl:function (cl:lambda ,@(cdr whole))))))
(defmacro let (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:let ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:let ,@(cdr whole)))))
(defmacro let* (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:let* ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:let* ,@(cdr whole)))))
#| TODO: (defmacro loop ...) |#
(defmacro multiple-value-bind (&whole whole
variables values-form &body body)
(cl:let ((declspecs '())
(pure-variables '()))
(cl:dolist (var variables)
(if (typed-var-p var)
(progn
(push (typed-var-variable var) pure-variables)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push var pure-variables)))
(setq declspecs (nreverse declspecs))
(setq pure-variables (nreverse pure-variables))
(if declspecs
`(cl:multiple-value-bind ,pure-variables ,values-form
(declare ,@declspecs)
,@body)
`(cl:multiple-value-bind ,@(cdr whole)))))
(defmacro prog (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:prog ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:prog ,@(cdr whole)))))
(defmacro prog* (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:prog* ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:prog* ,@(cdr whole)))))
#| TODO: (defmacro restart-case ... |#
(defmacro with-accessors (&whole whole
slot-entries instance-form &body body)
(cl:let ((declspecs '())
(pure-slot-entries '()))
(cl:dolist (slot-entry slot-entries)
(if (and (consp slot-entry) (typed-var-p (first slot-entry)))
(cl:let ((var (first slot-entry)))
(push (cons (typed-var-variable var) (rest slot-entry)) pure-slot-entries)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push slot-entry pure-slot-entries)))
(setq declspecs (nreverse declspecs))
(setq pure-slot-entries (nreverse pure-slot-entries))
(if declspecs
`(cl:with-accessors ,pure-slot-entries ,instance-form
(declare ,@declspecs)
,@body)
`(cl:with-accessors ,@(cdr whole)))))
(defmacro with-input-from-string (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-input-from-string (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-input-from-string ,@(cdr whole))))
(defmacro with-open-file (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-open-file (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-open-file ,@(cdr whole))))
(defmacro with-open-stream (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-open-stream (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-open-stream ,@(cdr whole))))
(defmacro with-output-to-string (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-output-to-string (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-output-to-string ,@(cdr whole))))
(defmacro with-slots (&whole whole
slot-entries instance-form &body body)
(cl:let ((declspecs '())
(pure-slot-entries '()))
(cl:dolist (slot-entry slot-entries)
(if (typed-var-p slot-entry)
(progn
(push (typed-var-variable slot-entry) pure-slot-entries)
(push `(type ,(typed-var-type slot-entry) ,(typed-var-variable slot-entry)) declspecs))
(if (and (consp slot-entry) (typed-var-p (first slot-entry)))
(cl:let ((var (first slot-entry)))
(push (cons (typed-var-variable var) (rest slot-entry)) pure-slot-entries)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push slot-entry pure-slot-entries))))
(setq declspecs (nreverse declspecs))
(setq pure-slot-entries (nreverse pure-slot-entries))
(if declspecs
`(cl:with-slots ,pure-slot-entries ,instance-form
(declare ,@declspecs)
,@body)
`(cl:with-slots ,@(cdr whole)))))
| null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/syntax/typedecl/typedvar.lisp | lisp | Typed variable syntax for Common Lisp
This file is put in the public domain by its authors.
A typed variable is a variable whose value at any time is guaranteed
by the programmer to belong to a given type. It is assumed that the
type's semantics doesn't change during the dynamic extent of the variable.
syntax to declare a typed variable is different each time:
(lambda (x ...) (declare (integer x)) ...)
(lambda (x ...) (declare (type integer x)) ...)
(let ((x ...)) (declare (integer x)) ...)
(let ((x ...)) (declare (type integer x)) ...)
(defmethod foo ((x integer) ...) ...)
- In LOOP:
(loop for x integer across v ...)
(loop for x of-type integer across v ...)
- Type declarations in function returns:
(declaim (ftype (function (t) integer) foo))
(defun foo (x) ...)
This file supports typed variables and typed function returns through
a simple common syntax: [variable type] and [type].
Examples:
(lambda ([x integer] ...) ...)
(let (([x integer] ...) ...)
- In LOOP:
(loop for [x integer] across v ...)
- Type declarations in function returns:
(defun foo (x) [integer] ...)
The variable name always comes before the type, because (assuming decent
coding style) it carries more information than the type.
Example:
(defun scale-long-float (x exp)
(declare (long-float x) (fixnum exp))
...)
-> (defun scale-long-float ([x long-float] [exp fixnum])
...)
an evaluated form, whereas type specifiers cannot. Therefore
(defmethod foo ([x (eql a)]) ...)
is equivalent to
and there is no typed-variable syntax for
(defmethod foo ((x (eql a))) ...).
that the typed variable syntax not only defines a specializer, but also
a declaration for the entire scope of variable. I.e.
(defmethod foo ([x integer]) ...)
is equivalent to
(defmethod foo ((x integer)) (declare (type integer x)) ...)
It would be bad style anyway to assign a non-integer value to x inside
the method.
Note: When a return type declaration and documentation string are both
(defun foo (x) [integer] "comment" ...)
============================ Package Setup ============================
"DESTRUCTURING-BIND"
"HANDLER-CASE"
"LOOP"
"RESTART-CASE"
============================ Basic definitions ============================
In-memory representation of syntax [type]: `(type-decl ,type).
In-memory representation of syntax [var type]: `(typed-var ,var ,type).
=================== Subroutines for the extended macros ===================
not self-evaluating?
============ Extended Common Lisp special operators and macros ============
TODO: Review the declaration scope in macros that establish several
bindings, like LET, LET*, LAMBDA, DO, DO*.
TODO: destructuring-bind
TODO: (defmacro loop ...)
TODO: (defmacro restart-case ... | 2004 - 08 - 05
Common Lisp supports typed variables in various situations , but the
- In LAMBDA , LET , LET * , MULTIPLE - VALUE - BIND :
- In DEFMETHOD , :
- In LAMBDA , LET , LET * , MULTIPLE - VALUE - BIND :
- In DEFMETHOD , :
( defmethod foo ( [ x integer ] ... ) ... )
Note : Specialized lambda lists in DEFMETHOD , can contain an
( defmethod foo ( ( x ( eql ' a ) ) ) ... ) ,
Note : Another difference with specialized lambda lists in DEFMETHOD is
specified together , the type declaration should come first :
(defpackage "TYPEDVAR-COMMON-LISP"
(:use "COMMON-LISP")
(:export . #1=("DEFCONSTANT"
"DEFGENERIC"
"DEFMETHOD"
"DEFPARAMETER"
"DEFUN"
"DEFVAR"
"DO"
"DO*"
"DO-ALL-SYMBOLS"
"DO-EXTERNAL-SYMBOLS"
"DO-SYMBOLS"
#+CLISP "DOHASH"
"DOLIST"
#+CLISP "DOSEQ"
"DOTIMES"
"FLET"
"FUNCTION"
"LABELS"
"LAMBDA"
"LET"
"LET*"
"MULTIPLE-VALUE-BIND"
"PROG"
"PROG*"
"WITH-ACCESSORS"
"WITH-INPUT-FROM-STRING"
"WITH-OPEN-FILE"
"WITH-OPEN-STREAM"
"WITH-OUTPUT-TO-STRING"
"WITH-SLOTS"))
(:shadow . #1#))
(in-package "TYPEDVAR-COMMON-LISP")
(cl:do-external-symbols (s "COMMON-LISP")
(unless (member (nth-value 1 (find-symbol (symbol-name s))) '(:internal :external))
(import (list s))
(export (list s))))
(defmacro type-decl (type)
(error "misplaced type declaration: [~S]" type))
(cl:defun type-decl-p (form)
(and (consp form) (eq (car form) 'type-decl)
(consp (cdr form))
(null (cddr form))))
(cl:defun type-decl-type (x) (second x))
(defmacro typed-var (var type)
(error "misplaced typed variable declaration: [~S ~S]" var type))
(cl:defun typed-var-p (form)
(and (consp form) (eq (car form) 'typed-var)
(consp (cdr form))
(consp (cddr form))
(null (cdddr form))))
(cl:defun typed-var-variable (x) (second x))
(cl:defun typed-var-type (x) (third x))
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(set-macro-character #\[
#'(cl:lambda (stream char)
(declare (ignore char))
(cl:let ((contents (read-delimited-list #\] stream t)))
(when (null contents)
(error "invalid syntax: []"))
(case (length contents)
(1 `(type-decl ,(first contents)))
(2 (unless (symbolp (first contents))
(error "invalid syntax, variable should be a symbol: [~S ~S]"
(first contents) (second contents)))
`(typed-var ,(first contents) ,(second contents)))))))
(set-syntax-from-char #\] #\))
(cl:defun variable-to-keyword (variable)
(if (symbolp variable)
(intern (symbol-name variable) (find-package "KEYWORD"))
nil))
(cl:defun analyze-typed-lambdalist (lambdalist)
(cl:let ((pure-lambdalist '())
(typelist '())
(declspecs '())
(seen-&key nil)
(seen-&aux nil))
(cl:dolist (item lambdalist)
(if (typed-var-p item)
(progn
(push (typed-var-variable item) pure-lambdalist)
(push `(type ,(typed-var-type item) ,(typed-var-variable item)) declspecs)
(unless seen-&aux
(push (if seen-&key
(list (variable-to-keyword (typed-var-variable item)) (typed-var-type item))
(typed-var-type item))
typelist)))
(if (atom item)
(progn
(push item pure-lambdalist)
(if (member item lambda-list-keywords)
(progn
(when (eq item '&key)
(setq seen-&key t))
(when (eq item '&aux)
(setq seen-&aux t))
(when (member item '(&optional &rest &key))
(push item typelist)))
(unless seen-&aux
(push (if seen-&key
(list (variable-to-keyword item) 't)
't)
typelist))))
(cl:multiple-value-bind (var1 type1 keyword)
(if (typed-var-p (first item))
(progn
(push `(type ,(typed-var-type (first item)) ,(typed-var-variable (first item))) declspecs)
(values (typed-var-variable (first item))
(typed-var-type (first item))
(if (and seen-&key (not seen-&aux))
(variable-to-keyword (typed-var-variable (first item)))
nil)))
(if (atom (first item))
(values (first item)
't
(if (and seen-&key (not seen-&aux))
(variable-to-keyword (first item))
nil))
(if (and (consp (cdr (first item)))
(null (cddr (first item))))
(if (typed-var-p (second (first item)))
(progn
(push `(type ,(typed-var-type (second (first item))) ,(typed-var-variable (second (first item)))) declspecs)
(values (list (first (first item))
(typed-var-variable (second (first item))))
(typed-var-type (second (first item)))
(first (first item))))
(values (first item)
't
(first (first item))))
(values (first item)
't
nil))))
(unless seen-&aux
(push (if seen-&key (list keyword type1) type1) typelist))
(push (cons var1
(if (and (consp (cdr item)) (consp (cddr item)))
(cl:let ((var3
(if (typed-var-p (third item))
(progn
(push `(type ,(typed-var-type (third item)) ,(typed-var-variable (third item))) declspecs)
(typed-var-variable (third item)))
(third item))))
(list* (second item) var3 (cdddr item)))
(cdr item)))
pure-lambdalist)))))
(values (nreverse pure-lambdalist)
(nreverse typelist)
(nreverse declspecs))))
(cl:defun analyze-typed-lambdabody (lambdalist body)
(cl:multiple-value-bind (pure-lambdalist typelist declspecs)
(analyze-typed-lambdalist lambdalist)
(if (or declspecs (and (consp body) (type-decl-p (car body))))
(cl:multiple-value-bind (resulttype rbody)
(if (and (consp body) (type-decl-p (car body)))
(values (type-decl-type (car body)) (cdr body))
(values 't body))
(values `(,pure-lambdalist
,@(if declspecs `((declare ,@declspecs)))
,@rbody)
`(cl:function ,typelist ,resulttype)))
(values `(,lambdalist ,@body) nil))))
(cl:defun untyped-flet-bindings (bindings)
(cl:let ((declspecs '())
(pure-bindings '()))
(cl:dolist (binding bindings)
(cl:let ((funname (car binding)))
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody (cadr binding) (cddr binding))
(when ftype (push `(ftype ,ftype ,funname) declspecs))
(push (cons funname pure-lambdabody) pure-bindings))))
(values (nreverse pure-bindings) (nreverse declspecs))))
(cl:defun untyped-variable-bindings (bindings)
(cl:let ((declspecs '())
(pure-bindings '()))
(cl:dolist (binding bindings)
(if (atom binding)
(if (typed-var-p binding)
(progn
(push (typed-var-variable binding) pure-bindings)
(push `(type ,(typed-var-type binding) ,(typed-var-variable binding)) declspecs))
(push binding pure-bindings))
(cl:let ((var (first binding)))
(if (typed-var-p var)
(progn
(push (cons (typed-var-variable var) (rest binding)) pure-bindings)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push binding pure-bindings)))))
(values (nreverse pure-bindings) (nreverse declspecs))))
(cl:defun untyped-method-body (method-body)
(cl:let* ((lambdalist-position (position-if #'listp method-body))
(qualifiers (subseq method-body 0 lambdalist-position))
(lambdalist (nth lambdalist-position method-body))
(body (nthcdr (+ lambdalist-position 1) method-body))
(req-num (or (position-if #'(cl:lambda (x) (member x lambda-list-keywords)) lambdalist)
(length lambdalist))))
(cl:multiple-value-bind (pure-lambdalist typelist declspecs)
(analyze-typed-lambdalist lambdalist)
(declare (ignore typelist))
`(,@qualifiers
(,@(mapcar #'(cl:lambda (specialized-argument)
(if (typed-var-p specialized-argument)
(list (typed-var-variable specialized-argument)
(cl:let ((type (typed-var-type specialized-argument)))
(if (and (consp type) (eq (car type) 'eql)
(consp (cdr type)) (null (cddr type))
(cl:let ((singleton (second type)))
(or (symbolp singleton) (consp singleton))))
`(eql ',(second type))
type)))
specialized-argument))
(subseq lambdalist 0 req-num))
,@(nthcdr req-num pure-lambdalist))
,@(if declspecs `((declare ,@declspecs)))
,@body))))
(defmacro defconstant (&whole whole
name initial-value &optional documentation)
(declare (ignore initial-value documentation))
(if (typed-var-p name)
`(progn
(declaim (type ,(typed-var-type name) ,(typed-var-variable name)))
(cl:defconstant ,(typed-var-variable name) ,@(cddr whole)))
`(cl:defconstant ,@(cdr whole))))
(defmacro defgeneric (funname gf-lambda-list &rest options)
`(cl:defgeneric ,funname ,gf-lambda-list
,@(mapcar #'(cl:lambda (option)
(if (and (consp option) (eq (car option) ':method))
`(:method ,@(untyped-method-body (cdr option)))
option))
options)))
(defmacro defmethod (funname &rest method-body)
`(cl:defmethod ,funname ,@(untyped-method-body method-body)))
(defmacro defparameter (&whole whole
name initial-value &optional documentation)
(declare (ignore initial-value documentation))
(if (typed-var-p name)
`(progn
(declaim (type ,(typed-var-type name) ,(typed-var-variable name)))
(cl:defparameter ,(typed-var-variable name) ,@(cddr whole)))
`(cl:defparameter ,@(cdr whole))))
(defmacro defun (&whole whole
funname lambdalist &body body)
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody lambdalist body)
(if ftype
`(progn
(declaim (ftype ,ftype ,funname))
(cl:defun ,funname ,@pure-lambdabody))
`(cl:defun ,@(cdr whole)))))
(defmacro defvar (&whole whole
name &optional initial-value documentation)
(declare (ignore initial-value documentation))
(if (typed-var-p name)
`(progn
(declaim (type ,(typed-var-type name) ,(typed-var-variable name)))
(cl:defvar ,(typed-var-variable name) ,@(cddr whole)))
`(cl:defvar ,@(cdr whole))))
(defmacro do (&whole whole
bindings endtest &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:do ,pure-bindings ,endtest (declare ,@declspecs) ,@body)
`(cl:do ,@(cdr whole)))))
(defmacro do* (&whole whole
bindings endtest &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:do* ,pure-bindings ,endtest (declare ,@declspecs) ,@body)
`(cl:do* ,@(cdr whole)))))
(defmacro do-all-symbols (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:do-all-symbols (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:do-all-symbols ,@(cdr whole))))
(defmacro do-external-symbols (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:do-external-symbols (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:do-external-symbols ,@(cdr whole))))
(defmacro do-symbols (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:do-symbols (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:do-symbols ,@(cdr whole))))
#+CLISP
(defmacro dohash (&whole whole
(var1 var2 &rest options) &body body)
(if (or (typed-var-p var1) (typed-var-p var2))
`(ext:dohash (,(if (typed-var-p var1) (typed-var-variable var1) var1)
,(if (typed-var-p var2) (typed-var-variable var2) var2)
,@options)
(declare
,@(if (typed-var-p var1)
`((type ,(typed-var-type var1) ,(typed-var-variable var1))))
,@(if (typed-var-p var2)
`((type ,(typed-var-type var2) ,(typed-var-variable var2)))))
,@body)
`(ext:dohash ,@(cdr whole))))
(defmacro dolist (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:dolist (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:dolist ,@(cdr whole))))
#+CLISP
(defmacro doseq (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(ext:doseq (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(ext:doseq ,@(cdr whole))))
(defmacro dotimes (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:dotimes (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:dotimes ,@(cdr whole))))
(defmacro flet (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-flet-bindings bindings)
(if declspecs
`(cl:flet ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:flet ,@(cdr whole)))))
#-CLISP
(defmacro function (arg)
(if (and (consp arg) (member (first arg) '(cl:lambda lambda)))
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody (cadr arg) (cddr arg))
(if ftype
`(the ,ftype (cl:function (cl:lambda ,@pure-lambdabody)))
`(cl:function (cl:lambda ,@(cdr arg)))))
`(cl:function ,arg)))
#+CLISP
(defmacro function (&whole whole arg1 &optional (arg2 nil arg2-p))
(cl:let ((named (if arg2-p (list arg1) '()))
(arg (if arg2-p arg2 arg1)))
(if (and (consp arg) (member (first arg) '(cl:lambda lambda)))
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody (cadr arg) (cddr arg))
(if ftype
`(the ,ftype (cl:function ,@named (cl:lambda ,@pure-lambdabody)))
`(cl:function ,@named (cl:lambda ,@(cdr arg)))))
`(cl:function ,@(cdr whole)))))
(setf (find-class 'function) (find-class 'cl:function))
(deftype function (&rest args) `(cl:function ,@args))
(cl:defmethod documentation (x (doc-type (eql 'function)))
(documentation x 'cl:function))
(cl:defmethod (setf documentation) (new-value x (doc-type (eql 'function)))
(funcall #'(setf documentation) new-value x 'cl:function))
(set-dispatch-macro-character #\# #\'
(cl:function
(cl:lambda (stream sub-char n)
(when (and n (not *read-suppress*))
(error "no number allowed between # and '"))
(list 'function (read stream t nil t)))))
TODO : ( - case
(defmacro labels (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-flet-bindings bindings)
(if declspecs
`(cl:labels ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:labels ,@(cdr whole)))))
(defmacro lambda (&whole whole
lambdalist &body body)
(cl:multiple-value-bind (pure-lambdabody ftype)
(analyze-typed-lambdabody lambdalist body)
(if ftype
`(the ,ftype (cl:function (cl:lambda ,@pure-lambdabody)))
`(cl:function (cl:lambda ,@(cdr whole))))))
(defmacro let (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:let ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:let ,@(cdr whole)))))
(defmacro let* (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:let* ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:let* ,@(cdr whole)))))
(defmacro multiple-value-bind (&whole whole
variables values-form &body body)
(cl:let ((declspecs '())
(pure-variables '()))
(cl:dolist (var variables)
(if (typed-var-p var)
(progn
(push (typed-var-variable var) pure-variables)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push var pure-variables)))
(setq declspecs (nreverse declspecs))
(setq pure-variables (nreverse pure-variables))
(if declspecs
`(cl:multiple-value-bind ,pure-variables ,values-form
(declare ,@declspecs)
,@body)
`(cl:multiple-value-bind ,@(cdr whole)))))
(defmacro prog (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:prog ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:prog ,@(cdr whole)))))
(defmacro prog* (&whole whole
bindings &body body)
(cl:multiple-value-bind (pure-bindings declspecs)
(untyped-variable-bindings bindings)
(if declspecs
`(cl:prog* ,pure-bindings (declare ,@declspecs) ,@body)
`(cl:prog* ,@(cdr whole)))))
(defmacro with-accessors (&whole whole
slot-entries instance-form &body body)
(cl:let ((declspecs '())
(pure-slot-entries '()))
(cl:dolist (slot-entry slot-entries)
(if (and (consp slot-entry) (typed-var-p (first slot-entry)))
(cl:let ((var (first slot-entry)))
(push (cons (typed-var-variable var) (rest slot-entry)) pure-slot-entries)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push slot-entry pure-slot-entries)))
(setq declspecs (nreverse declspecs))
(setq pure-slot-entries (nreverse pure-slot-entries))
(if declspecs
`(cl:with-accessors ,pure-slot-entries ,instance-form
(declare ,@declspecs)
,@body)
`(cl:with-accessors ,@(cdr whole)))))
(defmacro with-input-from-string (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-input-from-string (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-input-from-string ,@(cdr whole))))
(defmacro with-open-file (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-open-file (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-open-file ,@(cdr whole))))
(defmacro with-open-stream (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-open-stream (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-open-stream ,@(cdr whole))))
(defmacro with-output-to-string (&whole whole
(var &rest options) &body body)
(if (typed-var-p var)
`(cl:with-output-to-string (,(typed-var-variable var) ,@options)
(declare (type ,(typed-var-type var) ,(typed-var-variable var)))
,@body)
`(cl:with-output-to-string ,@(cdr whole))))
(defmacro with-slots (&whole whole
slot-entries instance-form &body body)
(cl:let ((declspecs '())
(pure-slot-entries '()))
(cl:dolist (slot-entry slot-entries)
(if (typed-var-p slot-entry)
(progn
(push (typed-var-variable slot-entry) pure-slot-entries)
(push `(type ,(typed-var-type slot-entry) ,(typed-var-variable slot-entry)) declspecs))
(if (and (consp slot-entry) (typed-var-p (first slot-entry)))
(cl:let ((var (first slot-entry)))
(push (cons (typed-var-variable var) (rest slot-entry)) pure-slot-entries)
(push `(type ,(typed-var-type var) ,(typed-var-variable var)) declspecs))
(push slot-entry pure-slot-entries))))
(setq declspecs (nreverse declspecs))
(setq pure-slot-entries (nreverse pure-slot-entries))
(if declspecs
`(cl:with-slots ,pure-slot-entries ,instance-form
(declare ,@declspecs)
,@body)
`(cl:with-slots ,@(cdr whole)))))
|
9c3cfbe224ece0d2b71fffc820dcbfa7ac3ac0fb3e0e5cfe3ab2da7b44e37fa9 | janestreet/vcaml | test_nvim.ml | open Core
open Async
open Vcaml
open Vcaml_test_helpers
let%expect_test "open neovim and get channel list" =
let%bind () =
simple [%here] Nvim.channels (fun channels ->
channels |> List.length > 0 |> sexp_of_bool)
in
[%expect "true"];
return ()
;;
let%expect_test "get_channel_info" =
let%bind () =
simple [%here] (Nvim.get_channel_info 1) ("call-succeeded" |> Sexp.Atom |> Fn.const)
in
[%expect "call-succeeded"];
return ()
;;
let%expect_test "command output" =
let%bind () = simple [%here] (Nvim.source "echo 'hi'") sexp_of_string in
[%expect "hi"];
return ()
;;
let%expect_test "command, list_bufs, Buffer.get_name" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "e foo.txt" |> run_join [%here] client in
let%bind () = Nvim.command "e bar.txt" |> run_join [%here] client in
let%bind () = Nvim.command "e baz.txt" |> run_join [%here] client in
let%bind buffers = Nvim.list_bufs |> run_join [%here] client in
let%map buffer_names =
buffers
|> List.map ~f:(fun buffer ->
Buffer.get_name (Id buffer) |> run_join [%here] client)
|> Deferred.Or_error.combine_errors
|> Deferred.Or_error.map ~f:(fun filenames ->
List.map filenames ~f:(fun file ->
file |> Filename.parts |> List.last_exn))
in
print_s [%message (buffers : Buffer.t list) (buffer_names : string list)])
in
[%expect {|
((buffers (1 2 3)) (buffer_names (foo.txt bar.txt baz.txt)))|}];
return ()
;;
let%expect_test "eval" =
let%bind () = simple [%here] (Nvim.eval "1 + 2" ~result_type:Integer) [%sexp_of: int] in
[%expect {| 3 |}];
return ()
;;
let%expect_test "set_current_buf" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "e foo.txt" |> run_join [%here] client in
let%bind expected_buf = Nvim.get_current_buf |> run_join [%here] client in
let%bind () = Nvim.command "e bar.txt" |> run_join [%here] client in
let%bind () = Nvim.set_current_buf expected_buf |> run_join [%here] client in
let%bind actual_buf = Nvim.get_current_buf |> run_join [%here] client in
print_s [%message (expected_buf : Buffer.t) (actual_buf : Buffer.t)];
return ())
in
[%expect "((expected_buf 1) (actual_buf 1))"];
return ()
;;
let%expect_test "set_client_info" =
let test_method =
{ Client_info.Client_method.async = false; nargs = Some (`Fixed 1) }
in
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
The initial setting happens when a VCaml client connects to Neovim .
let get_client_info () =
let%map.Deferred.Or_error channels = run_join [%here] client Nvim.channels in
let channel = List.hd_exn channels in
channel.client
in
let%bind client_before_setting_info = get_client_info () in
let%bind () =
Nvim.set_client_info
~version:
{ major = Some 1
; minor = Some 2
; patch = Some 3
; prerelease = Some "test_prerelease"
; commit = Some "test_commit"
}
~methods:(String.Map.of_alist_exn [ "test_method", test_method ])
~attributes:(String.Map.of_alist_exn [ "attr1", "val1" ])
~name:"foo"
~type_:`Embedder
()
|> run_join [%here] client
in
let%bind client_after_setting_info = get_client_info () in
print_s
[%message
(client_before_setting_info : Client_info.t option)
(client_after_setting_info : Client_info.t option)];
return ())
in
[%expect
{|
((client_before_setting_info
(((version
(((major (0)) (minor ()) (patch ()) (prerelease ()) (commit ()))))
(methods ()) (attributes ()) (name (<uuid-omitted-in-test>))
(type_ (Remote)))))
(client_after_setting_info
(((version
(((major (1)) (minor (2)) (patch (3)) (prerelease (test_prerelease))
(commit (test_commit)))))
(methods ((test_method ((async false) (nargs ((Fixed 1)))))))
(attributes ((attr1 val1))) (name (foo)) (type_ (Embedder))))))|}];
return ()
;;
let%expect_test "get_current_win, set_current_win" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind original_win = Nvim.get_current_win |> run_join [%here] client in
let%bind () = Nvim.command "split" |> run_join [%here] client in
let%bind win_after_split = Nvim.get_current_win |> run_join [%here] client in
let%bind () = Nvim.set_current_win original_win |> run_join [%here] client in
let%bind win_after_set = run_join [%here] client Nvim.get_current_win in
print_s
[%message
(original_win : Window.t)
(win_after_split : Window.t)
(win_after_set : Window.t)];
return ())
in
[%expect "((original_win 1000) (win_after_split 1001) (win_after_set 1000))"];
return ()
;;
let%expect_test "list_wins" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "split" |> run_join [%here] client in
let%bind () = Nvim.command "split" |> run_join [%here] client in
let%bind win_list = Nvim.list_wins |> run_join [%here] client in
print_s [%message (win_list : Window.t list)];
return ())
in
[%expect "(win_list (1002 1001 1000))"];
return ()
;;
let%expect_test "replace_termcodes" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind escaped_keys =
Nvim.replace_termcodes_and_keycodes "ifoobar<ESC><Left><Left>XXX"
|> run_join [%here] client
in
let%bind () =
Nvim.feedkeys (`Already_escaped escaped_keys) ~mode:"n"
|> run_join [%here] client
in
let%bind lines =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
print_s [%message (lines : string list)];
return ())
in
[%expect {| (lines (bar)) |}];
return ()
;;
let%expect_test "get_color_by_name" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind color = Nvim.get_color_by_name "#f0f8ff" |> run_join [%here] client in
print_s [%sexp (color : Color.True_color.t)];
let%bind color = Nvim.get_color_by_name "AliceBlue" |> run_join [%here] client in
print_s [%sexp (color : Color.True_color.t)];
return ())
in
[%expect {|
#f0f8ff
#f0f8ff |}];
return ()
;;
let%expect_test "color_map" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind color_map = Nvim.get_color_map |> run_join [%here] client in
print_s [%sexp (color_map : Color.True_color.t String.Map.t)];
return ())
in
[%expect
{|
((AliceBlue #f0f8ff) (AntiqueWhite #faebd7) (AntiqueWhite1 #ffefdb)
(AntiqueWhite2 #eedfcc) (AntiqueWhite3 #cdc0b0) (AntiqueWhite4 #8b8378)
(Aqua #00ffff) (Aquamarine #7fffd4) (Aquamarine1 #7fffd4)
(Aquamarine2 #76eec6) (Aquamarine3 #66cdaa) (Aquamarine4 #458b74)
(Azure #f0ffff) (Azure1 #f0ffff) (Azure2 #e0eeee) (Azure3 #c1cdcd)
(Azure4 #838b8b) (Beige #f5f5dc) (Bisque #ffe4c4) (Bisque1 #ffe4c4)
(Bisque2 #eed5b7) (Bisque3 #cdb79e) (Bisque4 #8b7d6b) (Black #000000)
(BlanchedAlmond #ffebcd) (Blue #0000ff) (Blue1 #0000ff) (Blue2 #0000ee)
(Blue3 #0000cd) (Blue4 #00008b) (BlueViolet #8a2be2) (Brown #a52a2a)
(Brown1 #ff4040) (Brown2 #ee3b3b) (Brown3 #cd3333) (Brown4 #8b2323)
(BurlyWood #deb887) (Burlywood1 #ffd39b) (Burlywood2 #eec591)
(Burlywood3 #cdaa7d) (Burlywood4 #8b7355) (CadetBlue #5f9ea0)
(CadetBlue1 #98f5ff) (CadetBlue2 #8ee5ee) (CadetBlue3 #7ac5cd)
(CadetBlue4 #53868b) (ChartReuse #7fff00) (Chartreuse1 #7fff00)
(Chartreuse2 #76ee00) (Chartreuse3 #66cd00) (Chartreuse4 #458b00)
(Chocolate #d2691e) (Chocolate1 #ff7f24) (Chocolate2 #ee7621)
(Chocolate3 #cd661d) (Chocolate4 #8b4513) (Coral #ff7f50) (Coral1 #ff7256)
(Coral2 #ee6a50) (Coral3 #cd5b45) (Coral4 #8b3e2f) (CornFlowerBlue #6495ed)
(Cornsilk #fff8dc) (Cornsilk1 #fff8dc) (Cornsilk2 #eee8cd)
(Cornsilk3 #cdc8b1) (Cornsilk4 #8b8878) (Crimson #dc143c) (Cyan #00ffff)
(Cyan1 #00ffff) (Cyan2 #00eeee) (Cyan3 #00cdcd) (Cyan4 #008b8b)
(DarkBlue #00008b) (DarkCyan #008b8b) (DarkGoldenRod #b8860b)
(DarkGoldenrod1 #ffb90f) (DarkGoldenrod2 #eead0e) (DarkGoldenrod3 #cd950c)
(DarkGoldenrod4 #8b6508) (DarkGray #a9a9a9) (DarkGreen #006400)
(DarkGrey #a9a9a9) (DarkKhaki #bdb76b) (DarkMagenta #8b008b)
(DarkOliveGreen #556b2f) (DarkOliveGreen1 #caff70) (DarkOliveGreen2 #bcee68)
(DarkOliveGreen3 #a2cd5a) (DarkOliveGreen4 #6e8b3d) (DarkOrange #ff8c00)
(DarkOrange1 #ff7f00) (DarkOrange2 #ee7600) (DarkOrange3 #cd6600)
(DarkOrange4 #8b4500) (DarkOrchid #9932cc) (DarkOrchid1 #bf3eff)
(DarkOrchid2 #b23aee) (DarkOrchid3 #9a32cd) (DarkOrchid4 #68228b)
(DarkRed #8b0000) (DarkSalmon #e9967a) (DarkSeaGreen #8fbc8f)
(DarkSeaGreen1 #c1ffc1) (DarkSeaGreen2 #b4eeb4) (DarkSeaGreen3 #9bcd9b)
(DarkSeaGreen4 #698b69) (DarkSlateBlue #483d8b) (DarkSlateGray #2f4f4f)
(DarkSlateGray1 #97ffff) (DarkSlateGray2 #8deeee) (DarkSlateGray3 #79cdcd)
(DarkSlateGray4 #528b8b) (DarkSlateGrey #2f4f4f) (DarkTurquoise #00ced1)
(DarkViolet #9400d3) (DarkYellow #bbbb00) (DeepPink #ff1493)
(DeepPink1 #ff1493) (DeepPink2 #ee1289) (DeepPink3 #cd1076)
(DeepPink4 #8b0a50) (DeepSkyBlue #00bfff) (DeepSkyBlue1 #00bfff)
(DeepSkyBlue2 #00b2ee) (DeepSkyBlue3 #009acd) (DeepSkyBlue4 #00688b)
(DimGray #696969) (DimGrey #696969) (DodgerBlue #1e90ff)
(DodgerBlue1 #1e90ff) (DodgerBlue2 #1c86ee) (DodgerBlue3 #1874cd)
(DodgerBlue4 #104e8b) (Firebrick #b22222) (Firebrick1 #ff3030)
(Firebrick2 #ee2c2c) (Firebrick3 #cd2626) (Firebrick4 #8b1a1a)
(FloralWhite #fffaf0) (ForestGreen #228b22) (Fuchsia #ff00ff)
(Gainsboro #dcdcdc) (GhostWhite #f8f8ff) (Gold #ffd700) (Gold1 #ffd700)
(Gold2 #eec900) (Gold3 #cdad00) (Gold4 #8b7500) (GoldenRod #daa520)
(Goldenrod1 #ffc125) (Goldenrod2 #eeb422) (Goldenrod3 #cd9b1d)
(Goldenrod4 #8b6914) (Gray #808080) (Gray0 #000000) (Gray1 #030303)
(Gray10 #1a1a1a) (Gray100 #ffffff) (Gray11 #1c1c1c) (Gray12 #1f1f1f)
(Gray13 #212121) (Gray14 #242424) (Gray15 #262626) (Gray16 #292929)
(Gray17 #2b2b2b) (Gray18 #2e2e2e) (Gray19 #303030) (Gray2 #050505)
(Gray20 #333333) (Gray21 #363636) (Gray22 #383838) (Gray23 #3b3b3b)
(Gray24 #3d3d3d) (Gray25 #404040) (Gray26 #424242) (Gray27 #454545)
(Gray28 #474747) (Gray29 #4a4a4a) (Gray3 #080808) (Gray30 #4d4d4d)
(Gray31 #4f4f4f) (Gray32 #525252) (Gray33 #545454) (Gray34 #575757)
(Gray35 #595959) (Gray36 #5c5c5c) (Gray37 #5e5e5e) (Gray38 #616161)
(Gray39 #636363) (Gray4 #0a0a0a) (Gray40 #666666) (Gray41 #696969)
(Gray42 #6b6b6b) (Gray43 #6e6e6e) (Gray44 #707070) (Gray45 #737373)
(Gray46 #757575) (Gray47 #787878) (Gray48 #7a7a7a) (Gray49 #7d7d7d)
(Gray5 #0d0d0d) (Gray50 #7f7f7f) (Gray51 #828282) (Gray52 #858585)
(Gray53 #878787) (Gray54 #8a8a8a) (Gray55 #8c8c8c) (Gray56 #8f8f8f)
(Gray57 #919191) (Gray58 #949494) (Gray59 #969696) (Gray6 #0f0f0f)
(Gray60 #999999) (Gray61 #9c9c9c) (Gray62 #9e9e9e) (Gray63 #a1a1a1)
(Gray64 #a3a3a3) (Gray65 #a6a6a6) (Gray66 #a8a8a8) (Gray67 #ababab)
(Gray68 #adadad) (Gray69 #b0b0b0) (Gray7 #121212) (Gray70 #b3b3b3)
(Gray71 #b5b5b5) (Gray72 #b8b8b8) (Gray73 #bababa) (Gray74 #bdbdbd)
(Gray75 #bfbfbf) (Gray76 #c2c2c2) (Gray77 #c4c4c4) (Gray78 #c7c7c7)
(Gray79 #c9c9c9) (Gray8 #141414) (Gray80 #cccccc) (Gray81 #cfcfcf)
(Gray82 #d1d1d1) (Gray83 #d4d4d4) (Gray84 #d6d6d6) (Gray85 #d9d9d9)
(Gray86 #dbdbdb) (Gray87 #dedede) (Gray88 #e0e0e0) (Gray89 #e3e3e3)
(Gray9 #171717) (Gray90 #e5e5e5) (Gray91 #e8e8e8) (Gray92 #ebebeb)
(Gray93 #ededed) (Gray94 #f0f0f0) (Gray95 #f2f2f2) (Gray96 #f5f5f5)
(Gray97 #f7f7f7) (Gray98 #fafafa) (Gray99 #fcfcfc) (Green #008000)
(Green1 #00ff00) (Green2 #00ee00) (Green3 #00cd00) (Green4 #008b00)
(GreenYellow #adff2f) (Grey #808080) (Grey0 #000000) (Grey1 #030303)
(Grey10 #1a1a1a) (Grey100 #ffffff) (Grey11 #1c1c1c) (Grey12 #1f1f1f)
(Grey13 #212121) (Grey14 #242424) (Grey15 #262626) (Grey16 #292929)
(Grey17 #2b2b2b) (Grey18 #2e2e2e) (Grey19 #303030) (Grey2 #050505)
(Grey20 #333333) (Grey21 #363636) (Grey22 #383838) (Grey23 #3b3b3b)
(Grey24 #3d3d3d) (Grey25 #404040) (Grey26 #424242) (Grey27 #454545)
(Grey28 #474747) (Grey29 #4a4a4a) (Grey3 #080808) (Grey30 #4d4d4d)
(Grey31 #4f4f4f) (Grey32 #525252) (Grey33 #545454) (Grey34 #575757)
(Grey35 #595959) (Grey36 #5c5c5c) (Grey37 #5e5e5e) (Grey38 #616161)
(Grey39 #636363) (Grey4 #0a0a0a) (Grey40 #666666) (Grey41 #696969)
(Grey42 #6b6b6b) (Grey43 #6e6e6e) (Grey44 #707070) (Grey45 #737373)
(Grey46 #757575) (Grey47 #787878) (Grey48 #7a7a7a) (Grey49 #7d7d7d)
(Grey5 #0d0d0d) (Grey50 #7f7f7f) (Grey51 #828282) (Grey52 #858585)
(Grey53 #878787) (Grey54 #8a8a8a) (Grey55 #8c8c8c) (Grey56 #8f8f8f)
(Grey57 #919191) (Grey58 #949494) (Grey59 #969696) (Grey6 #0f0f0f)
(Grey60 #999999) (Grey61 #9c9c9c) (Grey62 #9e9e9e) (Grey63 #a1a1a1)
(Grey64 #a3a3a3) (Grey65 #a6a6a6) (Grey66 #a8a8a8) (Grey67 #ababab)
(Grey68 #adadad) (Grey69 #b0b0b0) (Grey7 #121212) (Grey70 #b3b3b3)
(Grey71 #b5b5b5) (Grey72 #b8b8b8) (Grey73 #bababa) (Grey74 #bdbdbd)
(Grey75 #bfbfbf) (Grey76 #c2c2c2) (Grey77 #c4c4c4) (Grey78 #c7c7c7)
(Grey79 #c9c9c9) (Grey8 #141414) (Grey80 #cccccc) (Grey81 #cfcfcf)
(Grey82 #d1d1d1) (Grey83 #d4d4d4) (Grey84 #d6d6d6) (Grey85 #d9d9d9)
(Grey86 #dbdbdb) (Grey87 #dedede) (Grey88 #e0e0e0) (Grey89 #e3e3e3)
(Grey9 #171717) (Grey90 #e5e5e5) (Grey91 #e8e8e8) (Grey92 #ebebeb)
(Grey93 #ededed) (Grey94 #f0f0f0) (Grey95 #f2f2f2) (Grey96 #f5f5f5)
(Grey97 #f7f7f7) (Grey98 #fafafa) (Grey99 #fcfcfc) (Honeydew #f0fff0)
(Honeydew1 #f0fff0) (Honeydew2 #e0eee0) (Honeydew3 #c1cdc1)
(Honeydew4 #838b83) (HotPink #ff69b4) (HotPink1 #ff6eb4) (HotPink2 #ee6aa7)
(HotPink3 #cd6090) (HotPink4 #8b3a62) (IndianRed #cd5c5c)
(IndianRed1 #ff6a6a) (IndianRed2 #ee6363) (IndianRed3 #cd5555)
(IndianRed4 #8b3a3a) (Indigo #4b0082) (Ivory #fffff0) (Ivory1 #fffff0)
(Ivory2 #eeeee0) (Ivory3 #cdcdc1) (Ivory4 #8b8b83) (Khaki #f0e68c)
(Khaki1 #fff68f) (Khaki2 #eee685) (Khaki3 #cdc673) (Khaki4 #8b864e)
(Lavender #e6e6fa) (LavenderBlush #fff0f5) (LavenderBlush1 #fff0f5)
(LavenderBlush2 #eee0e5) (LavenderBlush3 #cdc1c5) (LavenderBlush4 #8b8386)
(LawnGreen #7cfc00) (LemonChiffon #fffacd) (LemonChiffon1 #fffacd)
(LemonChiffon2 #eee9bf) (LemonChiffon3 #cdc9a5) (LemonChiffon4 #8b8970)
(LightBlue #add8e6) (LightBlue1 #bfefff) (LightBlue2 #b2dfee)
(LightBlue3 #9ac0cd) (LightBlue4 #68838b) (LightCoral #f08080)
(LightCyan #e0ffff) (LightCyan1 #e0ffff) (LightCyan2 #d1eeee)
(LightCyan3 #b4cdcd) (LightCyan4 #7a8b8b) (LightGoldenRodYellow #fafad2)
(LightGoldenrod #eedd82) (LightGoldenrod1 #ffec8b) (LightGoldenrod2 #eedc82)
(LightGoldenrod3 #cdbe70) (LightGoldenrod4 #8b814c) (LightGray #d3d3d3)
(LightGreen #90ee90) (LightGrey #d3d3d3) (LightMagenta #ffbbff)
(LightPink #ffb6c1) (LightPink1 #ffaeb9) (LightPink2 #eea2ad)
(LightPink3 #cd8c95) (LightPink4 #8b5f65) (LightRed #ffbbbb)
(LightSalmon #ffa07a) (LightSalmon1 #ffa07a) (LightSalmon2 #ee9572)
(LightSalmon3 #cd8162) (LightSalmon4 #8b5742) (LightSeaGreen #20b2aa)
(LightSkyBlue #87cefa) (LightSkyBlue1 #b0e2ff) (LightSkyBlue2 #a4d3ee)
(LightSkyBlue3 #8db6cd) (LightSkyBlue4 #607b8b) (LightSlateBlue #8470ff)
(LightSlateGray #778899) (LightSlateGrey #778899) (LightSteelBlue #b0c4de)
(LightSteelBlue1 #cae1ff) (LightSteelBlue2 #bcd2ee)
(LightSteelBlue3 #a2b5cd) (LightSteelBlue4 #6e7b8b) (LightYellow #ffffe0)
(LightYellow1 #ffffe0) (LightYellow2 #eeeed1) (LightYellow3 #cdcdb4)
(LightYellow4 #8b8b7a) (Lime #00ff00) (LimeGreen #32cd32) (Linen #faf0e6)
(Magenta #ff00ff) (Magenta1 #ff00ff) (Magenta2 #ee00ee) (Magenta3 #cd00cd)
(Magenta4 #8b008b) (Maroon #800000) (Maroon1 #ff34b3) (Maroon2 #ee30a7)
(Maroon3 #cd2990) (Maroon4 #8b1c62) (MediumAquamarine #66cdaa)
(MediumBlue #0000cd) (MediumOrchid #ba55d3) (MediumOrchid1 #e066ff)
(MediumOrchid2 #d15fee) (MediumOrchid3 #b452cd) (MediumOrchid4 #7a378b)
(MediumPurple #9370db) (MediumPurple1 #ab82ff) (MediumPurple2 #9f79ee)
(MediumPurple3 #8968cd) (MediumPurple4 #5d478b) (MediumSeaGreen #3cb371)
(MediumSlateBlue #7b68ee) (MediumSpringGreen #00fa9a)
(MediumTurquoise #48d1cc) (MediumVioletRed #c71585) (MidnightBlue #191970)
(MintCream #f5fffa) (MistyRose #ffe4e1) (MistyRose1 #ffe4e1)
(MistyRose2 #eed5d2) (MistyRose3 #cdb7b5) (MistyRose4 #8b7d7b)
(Moccasin #ffe4b5) (NavajoWhite #ffdead) (NavajoWhite1 #ffdead)
(NavajoWhite2 #eecfa1) (NavajoWhite3 #cdb38b) (NavajoWhite4 #8b795e)
(Navy #000080) (NavyBlue #000080) (OldLace #fdf5e6) (Olive #808000)
(OliveDrab #6b8e23) (OliveDrab1 #c0ff3e) (OliveDrab2 #b3ee3a)
(OliveDrab3 #9acd32) (OliveDrab4 #698b22) (Orange #ffa500) (Orange1 #ffa500)
(Orange2 #ee9a00) (Orange3 #cd8500) (Orange4 #8b5a00) (OrangeRed #ff4500)
(OrangeRed1 #ff4500) (OrangeRed2 #ee4000) (OrangeRed3 #cd3700)
(OrangeRed4 #8b2500) (Orchid #da70d6) (Orchid1 #ff83fa) (Orchid2 #ee7ae9)
(Orchid3 #cd69c9) (Orchid4 #8b4789) (PaleGoldenRod #eee8aa)
(PaleGreen #98fb98) (PaleGreen1 #9aff9a) (PaleGreen2 #90ee90)
(PaleGreen3 #7ccd7c) (PaleGreen4 #548b54) (PaleTurquoise #afeeee)
(PaleTurquoise1 #bbffff) (PaleTurquoise2 #aeeeee) (PaleTurquoise3 #96cdcd)
(PaleTurquoise4 #668b8b) (PaleVioletRed #db7093) (PaleVioletRed1 #ff82ab)
(PaleVioletRed2 #ee799f) (PaleVioletRed3 #cd6889) (PaleVioletRed4 #8b475d)
(PapayaWhip #ffefd5) (PeachPuff #ffdab9) (PeachPuff1 #ffdab9)
(PeachPuff2 #eecbad) (PeachPuff3 #cdaf95) (PeachPuff4 #8b7765)
(Peru #cd853f) (Pink #ffc0cb) (Pink1 #ffb5c5) (Pink2 #eea9b8)
(Pink3 #cd919e) (Pink4 #8b636c) (Plum #dda0dd) (Plum1 #ffbbff)
(Plum2 #eeaeee) (Plum3 #cd96cd) (Plum4 #8b668b) (PowderBlue #b0e0e6)
(Purple #800080) (Purple1 #9b30ff) (Purple2 #912cee) (Purple3 #7d26cd)
(Purple4 #551a8b) (RebeccaPurple #663399) (Red #ff0000) (Red1 #ff0000)
(Red2 #ee0000) (Red3 #cd0000) (Red4 #8b0000) (RosyBrown #bc8f8f)
(RosyBrown1 #ffc1c1) (RosyBrown2 #eeb4b4) (RosyBrown3 #cd9b9b)
(RosyBrown4 #8b6969) (RoyalBlue #4169e1) (RoyalBlue1 #4876ff)
(RoyalBlue2 #436eee) (RoyalBlue3 #3a5fcd) (RoyalBlue4 #27408b)
(SaddleBrown #8b4513) (Salmon #fa8072) (Salmon1 #ff8c69) (Salmon2 #ee8262)
(Salmon3 #cd7054) (Salmon4 #8b4c39) (SandyBrown #f4a460) (SeaGreen #2e8b57)
(SeaGreen1 #54ff9f) (SeaGreen2 #4eee94) (SeaGreen3 #43cd80)
(SeaGreen4 #2e8b57) (SeaShell #fff5ee) (Seashell1 #fff5ee)
(Seashell2 #eee5de) (Seashell3 #cdc5bf) (Seashell4 #8b8682) (Sienna #a0522d)
(Sienna1 #ff8247) (Sienna2 #ee7942) (Sienna3 #cd6839) (Sienna4 #8b4726)
(Silver #c0c0c0) (SkyBlue #87ceeb) (SkyBlue1 #87ceff) (SkyBlue2 #7ec0ee)
(SkyBlue3 #6ca6cd) (SkyBlue4 #4a708b) (SlateBlue #6a5acd)
(SlateBlue1 #836fff) (SlateBlue2 #7a67ee) (SlateBlue3 #6959cd)
(SlateBlue4 #473c8b) (SlateGray #708090) (SlateGray1 #c6e2ff)
(SlateGray2 #b9d3ee) (SlateGray3 #9fb6cd) (SlateGray4 #6c7b8b)
(SlateGrey #708090) (Snow #fffafa) (Snow1 #fffafa) (Snow2 #eee9e9)
(Snow3 #cdc9c9) (Snow4 #8b8989) (SpringGreen #00ff7f) (SpringGreen1 #00ff7f)
(SpringGreen2 #00ee76) (SpringGreen3 #00cd66) (SpringGreen4 #008b45)
(SteelBlue #4682b4) (SteelBlue1 #63b8ff) (SteelBlue2 #5cacee)
(SteelBlue3 #4f94cd) (SteelBlue4 #36648b) (Tan #d2b48c) (Tan1 #ffa54f)
(Tan2 #ee9a49) (Tan3 #cd853f) (Tan4 #8b5a2b) (Teal #008080)
(Thistle #d8bfd8) (Thistle1 #ffe1ff) (Thistle2 #eed2ee) (Thistle3 #cdb5cd)
(Thistle4 #8b7b8b) (Tomato #ff6347) (Tomato1 #ff6347) (Tomato2 #ee5c42)
(Tomato3 #cd4f39) (Tomato4 #8b3626) (Turquoise #40e0d0) (Turquoise1 #00f5ff)
(Turquoise2 #00e5ee) (Turquoise3 #00c5cd) (Turquoise4 #00868b)
(Violet #ee82ee) (VioletRed #d02090) (VioletRed1 #ff3e96)
(VioletRed2 #ee3a8c) (VioletRed3 #cd3278) (VioletRed4 #8b2252)
(WebGray #808080) (WebGreen #008000) (WebGrey #808080) (WebMaroon #800000)
(WebPurple #800080) (Wheat #f5deb3) (Wheat1 #ffe7ba) (Wheat2 #eed8ae)
(Wheat3 #cdba96) (Wheat4 #8b7e66) (White #ffffff) (WhiteSmoke #f5f5f5)
(X11Gray #bebebe) (X11Green #00ff00) (X11Grey #bebebe) (X11Maroon #b03060)
(X11Purple #a020f0) (Yellow #ffff00) (Yellow1 #ffff00) (Yellow2 #eeee00)
(Yellow3 #cdcd00) (Yellow4 #8b8b00) (YellowGreen #9acd32)) |}];
return ()
;;
let%expect_test "get_hl_by_name" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind color256 =
Nvim.get_hl_by_name "ErrorMsg" ~color:Color256 |> run_join [%here] client
in
let%bind true_color =
Nvim.get_hl_by_name "ErrorMsg" ~color:True_color |> run_join [%here] client
in
let open Color in
print_s
[%message
(color256 : Color256.t Highlight.t) (true_color : True_color.t Highlight.t)];
return ())
in
[%expect
{|
((color256 ((fg 15) (bg 1))) (true_color ((fg #ffffff) (bg #ff0000)))) |}];
return ()
;;
let%expect_test "get_hl_by_id" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let get_hl_id =
wrap_viml_function
~type_:Defun.Vim.(String @-> return Integer)
~function_name:"hlID"
in
let%bind hl_id = get_hl_id "ErrorMsg" |> run_join [%here] client in
let%bind color256 =
Nvim.get_hl_by_id hl_id ~color:Color256 |> run_join [%here] client
in
let%bind true_color =
Nvim.get_hl_by_id hl_id ~color:True_color |> run_join [%here] client
in
let open Color in
print_s
[%message
(color256 : Color256.t Highlight.t) (true_color : True_color.t Highlight.t)];
return ())
in
[%expect
{|
((color256 ((fg 15) (bg 1))) (true_color ((fg #ffffff) (bg #ff0000)))) |}];
return ()
;;
let%expect_test "Check that all modes documented in the help are covered by [Mode.t]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "h mode()" |> run_join [%here] client in
let feedkeys keys =
let%bind keys =
Nvim.replace_termcodes_and_keycodes keys |> run_join [%here] client
in
Nvim.feedkeys (`Already_escaped keys) ~mode:"n" |> run_join [%here] client
in
let%bind () = feedkeys "}jy}<C-w>np<C-w>o" in
let%bind lines =
Buffer.get_lines Current ~start:1 ~end_:(-1) ~strict_indexing:true
|> run_join [%here] client
in
let modes_in_help, new_modes =
lines
|> List.filter ~f:(Fn.non (String.is_prefix ~prefix:"\t\t\t\t"))
|> List.partition_map ~f:(fun line ->
let lsplit2_whitespace_exn str =
let is_space_or_tab = function
| ' ' | '\t' -> true
| _ -> false
in
let end_of_first_word =
String.lfindi str ~f:(fun _ -> is_space_or_tab) |> Option.value_exn
in
let start_of_second_word =
String.lfindi str ~pos:end_of_first_word ~f:(fun _ ->
Fn.non is_space_or_tab)
|> Option.value_exn
in
let word1 = String.subo str ~len:end_of_first_word in
let word2 = String.subo str ~pos:start_of_second_word in
word1, word2
in
let symbol, description =
line |> String.strip |> lsplit2_whitespace_exn
in
let symbol =
match String.substr_index symbol ~pattern:"CTRL-" with
| None -> symbol
| Some idx ->
let ctrl_char =
symbol.[idx + 5]
|> Char.to_int
|> (fun c -> c - Char.to_int '@')
|> Char.of_int_exn
|> String.of_char
in
[ String.subo symbol ~len:idx
; ctrl_char
; String.subo symbol ~pos:(idx + 6)
]
|> String.concat ~sep:""
in
match Mode.of_mode_symbol symbol with
| Ok mode -> First mode
| Error _ -> Second (symbol, description))
in
let modes_in_help = modes_in_help |> Mode.Set.of_list in
let all_modes = Mode.all |> Mode.Set.of_list in
let removed_modes = Set.diff all_modes modes_in_help in
print_s [%message "New modes" ~_:(new_modes : (string * string) list)];
print_s [%message "Removed modes" ~_:(removed_modes : Mode.Set.t)];
[%expect {|
("New modes" ())
("Removed modes" ()) |}];
return ())
in
[%expect {||}];
return ()
;;
let%expect_test "Get and set variables" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%map result =
run_join
[%here]
client
(let open Api_call.Or_error.Let_syntax in
let%map () = Nvim.set_var "foo" ~type_:String ~value:"Hello"
and value = Nvim.get_var "foo" ~type_:String in
value)
in
print_s [%message result])
in
[%expect {| Hello |}];
return ()
;;
module _ = struct
module Nvim = Nvim.Fast
let%expect_test "[get_mode] and [input]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let input keys =
let%bind bytes_written = Nvim.input keys |> run_join [%here] client in
assert (bytes_written = String.length keys);
let%map mode = Nvim.get_mode |> run_join [%here] client in
print_s [%message keys ~_:(mode : Mode.With_blocking_info.t)]
in
let%bind () = input "g" in
let%bind () = input "<Esc>" in
let%bind () = input "itest" in
let%bind () = input "<C-o>" in
let%bind () = input "<Esc>" in
let%bind () = input "<Esc>r" in
let%bind () = input "<Esc>V" in
let%bind () = input "<Esc><C-v>" in
let%bind () = input "<Esc>gR" in
let%bind () = input "<Esc>:" in
return ())
in
[%expect
{|
(g ((mode Normal) (blocking true)))
(<Esc> ((mode Normal) (blocking false)))
(itest ((mode Insert) (blocking false)))
(<C-o> ((mode Normal_using_i_ctrl_o_in_insert_mode) (blocking false)))
(<Esc> ((mode Insert) (blocking false)))
(<Esc>r ((mode Replace) (blocking true)))
(<Esc>V ((mode Visual_by_line) (blocking false)))
(<Esc><C-v> ((mode Visual_blockwise) (blocking false)))
(<Esc>gR ((mode Virtual_replace) (blocking false)))
(<Esc>: ((mode Command_line_editing) (blocking false))) |}];
return ()
;;
let%expect_test "[paste]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.paste [ "hello"; "world!" ] |> run_join [%here] client in
let%bind lines =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
let%bind cursor_pos = Window.get_cursor Current |> run_join [%here] client in
print_s [%message (lines : string list)];
print_s [%message (cursor_pos : Position.One_indexed_row.t)];
return ())
in
[%expect {|
(lines (hello world!))
(cursor_pos ((row 2) (col 5))) |}];
return ()
;;
let%expect_test "[paste_stream]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let writer, flushed = Nvim.paste_stream [%here] client in
let%bind () = Pipe.write writer "hello\n" |> Deferred.ok in
let%bind () = Pipe.write writer "world!" |> Deferred.ok in
Pipe.close writer;
let%bind () = flushed in
let%bind lines =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
let%bind cursor_pos = Window.get_cursor Current |> run_join [%here] client in
print_s [%message (lines : string list)];
print_s [%message (cursor_pos : Position.One_indexed_row.t)];
return ())
in
[%expect {|
(lines (hello world!))
(cursor_pos ((row 2) (col 5))) |}];
return ()
;;
(* This behavior is perhaps surprising. *)
let%expect_test "API calls work while a [paste_stream] is open" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () =
Vcaml.Nvim.Untested.set_option "hidden" ~type_:Boolean ~value:true
|> run_join [%here] client
in
let get_lines () =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
let switch_buffers buffer =
let%map.Deferred result =
Vcaml.Nvim.set_current_buf buffer |> run_join [%here] client
in
match result with
| Ok () -> print_s [%message "Switched buffers!" (buffer : Buffer.t)]
| Error error -> print_s [%sexp (error : Error.t)]
in
let writer, flushed = Nvim.paste_stream [%here] client in
let%bind () = Pipe.write writer "hello\n" |> Deferred.ok in
let%bind lines = get_lines () in
print_s [%sexp (lines : string list)];
let%bind alt_buf =
Buffer.create ~listed:true ~scratch:false |> run_join [%here] client
in
let%bind () = switch_buffers alt_buf |> Deferred.ok in
let%bind () = Pipe.write writer "world!" |> Deferred.ok in
Pipe.close writer;
let%bind () = flushed in
let%bind lines = get_lines () in
print_s [%sexp (lines : string list)];
return ())
in
[%expect {|
(hello "")
("Switched buffers!" (buffer 2))
(world!) |}];
return ()
;;
end
| null | https://raw.githubusercontent.com/janestreet/vcaml/64d205c2d6eee4a7e57abd2d452f5979dc6cd797/test/bindings/test_nvim.ml | ocaml | This behavior is perhaps surprising. | open Core
open Async
open Vcaml
open Vcaml_test_helpers
let%expect_test "open neovim and get channel list" =
let%bind () =
simple [%here] Nvim.channels (fun channels ->
channels |> List.length > 0 |> sexp_of_bool)
in
[%expect "true"];
return ()
;;
let%expect_test "get_channel_info" =
let%bind () =
simple [%here] (Nvim.get_channel_info 1) ("call-succeeded" |> Sexp.Atom |> Fn.const)
in
[%expect "call-succeeded"];
return ()
;;
let%expect_test "command output" =
let%bind () = simple [%here] (Nvim.source "echo 'hi'") sexp_of_string in
[%expect "hi"];
return ()
;;
let%expect_test "command, list_bufs, Buffer.get_name" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "e foo.txt" |> run_join [%here] client in
let%bind () = Nvim.command "e bar.txt" |> run_join [%here] client in
let%bind () = Nvim.command "e baz.txt" |> run_join [%here] client in
let%bind buffers = Nvim.list_bufs |> run_join [%here] client in
let%map buffer_names =
buffers
|> List.map ~f:(fun buffer ->
Buffer.get_name (Id buffer) |> run_join [%here] client)
|> Deferred.Or_error.combine_errors
|> Deferred.Or_error.map ~f:(fun filenames ->
List.map filenames ~f:(fun file ->
file |> Filename.parts |> List.last_exn))
in
print_s [%message (buffers : Buffer.t list) (buffer_names : string list)])
in
[%expect {|
((buffers (1 2 3)) (buffer_names (foo.txt bar.txt baz.txt)))|}];
return ()
;;
let%expect_test "eval" =
let%bind () = simple [%here] (Nvim.eval "1 + 2" ~result_type:Integer) [%sexp_of: int] in
[%expect {| 3 |}];
return ()
;;
let%expect_test "set_current_buf" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "e foo.txt" |> run_join [%here] client in
let%bind expected_buf = Nvim.get_current_buf |> run_join [%here] client in
let%bind () = Nvim.command "e bar.txt" |> run_join [%here] client in
let%bind () = Nvim.set_current_buf expected_buf |> run_join [%here] client in
let%bind actual_buf = Nvim.get_current_buf |> run_join [%here] client in
print_s [%message (expected_buf : Buffer.t) (actual_buf : Buffer.t)];
return ())
in
[%expect "((expected_buf 1) (actual_buf 1))"];
return ()
;;
let%expect_test "set_client_info" =
let test_method =
{ Client_info.Client_method.async = false; nargs = Some (`Fixed 1) }
in
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
The initial setting happens when a VCaml client connects to Neovim .
let get_client_info () =
let%map.Deferred.Or_error channels = run_join [%here] client Nvim.channels in
let channel = List.hd_exn channels in
channel.client
in
let%bind client_before_setting_info = get_client_info () in
let%bind () =
Nvim.set_client_info
~version:
{ major = Some 1
; minor = Some 2
; patch = Some 3
; prerelease = Some "test_prerelease"
; commit = Some "test_commit"
}
~methods:(String.Map.of_alist_exn [ "test_method", test_method ])
~attributes:(String.Map.of_alist_exn [ "attr1", "val1" ])
~name:"foo"
~type_:`Embedder
()
|> run_join [%here] client
in
let%bind client_after_setting_info = get_client_info () in
print_s
[%message
(client_before_setting_info : Client_info.t option)
(client_after_setting_info : Client_info.t option)];
return ())
in
[%expect
{|
((client_before_setting_info
(((version
(((major (0)) (minor ()) (patch ()) (prerelease ()) (commit ()))))
(methods ()) (attributes ()) (name (<uuid-omitted-in-test>))
(type_ (Remote)))))
(client_after_setting_info
(((version
(((major (1)) (minor (2)) (patch (3)) (prerelease (test_prerelease))
(commit (test_commit)))))
(methods ((test_method ((async false) (nargs ((Fixed 1)))))))
(attributes ((attr1 val1))) (name (foo)) (type_ (Embedder))))))|}];
return ()
;;
let%expect_test "get_current_win, set_current_win" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind original_win = Nvim.get_current_win |> run_join [%here] client in
let%bind () = Nvim.command "split" |> run_join [%here] client in
let%bind win_after_split = Nvim.get_current_win |> run_join [%here] client in
let%bind () = Nvim.set_current_win original_win |> run_join [%here] client in
let%bind win_after_set = run_join [%here] client Nvim.get_current_win in
print_s
[%message
(original_win : Window.t)
(win_after_split : Window.t)
(win_after_set : Window.t)];
return ())
in
[%expect "((original_win 1000) (win_after_split 1001) (win_after_set 1000))"];
return ()
;;
let%expect_test "list_wins" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "split" |> run_join [%here] client in
let%bind () = Nvim.command "split" |> run_join [%here] client in
let%bind win_list = Nvim.list_wins |> run_join [%here] client in
print_s [%message (win_list : Window.t list)];
return ())
in
[%expect "(win_list (1002 1001 1000))"];
return ()
;;
let%expect_test "replace_termcodes" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind escaped_keys =
Nvim.replace_termcodes_and_keycodes "ifoobar<ESC><Left><Left>XXX"
|> run_join [%here] client
in
let%bind () =
Nvim.feedkeys (`Already_escaped escaped_keys) ~mode:"n"
|> run_join [%here] client
in
let%bind lines =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
print_s [%message (lines : string list)];
return ())
in
[%expect {| (lines (bar)) |}];
return ()
;;
let%expect_test "get_color_by_name" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind color = Nvim.get_color_by_name "#f0f8ff" |> run_join [%here] client in
print_s [%sexp (color : Color.True_color.t)];
let%bind color = Nvim.get_color_by_name "AliceBlue" |> run_join [%here] client in
print_s [%sexp (color : Color.True_color.t)];
return ())
in
[%expect {|
#f0f8ff
#f0f8ff |}];
return ()
;;
let%expect_test "color_map" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind color_map = Nvim.get_color_map |> run_join [%here] client in
print_s [%sexp (color_map : Color.True_color.t String.Map.t)];
return ())
in
[%expect
{|
((AliceBlue #f0f8ff) (AntiqueWhite #faebd7) (AntiqueWhite1 #ffefdb)
(AntiqueWhite2 #eedfcc) (AntiqueWhite3 #cdc0b0) (AntiqueWhite4 #8b8378)
(Aqua #00ffff) (Aquamarine #7fffd4) (Aquamarine1 #7fffd4)
(Aquamarine2 #76eec6) (Aquamarine3 #66cdaa) (Aquamarine4 #458b74)
(Azure #f0ffff) (Azure1 #f0ffff) (Azure2 #e0eeee) (Azure3 #c1cdcd)
(Azure4 #838b8b) (Beige #f5f5dc) (Bisque #ffe4c4) (Bisque1 #ffe4c4)
(Bisque2 #eed5b7) (Bisque3 #cdb79e) (Bisque4 #8b7d6b) (Black #000000)
(BlanchedAlmond #ffebcd) (Blue #0000ff) (Blue1 #0000ff) (Blue2 #0000ee)
(Blue3 #0000cd) (Blue4 #00008b) (BlueViolet #8a2be2) (Brown #a52a2a)
(Brown1 #ff4040) (Brown2 #ee3b3b) (Brown3 #cd3333) (Brown4 #8b2323)
(BurlyWood #deb887) (Burlywood1 #ffd39b) (Burlywood2 #eec591)
(Burlywood3 #cdaa7d) (Burlywood4 #8b7355) (CadetBlue #5f9ea0)
(CadetBlue1 #98f5ff) (CadetBlue2 #8ee5ee) (CadetBlue3 #7ac5cd)
(CadetBlue4 #53868b) (ChartReuse #7fff00) (Chartreuse1 #7fff00)
(Chartreuse2 #76ee00) (Chartreuse3 #66cd00) (Chartreuse4 #458b00)
(Chocolate #d2691e) (Chocolate1 #ff7f24) (Chocolate2 #ee7621)
(Chocolate3 #cd661d) (Chocolate4 #8b4513) (Coral #ff7f50) (Coral1 #ff7256)
(Coral2 #ee6a50) (Coral3 #cd5b45) (Coral4 #8b3e2f) (CornFlowerBlue #6495ed)
(Cornsilk #fff8dc) (Cornsilk1 #fff8dc) (Cornsilk2 #eee8cd)
(Cornsilk3 #cdc8b1) (Cornsilk4 #8b8878) (Crimson #dc143c) (Cyan #00ffff)
(Cyan1 #00ffff) (Cyan2 #00eeee) (Cyan3 #00cdcd) (Cyan4 #008b8b)
(DarkBlue #00008b) (DarkCyan #008b8b) (DarkGoldenRod #b8860b)
(DarkGoldenrod1 #ffb90f) (DarkGoldenrod2 #eead0e) (DarkGoldenrod3 #cd950c)
(DarkGoldenrod4 #8b6508) (DarkGray #a9a9a9) (DarkGreen #006400)
(DarkGrey #a9a9a9) (DarkKhaki #bdb76b) (DarkMagenta #8b008b)
(DarkOliveGreen #556b2f) (DarkOliveGreen1 #caff70) (DarkOliveGreen2 #bcee68)
(DarkOliveGreen3 #a2cd5a) (DarkOliveGreen4 #6e8b3d) (DarkOrange #ff8c00)
(DarkOrange1 #ff7f00) (DarkOrange2 #ee7600) (DarkOrange3 #cd6600)
(DarkOrange4 #8b4500) (DarkOrchid #9932cc) (DarkOrchid1 #bf3eff)
(DarkOrchid2 #b23aee) (DarkOrchid3 #9a32cd) (DarkOrchid4 #68228b)
(DarkRed #8b0000) (DarkSalmon #e9967a) (DarkSeaGreen #8fbc8f)
(DarkSeaGreen1 #c1ffc1) (DarkSeaGreen2 #b4eeb4) (DarkSeaGreen3 #9bcd9b)
(DarkSeaGreen4 #698b69) (DarkSlateBlue #483d8b) (DarkSlateGray #2f4f4f)
(DarkSlateGray1 #97ffff) (DarkSlateGray2 #8deeee) (DarkSlateGray3 #79cdcd)
(DarkSlateGray4 #528b8b) (DarkSlateGrey #2f4f4f) (DarkTurquoise #00ced1)
(DarkViolet #9400d3) (DarkYellow #bbbb00) (DeepPink #ff1493)
(DeepPink1 #ff1493) (DeepPink2 #ee1289) (DeepPink3 #cd1076)
(DeepPink4 #8b0a50) (DeepSkyBlue #00bfff) (DeepSkyBlue1 #00bfff)
(DeepSkyBlue2 #00b2ee) (DeepSkyBlue3 #009acd) (DeepSkyBlue4 #00688b)
(DimGray #696969) (DimGrey #696969) (DodgerBlue #1e90ff)
(DodgerBlue1 #1e90ff) (DodgerBlue2 #1c86ee) (DodgerBlue3 #1874cd)
(DodgerBlue4 #104e8b) (Firebrick #b22222) (Firebrick1 #ff3030)
(Firebrick2 #ee2c2c) (Firebrick3 #cd2626) (Firebrick4 #8b1a1a)
(FloralWhite #fffaf0) (ForestGreen #228b22) (Fuchsia #ff00ff)
(Gainsboro #dcdcdc) (GhostWhite #f8f8ff) (Gold #ffd700) (Gold1 #ffd700)
(Gold2 #eec900) (Gold3 #cdad00) (Gold4 #8b7500) (GoldenRod #daa520)
(Goldenrod1 #ffc125) (Goldenrod2 #eeb422) (Goldenrod3 #cd9b1d)
(Goldenrod4 #8b6914) (Gray #808080) (Gray0 #000000) (Gray1 #030303)
(Gray10 #1a1a1a) (Gray100 #ffffff) (Gray11 #1c1c1c) (Gray12 #1f1f1f)
(Gray13 #212121) (Gray14 #242424) (Gray15 #262626) (Gray16 #292929)
(Gray17 #2b2b2b) (Gray18 #2e2e2e) (Gray19 #303030) (Gray2 #050505)
(Gray20 #333333) (Gray21 #363636) (Gray22 #383838) (Gray23 #3b3b3b)
(Gray24 #3d3d3d) (Gray25 #404040) (Gray26 #424242) (Gray27 #454545)
(Gray28 #474747) (Gray29 #4a4a4a) (Gray3 #080808) (Gray30 #4d4d4d)
(Gray31 #4f4f4f) (Gray32 #525252) (Gray33 #545454) (Gray34 #575757)
(Gray35 #595959) (Gray36 #5c5c5c) (Gray37 #5e5e5e) (Gray38 #616161)
(Gray39 #636363) (Gray4 #0a0a0a) (Gray40 #666666) (Gray41 #696969)
(Gray42 #6b6b6b) (Gray43 #6e6e6e) (Gray44 #707070) (Gray45 #737373)
(Gray46 #757575) (Gray47 #787878) (Gray48 #7a7a7a) (Gray49 #7d7d7d)
(Gray5 #0d0d0d) (Gray50 #7f7f7f) (Gray51 #828282) (Gray52 #858585)
(Gray53 #878787) (Gray54 #8a8a8a) (Gray55 #8c8c8c) (Gray56 #8f8f8f)
(Gray57 #919191) (Gray58 #949494) (Gray59 #969696) (Gray6 #0f0f0f)
(Gray60 #999999) (Gray61 #9c9c9c) (Gray62 #9e9e9e) (Gray63 #a1a1a1)
(Gray64 #a3a3a3) (Gray65 #a6a6a6) (Gray66 #a8a8a8) (Gray67 #ababab)
(Gray68 #adadad) (Gray69 #b0b0b0) (Gray7 #121212) (Gray70 #b3b3b3)
(Gray71 #b5b5b5) (Gray72 #b8b8b8) (Gray73 #bababa) (Gray74 #bdbdbd)
(Gray75 #bfbfbf) (Gray76 #c2c2c2) (Gray77 #c4c4c4) (Gray78 #c7c7c7)
(Gray79 #c9c9c9) (Gray8 #141414) (Gray80 #cccccc) (Gray81 #cfcfcf)
(Gray82 #d1d1d1) (Gray83 #d4d4d4) (Gray84 #d6d6d6) (Gray85 #d9d9d9)
(Gray86 #dbdbdb) (Gray87 #dedede) (Gray88 #e0e0e0) (Gray89 #e3e3e3)
(Gray9 #171717) (Gray90 #e5e5e5) (Gray91 #e8e8e8) (Gray92 #ebebeb)
(Gray93 #ededed) (Gray94 #f0f0f0) (Gray95 #f2f2f2) (Gray96 #f5f5f5)
(Gray97 #f7f7f7) (Gray98 #fafafa) (Gray99 #fcfcfc) (Green #008000)
(Green1 #00ff00) (Green2 #00ee00) (Green3 #00cd00) (Green4 #008b00)
(GreenYellow #adff2f) (Grey #808080) (Grey0 #000000) (Grey1 #030303)
(Grey10 #1a1a1a) (Grey100 #ffffff) (Grey11 #1c1c1c) (Grey12 #1f1f1f)
(Grey13 #212121) (Grey14 #242424) (Grey15 #262626) (Grey16 #292929)
(Grey17 #2b2b2b) (Grey18 #2e2e2e) (Grey19 #303030) (Grey2 #050505)
(Grey20 #333333) (Grey21 #363636) (Grey22 #383838) (Grey23 #3b3b3b)
(Grey24 #3d3d3d) (Grey25 #404040) (Grey26 #424242) (Grey27 #454545)
(Grey28 #474747) (Grey29 #4a4a4a) (Grey3 #080808) (Grey30 #4d4d4d)
(Grey31 #4f4f4f) (Grey32 #525252) (Grey33 #545454) (Grey34 #575757)
(Grey35 #595959) (Grey36 #5c5c5c) (Grey37 #5e5e5e) (Grey38 #616161)
(Grey39 #636363) (Grey4 #0a0a0a) (Grey40 #666666) (Grey41 #696969)
(Grey42 #6b6b6b) (Grey43 #6e6e6e) (Grey44 #707070) (Grey45 #737373)
(Grey46 #757575) (Grey47 #787878) (Grey48 #7a7a7a) (Grey49 #7d7d7d)
(Grey5 #0d0d0d) (Grey50 #7f7f7f) (Grey51 #828282) (Grey52 #858585)
(Grey53 #878787) (Grey54 #8a8a8a) (Grey55 #8c8c8c) (Grey56 #8f8f8f)
(Grey57 #919191) (Grey58 #949494) (Grey59 #969696) (Grey6 #0f0f0f)
(Grey60 #999999) (Grey61 #9c9c9c) (Grey62 #9e9e9e) (Grey63 #a1a1a1)
(Grey64 #a3a3a3) (Grey65 #a6a6a6) (Grey66 #a8a8a8) (Grey67 #ababab)
(Grey68 #adadad) (Grey69 #b0b0b0) (Grey7 #121212) (Grey70 #b3b3b3)
(Grey71 #b5b5b5) (Grey72 #b8b8b8) (Grey73 #bababa) (Grey74 #bdbdbd)
(Grey75 #bfbfbf) (Grey76 #c2c2c2) (Grey77 #c4c4c4) (Grey78 #c7c7c7)
(Grey79 #c9c9c9) (Grey8 #141414) (Grey80 #cccccc) (Grey81 #cfcfcf)
(Grey82 #d1d1d1) (Grey83 #d4d4d4) (Grey84 #d6d6d6) (Grey85 #d9d9d9)
(Grey86 #dbdbdb) (Grey87 #dedede) (Grey88 #e0e0e0) (Grey89 #e3e3e3)
(Grey9 #171717) (Grey90 #e5e5e5) (Grey91 #e8e8e8) (Grey92 #ebebeb)
(Grey93 #ededed) (Grey94 #f0f0f0) (Grey95 #f2f2f2) (Grey96 #f5f5f5)
(Grey97 #f7f7f7) (Grey98 #fafafa) (Grey99 #fcfcfc) (Honeydew #f0fff0)
(Honeydew1 #f0fff0) (Honeydew2 #e0eee0) (Honeydew3 #c1cdc1)
(Honeydew4 #838b83) (HotPink #ff69b4) (HotPink1 #ff6eb4) (HotPink2 #ee6aa7)
(HotPink3 #cd6090) (HotPink4 #8b3a62) (IndianRed #cd5c5c)
(IndianRed1 #ff6a6a) (IndianRed2 #ee6363) (IndianRed3 #cd5555)
(IndianRed4 #8b3a3a) (Indigo #4b0082) (Ivory #fffff0) (Ivory1 #fffff0)
(Ivory2 #eeeee0) (Ivory3 #cdcdc1) (Ivory4 #8b8b83) (Khaki #f0e68c)
(Khaki1 #fff68f) (Khaki2 #eee685) (Khaki3 #cdc673) (Khaki4 #8b864e)
(Lavender #e6e6fa) (LavenderBlush #fff0f5) (LavenderBlush1 #fff0f5)
(LavenderBlush2 #eee0e5) (LavenderBlush3 #cdc1c5) (LavenderBlush4 #8b8386)
(LawnGreen #7cfc00) (LemonChiffon #fffacd) (LemonChiffon1 #fffacd)
(LemonChiffon2 #eee9bf) (LemonChiffon3 #cdc9a5) (LemonChiffon4 #8b8970)
(LightBlue #add8e6) (LightBlue1 #bfefff) (LightBlue2 #b2dfee)
(LightBlue3 #9ac0cd) (LightBlue4 #68838b) (LightCoral #f08080)
(LightCyan #e0ffff) (LightCyan1 #e0ffff) (LightCyan2 #d1eeee)
(LightCyan3 #b4cdcd) (LightCyan4 #7a8b8b) (LightGoldenRodYellow #fafad2)
(LightGoldenrod #eedd82) (LightGoldenrod1 #ffec8b) (LightGoldenrod2 #eedc82)
(LightGoldenrod3 #cdbe70) (LightGoldenrod4 #8b814c) (LightGray #d3d3d3)
(LightGreen #90ee90) (LightGrey #d3d3d3) (LightMagenta #ffbbff)
(LightPink #ffb6c1) (LightPink1 #ffaeb9) (LightPink2 #eea2ad)
(LightPink3 #cd8c95) (LightPink4 #8b5f65) (LightRed #ffbbbb)
(LightSalmon #ffa07a) (LightSalmon1 #ffa07a) (LightSalmon2 #ee9572)
(LightSalmon3 #cd8162) (LightSalmon4 #8b5742) (LightSeaGreen #20b2aa)
(LightSkyBlue #87cefa) (LightSkyBlue1 #b0e2ff) (LightSkyBlue2 #a4d3ee)
(LightSkyBlue3 #8db6cd) (LightSkyBlue4 #607b8b) (LightSlateBlue #8470ff)
(LightSlateGray #778899) (LightSlateGrey #778899) (LightSteelBlue #b0c4de)
(LightSteelBlue1 #cae1ff) (LightSteelBlue2 #bcd2ee)
(LightSteelBlue3 #a2b5cd) (LightSteelBlue4 #6e7b8b) (LightYellow #ffffe0)
(LightYellow1 #ffffe0) (LightYellow2 #eeeed1) (LightYellow3 #cdcdb4)
(LightYellow4 #8b8b7a) (Lime #00ff00) (LimeGreen #32cd32) (Linen #faf0e6)
(Magenta #ff00ff) (Magenta1 #ff00ff) (Magenta2 #ee00ee) (Magenta3 #cd00cd)
(Magenta4 #8b008b) (Maroon #800000) (Maroon1 #ff34b3) (Maroon2 #ee30a7)
(Maroon3 #cd2990) (Maroon4 #8b1c62) (MediumAquamarine #66cdaa)
(MediumBlue #0000cd) (MediumOrchid #ba55d3) (MediumOrchid1 #e066ff)
(MediumOrchid2 #d15fee) (MediumOrchid3 #b452cd) (MediumOrchid4 #7a378b)
(MediumPurple #9370db) (MediumPurple1 #ab82ff) (MediumPurple2 #9f79ee)
(MediumPurple3 #8968cd) (MediumPurple4 #5d478b) (MediumSeaGreen #3cb371)
(MediumSlateBlue #7b68ee) (MediumSpringGreen #00fa9a)
(MediumTurquoise #48d1cc) (MediumVioletRed #c71585) (MidnightBlue #191970)
(MintCream #f5fffa) (MistyRose #ffe4e1) (MistyRose1 #ffe4e1)
(MistyRose2 #eed5d2) (MistyRose3 #cdb7b5) (MistyRose4 #8b7d7b)
(Moccasin #ffe4b5) (NavajoWhite #ffdead) (NavajoWhite1 #ffdead)
(NavajoWhite2 #eecfa1) (NavajoWhite3 #cdb38b) (NavajoWhite4 #8b795e)
(Navy #000080) (NavyBlue #000080) (OldLace #fdf5e6) (Olive #808000)
(OliveDrab #6b8e23) (OliveDrab1 #c0ff3e) (OliveDrab2 #b3ee3a)
(OliveDrab3 #9acd32) (OliveDrab4 #698b22) (Orange #ffa500) (Orange1 #ffa500)
(Orange2 #ee9a00) (Orange3 #cd8500) (Orange4 #8b5a00) (OrangeRed #ff4500)
(OrangeRed1 #ff4500) (OrangeRed2 #ee4000) (OrangeRed3 #cd3700)
(OrangeRed4 #8b2500) (Orchid #da70d6) (Orchid1 #ff83fa) (Orchid2 #ee7ae9)
(Orchid3 #cd69c9) (Orchid4 #8b4789) (PaleGoldenRod #eee8aa)
(PaleGreen #98fb98) (PaleGreen1 #9aff9a) (PaleGreen2 #90ee90)
(PaleGreen3 #7ccd7c) (PaleGreen4 #548b54) (PaleTurquoise #afeeee)
(PaleTurquoise1 #bbffff) (PaleTurquoise2 #aeeeee) (PaleTurquoise3 #96cdcd)
(PaleTurquoise4 #668b8b) (PaleVioletRed #db7093) (PaleVioletRed1 #ff82ab)
(PaleVioletRed2 #ee799f) (PaleVioletRed3 #cd6889) (PaleVioletRed4 #8b475d)
(PapayaWhip #ffefd5) (PeachPuff #ffdab9) (PeachPuff1 #ffdab9)
(PeachPuff2 #eecbad) (PeachPuff3 #cdaf95) (PeachPuff4 #8b7765)
(Peru #cd853f) (Pink #ffc0cb) (Pink1 #ffb5c5) (Pink2 #eea9b8)
(Pink3 #cd919e) (Pink4 #8b636c) (Plum #dda0dd) (Plum1 #ffbbff)
(Plum2 #eeaeee) (Plum3 #cd96cd) (Plum4 #8b668b) (PowderBlue #b0e0e6)
(Purple #800080) (Purple1 #9b30ff) (Purple2 #912cee) (Purple3 #7d26cd)
(Purple4 #551a8b) (RebeccaPurple #663399) (Red #ff0000) (Red1 #ff0000)
(Red2 #ee0000) (Red3 #cd0000) (Red4 #8b0000) (RosyBrown #bc8f8f)
(RosyBrown1 #ffc1c1) (RosyBrown2 #eeb4b4) (RosyBrown3 #cd9b9b)
(RosyBrown4 #8b6969) (RoyalBlue #4169e1) (RoyalBlue1 #4876ff)
(RoyalBlue2 #436eee) (RoyalBlue3 #3a5fcd) (RoyalBlue4 #27408b)
(SaddleBrown #8b4513) (Salmon #fa8072) (Salmon1 #ff8c69) (Salmon2 #ee8262)
(Salmon3 #cd7054) (Salmon4 #8b4c39) (SandyBrown #f4a460) (SeaGreen #2e8b57)
(SeaGreen1 #54ff9f) (SeaGreen2 #4eee94) (SeaGreen3 #43cd80)
(SeaGreen4 #2e8b57) (SeaShell #fff5ee) (Seashell1 #fff5ee)
(Seashell2 #eee5de) (Seashell3 #cdc5bf) (Seashell4 #8b8682) (Sienna #a0522d)
(Sienna1 #ff8247) (Sienna2 #ee7942) (Sienna3 #cd6839) (Sienna4 #8b4726)
(Silver #c0c0c0) (SkyBlue #87ceeb) (SkyBlue1 #87ceff) (SkyBlue2 #7ec0ee)
(SkyBlue3 #6ca6cd) (SkyBlue4 #4a708b) (SlateBlue #6a5acd)
(SlateBlue1 #836fff) (SlateBlue2 #7a67ee) (SlateBlue3 #6959cd)
(SlateBlue4 #473c8b) (SlateGray #708090) (SlateGray1 #c6e2ff)
(SlateGray2 #b9d3ee) (SlateGray3 #9fb6cd) (SlateGray4 #6c7b8b)
(SlateGrey #708090) (Snow #fffafa) (Snow1 #fffafa) (Snow2 #eee9e9)
(Snow3 #cdc9c9) (Snow4 #8b8989) (SpringGreen #00ff7f) (SpringGreen1 #00ff7f)
(SpringGreen2 #00ee76) (SpringGreen3 #00cd66) (SpringGreen4 #008b45)
(SteelBlue #4682b4) (SteelBlue1 #63b8ff) (SteelBlue2 #5cacee)
(SteelBlue3 #4f94cd) (SteelBlue4 #36648b) (Tan #d2b48c) (Tan1 #ffa54f)
(Tan2 #ee9a49) (Tan3 #cd853f) (Tan4 #8b5a2b) (Teal #008080)
(Thistle #d8bfd8) (Thistle1 #ffe1ff) (Thistle2 #eed2ee) (Thistle3 #cdb5cd)
(Thistle4 #8b7b8b) (Tomato #ff6347) (Tomato1 #ff6347) (Tomato2 #ee5c42)
(Tomato3 #cd4f39) (Tomato4 #8b3626) (Turquoise #40e0d0) (Turquoise1 #00f5ff)
(Turquoise2 #00e5ee) (Turquoise3 #00c5cd) (Turquoise4 #00868b)
(Violet #ee82ee) (VioletRed #d02090) (VioletRed1 #ff3e96)
(VioletRed2 #ee3a8c) (VioletRed3 #cd3278) (VioletRed4 #8b2252)
(WebGray #808080) (WebGreen #008000) (WebGrey #808080) (WebMaroon #800000)
(WebPurple #800080) (Wheat #f5deb3) (Wheat1 #ffe7ba) (Wheat2 #eed8ae)
(Wheat3 #cdba96) (Wheat4 #8b7e66) (White #ffffff) (WhiteSmoke #f5f5f5)
(X11Gray #bebebe) (X11Green #00ff00) (X11Grey #bebebe) (X11Maroon #b03060)
(X11Purple #a020f0) (Yellow #ffff00) (Yellow1 #ffff00) (Yellow2 #eeee00)
(Yellow3 #cdcd00) (Yellow4 #8b8b00) (YellowGreen #9acd32)) |}];
return ()
;;
let%expect_test "get_hl_by_name" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind color256 =
Nvim.get_hl_by_name "ErrorMsg" ~color:Color256 |> run_join [%here] client
in
let%bind true_color =
Nvim.get_hl_by_name "ErrorMsg" ~color:True_color |> run_join [%here] client
in
let open Color in
print_s
[%message
(color256 : Color256.t Highlight.t) (true_color : True_color.t Highlight.t)];
return ())
in
[%expect
{|
((color256 ((fg 15) (bg 1))) (true_color ((fg #ffffff) (bg #ff0000)))) |}];
return ()
;;
let%expect_test "get_hl_by_id" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let get_hl_id =
wrap_viml_function
~type_:Defun.Vim.(String @-> return Integer)
~function_name:"hlID"
in
let%bind hl_id = get_hl_id "ErrorMsg" |> run_join [%here] client in
let%bind color256 =
Nvim.get_hl_by_id hl_id ~color:Color256 |> run_join [%here] client
in
let%bind true_color =
Nvim.get_hl_by_id hl_id ~color:True_color |> run_join [%here] client
in
let open Color in
print_s
[%message
(color256 : Color256.t Highlight.t) (true_color : True_color.t Highlight.t)];
return ())
in
[%expect
{|
((color256 ((fg 15) (bg 1))) (true_color ((fg #ffffff) (bg #ff0000)))) |}];
return ()
;;
let%expect_test "Check that all modes documented in the help are covered by [Mode.t]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.command "h mode()" |> run_join [%here] client in
let feedkeys keys =
let%bind keys =
Nvim.replace_termcodes_and_keycodes keys |> run_join [%here] client
in
Nvim.feedkeys (`Already_escaped keys) ~mode:"n" |> run_join [%here] client
in
let%bind () = feedkeys "}jy}<C-w>np<C-w>o" in
let%bind lines =
Buffer.get_lines Current ~start:1 ~end_:(-1) ~strict_indexing:true
|> run_join [%here] client
in
let modes_in_help, new_modes =
lines
|> List.filter ~f:(Fn.non (String.is_prefix ~prefix:"\t\t\t\t"))
|> List.partition_map ~f:(fun line ->
let lsplit2_whitespace_exn str =
let is_space_or_tab = function
| ' ' | '\t' -> true
| _ -> false
in
let end_of_first_word =
String.lfindi str ~f:(fun _ -> is_space_or_tab) |> Option.value_exn
in
let start_of_second_word =
String.lfindi str ~pos:end_of_first_word ~f:(fun _ ->
Fn.non is_space_or_tab)
|> Option.value_exn
in
let word1 = String.subo str ~len:end_of_first_word in
let word2 = String.subo str ~pos:start_of_second_word in
word1, word2
in
let symbol, description =
line |> String.strip |> lsplit2_whitespace_exn
in
let symbol =
match String.substr_index symbol ~pattern:"CTRL-" with
| None -> symbol
| Some idx ->
let ctrl_char =
symbol.[idx + 5]
|> Char.to_int
|> (fun c -> c - Char.to_int '@')
|> Char.of_int_exn
|> String.of_char
in
[ String.subo symbol ~len:idx
; ctrl_char
; String.subo symbol ~pos:(idx + 6)
]
|> String.concat ~sep:""
in
match Mode.of_mode_symbol symbol with
| Ok mode -> First mode
| Error _ -> Second (symbol, description))
in
let modes_in_help = modes_in_help |> Mode.Set.of_list in
let all_modes = Mode.all |> Mode.Set.of_list in
let removed_modes = Set.diff all_modes modes_in_help in
print_s [%message "New modes" ~_:(new_modes : (string * string) list)];
print_s [%message "Removed modes" ~_:(removed_modes : Mode.Set.t)];
[%expect {|
("New modes" ())
("Removed modes" ()) |}];
return ())
in
[%expect {||}];
return ()
;;
let%expect_test "Get and set variables" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%map result =
run_join
[%here]
client
(let open Api_call.Or_error.Let_syntax in
let%map () = Nvim.set_var "foo" ~type_:String ~value:"Hello"
and value = Nvim.get_var "foo" ~type_:String in
value)
in
print_s [%message result])
in
[%expect {| Hello |}];
return ()
;;
module _ = struct
module Nvim = Nvim.Fast
let%expect_test "[get_mode] and [input]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let input keys =
let%bind bytes_written = Nvim.input keys |> run_join [%here] client in
assert (bytes_written = String.length keys);
let%map mode = Nvim.get_mode |> run_join [%here] client in
print_s [%message keys ~_:(mode : Mode.With_blocking_info.t)]
in
let%bind () = input "g" in
let%bind () = input "<Esc>" in
let%bind () = input "itest" in
let%bind () = input "<C-o>" in
let%bind () = input "<Esc>" in
let%bind () = input "<Esc>r" in
let%bind () = input "<Esc>V" in
let%bind () = input "<Esc><C-v>" in
let%bind () = input "<Esc>gR" in
let%bind () = input "<Esc>:" in
return ())
in
[%expect
{|
(g ((mode Normal) (blocking true)))
(<Esc> ((mode Normal) (blocking false)))
(itest ((mode Insert) (blocking false)))
(<C-o> ((mode Normal_using_i_ctrl_o_in_insert_mode) (blocking false)))
(<Esc> ((mode Insert) (blocking false)))
(<Esc>r ((mode Replace) (blocking true)))
(<Esc>V ((mode Visual_by_line) (blocking false)))
(<Esc><C-v> ((mode Visual_blockwise) (blocking false)))
(<Esc>gR ((mode Virtual_replace) (blocking false)))
(<Esc>: ((mode Command_line_editing) (blocking false))) |}];
return ()
;;
let%expect_test "[paste]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () = Nvim.paste [ "hello"; "world!" ] |> run_join [%here] client in
let%bind lines =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
let%bind cursor_pos = Window.get_cursor Current |> run_join [%here] client in
print_s [%message (lines : string list)];
print_s [%message (cursor_pos : Position.One_indexed_row.t)];
return ())
in
[%expect {|
(lines (hello world!))
(cursor_pos ((row 2) (col 5))) |}];
return ()
;;
let%expect_test "[paste_stream]" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let writer, flushed = Nvim.paste_stream [%here] client in
let%bind () = Pipe.write writer "hello\n" |> Deferred.ok in
let%bind () = Pipe.write writer "world!" |> Deferred.ok in
Pipe.close writer;
let%bind () = flushed in
let%bind lines =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
let%bind cursor_pos = Window.get_cursor Current |> run_join [%here] client in
print_s [%message (lines : string list)];
print_s [%message (cursor_pos : Position.One_indexed_row.t)];
return ())
in
[%expect {|
(lines (hello world!))
(cursor_pos ((row 2) (col 5))) |}];
return ()
;;
let%expect_test "API calls work while a [paste_stream] is open" =
let%bind () =
with_client (fun client ->
let open Deferred.Or_error.Let_syntax in
let%bind () =
Vcaml.Nvim.Untested.set_option "hidden" ~type_:Boolean ~value:true
|> run_join [%here] client
in
let get_lines () =
Buffer.get_lines Current ~start:0 ~end_:(-1) ~strict_indexing:false
|> run_join [%here] client
in
let switch_buffers buffer =
let%map.Deferred result =
Vcaml.Nvim.set_current_buf buffer |> run_join [%here] client
in
match result with
| Ok () -> print_s [%message "Switched buffers!" (buffer : Buffer.t)]
| Error error -> print_s [%sexp (error : Error.t)]
in
let writer, flushed = Nvim.paste_stream [%here] client in
let%bind () = Pipe.write writer "hello\n" |> Deferred.ok in
let%bind lines = get_lines () in
print_s [%sexp (lines : string list)];
let%bind alt_buf =
Buffer.create ~listed:true ~scratch:false |> run_join [%here] client
in
let%bind () = switch_buffers alt_buf |> Deferred.ok in
let%bind () = Pipe.write writer "world!" |> Deferred.ok in
Pipe.close writer;
let%bind () = flushed in
let%bind lines = get_lines () in
print_s [%sexp (lines : string list)];
return ())
in
[%expect {|
(hello "")
("Switched buffers!" (buffer 2))
(world!) |}];
return ()
;;
end
|
5184dfeb93055cb4ba910b575297fc442d94f3b3e72944beec4d7da8b3f1923a | Bogdanp/racket-gui-extra | outline-view.rkt | #lang racket/gui
(require racket/gui/extra)
;; NOTE: The outline view is not ready for use yet. The code below
;; mostly works, but the implementation is incomplete and partially
;; wrong.
(define tree
(hash
"/" '("a" "b")
"a" '()
"b" '("c")
"c" '()))
(define ds
(new
(class outline-view-datasource%
(super-new)
(define/override (get-item-child-count it)
(length (hash-ref tree (or it "/") null)))
(define/override (get-item-child it idx)
(cond
[(not it) "/"]
[else (list-ref (hash-ref tree it) idx)]))
(define/override (is-item-expandable? it)
(not (null? (hash-ref tree (or it "/"))))))))
(define f (new frame%
[label "Outline"]
[width 600]
[height 300]))
(define o (new outline-view%
[parent f]
[callback void]
[datasource ds]))
(send f show #t)
| null | https://raw.githubusercontent.com/Bogdanp/racket-gui-extra/6e1d2d154427707424dcc8bbfe2115009e38d3d4/examples/outline-view.rkt | racket | NOTE: The outline view is not ready for use yet. The code below
mostly works, but the implementation is incomplete and partially
wrong. | #lang racket/gui
(require racket/gui/extra)
(define tree
(hash
"/" '("a" "b")
"a" '()
"b" '("c")
"c" '()))
(define ds
(new
(class outline-view-datasource%
(super-new)
(define/override (get-item-child-count it)
(length (hash-ref tree (or it "/") null)))
(define/override (get-item-child it idx)
(cond
[(not it) "/"]
[else (list-ref (hash-ref tree it) idx)]))
(define/override (is-item-expandable? it)
(not (null? (hash-ref tree (or it "/"))))))))
(define f (new frame%
[label "Outline"]
[width 600]
[height 300]))
(define o (new outline-view%
[parent f]
[callback void]
[datasource ds]))
(send f show #t)
|
6396cb7f650cda958e2d16b5f0c140d8e1f9aeb60ca5f910972a95e646299446 | cmr-exchange/cmr-client | project.clj | (defproject gov.nasa.earthdata/cmr-client "0.3.0-SNAPSHOT"
:description "A Clojure(Script) Client for NASA's Common Metadata Repository"
:url "-exchange/cmr-client"
:license {
:name "Apache License, Version 2.0"
:url "-2.0"}
:exclusions [
org.clojure/clojure
potemkin]
:dependencies [
[clj-http "3.8.0"]
[cljs-http "0.1.44"]
[clojusc/ltest "0.3.0"]
[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.217"]
[org.clojure/core.async "0.4.474"]
[org.clojure/data.json "0.2.6"]
[org.clojure/data.xml "0.2.0-alpha2"]
[potemkin "0.4.4"]]
:source-paths ["src/clj" "src/cljc"]
:profiles {
:uberjar {
:aot :all}
:dev {
:dependencies [
[leiningen-core "2.8.1"]
[org.clojure/tools.namespace "0.2.11"]]
:plugins [
[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.15"]
[lein-shell "0.5.0"]]
:resource-paths ["dev-resources" "test/data" "test/clj"]
:source-paths ["src/clj" "src/cljc" "test/clj" "dev-resources/src"]
:test-paths ["test/clj"]
:repl-options {
:init-ns cmr.client.dev}}
:test {
:resource-paths ["test/data"]
:source-paths ["test/clj"]
:test-paths ["test/clj"]
:test-selectors {
:default :unit
:unit :unit
:integration :integration
:system :system}
}
:lint {
:exclusions ^:replace [
org.clojure/clojure
org.clojure/tools.namespace]
:dependencies ^:replace [
[org.clojure/clojure "1.9.0"]
[org.clojure/tools.namespace "0.2.11"]]
:source-paths ^:replace ["src/clj" "src/cljc"]
:test-paths ^:replace []
:plugins [
[jonase/eastwood "0.2.5"]
[lein-ancient "0.6.15"]
[lein-bikeshed "0.5.1"]
[lein-kibit "0.1.6"]
[venantius/yagni "0.1.4"]]}
:cljs {
:source-paths ^:replace ["src/cljs" "src/cljc"]}
:docs {
:dependencies [
[clojang/codox-theme "0.2.0-SNAPSHOT"]]
:plugins [
[lein-codox "0.10.3"]
[lein-marginalia "0.9.1"]
[lein-simpleton "1.3.0"]]
:codox {
:project {
:name "CMR Client"
:description "A Clojure(Script)+JavaScript Client for NASA's Common Metadata Repository"}
:namespaces [#"^cmr\.client\..*"]
:metadata {
:doc/format :markdown
:doc "Documentation forthcoming"}
:themes [:clojang]
:doc-paths ["resources/docs"]
:output-path "docs/current"}}}
:cljsbuild {
:builds [
{:id "cmr-dev"
:source-paths ["src/cljs" "src/cljc"]
:figwheel true
:compiler {
:main "cmr.client"
:asset-path "js/out"
:output-to "resources/public/js/cmr_dev.js"
:output-dir "resources/public/js/out"}}
{:id "cmr-prod"
:source-paths ["src/cljs" "src/cljc"]
:compiler {
:main "cmr.client"
:static-fns true
:fn-invoke-direct true
:optimizations :simple
:output-to "resources/public/js/cmr_client.js"}}]}
:aliases {
"repl"
["with-profile" "+dev" "repl"]
"build-cljs-dev"
^{:doc "Build just the dev version of the ClojureScript code"}
["cljsbuild" "once" "cmr-dev"]
"build-cljs-prod"
^{:doc "Build just the prod version of the ClojureScript code"}
["do"
["shell" "rm" "-f" "resources/public/js/cmr_client.js"]
["cljsbuild" "once" "cmr-prod"]]
"run-tests"
^{:doc "Use the ltest runner for verbose, colourful test output"}
["with-profile" "+test"
"run" "-m" "cmr.client.testing.runner"]
"check-vers" ["with-profile" "+lint" "ancient" "check" ":all"]
"check-jars" ["with-profile" "+lint" "do"
["deps" ":tree"]
["deps" ":plugin-tree"]]
"check-deps"
^{:doc "Check to see if any dependencies are out of date or if jars are conflicting"}
["do"
["check-jars"]
["check-vers"]]
"lint"
^{:doc "Run linting tools against the source"}
["with-profile" "+lint" "kibit"]
"docs"
^{:doc "Generate API documentation"}
["with-profile" "+docs" "do"
["codox"]
[ " marg " " " " docs / current "
" --file " " marginalia.html "
; "--name" "sockets"]
;["shell" "cp" "resources/public/cdn.html" "docs"]
]
"build"
^{:doc "Perform the build tasks"}
["with-profile" "+test" "do"
;["check-deps"]
["lint"]
["test"]
["compile"]
["docs"]
["uberjar"]
["build-cljs-dev"]
["build-cljs-prod"]]
"npm"
^{:doc "Publish compiled JavaScript client"}
["do"
["shell" "rm" "-rf" "dist"]
["shell" "mkdir" "dist"]
["shell" "cp" "resources/public/js/cmr_client.js" "dist"]
["shell" "npm" "publish" "--access" "public"]
["shell" "rm" "-rf" "dist"]]
"publish"
^{:doc "Publish to Clojars and npm"}
["do"
["deploy" "clojars"]
["npm"]]})
| null | https://raw.githubusercontent.com/cmr-exchange/cmr-client/0b4dd4114e3b5ed28fc5b57db0f8dcd8773c1c14/project.clj | clojure | "--name" "sockets"]
["shell" "cp" "resources/public/cdn.html" "docs"]
["check-deps"] | (defproject gov.nasa.earthdata/cmr-client "0.3.0-SNAPSHOT"
:description "A Clojure(Script) Client for NASA's Common Metadata Repository"
:url "-exchange/cmr-client"
:license {
:name "Apache License, Version 2.0"
:url "-2.0"}
:exclusions [
org.clojure/clojure
potemkin]
:dependencies [
[clj-http "3.8.0"]
[cljs-http "0.1.44"]
[clojusc/ltest "0.3.0"]
[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.217"]
[org.clojure/core.async "0.4.474"]
[org.clojure/data.json "0.2.6"]
[org.clojure/data.xml "0.2.0-alpha2"]
[potemkin "0.4.4"]]
:source-paths ["src/clj" "src/cljc"]
:profiles {
:uberjar {
:aot :all}
:dev {
:dependencies [
[leiningen-core "2.8.1"]
[org.clojure/tools.namespace "0.2.11"]]
:plugins [
[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.15"]
[lein-shell "0.5.0"]]
:resource-paths ["dev-resources" "test/data" "test/clj"]
:source-paths ["src/clj" "src/cljc" "test/clj" "dev-resources/src"]
:test-paths ["test/clj"]
:repl-options {
:init-ns cmr.client.dev}}
:test {
:resource-paths ["test/data"]
:source-paths ["test/clj"]
:test-paths ["test/clj"]
:test-selectors {
:default :unit
:unit :unit
:integration :integration
:system :system}
}
:lint {
:exclusions ^:replace [
org.clojure/clojure
org.clojure/tools.namespace]
:dependencies ^:replace [
[org.clojure/clojure "1.9.0"]
[org.clojure/tools.namespace "0.2.11"]]
:source-paths ^:replace ["src/clj" "src/cljc"]
:test-paths ^:replace []
:plugins [
[jonase/eastwood "0.2.5"]
[lein-ancient "0.6.15"]
[lein-bikeshed "0.5.1"]
[lein-kibit "0.1.6"]
[venantius/yagni "0.1.4"]]}
:cljs {
:source-paths ^:replace ["src/cljs" "src/cljc"]}
:docs {
:dependencies [
[clojang/codox-theme "0.2.0-SNAPSHOT"]]
:plugins [
[lein-codox "0.10.3"]
[lein-marginalia "0.9.1"]
[lein-simpleton "1.3.0"]]
:codox {
:project {
:name "CMR Client"
:description "A Clojure(Script)+JavaScript Client for NASA's Common Metadata Repository"}
:namespaces [#"^cmr\.client\..*"]
:metadata {
:doc/format :markdown
:doc "Documentation forthcoming"}
:themes [:clojang]
:doc-paths ["resources/docs"]
:output-path "docs/current"}}}
:cljsbuild {
:builds [
{:id "cmr-dev"
:source-paths ["src/cljs" "src/cljc"]
:figwheel true
:compiler {
:main "cmr.client"
:asset-path "js/out"
:output-to "resources/public/js/cmr_dev.js"
:output-dir "resources/public/js/out"}}
{:id "cmr-prod"
:source-paths ["src/cljs" "src/cljc"]
:compiler {
:main "cmr.client"
:static-fns true
:fn-invoke-direct true
:optimizations :simple
:output-to "resources/public/js/cmr_client.js"}}]}
:aliases {
"repl"
["with-profile" "+dev" "repl"]
"build-cljs-dev"
^{:doc "Build just the dev version of the ClojureScript code"}
["cljsbuild" "once" "cmr-dev"]
"build-cljs-prod"
^{:doc "Build just the prod version of the ClojureScript code"}
["do"
["shell" "rm" "-f" "resources/public/js/cmr_client.js"]
["cljsbuild" "once" "cmr-prod"]]
"run-tests"
^{:doc "Use the ltest runner for verbose, colourful test output"}
["with-profile" "+test"
"run" "-m" "cmr.client.testing.runner"]
"check-vers" ["with-profile" "+lint" "ancient" "check" ":all"]
"check-jars" ["with-profile" "+lint" "do"
["deps" ":tree"]
["deps" ":plugin-tree"]]
"check-deps"
^{:doc "Check to see if any dependencies are out of date or if jars are conflicting"}
["do"
["check-jars"]
["check-vers"]]
"lint"
^{:doc "Run linting tools against the source"}
["with-profile" "+lint" "kibit"]
"docs"
^{:doc "Generate API documentation"}
["with-profile" "+docs" "do"
["codox"]
[ " marg " " " " docs / current "
" --file " " marginalia.html "
]
"build"
^{:doc "Perform the build tasks"}
["with-profile" "+test" "do"
["lint"]
["test"]
["compile"]
["docs"]
["uberjar"]
["build-cljs-dev"]
["build-cljs-prod"]]
"npm"
^{:doc "Publish compiled JavaScript client"}
["do"
["shell" "rm" "-rf" "dist"]
["shell" "mkdir" "dist"]
["shell" "cp" "resources/public/js/cmr_client.js" "dist"]
["shell" "npm" "publish" "--access" "public"]
["shell" "rm" "-rf" "dist"]]
"publish"
^{:doc "Publish to Clojars and npm"}
["do"
["deploy" "clojars"]
["npm"]]})
|
3bcf79ba277d9c11f2a02cc1b8ca39331dee41bac40efefc9faf2c30983a650a | eta-lang/eta-prelude | ByteString.hs | module Eta.Types.ByteString
( ByteString(..)
, pack
, unpack
)
where
import Data.ByteString
| null | https://raw.githubusercontent.com/eta-lang/eta-prelude/e25e9aa42093e090a86d2728b0cac288a25bc52e/src/Eta/Types/ByteString.hs | haskell | module Eta.Types.ByteString
( ByteString(..)
, pack
, unpack
)
where
import Data.ByteString
|
|
b621d980ce7995f99892211338a03867055665fa8653b543767168850c3578de | sellout/haskerwaul | Stable.hs | # language UndecidableInstances
, UndecidableSuperClasses #
, UndecidableSuperClasses #-}
module Haskerwaul.Relation.Equality.Stable
( module Haskerwaul.Relation.Equality.Stable
-- * extended modules
, module Haskerwaul.Relation.Equality
) where
import Data.Bool (Bool)
import Data.Int (Int, Int8, Int16, Int32, Int64)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import Numeric.Natural (Natural)
import Prelude (Double, Float, Integer)
import Haskerwaul.Negation
import Haskerwaul.Object
import Haskerwaul.Relation.Equality
import Haskerwaul.Semiring.Components
import Haskerwaul.Topos.Elementary
-- | [nLab](+equality)
class EqualityRelation c a => StableEquality c a
instance StableEquality (->) (Negate ())
instance StableEquality (->) (Negate Bool)
instance StableEquality (->) (Negate Natural)
instance StableEquality (->) (Negate Int)
instance StableEquality (->) (Negate Int8)
instance StableEquality (->) (Negate Int16)
instance StableEquality (->) (Negate Int32)
instance StableEquality (->) (Negate Int64)
instance StableEquality (->) (Negate Integer)
instance StableEquality (->) (Negate Word)
instance StableEquality (->) (Negate Word8)
instance StableEquality (->) (Negate Word16)
instance StableEquality (->) (Negate Word32)
instance StableEquality (->) (Negate Word64)
instance StableEquality (->) (Negate Float)
instance StableEquality (->) (Negate Double)
instance (c ~ (->), ElementaryTopos c, StableEquality c a, Ob c (Additive a)) =>
StableEquality c (Additive a)
instance (c ~ (->), ElementaryTopos c, StableEquality c a, Ob c (Multiplicative a)) =>
StableEquality c (Multiplicative a)
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Relation/Equality/Stable.hs | haskell | * extended modules
| [nLab](+equality) | # language UndecidableInstances
, UndecidableSuperClasses #
, UndecidableSuperClasses #-}
module Haskerwaul.Relation.Equality.Stable
( module Haskerwaul.Relation.Equality.Stable
, module Haskerwaul.Relation.Equality
) where
import Data.Bool (Bool)
import Data.Int (Int, Int8, Int16, Int32, Int64)
import Data.Word (Word, Word8, Word16, Word32, Word64)
import Numeric.Natural (Natural)
import Prelude (Double, Float, Integer)
import Haskerwaul.Negation
import Haskerwaul.Object
import Haskerwaul.Relation.Equality
import Haskerwaul.Semiring.Components
import Haskerwaul.Topos.Elementary
class EqualityRelation c a => StableEquality c a
instance StableEquality (->) (Negate ())
instance StableEquality (->) (Negate Bool)
instance StableEquality (->) (Negate Natural)
instance StableEquality (->) (Negate Int)
instance StableEquality (->) (Negate Int8)
instance StableEquality (->) (Negate Int16)
instance StableEquality (->) (Negate Int32)
instance StableEquality (->) (Negate Int64)
instance StableEquality (->) (Negate Integer)
instance StableEquality (->) (Negate Word)
instance StableEquality (->) (Negate Word8)
instance StableEquality (->) (Negate Word16)
instance StableEquality (->) (Negate Word32)
instance StableEquality (->) (Negate Word64)
instance StableEquality (->) (Negate Float)
instance StableEquality (->) (Negate Double)
instance (c ~ (->), ElementaryTopos c, StableEquality c a, Ob c (Additive a)) =>
StableEquality c (Additive a)
instance (c ~ (->), ElementaryTopos c, StableEquality c a, Ob c (Multiplicative a)) =>
StableEquality c (Multiplicative a)
|
b29110eda7f6b073329a9064a3fb4f86fe2e3ec5a68b76f7258635485b3476ad | BU-CS320/Fall-2018 | WarmUp.hs | module WarmUp where
-- how to write good tests
-- write a function that returns a number bigger than its input
biggerNumber :: Integer -> Integer
biggerNumber i = undefined | null | https://raw.githubusercontent.com/BU-CS320/Fall-2018/beec3ca88be5c5a62271a45c8053fb1b092e0af1/assignments/week5/hw/src/WarmUp.hs | haskell | how to write good tests
write a function that returns a number bigger than its input
| module WarmUp where
biggerNumber :: Integer -> Integer
biggerNumber i = undefined |
6b3fc2430ea427f465d79662be79c7be67109ef10c530502e73bbc9e7178bf41 | untangled-web/untangled-ui | components.cljs | (ns styles.components
(:require [om.next :as om :refer-macros [defui]]
[styles.util :as util :refer [to-cljs] :refer-macros [source->react defexample defarticle defview defviewport]]
[untangled.ui.layout :as l]
[untangled.icons :as icons]
[om.dom :as dom]
[untangled.ui.elements :as e]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF EXAMPLES
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -------------------------
;; Avatar
;; -------------------------
(def avatar-header
"# Avatar")
(defexample avatar
"An avatar is a round symbol to represent a person's identity. When there is no visual, we use the first and last
initial of their name."
(l/row {}
(l/col {:width 2}
(dom/span #js {:className "c-avatar"} "AV"))
(l/col {:width 2}
(dom/span #js {:className "c-avatar"} (icons/icon :help)))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account)))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :supervisor_account)))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--bordered c-avatar--primary"} "KB"))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--bordered c-avatar--accent"} "KB"))
(l/col {:width 12}
(dom/span #js {:className "c-avatar c-avatar--medium"} "MD")
(dom/span #js {:className "c-avatar c-avatar--large"} "LG")
(dom/span #js {:className "c-avatar c-avatar--xlarge"} "XL")
(dom/span #js {:className "c-avatar c-avatar--huge"} "HU"))))
(defexample avatar-group
"### Avatar Group
A group of avatars bundled into one block"
(dom/div nil
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--medium"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--medium"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--medium"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--large"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--large"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--large"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--xlarge"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--xlarge"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--xlarge"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--huge"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)})
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)})))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--huge"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)})
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)})
(dom/img #js {:src (:photo (util/mock-users :3)) :alt (util/full-name :3)})))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--huge"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)})
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)})
(dom/img #js {:src (:photo (util/mock-users :3)) :alt (util/full-name :3)})
(dom/img #js {:src (:photo (util/mock-users :4)) :alt (util/full-name :4)}))))
)
)
(defarticle avatar-customize
"### Customize
Use these custom properties in your stylesheet to change how your avatars look.
```css
--borderRadius-avatar: 100px;
--borderSize-avatar: 2px;
--borderSize-avatar--medium: 3px;
--borderSize-avatar--large: 4px;
--borderSize-avatar--xlarge: 5px;
--borderSize-avatar--huge: 6px;
--color-avatar: color(var(--grey) a(.5));
--color-avatar--secondary: color(var(--grey-900) a(60%));
--color-avatar-alt--primary: var(--color-primary);
--color-avatar-alt--accent: var(--color-accent);
--color-avatar-alt--secondary: var(--color-primary-contrast);
--divisor-avatar: 2.5;
--size-avatar: 40px;
--scale-avatar: calc(var(--size-avatar) / var(--divisor-avatar));
--size-avatar--medium: 55px;
--scale-avatar--medium: calc(var(--size-avatar--medium) / var(--divisor-avatar));
--size-avatar--large: 75px;
--scale-avatar--large: calc(var(--size-avatar--large) / var(--divisor-avatar));
--size-avatar--xlarge: 90px;
--scale-avatar--xlarge: calc(var(--size-avatar--xlarge) / var(--divisor-avatar));
--size-avatar--huge: 110px;
--scale-avatar--huge: calc(var(--size-avatar--huge) / var(--divisor-avatar));
```
")
;; -------------------------
;; Badges
;; -------------------------
(def badge-header
"# Badge")
(defexample badge
"### Basic
You can make a badge from a `span` or `div` element using the `.c-badge` classname."
(dom/a #js {:href "guide-css.html"} "Inbox "
(dom/span #js {:className "c-badge"} 7)))
(defexample badge-button
"### In a button"
(dom/p #js {}
(dom/button #js {:className "c-button c-button--raised" :type "button"} " Messages "
(dom/span #js {:className "c-badge"} "37"))
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} " Messages "
(dom/span #js {:className "c-badge"} "37"))
(dom/button #js {:className "c-button c-button--raised c-button--accent" :type "button"} " Messages "
(dom/span #js {:className "c-badge"} "37"))))
(defexample badge-icon
"### Icon, no text"
(dom/span #js {:className "c-badge c-badge--round"}
(icons/icon :alarm)))
(defarticle badge-customize
"### Customize
Use these custom properties in your stylesheet to change how your badges look.
```css
--borderRadius-badge: 50px;
--color-badge--primary: color(var(--grey) a(.7));
--color-badge--secondary: var(--white);
--color-badge-alt--primary: var(--color-primary);
--color-badge-accent--primary: var(--color-accent);
--marginRight-badge: 6px;
--padding-badge: 3px 8px;
--padding-badge--icon: 4px;
--size-badge--small: 14px;
--size-badge--icon: 30px;
```
")
;; -------------------------
;; Buttons
;; -------------------------
(def button-header
"# Buttons
Use these button classes on `<button>` or `<input type='submit'>` element. It's easy to make a new button.")
(defview button
"### Button types"
(dom/div #js {:className "u-row u-center"}
(dom/div #js {:className "u-column"}
(dom/button #js {:className "c-button c-button--primary c-button--circular" :type "button"} (icons/icon :add))
(dom/div #js {:className "u-font-size--small u-leader"} "Circular button"))
(dom/div #js {:className "u-column"}
(dom/button #js {:className "c-button c-button--primary c-button--raised" :type "button"} "Button")
(dom/div #js {:className "u-font-size--small u-leader"} "Raised button"))
(dom/div #js {:className "u-column"}
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Button")
(dom/div #js {:className "u-font-size--small u-leader"} "Flat button"))))
(defexample button-shape
"### Size and form
You can optionally use modifier classes that let you manipulate the size and shape of your button.
"
(dom/div #js {}
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} "Regular")
(dom/button #js {:className "c-button c-button--raised c-button--primary c-button--round" :type "button"} "Round")
(dom/button #js {:className "c-button c-button--raised c-button--primary c-button--dense" :type "button"} "Dense")
(dom/div #js {:className "u-trailer--quarter"}
(dom/button #js {:className "c-button c-button--raised c-button--primary c-button--wide" :type "button"} "Wide"))))
(defexample button-color
"### Colors
Stateful color classes are provided to further communicate the intentions of your button action."
(dom/div #js {}
(dom/button #js {:className "c-button" :type "button"} "Flat")
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Flat Primary")
(dom/button #js {:className "c-button c-button--accent" :type "button"} "Flat Accent")
(dom/button #js {:className "c-button c-button--raised" :type "button"} "Raised")
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} "Raised Primary")
(dom/button #js {:className "c-button c-button--raised c-button--accent" :type "button"} "Raised Accent")))
(defview button-state
"### Flat Button States"
(dom/div #js {:className "u-row u-row--collapsed u-center"}
(dom/div #js {:className "u-column--12 u-column--6@md"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button" :disabled true :type "button"} "Disabled")))
(dom/div #js {:className "u-column--12 u-column--6@md t-dark"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button" :disabled true :type "button"} "Disabled")))))
(defview button-state-raised
"### Raised Button States"
(dom/div #js {:className "u-row u-row--collapsed u-center"}
(dom/div #js {:className "u-column--12 u-column--6@md"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button c-button--raised" :disabled true :type "button"} "Disabled"))
)
(dom/div #js {:className "u-column--12 u-column--6@md t-dark"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised c-button--primary is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised c-button--primary is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button c-button--raised c-button--primary" :disabled true :type "button"} "Disabled")))))
(defexample button-icon
"### Buttons with icons"
(dom/div nil
(dom/button #js {:className "c-button c-button--raised" :type "button"}
(icons/icon :arrow_back)
(dom/span #js {:className "c-button__content"} "Left Icon"))
(dom/button #js {:className "c-button c-button--raised" :type "button"}
(dom/span #js {:className "c-button__content"} "Right Icon")
(icons/icon :arrow_forward))
(dom/button #js {:title "Icon Button" :className "c-button c-button--icon" :type "button"}
(icons/icon :translate))))
;; -------------------------
;; Card
;; -------------------------
(def card-header
"# Cards")
(defexample card
"### Basic"
(dom/div #js {:className "u-row u-center"}
(dom/div #js {:className "c-card c-card--primary c-card--bordered c-card--wide c-card--3587358"}
(dom/div #js {:className "c-card__title c-card__title--image-bottom-right"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "Suspendisse potenti. Phasellus ac ex sit amet erat elementum
suscipit id sed sapien. Sed sit amet sagittis ipsum.")
(dom/div #js {:className "c-card__actions"}
(dom/button #js {:className "c-button c-button--primary" :type "button"} "View Updates")))
(dom/style nil (str ".c-card--3587358 .c-card__title { background-image: url('img/bubbles.png'); }"))))
(defexample card-transparent
"### Transparent Card"
(dom/div #js {:className "c-card c-card--transparent"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "This gives you the basic box properties without any background color or text color.")))
(defexample card-ruled
"### Ruled Card"
(dom/div #js {:className "u-wrapper"}
(dom/div #js {:className "c-card c-card--bordered"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "Suspendisse potenti. Phasellus ac ex sit amet erat elementum
suscipit id sed sapien. Sed sit amet sagittis ipsum. A simple card, horizontal ruled.")
(dom/div #js {:className "c-card__actions"}
(dom/button #js {:className "c-button c-button--accent" :type "button"} "Action")))))
(defexample card-states
"### States"
(dom/div nil
(dom/div #js {:className "c-card c-card--row is-active u-trailer--half"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "I could have used lorem ipsum, but what's the fun in that?"))
(dom/div #js {:className "c-card c-card--row is-inactive"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "I could have used lorem ipsum, but what's the fun in that?"))))
;; -------------------------
Checkboxes
;; -------------------------
(def checkbox-header
"# Checkboxes")
(defexample checkboxes
"The following examples show the various rendered states of checkboxes."
(dom/div #js {}
;; Single checkbox, no label text
(dom/input #js {:id "checkbox-1" :type "checkbox" :className "c-checkbox"})
(dom/label #js {:htmlFor "checkbox-1"} \u00A0)
(dom/input #js {:id "checkbox-1" :type "checkbox" :className "c-checkbox"})
(dom/label #js {:htmlFor "checkbox-1"} "Checkbox")
(dom/input #js {:id "checkbox-2" :type "checkbox" :checked true :className "c-checkbox"})
(dom/label #js {:htmlFor "checkbox-2"} "Checked Checkbox")
(dom/input #js {:id "checkbox-3" :type "checkbox" :className "c-checkbox is-indeterminate"})
(dom/label #js {:htmlFor "checkbox-3"} "Indeterminate Checkbox")
(dom/input #js {:id "checkbox-4" :type "checkbox" :className "c-checkbox" :disabled true})
(dom/label #js {:htmlFor "checkbox-4"} "Disabled Checkbox")
(dom/input #js {:id "checkbox-5" :type "checkbox" :checked true :className "c-checkbox" :disabled true})
(dom/label #js {:htmlFor "checkbox-5"} "Disabled Checked Checkbox")
(dom/input #js {:id "checkbox-5" :type "checkbox" :className "c-checkbox is-indeterminate" :disabled true})
(dom/label #js {:htmlFor "checkbox-5"} "Disabled Indeterminate Checkbox")))
(defn toggle-open [this] (om/update-state! this update :open not))
;; -------------------------
;; Menus
;; -------------------------
(def menus-header
"# Menus")
(defexample menus
"### Basic
This example uses component local state to toggle the is-active class to open/close the dropdown."
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Not Selected")]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "150px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/div #js {:id "test-dropdown"
:tabIndex "-1"
:aria-hidden "true"
:className "c-menu"}
(dom/div #js {:className "c-menu__group"}
(map (fn [s]
(dom/div #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s)
)}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active"))} s))) selections))))))
(defexample menus-shape
"### Shape and form"
(dom/div nil
;; Top left
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Top Left Aligned")]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/ul #js {:id "test-dropdown" :tabIndex "-1" :aria-hidden "true"
:className "c-menu c-menu--top-left"}
(map (fn [s]
(dom/li #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s))}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active")) :type "button"} s))) selections))))
;; Bottom left
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Bottom Left Aligned")]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/ul #js {:id "test-dropdown" :tabIndex "-1" :aria-hidden "true"
:className "c-menu"}
(map (fn [s]
(dom/li #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s))}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active")) :type "button"} s))) selections))))
;; Top right
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Top Right Aligned")]
(dom/div #js {:className "u-end"}
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/ul #js {:id "test-dropdown" :tabIndex "-1" :aria-hidden "true"
:className "c-menu c-menu--top-right"}
(map (fn [s]
(dom/li #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s))}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active")) :type "button"} s))) selections)))))
;; Bottom right
(let [open (boolean (om/get-state this :open))]
(dom/div #js {:className "u-end" :style #js {:width "180px"}}
(dom/div #js {:className (str "has-menu" (when open " is-active"))}
(dom/button #js {:onClick #(toggle-open this) :className "c-button " :type "button"} "Bottom Right Aligned")
(dom/div #js {:id "test-dropdown" :aria-hidden "true" :className "c-menu c-menu--bottom-right" :tabIndex "-1"}
(dom/div #js {:className "c-menu__group"}
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"} (icons/icon :done))
"Show ruler")
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"} (icons/icon :done))
"Show grid"))
(dom/div #js {:className "c-menu__group"}
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"})
"Hide layout")
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"} (icons/icon :done))
"Show bleed"))))))))
(defexample menus-search-multi
"### Multi-Select, Searchable Dropdown"
(let [open (boolean (om/get-state this :open))
items (mapv #(str "Item " %) (range 1 20))]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(toggle-open this) :className "c-button c-button--dropdown " :type "button"} "Filter")
(dom/div #js {:id "test-dropdown" :aria-hidden "true" :className "c-menu c-menu--large" :tabIndex "-1"}
(dom/div #js {:className "c-field"}
(icons/icon :search)
(dom/input #js {:type "text" :placeholder "Search..." :className "c-field__input"}))
(dom/div #js {:className "c-menu__viewer"}
(map (fn [item]
(dom/div #js {:key item :className "u-leader--sixth u-trailer--sixth"}
(dom/input #js {:type "checkbox" :id (str item "-cb") :className "c-checkbox"})
(dom/label #js {:htmlFor (str item "-cb")} item)))
items))
(dom/button #js {:onClick #(om/update-state! this assoc :open false) :className "c-button c-button--primary c-button--wide" :type "button"} "Apply")))))
(defexample menus-data
"### Multiple list group selection
This is a control that is meant to let you view what various dropdowns would show, for example in cases
of UI that lets you configure UI.
Note: The dropdown list underneath should not be enabled when the dropdown list is visible. Doing this fosters a better interaction for the user."
(let [open (boolean (om/get-state this :open))
name (or (om/get-state this :menu-name) "Menu 1")
menu-1-items (mapv #(str "Item " %) (range 1 5))
menu-2-items (mapv #(str "Other " %) (range 1 3))
menu (or (om/get-state this :menu) menu-1-items)]
(dom/div nil
(l/row {}
(l/col {:width 4}
(dom/div #js {:className "c-card c-card--collapse"}
(dom/div #js {:className (str "has-menu" (when open " is-active"))}
(dom/button #js {:onClick #(toggle-open this)
:type "button"
:className "c-button c-button--wide"} (str "List: " name))
(dom/div #js {:id "test-dropdown" :aria-hidden "true"
:className "c-menu" :tabIndex "-1"}
(dom/button #js {:onClick #(om/update-state! this assoc :open false :menu menu-1-items :menu-name "Menu 1")
:type "button"
:className "c-menu__item"} "Menu 1")
(dom/button #js {:onClick #(om/update-state! this assoc :open false :menu menu-2-items :menu-name "Menu 2")
:type "button"
:className "c-menu__item"} "Menu 2")))
(dom/div #js {:className "c-list" :tabIndex "-1"}
(map (fn [item]
(dom/div #js {:className "c-list__row c-list__row--bordered is-selectable" :key item}
(dom/div #js {:className "c-list__tile"} item))) menu))))))))
;; -------------------------
;; Expanding Panel
;; -------------------------
(def expansion-panel-header
"# Expansion panels"
)
(defexample expansion-panel
"### Usage
This is a collapsed expansion panel"
(dom/div nil
(let [expanded-1 (boolean (om/get-state this :expanded-1))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-1 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-1 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Trip name")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-1
"Caribbean cruise"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(dom/input #js {:className "c-field" :type "text" :placeholder "Type in a name for your trip..." :value "Caribbean cruise" :id "inputAB"})
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:className "c-button" :type "button"} "Cancel")
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Save")))))))
(let [expanded-2 (boolean (om/get-state this :expanded-2))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-2 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-2 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Location")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(if-not expanded-2
"Barbados"
(dom/span nil "Select trip destination" (icons/icon :help_outline))))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-column--8@md u-center@md"}
(dom/span #js {:className "c-badge c-badge--large"} "Barbados" (icons/icon :cancel)))
(dom/div #js {:className "u-column--12 u-column--4@md"}
(dom/div #js {:className "u-helper-text"}
(dom/div nil "Select your destination of choice")
(dom/div nil (dom/a #js {:href "http://"} "Learn more")))))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:className "c-button" :type "button"} "Cancel")
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Save")))))))
(let [expanded-3 (boolean (om/get-state this :expanded-3))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-3 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-3 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Start and end dates")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-3 "Start date: Feb 29, 2016"))
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-3 "End date: Not set"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"} "Controls for dates")))
(let [expanded-4 (boolean (om/get-state this :expanded-4))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-4 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-4 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Carrier")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-4 "The best cruise line"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"} "Controls for carrier")))
(let [expanded-5 (boolean (om/get-state this :expanded-5))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-5 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-5 not)}
(dom/div #js {:className "c-expansion-panel__title"}
(dom/div nil "Meal preferences")
(dom/div #js {:className "c-message--neutral"} "Optional"))
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-5 "Vegetarian"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"} "Stuff here")))))
(defexample expansion-panel-survey
"### Example: Editing a question
As another example of how to use this we look at how you would edit a survey question and apply conditional questions to it."
(dom/div nil
(let [expanded-1 (boolean (om/get-state this :expanded-1))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-1 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-1 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Question")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-1 "What kind of beverage do you prefer?"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse :valign :middle}
(l/col {:width 1}
(dom/label #js {:htmlFor "input1"} "Text"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input1" :type "text" :placeholder "Type a question..." :value "How was your last stay at the premium village?"}))
(l/col {:width 2 :halign :end}
(dom/label #js {:htmlFor "h-switch-input-1"} "Required?")
(dom/div #js {:className "c-switch"}
(dom/input #js {:type "checkbox"
:id "h-switch-input-1"
:checked true
:className "c-switch__input"})
(dom/span #js {:className "c-switch__paddle"
:aria-hidden false
:htmlFor "h-switch-input-1"}))))
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "input2"} "Short label"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input2" :type "text" :placeholder "Type a short question..." :value "How was your last stay?"})))
(l/row {}
(l/col {:width 9 :push 1}
(l/row {:density :collapse :className "u-trailer" :valign :bottom :halign :center}
(l/col {:className "u-column has-xpipe has-start-pipe" :halign :center}
(icons/icon :sentiment_very_dissatisfied))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel1"}
"Extremely dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "1" :id "sel1" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel2"}
"Moderately dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "2" :id "sel2" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel3"}
"Slightly dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "3" :id "sel3" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel4"}
"Neither satisfied nor dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "4" :id "sel4" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel5"}
"Slightly satisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "5" :id "sel5" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel6"}
"Moderately satisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "6" :id "sel6" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel7"}
"Extremely satisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "7" :id "sel7" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe has-end-pipe" :halign :center}
(icons/icon :sentiment_very_satisfied)))))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:type "button" :className "c-button"} "Options")
(dom/button #js {:type "button" :className "c-button"} "Move")
(dom/button #js {:type "button" :className "c-button c-button--accent"} "Add Conditional")
(dom/button #js {:type "button" :className "c-button c-button--primary"} "Save")))))))
(let [expanded-2 (boolean (om/get-state this :expanded-2))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-2 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-2 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Conditional")
(dom/div #js {:className "c-expansion-panel__info"}
(if-not expanded-2
"If beverage prefrerence is red wine."
(dom/span nil "Select conditions first" (icons/icon :help_outline))))
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(if-not expanded-2 "Would you like our gm to get in touch?"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "cond-op"} "If answer "))
(l/col {:width 1}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button" :id "cond-op"} "is")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "exactly")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "red wine"))))
(l/row {:density :collapse :valign :middle}
(l/col {:width 1}
(dom/label #js {:htmlFor "input1"} "Text"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input1" :type "text" :placeholder "Type a question..." :value "Would you like our general manager to get in touch with you?"}))
(l/col {:width 2 :halign :end}
(dom/label #js {:htmlFor "h-switch-input-1"} "Required?")
(dom/div #js {:className "c-switch"}
(dom/input #js {:type "checkbox"
:id "h-switch-input-1"
:className "c-switch__input"})
(dom/span #js {:className "c-switch__paddle"
:aria-hidden false
:htmlFor "h-switch-input-1"}))))
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "input2"} "Short label"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input2" :type "text" :placeholder "Type a question..." :value "Would you like our gm to get in touch?"})))
(l/row {}
(l/col {:width 11 :push 1}
(l/row {:density :collapse :valign :middle :distribute-extra-columns :between}
(l/col {:width 12 :className "u-trailer--quarter"}
(dom/input #js {:className "c-radio c-radio--expanded" :type "radio" :value "1" :id "sel1" :name "q1"})
(dom/label #js {:htmlFor "sel1"} "Yes"))
(l/col {:width 12}
(dom/input #js {:className "c-radio c-radio--expanded" :type "radio" :value "5" :id "sel5" :name "q1"})
(dom/label #js {:htmlFor "sel1"} "No")))))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:type "button" :className "c-button"} "Options")
(dom/button #js {:type "button" :className "c-button"} "Move")
(dom/button #js {:type "button" :className "c-button c-button--primary"} "Save")))))))
(let [expanded-3 (boolean (om/get-state this :expanded-3))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-3 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-3 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Conditional")
(dom/div #js {:className "c-expansion-panel__info"}
(if-not expanded-3
"Choose a question"
(dom/span nil "Select conditions first" (icons/icon :help_outline))))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "cond-op"} "If answer "))
(l/col {:width 1}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button" :id "cond-op"} "is")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "exactly")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "red wine"))))
(l/row {:density :collapse :valign :middle :halign :center :className "u-trailer"}
(dom/button #js {:type "button" :className "c-button c-button--primary c-button--raised"} "Choose a question"))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:type "button" :className "c-button"} "Options")
(dom/button #js {:type "button" :className "c-button"} "Move")
(dom/button #js {:type "button" :className "c-button c-button--primary"} "Save")))))))))
;; -------------------------
;; Field
;; -------------------------
(def field-header
"# Fields")
(defexample field
"### Basic"
(dom/div nil
(dom/input #js {:type "text" :required "true" :placeholder "Required field" :className "c-field" :id "field-reg"})
(dom/input #js {:type "text" :placeholder "Optional field" :className "c-field" :id "field-opt"})
(mapv (fn [typ] (dom/div #js {:key typ :className ""}
(dom/input #js {:type typ :placeholder typ :id (str "field-" typ) :className "c-field"})))
["text" "password" "date" "datetime" "datetime-local" "month" "week" "email" "number" "search" "tel" "time" "url" "color"])
;; File upload
(l/row {:density :collapse}
(l/col {:width 1}
;; This is the button to init the upload dialog
(dom/label #js {:htmlFor "file-input-text"}
(dom/span #js {:className "c-button c-button--circular c-button--primary c-button--dense"}
(icons/icon :file_upload)
(dom/input #js {:type "file" :className "u-hide" :id "file-input-file"}))))
(l/col {:width 3}
;; This is the input that displays the file name when selected
;; When you have multiple files selected, this label should read "X files selected"
(dom/input #js {:type "text" :className "c-field" :disabled true :readOnly true :id "file-input-text"})
(dom/label #js {:htmlFor "file-input-text"})))))
(defexample field-sizes
"### Sizes"
(dom/div #js {}
(dom/input #js {:type "text" :className "c-field c-field--small" :placeholder "The quick brown fox..." :id "field-small"})
(dom/input #js {:type "text" :className "c-field" :placeholder "The quick brown fox..." :id "field-regular"})
(dom/input #js {:type "text" :className "c-field c-field--medium" :placeholder "The quick brown fox..." :id "field-medium"})
(dom/input #js {:type "text" :className "c-field c-field--large" :placeholder "The quick brown fox..." :id "field-large"})))
(defexample field-states
"### States"
(dom/div #js {}
(dom/input #js {:type "text" :placeholder "FOCUSED" :className "c-field has-focus" :id "field-focus"})
(dom/input #js {:type "text" :placeholder "INVALID" :className "c-field is-invalid" :id "field-invalid"})
(dom/input #js {:type "text" :placeholder "ERROR" :className "c-field is-error" :id "field-error"})
(dom/input #js {:type "text" :placeholder "Disabled" :className "c-field" :disabled true :id "field-disabled"})))
(defexample field-icon
"### Icons"
(l/row {:density :collapse}
(dom/div #js {:className "c-icon-column"}
(icons/icon :search :className ["c-icon--framed"]))
(l/col {:className "u-column"}
(dom/div #js {:className "c-field"}
(dom/input #js {:type "search" :className "c-field__input" :placeholder "Search..." :id "field-icon"})))))
(defexample field-content
"### Content"
(l/row {}
(l/col {:width 4}
(dom/div #js {:className "c-field"}
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :1))
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :2))
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :3))
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :4))
(dom/input #js {:type "text" :className "c-field__input" :id "field1"})))))
(defexample textarea
"# Text Area"
(dom/textarea #js {:className "c-input c-input--multi-line" :id "textarea"}))
;; -------------------------
;; Icons
;; -------------------------
(def icon-header
"# Icons
The preferred icon library is Google's <a href='/'>Material icons</a>. We include the entire library in the UI Components project in the form of svg paths that get inlined into your markup.
Use these icon classes on `<span>` elements wrapping your inline svg icons. Here is a simple icon in it's purest form.")
(defexample icons
"### Basic"
(dom/span #js {:className "c-icon c-icon--large"}
(icons/icon :timer)))
(defexample icon-sizes
"### Sizes
NOTE: If you would like to include states on the icon itself, you can use
the helper function `(untangled.icons/icon :icon-name :modifiers [:xlarge])`
"
(let [sizes ["--small" "" "--medium" "--large" "--xlarge" "--huge"]]
(dom/div #js {}
(mapv (fn [sz]
(dom/figure #js {:role "group" :key (str "a" sz)}
(dom/span #js {:className (str "c-icon c-icon" sz)}
(icons/icon :alarm))
(dom/figcaption #js {} (str ".c-icon" sz)))
) sizes))))
(defexample icon-states
"### States
NOTE: If you would like to include states on the icon itself, you can use
the helper function `(untangled.icons/icon :icon-name :state [:positive])`
"
(let [states ["active" "passive" "disabled"]]
(dom/div #js {}
(mapv (fn [state]
(dom/figure #js {:role "group" :key state}
(dom/span #js {:className (str "c-icon c-icon--large is-" state)}
(icons/icon :alarm))
(dom/figcaption #js {} (str "is-" state)))
) states))))
(defexample icon-library
"### All Available Icons `(untangled.icons/icon :name)`
NOTE: Some icons have an additonal CSS set of rules in this style kit, so it
is recommended that you wrap icons with c-icon-{iconname}."
(dom/div #js {}
(mapv (fn [nm]
(dom/figure #js {:role "group" :key nm}
(dom/span #js {:className (str "c-icon c-icon-" nm)}
(icons/icon nm))
(dom/figcaption #js {} (str nm)))
) icons/icon-names)))
;; -------------------------
;; Labels
;; -------------------------
(def label-header
"# Labels")
(defexample labels
"### Types"
(dom/div #js {}
(dom/span #js {:className "c-label"} "Default")
(dom/span #js {:className "c-label c-label--primary"} "Primary")
(dom/span #js {:className "c-label c-label--accent"} "Accent")))
(defexample label-icons
"### With Icons"
(dom/div #js {}
(dom/span #js {:className "c-label c-label--primary"}
(icons/icon :add) " Add ")
(dom/span #js {:className "c-label c-label--accent"}
(icons/icon :close) " Remove ")))
;; -------------------------
;; Lists
;; -------------------------
(def lists-header
"# Lists")
(defexample lists
"Lists present multiple line items vertically as a single continuous element."
(dom/div #js {:className "c-list"}
(dom/div #js {:className "c-list__row c-list__row--collapse"}
(dom/div #js {:className "c-list__tile"}
(dom/span #js {:className "c-list__title"} "Today")))
(dom/div #js {:className "c-list__row c-list__row--collapse c-list__row--bordered is-selectable"}
(dom/div #js {:className "c-list__tile"}
(dom/div #js {:className "u-row"}
(dom/div #js {:className "c-list__avatar c-list__avatar--round"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)}))
(dom/div #js {:className "c-list__name"}
(dom/div nil "Brunch this weekend?")
(dom/div nil
(dom/span nil (util/full-name :1))
(dom/span #js {:className "c-list__subtext"} " - I'll be in your neighborhood"))))))
(dom/div #js {:className "c-list__row c-list__row--collapse c-list__row--bordered is-selectable"}
(dom/div #js {:className "c-list__tile"}
(dom/div #js {:className "u-row"}
(dom/div #js {:className "c-list__avatar c-list__avatar--round"}
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)}))
(dom/div #js {:className "c-list__name"}
(dom/div nil "Brunch this weekend?")
(dom/div nil (dom/span nil (util/full-name :2))
(dom/span #js {:className "c-list__subtext"} " - I'll be in your neighborhood"))))))))
;; -------------------------
;; Loader
;; -------------------------
(def loader-header
"# Loader
Webapps often need to provide feedback to the user for when things are loading, so we have a few loader components
that are animated using only CSS techniques.")
(defexample loader
"# Loader"
(l/row {}
(l/col {:width 3 :halign :center}
(dom/div #js {:className "c-loader" :aria-hidden false}))
(l/col {:width 3 :halign :center}
(dom/div #js {:className "c-loader c-loader--primary" :aria-hidden false}))
(l/col {:width 3 :halign :center}
(dom/div #js {:className "c-loader c-loader--accent" :aria-hidden false}))
(l/col {:width 3 :halign :center}
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"}
(dom/span #js {:className "c-loader c-loader--inverted" :aria-hidden false}))
(dom/button #js {:className "c-button c-button--raised" :type "button"}
(dom/span #js {:className "c-loader" :aria-hidden false})))))
;; -------------------------
;; Tabs
;; -------------------------
(def tabs-header
"# Tabs")
(defexample tabs
"### Basic"
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab is-active" :type "button"} "Widgets")
(dom/button #js {:className "c-tab" :type "button"} "Doodads")
(dom/button #js {:className "c-tab" :type "button"} "Apparatuses")
(dom/button #js {:className "c-tab" :type "button"} "Things")))
(defexample tabs-colors
"### Colors"
(dom/div nil
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab c-tab--primary is-active" :type "button"} "Widgets")
(dom/button #js {:className "c-tab c-tab--primary" :type "button"} "Doodads")
(dom/button #js {:className "c-tab c-tab--primary" :type "button"} "Apparatuses")
(dom/button #js {:className "c-tab c-tab--primary" :type "button"} "Things"))
(dom/div #js {:className "t-dark"}
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab c-tab--contrast is-active" :type "button"} "Widgets")
(dom/button #js {:className "c-tab c-tab--contrast" :type "button"} "Doodads")
(dom/button #js {:className "c-tab c-tab--contrast" :type "button"} "Apparatuses")
(dom/button #js {:className "c-tab c-tab--contrast" :type "button"} "Things")))))
(defexample tabs-dropdown
"### With Dropdowns"
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab" :type "button"} "Widgets")
(dom/button #js {:className "c-tab" :type "button"} "Doodads")
(dom/button #js {:className "c-tab" :type "button"} "Apparatuses")
(dom/span #js {:className "has-menu"}
(dom/button #js {:className "c-tab is-active" :type "button"} "Things")
(dom/ul #js {:className "c-menu"}
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamabob"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamajig"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thinger")))
(dom/button #js {:className "c-tab" :type "button"} "Doodads")
(dom/button #js {:className "c-tab" :type "button"} "Apparatuses")
(dom/span #js {:className "has-menu"}
(dom/button #js {:className "c-tab is-active" :type "button"} "Things")
(dom/ul #js {:className "c-menu is-active"}
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamabob"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamajig"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thinger")))))))
;; -------------------------
;; Messages
;; -------------------------
(def messages-header
"# Messages")
(defexample messages
"A basic message"
(dom/div #js {}
(dom/div #js {:className "c-message"} "This is a message")
(dom/div #js {:className "c-message c-message--primary"} "This is a primary message")
(dom/div #js {:className "c-message c-message--accent"} "This is an accent message")))
(defexample messages-raised
"Chat style messages"
(dom/div #js {}
(dom/div #js {:className ""}
(dom/span #js {:className "c-message c-message--raised c-message--large"} "This is a message"))
(dom/div #js {:className "u-center"}
(dom/div #js {:className "c-message c-message--expanded"} "Today maybe")
(dom/span #js {:className "c-message c-message--raised c-message--primary c-message--large"} "This is a primary message"))
(dom/div #js {:className "u-end"}
(dom/span #js {:className "c-message c-message--raised c-message--accent c-message--large"} "This is an accent message"))))
;; -------------------------
;; Notifications
;; -------------------------
(def notification-header
"# Notifications
Used to communicate the state of your user's interactions as well as system status.
In general, use the positioning classes (e.g. `u-absolute--middle-center`) to place these in
the UI.")
(defexample notification
"### Basic"
(dom/div #js {:className "c-notification"}
(icons/icon :info)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Info Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-success
"### Success"
(dom/div #js {:className "c-notification"}
(icons/icon :check_circle :states [:positive])
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Successful Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-warning
"### Warning"
(dom/div #js {:className "c-notification c-notification--warning"}
(icons/icon :warning)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Warning Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-error
"### Error"
(dom/div #js {:className "c-notification c-notification--error"}
(icons/icon :error)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Error Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-wide
"## Wide"
(dom/div #js {:className "c-notification c-notification--wide c-notification--informative"}
(icons/icon :info)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Wide Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
;; -------------------------
;; Progress
;; -------------------------
(def progress-header
"# Progress")
(defexample progress-basic
"## Basic"
(dom/div #js {}
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Indeterminate")
(dom/progress #js {:className "c-progress" :aria-hidden false}))
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Indeterminate & Dense")
(dom/progress #js {:className "c-progress c-progress--dense" :aria-hidden false}))
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Value")
(dom/progress #js {:className "c-progress" :max "100" :value "70" :aria-hidden false}))
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Value & Small")
(dom/progress #js {:className "c-progress c-progress--dense" :max "100" :value "70" :aria-hidden false}))))
;; -------------------------
;; Radio
;; -------------------------
(def radio-header
"# Radio")
(defexample radio
"### Basic"
(let [selection (or (om/get-state this :selection) 1)
select (fn [n] (om/update-state! this assoc :selection n))]
(dom/div #js {}
(dom/div #js {:className "u-trailer--quarter"}
(dom/input #js {:id "r1" :type "radio" :className "c-radio c-radio--expanded" :name "radiogroup"
:checked (= 1 selection) :onClick #(select 1)})
(dom/label #js {:id "r1l" :htmlFor "r1"} "A"))
(dom/div #js {:className "u-trailer--quarter"}
(dom/input #js {:id "r2" :type "radio" :className "c-radio c-radio--expanded" :name "radiogroup"
:checked (= 2 selection) :onClick #(select 2)})
(dom/label #js {:id "r2l" :htmlFor "r2"} "B"))
(dom/div #js {:className "u-trailer--quarter"}
(dom/input #js {:id "r3" :type "radio" :className "c-radio c-radio--expanded" :name "radiogroup"
:checked (= 3 selection) :onClick #(select 3)})
(dom/label #js {:htmlFor "r3"} "C")))))
(defexample radio-stacked
"### Stacked"
(let [selection (or (om/get-state this :selection) 1)
select (fn [n] (om/update-state! this assoc :selection n))]
(dom/div #js {}
(dom/input #js {:id "sr1" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 1 selection) :onClick #(select 1)})
(dom/label #js {:id "sr1l" :htmlFor "sr1"} "1")
(dom/input #js {:id "sr2" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 2 selection) :onClick #(select 2)})
(dom/label #js {:id "sr2l" :htmlFor "sr2"} "2")
(dom/input #js {:id "sr3" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 3 selection) :onClick #(select 3)})
(dom/label #js {:htmlFor "sr3"} "3")
(dom/input #js {:id "sr4" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 4 selection) :onClick #(select 4)})
(dom/label #js {:htmlFor "sr4"} "4")
(dom/input #js {:id "sr5" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 5 selection) :onClick #(select 5)})
(dom/label #js {:htmlFor "sr5"} "5"))))
;; -------------------------
;; Slider
;; -------------------------
(def slider-header
"# Slider
A simple range input slider")
(defexample slider
"### Simple
"
(let [active (boolean (om/get-state this :active))
]
(dom/div nil
(dom/input #js {:className "c-slider"
:id "range-1"
:type "range"
:value 0})
(dom/input #js {:className "c-slider"
:id "range-1"
:type "range"
:value 25})
(dom/input #js {:className "c-slider"
:id "range-1"
:type "range" })
(dom/input #js {:className "c-slider"
:id "range-1"
:disabled true
:type "range"
:value 0})
(dom/input #js {:className "c-slider"
:id "range-1"
:disabled true
:type "range" })
)))
;; -------------------------
Switch
;; -------------------------
(def switch-header
"# Switch
A simple control to indicate if somehting is on or off.")
(defexample switch
"### Simple
Click this example to see it's active state which is a simple `:checked` attribute on `.c-switch__input`."
(let [active (boolean (om/get-state this :active))]
(dom/div #js {:className "c-switch"
:onClick #(om/update-state! this update :active not)}
(dom/input #js {:className "c-switch__input"
:id "h-switch-input-1"
:type "checkbox"
:checked (= active true)})
(dom/label #js {:className "c-switch__paddle"
:aria-hidden false
:htmlFor "h-switch-input-1"}))))
(defexample switch-icon
"### Icons
You can put up to 2 icons inside the `.c-switch__paddle` that represent what off and on actually do."
(let [active (boolean (om/get-state this :active))]
(dom/div #js {:className "c-switch"
:onClick #(om/update-state! this update :active not)}
(dom/input #js {:className "c-switch__input"
:id "h-switch-input-1"
:type "checkbox"
:checked (= active true)})
(dom/label #js {:className "c-switch__paddle"
:htmlFor "h-switch-input-1"}
(icons/icon :clear)
(icons/icon :done)))))
;; -------------------------
;; Tables
;; -------------------------
(def tables-header
"# Tables")
(defexample tables
"### Basic"
(let [kind (or (om/get-state this :kind))
set-kind (fn [k] (om/update-state! this assoc :kind k))]
(dom/div #js {}
(dom/div #js {}
(dom/span nil "View ")
(dom/button #js {:aria-label "Default" :onClick #(set-kind nil)
:type "button"
:className (str "c-button c-button--small " (when (= kind nil) "is-active"))}
(dom/span #js {:className "c-button__content"} "Default"))
(dom/button #js {:aria-label "Swipe View" :onClick #(set-kind "swipe")
:type "button"
:className (str "c-button c-button--small " (when (= kind "swipe") "is-active"))}
(icons/icon :view_headline)
(dom/span #js {:className "c-button__content"} "Swipe"))
(dom/button #js {:aria-label "Toggle View" :onClick #(set-kind "toggle")
:type "button"
:className (str "c-button c-button--small " (when (= kind "toggle") "is-active"))}
(icons/icon :view_week)
(dom/span #js {:className "c-button__content"} "Toggle"))
(dom/button #js {:aria-label "Stacked View" :onClick #(set-kind "stacked")
:type "button"
:className (str "c-button c-button--small " (when (= kind "stacked") "is-active"))}
(icons/icon :view_agenda)
(dom/span #js {:className "c-button__content"} "Stacked")))
(dom/table #js {:className (str "c-table c-table--" kind)}
(dom/caption nil "Table Example")
(dom/thead nil
(dom/tr #js {:className "c-table__week"}
(dom/th #js {:scope "col"} "Agent")
(dom/th #js {:scope "col" :className "c-table__priority-3"} "Opens")
(dom/th #js {:scope "col" :className "c-table__priority-2"} "Open %")
(dom/th #js {:scope "col" :className "c-table__priority-1"} "Clicks")
(dom/th #js {:scope "col" :className "c-table__priority-4"} "Click %")
(dom/th #js {:scope "col" :className "c-table__priority-5"} "Booked")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Attr Rev")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Bounce %")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Share %")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Unsub %")))
(dom/tbody #js {}
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "GMC"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "300"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "60"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "3000"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "12000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "32800"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "32")))
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "Dodge"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "100"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "54"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "1200"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "18"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "6000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "24000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "18"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "18"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "18")))
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "Volvo"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "600"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "72"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "960"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "42"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "3000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "1200"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "42"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "42"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "42")))
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "Audi"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "300"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "60"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "840"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "12000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "30800"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "32"))))))))
;; -------------------------
;; Tooltips
;; -------------------------
(def tooltips-header
"# Tooltips
Tool tips are based on `data` attributes.")
(defexample tooltips
"### Basic"
(dom/button #js {:data-tooltip "Hey!" :className "c-button" :type "button"} "Hover me!"))
(defexample tooltip-directions
"### Directions"
(dom/div #js {}
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "up" :className "c-button c-button--large" :type "button"} "Hover me!"))
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "left" :className "c-button c-button--large" :type "button"} "Hover me!"))
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "right" :className "c-button c-button--large" :type "button"} "Hover me!"))
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "down" :className "c-button c-button--large" :type "button"} "Hover me!"))))
(defexample tooltip-sizes
"### Sizes"
(dom/div #js {}
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-length "small" :className "c-button c-button--large" :type "button"} "Small") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "Now that's a super big text we have over here right? Lorem ipsum dolor sit I'm done." :data-tooltip-length "medium" :className "c-button c-button--large" :type "button"} "Medium") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "What about something really big? This may surpass your window dimensions. Imagine you're on that boring class with that boring teacher and you didn't slept so well last night. Suddenly you're sleeping in class. Can you believe it?!" :data-tooltip-length "large" :className "c-button c-button--large" :type "button"} "Large") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "What about something really big? This may surpass your window dimensions. Imagine you're on that boring class with that boring teacher and you didn't slept so well last night. Suddenly you're sleeping in class. Can you believe it?!" :data-tooltip-length "xlarge" :className "c-button c-button--large" :type "button"} "X-Large") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "What about something really big? This may surpass your window dimensions. Imagine you're on that boring class with that boring teacher and you didn't slept so well last night. Suddenly you're sleeping in class. Can you believe it?!" :data-tooltip-length "fit" :className "c-button c-button--large" :type "button"} "My width will fit to element") " ") " "))
(defn toggle-pause [this] (om/update-state! this update :pause not))
(defexample button-group
"# Button Group"
(let [pause (boolean (om/get-state this :pause))]
(dom/div #js {}
(dom/label #js {:htmlFor "target"} "Control")
(dom/div #js {:className "o-button-group--toggle" :id "target"}
(dom/button #js {:className (str "c-button " (if pause "" " c-button--raised c-button--primary"))
:type "button"
:onClick #(toggle-pause this)} "Play")
(dom/button #js {:className (str "c-button " (if (not pause) "" "c-button--raised c-button--primary"))
:type "button"
:onClick #(toggle-pause this)} "Pause")))))
(defexample postfix-group
"# Button Group Postfix Example
**Please Note** This does not work well on mobile with multiple buttons. To fix this we hacked out the second button. Use at your own risk.
"
(dom/div #js {}
(dom/div #js {:className "u-row u-row--collapse"}
(dom/div #js {:className "u-column--9"}
(dom/input #js {:type "text" :placeholder "Multiple buttons on the end" :className "c-input"}))
(dom/div #js {:className "u-column--3"}
(dom/div #js {:className "o-button-group"}
(dom/button #js {:className "c-button c-button--postfix"} "Go")
(dom/button #js {:className "c-button c-button--postfix u-hide@sm"} "Start"))))))
(defn render-calendar-week [lowerRange upperRange]
(for [x (range lowerRange (+ upperRange 1))
:let [y (dom/td #js {:key (str "id-" x) :className "c-calendar__day"} x)]]
y))
(defexample calendar-example
"### Calendar Example"
(dom/div #js {}
(dom/div #js {:className "u-wrapper"}
(dom/label #js {:className "is-optional" :htmlFor "dateInput"} " X Date")
(dom/div #js {:className "c-field"}
(dom/input #js {:readOnly true :value "January 19, 2017" :id "dateInput" :type "text" :className "c-field__input"}))
(dom/div #js {:className "c-calendar"}
(dom/header #js {:className "c-calendar__control u-middle"}
(dom/button #js {:title "Last Month" :className "c-button c-button--icon" :type "button"}
(icons/icon :keyboard_arrow_left))
(dom/span #js {} "January 2017")
(dom/button #js {:title "Today" :className "c-button c-button--icon" :type "button"}
(icons/icon :today))
(dom/button #js {:title "Next Month" :className "c-button c-button--icon" :type "button"}
(icons/icon :keyboard_arrow_right)))
(dom/div #js {:className "o-calendar__month"}
(dom/table #js {:role "presentation"}
(dom/tbody #js {}
(dom/tr #js {:className "c-calendar__week"}
(dom/td #js {} "Su")
(dom/td #js {} "M")
(dom/td #js {} "Tu")
(dom/td #js {} "W")
(dom/td #js {} "Th")
(dom/td #js {} "F")
(dom/td #js {} "Sa"))
(dom/tr #js {}
(dom/td #js {:className "c-calendar__day is-inactive"} "27")
(dom/td #js {:className "c-calendar__day is-inactive"} "28")
(dom/td #js {:className "c-calendar__day is-inactive"} "29")
(dom/td #js {:className "c-calendar__day is-inactive"} "30")
(dom/td #js {:className "c-calendar__day is-inactive"} "31")
(render-calendar-week 1 2))
(dom/tr #js {}
(render-calendar-week 3 9))
(dom/tr #js {}
(render-calendar-week 10 16))
(dom/tr #js {}
(render-calendar-week 17 18)
(dom/td #js {:className "c-calendar__day is-active"} "19")
(render-calendar-week 20 23))
(dom/tr #js {}
(render-calendar-week 24 30)
))))))))
(defn toggle-drawer [this] (om/update-state! this update :drawer not))
(defexample drawer
"# Drawer"
(let [drawer (boolean (om/get-state this :drawer))]
(e/ui-iframe {:width "100%" :height "480px"}
(dom/div #js {}
(dom/link #js {:rel "stylesheet" :href "css/untangled-ui.css"})
(dom/button #js {:className "c-button"
:onClick #(toggle-drawer this)} "Show/Hide Drawer Example")
(dom/div #js {:className (str "c-drawer c-drawer--right" (when drawer " is-open"))}
(dom/header #js {:className "c-drawer__header u-row u-middle"}
(dom/h1 #js {:className ""} "Just Another Drawer"))
(dom/div #js {:className "c-list"}
(dom/div #js {:className "c-drawer__group"}
(dom/div #js {:className "c-drawer__action"}
(icons/icon :games) "Games")
(dom/div #js {:className "c-drawer__action"}
(icons/icon :movie) "Movies")
(dom/div #js {:className "c-drawer__action"}
(icons/icon :book) "Books"))
(dom/div #js {:className "c-drawer__group"}
(dom/div #js {:className "c-drawer__subheader"} "Subheader")
(dom/div #js {:className "c-drawer__action"}
"Settings")
(dom/div #js {:className "c-drawer__action"}
"Help & Feedback"))
))
(dom/div #js {:className (str "c-backdrop" (when drawer " is-active"))
:onClick #(toggle-drawer this)})))))
(defexample icon-bar
"# Icon Bar"
(dom/div #js {}
(dom/nav #js {:className "c-iconbar"}
(dom/button #js {:className "c-iconbar__item is-active" :type "button"}
(icons/icon :home)
(dom/span #js {:className "c-iconbar__label"} "Home"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :description)
(dom/span #js {:className "c-iconbar__label"} "Docs"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :feedback)
(dom/span #js {:className "c-iconbar__label"} "Support"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(dom/span #js {:className "c-icon"}
(dom/svg #js {:width "24" :height "24" :xmlns "" :viewBox "0 0 24 24" :role "img"}
(dom/path #js {:d "M12 0c-6.627 0-12 5.406-12 12.073 0 5.335 3.438 9.859 8.207 11.455.6.111.819-.262.819-.581l-.017-2.247c-3.337.729-4.042-1.424-4.042-1.424-.546-1.394-1.332-1.765-1.332-1.765-1.091-.749.083-.734.083-.734 1.205.084 1.839 1.244 1.839 1.244 1.071 1.845 2.81 1.312 3.492 1.002.109-.778.42-1.312.762-1.612-2.664-.305-5.466-1.341-5.466-5.967 0-1.319.468-2.395 1.234-3.24-.122-.307-.535-1.535.119-3.196 0 0 1.006-.324 3.3 1.238.957-.269 1.983-.402 3.003-.406 1.02.004 2.046.139 3.004.407 2.29-1.564 3.297-1.238 3.297-1.238.656 1.663.243 2.89.12 3.195.769.845 1.233 1.921 1.233 3.24 0 4.638-2.807 5.659-5.48 5.958.432.374.814 1.108.814 2.234 0 1.614-.016 2.915-.016 3.313 0 .321.218.697.826.579 4.765-1.599 8.2-6.123 8.2-11.455 0-6.667-5.373-12.073-12-12.073z"})))
(dom/span #js {:className "c-iconbar__label"} "Github")))))
(defexample icon-rail
"# Icon Rail Example
Just add an extra modifier class `.c-iconbar--rail` and you'll get this effect.
"
(dom/div #js {}
(dom/nav #js {:className "c-iconbar c-iconbar--rail"}
(dom/button #js {:className "c-iconbar__item is-active" :type "button"}
(icons/icon :home)
(dom/span #js {:className "c-iconbar__label"} "Home"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :description)
(dom/span #js {:className "c-iconbar__label"} "Docs"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :feedback)
(dom/span #js {:className "c-iconbar__label"} "Support"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(dom/span #js {:className "c-icon"}
(dom/svg #js {:width "24" :height "24" :xmlns "" :viewBox "0 0 24 24" :role "img"}
(dom/path #js {:d "M12 0c-6.627 0-12 5.406-12 12.073 0 5.335 3.438 9.859 8.207 11.455.6.111.819-.262.819-.581l-.017-2.247c-3.337.729-4.042-1.424-4.042-1.424-.546-1.394-1.332-1.765-1.332-1.765-1.091-.749.083-.734.083-.734 1.205.084 1.839 1.244 1.839 1.244 1.071 1.845 2.81 1.312 3.492 1.002.109-.778.42-1.312.762-1.612-2.664-.305-5.466-1.341-5.466-5.967 0-1.319.468-2.395 1.234-3.24-.122-.307-.535-1.535.119-3.196 0 0 1.006-.324 3.3 1.238.957-.269 1.983-.402 3.003-.406 1.02.004 2.046.139 3.004.407 2.29-1.564 3.297-1.238 3.297-1.238.656 1.663.243 2.89.12 3.195.769.845 1.233 1.921 1.233 3.24 0 4.638-2.807 5.659-5.48 5.958.432.374.814 1.108.814 2.234 0 1.614-.016 2.915-.016 3.313 0 .321.218.697.826.579 4.765-1.599 8.2-6.123 8.2-11.455 0-6.667-5.373-12.073-12-12.073z"})))
(dom/span #js {:className "c-iconbar__label"} "Github")))))
(defexample icon-bar-shifting
"# Icon Bar Shifting Example
Just add an extra modifier class `.c-iconbar--shifting` and you'll get this effect.
"
(dom/div #js {}
(dom/nav #js {:className "c-iconbar c-iconbar--shifting is-mobile"}
(dom/button #js {:className "c-iconbar__item is-active" :type "button"}
(icons/icon :home)
(dom/span #js {:className "c-iconbar__label"} "Home"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :description)
(dom/span #js {:className "c-iconbar__label"} "Docs"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :feedback)
(dom/span #js {:className "c-iconbar__label"} "Support"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(dom/span #js {:className "c-icon"}
(dom/svg #js {:width "24" :height "24" :xmlns "" :viewBox "0 0 24 24" :role "img"}
(dom/path #js {:d "M12 0c-6.627 0-12 5.406-12 12.073 0 5.335 3.438 9.859 8.207 11.455.6.111.819-.262.819-.581l-.017-2.247c-3.337.729-4.042-1.424-4.042-1.424-.546-1.394-1.332-1.765-1.332-1.765-1.091-.749.083-.734.083-.734 1.205.084 1.839 1.244 1.839 1.244 1.071 1.845 2.81 1.312 3.492 1.002.109-.778.42-1.312.762-1.612-2.664-.305-5.466-1.341-5.466-5.967 0-1.319.468-2.395 1.234-3.24-.122-.307-.535-1.535.119-3.196 0 0 1.006-.324 3.3 1.238.957-.269 1.983-.402 3.003-.406 1.02.004 2.046.139 3.004.407 2.29-1.564 3.297-1.238 3.297-1.238.656 1.663.243 2.89.12 3.195.769.845 1.233 1.921 1.233 3.24 0 4.638-2.807 5.659-5.48 5.958.432.374.814 1.108.814 2.234 0 1.614-.016 2.915-.016 3.313 0 .321.218.697.826.579 4.765-1.599 8.2-6.123 8.2-11.455 0-6.667-5.373-12.073-12-12.073z"})))
(dom/span #js {:className "c-iconbar__label"} "Github")))))
(defexample modal-example
"# Modal
### Basic"
(dom/div #js {:style #js {:position "relative" :height "400px"}}
(dom/div #js {:className (str "c-dialog is-active") :style #js {:position "absolute"}}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-dialog__title"} "Dialog title")
(dom/div #js {:className "c-dialog__content"}
(dom/span #js {} "This is a card in a dialog, what will they think of next?")
)
(dom/div #js {:className "c-dialog__actions"}
(dom/button #js {:className "c-button c-button--primary"
:type "button"
:onClick #(om/update-state! this assoc :modal-visible false)} "Cancel")
(dom/button #js {:className "c-button c-button--primary"
:type "button"
:onClick #(om/update-state! this assoc :modal-visible false)} "Ok"))
))
(dom/div #js {:className (str "c-backdrop _is-active") :style #js {:position "absolute"}})))
(defviewport modal-fullscreen-1
"Fullscreen modal"
(dom/div #js {:className "c-dialog c-dialog--fullscreen"}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-toolbar c-toolbar--primary c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__row c-toolbar__row--expanded"}
(dom/div #js {:className "c-toolbar__view"}
(dom/button #js {:className "c-button c-button--icon"} (icons/icon :close))
(dom/span #js {:className "c-toolbar__label"} "Modal title"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button"} "Save"))))
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button c-button--wide"} ""))
(dom/div #js {:className "c-dialog__content"}
(dom/input #js {:className "c-field c-field--large u-trailer" :placeholder "Event name"})
(dom/input #js {:className "c-field" :placeholder "Location"})
(dom/label #js {:className "is-optional u-leader--half"} "Start time")
(dom/input #js {:className "c-field" :placeholder "12:00 AM"})
(dom/label #js {:className "is-optional u-leader--half"} "End time")
(dom/input #js {:className "c-field" :placeholder "1:00 PM"})
(dom/input #js {:className "c-field" :placeholder "Room"})))))
(defviewport modal-fullscreen-2
"Fullscreen modal with another modal"
(dom/div #js {:style #js {:position "relative" :height "570px"}}
(dom/div #js {:className (str "c-dialog is-active") :style #js {:position "absolute"}}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-dialog__content"}
(dom/span #js {} "Discard new event?"))
(dom/div #js {:className "c-dialog__actions"}
(dom/button #js {:className "c-button c-button--primary"
:onClick #(om/update-state! this assoc :modal-visible false)} "Cancel")
(dom/button #js {:className "c-button c-button--primary"
:onClick #(om/update-state! this assoc :modal-visible false)} "Erase"))))
(dom/div #js {:className (str "c-backdrop is-active") :style #js {:position "absolute"}})
(dom/div #js {:className "c-dialog c-dialog--fullscreen"}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-toolbar c-toolbar--primary c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__row c-toolbar__row--expanded"}
(dom/div #js {:className "c-toolbar__view"}
(dom/button #js {:className "c-button c-button--icon"} (icons/icon :close))
(dom/span #js {:className "c-toolbar__label"} "Modal title"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button"} "Save"))))
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button c-button--wide"} ""))
(dom/div #js {:className "c-dialog__content"}
(dom/input #js {:className "c-field c-field--large u-trailer" :placeholder "Event name"})
(dom/input #js {:className "c-field" :placeholder "Location"})
(dom/label #js {:className "is-optional u-leader--half"} "Start time")
(dom/input #js {:className "c-field" :placeholder "12:00 AM"})
(dom/label #js {:className "is-optional u-leader--half"} "End time")
(dom/input #js {:className "c-field" :placeholder "1:00 PM"})
(dom/input #js {:className "c-field" :placeholder "Room"}))))))
(defexample toolbar
"# Toolbar Example"
(let [changed-menu (om/get-state this :changed-menu)
ui-menu-open (if (= (:id changed-menu) :ui) (:open-state changed-menu) nil)
lang-menu-open (if (= (:id changed-menu) :lang) (:open-state changed-menu) nil)
ui-menu-class (str "c-menu" (if ui-menu-open " is-active" ""))
lang-menu-class (str "c-menu c-menu--right " (if lang-menu-open " is-active" ""))
lang-item-selected (or (if (= (:id changed-menu) :lang) (:selected-item changed-menu) nil) "English-US")
menu-action (fn [menu opened item]
(om/update-state! this assoc :changed-menu {:id menu :open-state opened :selected-item item}))]
(e/ui-iframe {:width "100%" :height "300px"}
(dom/div #js { :style #js {:backgroundColor "#efefef" :height "300px"}}
(dom/div #js {:className "c-toolbar"}
(dom/link #js {:rel "stylesheet" :href "css/untangled-ui.css"})
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(e/ui-icon {:glyph :menu})))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"} (icons/icon :help))
(dom/button #js {:className "c-button c-button--icon"
:title "Kevin Mitnick" :type "button"}
(icons/icon :account_circle)))))))))
(defexample toolbar-colors
"### Colors"
(let [changed-menu (om/get-state this :changed-menu)
ui-menu-open (if (= (:id changed-menu) :ui) (:open-state changed-menu) nil)
lang-menu-open (if (= (:id changed-menu) :lang) (:open-state changed-menu) nil)
ui-menu-class (str "c-menu" (if ui-menu-open " is-active" ""))
lang-menu-class (str "c-menu c-menu--right " (if lang-menu-open " is-active" ""))
lang-item-selected (or (if (= (:id changed-menu) :lang) (:selected-item changed-menu) nil) "English-US")
menu-action (fn [menu opened item]
(om/update-state! this assoc :changed-menu {:id menu :open-state opened :selected-item item}))]
(dom/div nil
(dom/div #js {:className "c-toolbar c-toolbar--primary c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :menu)))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__view"}
(dom/span #js {:className "c-toolbar__label"} "Primary toolbar"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :help))
(dom/span #js {:title "Kevin Mitnick"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :account_circle))))))
(dom/p nil " ")
(dom/div #js {:className "c-toolbar c-toolbar--dark c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :arrow_back)))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__view"}
(dom/span #js {:className "c-toolbar__label"} "Dark toolbar"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :filter_list))
(dom/span #js {:title "Kevin Mitnick"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :search)))))))))
(defexample toolbar-dense
"### Dense
This toolbar is mainly used for specific operations and navigation for the current app you are using.
"
(let [selected-item (or (om/get-state this :selected-item) :widgets)
get-class (fn [item] (str "c-tab c-tab--contrast " (if (= item selected-item) " is-active" "")))
select-item (fn [item] (om/update-state! this assoc :selected-item item))]
(e/ui-iframe {:width "100%"}
(dom/div #js {:className "c-toolbar c-toolbar--raised c-toolbar--dark"}
(dom/link #js {:rel "stylesheet" :href "css/untangled-ui.css"})
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :menu)))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__view"}
(dom/span #js {:className "c-toolbar__label"} "Second row is dense"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :help))
(dom/span #js {:title "Kevin Mitnick"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :account_circle)))))
(dom/div #js {:className "c-toolbar__row c-toolbar__row--dense"}
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className (get-class :widgets)
:type "button"
:onClick #(select-item :widgets)} "Widgets")
(dom/button #js {:className (get-class :doodads)
:type "button"
:onClick #(select-item :doodads)} "Doodads")
(dom/button #js {:className (get-class :apparatuses)
:type "button"
:onClick #(select-item :apparatuses)} "Apparatuses")
(dom/button #js {:className (get-class :things)
:type "button"
:onClick #(select-item :things)} "Things")))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; START OF SECTIONS (within a feature set...e.g. components)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NOTE: This is where you add the sections for index
(def sections
(vec (sort-by :title
[
;; NOTE: :examples is a list of example names, rendered in order given
First show the basic pattern , then modifiers , then elements .
;; This order is important to the learning process.
{:id :avatar
:title "Avatar"
:documentation avatar-header
:examples [ avatar avatar-group avatar-customize ]}
{:id :badges
:title "Badges"
:documentation badge-header
:examples [ badge badge-button badge-icon badge-customize ]}
{:id :buttons
:title "Buttons"
:documentation button-header
:examples [ button button-shape button-color button-state button-state-raised button-icon button-group ]}
{:id :calendar-example :title "Calendar" :examples [calendar-example]
:documentation
"# Calendar
This is a month view calendar for overlaying on input fields that control date selection."}
{:id :card
:title "Card"
:documentation card-header
:examples [ card card-states card-transparent card-ruled ]}
{:id :checkboxes
:title "Checkboxes"
:documentation checkbox-header
:examples [ checkboxes ]}
{:id :drawer
:title "Drawer"
:examples [ drawer ]}
{:id :expanding_panel
:title "Expansion panels"
:documentation expansion-panel-header
:examples [ expansion-panel expansion-panel-survey ] }
{:id :fields
:title "Fields"
:documentation field-header
:examples [ field field-states field-sizes field-icon field-content textarea ]}
{:id :icons
:title "Icons"
:documentation icon-header
:examples [ icons icon-sizes icon-states icon-library ]}
{:id :icon-bar
:title "Icon Bar"
:examples [ icon-bar icon-rail icon-bar-shifting ]}
{:id :labels
:title "Labels"
:documentation label-header
:examples [ labels label-icons ]}
{:id :lists
:title "Lists"
:documentation lists-header
:examples [ lists ]}
{:id :loader
:title "Loader"
:documentation loader-header
:examples [ loader ]}
{:id :dropdowns
:title "Menus"
:documentation menus-header
:examples [ menus menus-shape menus-search-multi menus-data ]}
{:id :messages
:title "Messages"
:documentation messages-header
:examples [ messages messages-raised ]}
{:id :modal
:title "Dialog"
:examples [ modal-example modal-fullscreen-1 modal-fullscreen-2 ]}
{:id :notifications
:title "Notifications"
:documentation notification-header
:examples [ notification notification-success notification-warning notification-error notification-wide ]}
{:id :progressbar
:title "Progress"
:documentation progress-header
:examples [ progress-basic]}
{:id :radio
:title "Radio Buttons"
:documentation radio-header
:examples [ radio radio-stacked]}
{:id :slider
:title "Slider"
:documentation slider-header
:examples [ slider ]}
{:id :switch
:title "Switch"
:documentation switch-header
:examples [ switch switch-icon ]}
{:id :table
:title "Tables"
:documentation tables-header
:examples [ tables ]}
{:id :menus
:title "Tabs"
:documentation tabs-header
:examples [ tabs tabs-colors tabs-dropdown ]}
{:id :toolbar
:title "Toolbar"
:examples [ toolbar toolbar-colors toolbar-dense ]}
{:id :tooltip
:title "Tooltips"
:documentation tooltips-header
:examples [ tooltips tooltip-directions tooltip-sizes ]}])))
| null | https://raw.githubusercontent.com/untangled-web/untangled-ui/ae101f90cd9b7bf5d0c80e9453595fdfe784923c/src/css-guide/styles/components.cljs | clojure |
START OF EXAMPLES
-------------------------
Avatar
-------------------------
-------------------------
Badges
-------------------------
-------------------------
Buttons
-------------------------
-------------------------
Card
-------------------------
-------------------------
-------------------------
Single checkbox, no label text
-------------------------
Menus
-------------------------
Top left
Bottom left
Top right
Bottom right
-------------------------
Expanding Panel
-------------------------
-------------------------
Field
-------------------------
File upload
This is the button to init the upload dialog
This is the input that displays the file name when selected
When you have multiple files selected, this label should read "X files selected"
-------------------------
Icons
-------------------------
-------------------------
Labels
-------------------------
-------------------------
Lists
-------------------------
-------------------------
Loader
-------------------------
-------------------------
Tabs
-------------------------
-------------------------
Messages
-------------------------
-------------------------
Notifications
-------------------------
-------------------------
Progress
-------------------------
-------------------------
Radio
-------------------------
-------------------------
Slider
-------------------------
-------------------------
-------------------------
-------------------------
Tables
-------------------------
-------------------------
Tooltips
-------------------------
START OF SECTIONS (within a feature set...e.g. components)
NOTE: This is where you add the sections for index
NOTE: :examples is a list of example names, rendered in order given
This order is important to the learning process. | (ns styles.components
(:require [om.next :as om :refer-macros [defui]]
[styles.util :as util :refer [to-cljs] :refer-macros [source->react defexample defarticle defview defviewport]]
[untangled.ui.layout :as l]
[untangled.icons :as icons]
[om.dom :as dom]
[untangled.ui.elements :as e]))
(def avatar-header
"# Avatar")
(defexample avatar
"An avatar is a round symbol to represent a person's identity. When there is no visual, we use the first and last
initial of their name."
(l/row {}
(l/col {:width 2}
(dom/span #js {:className "c-avatar"} "AV"))
(l/col {:width 2}
(dom/span #js {:className "c-avatar"} (icons/icon :help)))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account)))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :supervisor_account)))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--bordered c-avatar--primary"} "KB"))
(l/col {:width 2}
(dom/span #js {:className "c-avatar c-avatar--bordered c-avatar--accent"} "KB"))
(l/col {:width 12}
(dom/span #js {:className "c-avatar c-avatar--medium"} "MD")
(dom/span #js {:className "c-avatar c-avatar--large"} "LG")
(dom/span #js {:className "c-avatar c-avatar--xlarge"} "XL")
(dom/span #js {:className "c-avatar c-avatar--huge"} "HU"))))
(defexample avatar-group
"### Avatar Group
A group of avatars bundled into one block"
(dom/div nil
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--medium"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--medium"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--medium"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--large"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--large"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--large"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {:className "u-trailer"}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--xlarge"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--xlarge"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar"} (icons/icon :add))))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--xlarge"}
(dom/span #js {:className "c-avatar c-avatar--primary"} (icons/icon :supervisor_account))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :person))
(dom/span #js {:className "c-avatar c-avatar--accent"} (icons/icon :weekend))
(dom/span #js {:className "c-avatar"} (icons/icon :add)))))
(l/row {}
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--huge"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)})
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)})))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--huge"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)})
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)})
(dom/img #js {:src (:photo (util/mock-users :3)) :alt (util/full-name :3)})))
(l/col {:width 2}
(dom/span #js {:className "c-avatar-group c-avatar-group--huge"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)})
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)})
(dom/img #js {:src (:photo (util/mock-users :3)) :alt (util/full-name :3)})
(dom/img #js {:src (:photo (util/mock-users :4)) :alt (util/full-name :4)}))))
)
)
(defarticle avatar-customize
"### Customize
Use these custom properties in your stylesheet to change how your avatars look.
```css
```
")
(def badge-header
"# Badge")
(defexample badge
"### Basic
You can make a badge from a `span` or `div` element using the `.c-badge` classname."
(dom/a #js {:href "guide-css.html"} "Inbox "
(dom/span #js {:className "c-badge"} 7)))
(defexample badge-button
"### In a button"
(dom/p #js {}
(dom/button #js {:className "c-button c-button--raised" :type "button"} " Messages "
(dom/span #js {:className "c-badge"} "37"))
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} " Messages "
(dom/span #js {:className "c-badge"} "37"))
(dom/button #js {:className "c-button c-button--raised c-button--accent" :type "button"} " Messages "
(dom/span #js {:className "c-badge"} "37"))))
(defexample badge-icon
"### Icon, no text"
(dom/span #js {:className "c-badge c-badge--round"}
(icons/icon :alarm)))
(defarticle badge-customize
"### Customize
Use these custom properties in your stylesheet to change how your badges look.
```css
```
")
(def button-header
"# Buttons
Use these button classes on `<button>` or `<input type='submit'>` element. It's easy to make a new button.")
(defview button
"### Button types"
(dom/div #js {:className "u-row u-center"}
(dom/div #js {:className "u-column"}
(dom/button #js {:className "c-button c-button--primary c-button--circular" :type "button"} (icons/icon :add))
(dom/div #js {:className "u-font-size--small u-leader"} "Circular button"))
(dom/div #js {:className "u-column"}
(dom/button #js {:className "c-button c-button--primary c-button--raised" :type "button"} "Button")
(dom/div #js {:className "u-font-size--small u-leader"} "Raised button"))
(dom/div #js {:className "u-column"}
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Button")
(dom/div #js {:className "u-font-size--small u-leader"} "Flat button"))))
(defexample button-shape
"### Size and form
You can optionally use modifier classes that let you manipulate the size and shape of your button.
"
(dom/div #js {}
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} "Regular")
(dom/button #js {:className "c-button c-button--raised c-button--primary c-button--round" :type "button"} "Round")
(dom/button #js {:className "c-button c-button--raised c-button--primary c-button--dense" :type "button"} "Dense")
(dom/div #js {:className "u-trailer--quarter"}
(dom/button #js {:className "c-button c-button--raised c-button--primary c-button--wide" :type "button"} "Wide"))))
(defexample button-color
"### Colors
Stateful color classes are provided to further communicate the intentions of your button action."
(dom/div #js {}
(dom/button #js {:className "c-button" :type "button"} "Flat")
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Flat Primary")
(dom/button #js {:className "c-button c-button--accent" :type "button"} "Flat Accent")
(dom/button #js {:className "c-button c-button--raised" :type "button"} "Raised")
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} "Raised Primary")
(dom/button #js {:className "c-button c-button--raised c-button--accent" :type "button"} "Raised Accent")))
(defview button-state
"### Flat Button States"
(dom/div #js {:className "u-row u-row--collapsed u-center"}
(dom/div #js {:className "u-column--12 u-column--6@md"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button" :disabled true :type "button"} "Disabled")))
(dom/div #js {:className "u-column--12 u-column--6@md t-dark"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button" :disabled true :type "button"} "Disabled")))))
(defview button-state-raised
"### Raised Button States"
(dom/div #js {:className "u-row u-row--collapsed u-center"}
(dom/div #js {:className "u-column--12 u-column--6@md"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button c-button--raised" :disabled true :type "button"} "Disabled"))
)
(dom/div #js {:className "u-column--12 u-column--6@md t-dark"}
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"} "Normal"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised c-button--primary is-focused" :type "button"} "Focused"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:className "c-button c-button--raised c-button--primary is-active" :type "button"} "Pressed"))
(dom/div #js {:className "u-leader u-trailer"} (dom/button #js {:aria-disabled "true" :className "c-button c-button--raised c-button--primary" :disabled true :type "button"} "Disabled")))))
(defexample button-icon
"### Buttons with icons"
(dom/div nil
(dom/button #js {:className "c-button c-button--raised" :type "button"}
(icons/icon :arrow_back)
(dom/span #js {:className "c-button__content"} "Left Icon"))
(dom/button #js {:className "c-button c-button--raised" :type "button"}
(dom/span #js {:className "c-button__content"} "Right Icon")
(icons/icon :arrow_forward))
(dom/button #js {:title "Icon Button" :className "c-button c-button--icon" :type "button"}
(icons/icon :translate))))
(def card-header
"# Cards")
(defexample card
"### Basic"
(dom/div #js {:className "u-row u-center"}
(dom/div #js {:className "c-card c-card--primary c-card--bordered c-card--wide c-card--3587358"}
(dom/div #js {:className "c-card__title c-card__title--image-bottom-right"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "Suspendisse potenti. Phasellus ac ex sit amet erat elementum
suscipit id sed sapien. Sed sit amet sagittis ipsum.")
(dom/div #js {:className "c-card__actions"}
(dom/button #js {:className "c-button c-button--primary" :type "button"} "View Updates")))
(dom/style nil (str ".c-card--3587358 .c-card__title { background-image: url('img/bubbles.png'); }"))))
(defexample card-transparent
"### Transparent Card"
(dom/div #js {:className "c-card c-card--transparent"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "This gives you the basic box properties without any background color or text color.")))
(defexample card-ruled
"### Ruled Card"
(dom/div #js {:className "u-wrapper"}
(dom/div #js {:className "c-card c-card--bordered"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "Suspendisse potenti. Phasellus ac ex sit amet erat elementum
suscipit id sed sapien. Sed sit amet sagittis ipsum. A simple card, horizontal ruled.")
(dom/div #js {:className "c-card__actions"}
(dom/button #js {:className "c-button c-button--accent" :type "button"} "Action")))))
(defexample card-states
"### States"
(dom/div nil
(dom/div #js {:className "c-card c-card--row is-active u-trailer--half"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "I could have used lorem ipsum, but what's the fun in that?"))
(dom/div #js {:className "c-card c-card--row is-inactive"}
(dom/div #js {:className "c-card__title"}
(dom/h1 #js {:className "c-card__title-text"} "Title"))
(dom/div #js {:className "c-card__supporting-text"} "I could have used lorem ipsum, but what's the fun in that?"))))
Checkboxes
(def checkbox-header
"# Checkboxes")
(defexample checkboxes
"The following examples show the various rendered states of checkboxes."
(dom/div #js {}
(dom/input #js {:id "checkbox-1" :type "checkbox" :className "c-checkbox"})
(dom/label #js {:htmlFor "checkbox-1"} \u00A0)
(dom/input #js {:id "checkbox-1" :type "checkbox" :className "c-checkbox"})
(dom/label #js {:htmlFor "checkbox-1"} "Checkbox")
(dom/input #js {:id "checkbox-2" :type "checkbox" :checked true :className "c-checkbox"})
(dom/label #js {:htmlFor "checkbox-2"} "Checked Checkbox")
(dom/input #js {:id "checkbox-3" :type "checkbox" :className "c-checkbox is-indeterminate"})
(dom/label #js {:htmlFor "checkbox-3"} "Indeterminate Checkbox")
(dom/input #js {:id "checkbox-4" :type "checkbox" :className "c-checkbox" :disabled true})
(dom/label #js {:htmlFor "checkbox-4"} "Disabled Checkbox")
(dom/input #js {:id "checkbox-5" :type "checkbox" :checked true :className "c-checkbox" :disabled true})
(dom/label #js {:htmlFor "checkbox-5"} "Disabled Checked Checkbox")
(dom/input #js {:id "checkbox-5" :type "checkbox" :className "c-checkbox is-indeterminate" :disabled true})
(dom/label #js {:htmlFor "checkbox-5"} "Disabled Indeterminate Checkbox")))
(defn toggle-open [this] (om/update-state! this update :open not))
(def menus-header
"# Menus")
(defexample menus
"### Basic
This example uses component local state to toggle the is-active class to open/close the dropdown."
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Not Selected")]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "150px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/div #js {:id "test-dropdown"
:tabIndex "-1"
:aria-hidden "true"
:className "c-menu"}
(dom/div #js {:className "c-menu__group"}
(map (fn [s]
(dom/div #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s)
)}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active"))} s))) selections))))))
(defexample menus-shape
"### Shape and form"
(dom/div nil
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Top Left Aligned")]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/ul #js {:id "test-dropdown" :tabIndex "-1" :aria-hidden "true"
:className "c-menu c-menu--top-left"}
(map (fn [s]
(dom/li #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s))}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active")) :type "button"} s))) selections))))
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Bottom Left Aligned")]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/ul #js {:id "test-dropdown" :tabIndex "-1" :aria-hidden "true"
:className "c-menu"}
(map (fn [s]
(dom/li #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s))}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active")) :type "button"} s))) selections))))
(let [open (boolean (om/get-state this :open))
selections ["Apples" "Oranges" "Banannas"]
current (or (om/get-state this :selection) "Top Right Aligned")]
(dom/div #js {:className "u-end"}
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(om/update-state! this update :open not)
:type "button"
:className "c-button "} current)
(dom/ul #js {:id "test-dropdown" :tabIndex "-1" :aria-hidden "true"
:className "c-menu c-menu--top-right"}
(map (fn [s]
(dom/li #js {:key s :onClick (fn [evt]
(om/update-state! this assoc :open false)
(om/update-state! this assoc :selection s))}
(dom/button #js {:className (str "c-menu__item" (when (= s current) " is-active")) :type "button"} s))) selections)))))
(let [open (boolean (om/get-state this :open))]
(dom/div #js {:className "u-end" :style #js {:width "180px"}}
(dom/div #js {:className (str "has-menu" (when open " is-active"))}
(dom/button #js {:onClick #(toggle-open this) :className "c-button " :type "button"} "Bottom Right Aligned")
(dom/div #js {:id "test-dropdown" :aria-hidden "true" :className "c-menu c-menu--bottom-right" :tabIndex "-1"}
(dom/div #js {:className "c-menu__group"}
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"} (icons/icon :done))
"Show ruler")
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"} (icons/icon :done))
"Show grid"))
(dom/div #js {:className "c-menu__group"}
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"})
"Hide layout")
(dom/button #js {:className (str "c-menu__item") :type "button"}
(dom/div #js {:className "c-menu__item-icon"} (icons/icon :done))
"Show bleed"))))))))
(defexample menus-search-multi
"### Multi-Select, Searchable Dropdown"
(let [open (boolean (om/get-state this :open))
items (mapv #(str "Item " %) (range 1 20))]
(dom/div #js {:className (str "has-menu" (when open " is-active")) :style #js {:width "180px"}}
(dom/button #js {:onClick #(toggle-open this) :className "c-button c-button--dropdown " :type "button"} "Filter")
(dom/div #js {:id "test-dropdown" :aria-hidden "true" :className "c-menu c-menu--large" :tabIndex "-1"}
(dom/div #js {:className "c-field"}
(icons/icon :search)
(dom/input #js {:type "text" :placeholder "Search..." :className "c-field__input"}))
(dom/div #js {:className "c-menu__viewer"}
(map (fn [item]
(dom/div #js {:key item :className "u-leader--sixth u-trailer--sixth"}
(dom/input #js {:type "checkbox" :id (str item "-cb") :className "c-checkbox"})
(dom/label #js {:htmlFor (str item "-cb")} item)))
items))
(dom/button #js {:onClick #(om/update-state! this assoc :open false) :className "c-button c-button--primary c-button--wide" :type "button"} "Apply")))))
(defexample menus-data
"### Multiple list group selection
This is a control that is meant to let you view what various dropdowns would show, for example in cases
of UI that lets you configure UI.
Note: The dropdown list underneath should not be enabled when the dropdown list is visible. Doing this fosters a better interaction for the user."
(let [open (boolean (om/get-state this :open))
name (or (om/get-state this :menu-name) "Menu 1")
menu-1-items (mapv #(str "Item " %) (range 1 5))
menu-2-items (mapv #(str "Other " %) (range 1 3))
menu (or (om/get-state this :menu) menu-1-items)]
(dom/div nil
(l/row {}
(l/col {:width 4}
(dom/div #js {:className "c-card c-card--collapse"}
(dom/div #js {:className (str "has-menu" (when open " is-active"))}
(dom/button #js {:onClick #(toggle-open this)
:type "button"
:className "c-button c-button--wide"} (str "List: " name))
(dom/div #js {:id "test-dropdown" :aria-hidden "true"
:className "c-menu" :tabIndex "-1"}
(dom/button #js {:onClick #(om/update-state! this assoc :open false :menu menu-1-items :menu-name "Menu 1")
:type "button"
:className "c-menu__item"} "Menu 1")
(dom/button #js {:onClick #(om/update-state! this assoc :open false :menu menu-2-items :menu-name "Menu 2")
:type "button"
:className "c-menu__item"} "Menu 2")))
(dom/div #js {:className "c-list" :tabIndex "-1"}
(map (fn [item]
(dom/div #js {:className "c-list__row c-list__row--bordered is-selectable" :key item}
(dom/div #js {:className "c-list__tile"} item))) menu))))))))
(def expansion-panel-header
"# Expansion panels"
)
(defexample expansion-panel
"### Usage
This is a collapsed expansion panel"
(dom/div nil
(let [expanded-1 (boolean (om/get-state this :expanded-1))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-1 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-1 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Trip name")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-1
"Caribbean cruise"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(dom/input #js {:className "c-field" :type "text" :placeholder "Type in a name for your trip..." :value "Caribbean cruise" :id "inputAB"})
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:className "c-button" :type "button"} "Cancel")
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Save")))))))
(let [expanded-2 (boolean (om/get-state this :expanded-2))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-2 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-2 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Location")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(if-not expanded-2
"Barbados"
(dom/span nil "Select trip destination" (icons/icon :help_outline))))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-column--8@md u-center@md"}
(dom/span #js {:className "c-badge c-badge--large"} "Barbados" (icons/icon :cancel)))
(dom/div #js {:className "u-column--12 u-column--4@md"}
(dom/div #js {:className "u-helper-text"}
(dom/div nil "Select your destination of choice")
(dom/div nil (dom/a #js {:href "http://"} "Learn more")))))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:className "c-button" :type "button"} "Cancel")
(dom/button #js {:className "c-button c-button--primary" :type "button"} "Save")))))))
(let [expanded-3 (boolean (om/get-state this :expanded-3))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-3 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-3 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Start and end dates")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-3 "Start date: Feb 29, 2016"))
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-3 "End date: Not set"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"} "Controls for dates")))
(let [expanded-4 (boolean (om/get-state this :expanded-4))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-4 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-4 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Carrier")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-4 "The best cruise line"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"} "Controls for carrier")))
(let [expanded-5 (boolean (om/get-state this :expanded-5))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-5 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-5 not)}
(dom/div #js {:className "c-expansion-panel__title"}
(dom/div nil "Meal preferences")
(dom/div #js {:className "c-message--neutral"} "Optional"))
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-5 "Vegetarian"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"} "Stuff here")))))
(defexample expansion-panel-survey
"### Example: Editing a question
As another example of how to use this we look at how you would edit a survey question and apply conditional questions to it."
(dom/div nil
(let [expanded-1 (boolean (om/get-state this :expanded-1))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-1 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-1 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Question")
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(when-not expanded-1 "What kind of beverage do you prefer?"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse :valign :middle}
(l/col {:width 1}
(dom/label #js {:htmlFor "input1"} "Text"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input1" :type "text" :placeholder "Type a question..." :value "How was your last stay at the premium village?"}))
(l/col {:width 2 :halign :end}
(dom/label #js {:htmlFor "h-switch-input-1"} "Required?")
(dom/div #js {:className "c-switch"}
(dom/input #js {:type "checkbox"
:id "h-switch-input-1"
:checked true
:className "c-switch__input"})
(dom/span #js {:className "c-switch__paddle"
:aria-hidden false
:htmlFor "h-switch-input-1"}))))
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "input2"} "Short label"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input2" :type "text" :placeholder "Type a short question..." :value "How was your last stay?"})))
(l/row {}
(l/col {:width 9 :push 1}
(l/row {:density :collapse :className "u-trailer" :valign :bottom :halign :center}
(l/col {:className "u-column has-xpipe has-start-pipe" :halign :center}
(icons/icon :sentiment_very_dissatisfied))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel1"}
"Extremely dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "1" :id "sel1" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel2"}
"Moderately dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "2" :id "sel2" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel3"}
"Slightly dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "3" :id "sel3" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel4"}
"Neither satisfied nor dissatisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "4" :id "sel4" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel5"}
"Slightly satisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "5" :id "sel5" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel6"}
"Moderately satisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "6" :id "sel6" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe" :halign :center}
(dom/label #js {:className "is-optional u-trailer--third" :htmlFor "sel7"}
"Extremely satisfied")
(dom/input #js {:className "c-radio" :type "radio" :value "7" :id "sel7" :name "q1"})
(dom/label #js {:htmlFor "sel1"} \u00A0))
(l/col {:className "u-column has-xpipe has-end-pipe" :halign :center}
(icons/icon :sentiment_very_satisfied)))))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:type "button" :className "c-button"} "Options")
(dom/button #js {:type "button" :className "c-button"} "Move")
(dom/button #js {:type "button" :className "c-button c-button--accent"} "Add Conditional")
(dom/button #js {:type "button" :className "c-button c-button--primary"} "Save")))))))
(let [expanded-2 (boolean (om/get-state this :expanded-2))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-2 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-2 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Conditional")
(dom/div #js {:className "c-expansion-panel__info"}
(if-not expanded-2
"If beverage prefrerence is red wine."
(dom/span nil "Select conditions first" (icons/icon :help_outline))))
(dom/div #js {:className "c-expansion-panel__info" :aria-hidden false}
(if-not expanded-2 "Would you like our gm to get in touch?"))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "cond-op"} "If answer "))
(l/col {:width 1}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button" :id "cond-op"} "is")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "exactly")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "red wine"))))
(l/row {:density :collapse :valign :middle}
(l/col {:width 1}
(dom/label #js {:htmlFor "input1"} "Text"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input1" :type "text" :placeholder "Type a question..." :value "Would you like our general manager to get in touch with you?"}))
(l/col {:width 2 :halign :end}
(dom/label #js {:htmlFor "h-switch-input-1"} "Required?")
(dom/div #js {:className "c-switch"}
(dom/input #js {:type "checkbox"
:id "h-switch-input-1"
:className "c-switch__input"})
(dom/span #js {:className "c-switch__paddle"
:aria-hidden false
:htmlFor "h-switch-input-1"}))))
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "input2"} "Short label"))
(l/col {:width 9}
(dom/input #js {:className "c-field" :id "input2" :type "text" :placeholder "Type a question..." :value "Would you like our gm to get in touch?"})))
(l/row {}
(l/col {:width 11 :push 1}
(l/row {:density :collapse :valign :middle :distribute-extra-columns :between}
(l/col {:width 12 :className "u-trailer--quarter"}
(dom/input #js {:className "c-radio c-radio--expanded" :type "radio" :value "1" :id "sel1" :name "q1"})
(dom/label #js {:htmlFor "sel1"} "Yes"))
(l/col {:width 12}
(dom/input #js {:className "c-radio c-radio--expanded" :type "radio" :value "5" :id "sel5" :name "q1"})
(dom/label #js {:htmlFor "sel1"} "No")))))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:type "button" :className "c-button"} "Options")
(dom/button #js {:type "button" :className "c-button"} "Move")
(dom/button #js {:type "button" :className "c-button c-button--primary"} "Save")))))))
(let [expanded-3 (boolean (om/get-state this :expanded-3))]
(dom/div #js {:className (str "c-expansion-panel" (when expanded-3 " is-expanded"))
:tabIndex "0"}
(dom/div #js {:className "c-expansion-panel__list-content"
:onClick #(om/update-state! this update :expanded-3 not)}
(dom/div #js {:className "c-expansion-panel__title"} "Conditional")
(dom/div #js {:className "c-expansion-panel__info"}
(if-not expanded-3
"Choose a question"
(dom/span nil "Select conditions first" (icons/icon :help_outline))))
(dom/div #js {:className "c-expansion-panel__expand-icon"} (icons/icon :expand_more)))
(dom/div #js {:className "c-expansion-panel__secondary-content"}
(l/row {:density :collapse :valign :middle :className "u-trailer"}
(l/col {:width 1}
(dom/label #js {:htmlFor "cond-op"} "If answer "))
(l/col {:width 1}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button" :id "cond-op"} "is")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "exactly")))
(l/col {:width 2}
(dom/span #js {:className "has-menu"}
(dom/button #js {:type "button" :className "c-button"} "red wine"))))
(l/row {:density :collapse :valign :middle :halign :center :className "u-trailer"}
(dom/button #js {:type "button" :className "c-button c-button--primary c-button--raised"} "Choose a question"))
(dom/div #js {:className "c-expansion-panel__actions"}
(l/row {:density :collapse}
(dom/div #js {:className "u-column--12 u-end"}
(dom/button #js {:type "button" :className "c-button"} "Options")
(dom/button #js {:type "button" :className "c-button"} "Move")
(dom/button #js {:type "button" :className "c-button c-button--primary"} "Save")))))))))
(def field-header
"# Fields")
(defexample field
"### Basic"
(dom/div nil
(dom/input #js {:type "text" :required "true" :placeholder "Required field" :className "c-field" :id "field-reg"})
(dom/input #js {:type "text" :placeholder "Optional field" :className "c-field" :id "field-opt"})
(mapv (fn [typ] (dom/div #js {:key typ :className ""}
(dom/input #js {:type typ :placeholder typ :id (str "field-" typ) :className "c-field"})))
["text" "password" "date" "datetime" "datetime-local" "month" "week" "email" "number" "search" "tel" "time" "url" "color"])
(l/row {:density :collapse}
(l/col {:width 1}
(dom/label #js {:htmlFor "file-input-text"}
(dom/span #js {:className "c-button c-button--circular c-button--primary c-button--dense"}
(icons/icon :file_upload)
(dom/input #js {:type "file" :className "u-hide" :id "file-input-file"}))))
(l/col {:width 3}
(dom/input #js {:type "text" :className "c-field" :disabled true :readOnly true :id "file-input-text"})
(dom/label #js {:htmlFor "file-input-text"})))))
(defexample field-sizes
"### Sizes"
(dom/div #js {}
(dom/input #js {:type "text" :className "c-field c-field--small" :placeholder "The quick brown fox..." :id "field-small"})
(dom/input #js {:type "text" :className "c-field" :placeholder "The quick brown fox..." :id "field-regular"})
(dom/input #js {:type "text" :className "c-field c-field--medium" :placeholder "The quick brown fox..." :id "field-medium"})
(dom/input #js {:type "text" :className "c-field c-field--large" :placeholder "The quick brown fox..." :id "field-large"})))
(defexample field-states
"### States"
(dom/div #js {}
(dom/input #js {:type "text" :placeholder "FOCUSED" :className "c-field has-focus" :id "field-focus"})
(dom/input #js {:type "text" :placeholder "INVALID" :className "c-field is-invalid" :id "field-invalid"})
(dom/input #js {:type "text" :placeholder "ERROR" :className "c-field is-error" :id "field-error"})
(dom/input #js {:type "text" :placeholder "Disabled" :className "c-field" :disabled true :id "field-disabled"})))
(defexample field-icon
"### Icons"
(l/row {:density :collapse}
(dom/div #js {:className "c-icon-column"}
(icons/icon :search :className ["c-icon--framed"]))
(l/col {:className "u-column"}
(dom/div #js {:className "c-field"}
(dom/input #js {:type "search" :className "c-field__input" :placeholder "Search..." :id "field-icon"})))))
(defexample field-content
"### Content"
(l/row {}
(l/col {:width 4}
(dom/div #js {:className "c-field"}
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :1))
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :2))
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :3))
(dom/span #js {:className "c-label c-label--blue"} (util/full-name :4))
(dom/input #js {:type "text" :className "c-field__input" :id "field1"})))))
(defexample textarea
"# Text Area"
(dom/textarea #js {:className "c-input c-input--multi-line" :id "textarea"}))
(def icon-header
"# Icons
The preferred icon library is Google's <a href='/'>Material icons</a>. We include the entire library in the UI Components project in the form of svg paths that get inlined into your markup.
Use these icon classes on `<span>` elements wrapping your inline svg icons. Here is a simple icon in it's purest form.")
(defexample icons
"### Basic"
(dom/span #js {:className "c-icon c-icon--large"}
(icons/icon :timer)))
(defexample icon-sizes
"### Sizes
NOTE: If you would like to include states on the icon itself, you can use
the helper function `(untangled.icons/icon :icon-name :modifiers [:xlarge])`
"
(let [sizes ["--small" "" "--medium" "--large" "--xlarge" "--huge"]]
(dom/div #js {}
(mapv (fn [sz]
(dom/figure #js {:role "group" :key (str "a" sz)}
(dom/span #js {:className (str "c-icon c-icon" sz)}
(icons/icon :alarm))
(dom/figcaption #js {} (str ".c-icon" sz)))
) sizes))))
(defexample icon-states
"### States
NOTE: If you would like to include states on the icon itself, you can use
the helper function `(untangled.icons/icon :icon-name :state [:positive])`
"
(let [states ["active" "passive" "disabled"]]
(dom/div #js {}
(mapv (fn [state]
(dom/figure #js {:role "group" :key state}
(dom/span #js {:className (str "c-icon c-icon--large is-" state)}
(icons/icon :alarm))
(dom/figcaption #js {} (str "is-" state)))
) states))))
(defexample icon-library
"### All Available Icons `(untangled.icons/icon :name)`
NOTE: Some icons have an additonal CSS set of rules in this style kit, so it
is recommended that you wrap icons with c-icon-{iconname}."
(dom/div #js {}
(mapv (fn [nm]
(dom/figure #js {:role "group" :key nm}
(dom/span #js {:className (str "c-icon c-icon-" nm)}
(icons/icon nm))
(dom/figcaption #js {} (str nm)))
) icons/icon-names)))
(def label-header
"# Labels")
(defexample labels
"### Types"
(dom/div #js {}
(dom/span #js {:className "c-label"} "Default")
(dom/span #js {:className "c-label c-label--primary"} "Primary")
(dom/span #js {:className "c-label c-label--accent"} "Accent")))
(defexample label-icons
"### With Icons"
(dom/div #js {}
(dom/span #js {:className "c-label c-label--primary"}
(icons/icon :add) " Add ")
(dom/span #js {:className "c-label c-label--accent"}
(icons/icon :close) " Remove ")))
(def lists-header
"# Lists")
(defexample lists
"Lists present multiple line items vertically as a single continuous element."
(dom/div #js {:className "c-list"}
(dom/div #js {:className "c-list__row c-list__row--collapse"}
(dom/div #js {:className "c-list__tile"}
(dom/span #js {:className "c-list__title"} "Today")))
(dom/div #js {:className "c-list__row c-list__row--collapse c-list__row--bordered is-selectable"}
(dom/div #js {:className "c-list__tile"}
(dom/div #js {:className "u-row"}
(dom/div #js {:className "c-list__avatar c-list__avatar--round"}
(dom/img #js {:src (:photo (util/mock-users :1)) :alt (util/full-name :1)}))
(dom/div #js {:className "c-list__name"}
(dom/div nil "Brunch this weekend?")
(dom/div nil
(dom/span nil (util/full-name :1))
(dom/span #js {:className "c-list__subtext"} " - I'll be in your neighborhood"))))))
(dom/div #js {:className "c-list__row c-list__row--collapse c-list__row--bordered is-selectable"}
(dom/div #js {:className "c-list__tile"}
(dom/div #js {:className "u-row"}
(dom/div #js {:className "c-list__avatar c-list__avatar--round"}
(dom/img #js {:src (:photo (util/mock-users :2)) :alt (util/full-name :2)}))
(dom/div #js {:className "c-list__name"}
(dom/div nil "Brunch this weekend?")
(dom/div nil (dom/span nil (util/full-name :2))
(dom/span #js {:className "c-list__subtext"} " - I'll be in your neighborhood"))))))))
(def loader-header
"# Loader
Webapps often need to provide feedback to the user for when things are loading, so we have a few loader components
that are animated using only CSS techniques.")
(defexample loader
"# Loader"
(l/row {}
(l/col {:width 3 :halign :center}
(dom/div #js {:className "c-loader" :aria-hidden false}))
(l/col {:width 3 :halign :center}
(dom/div #js {:className "c-loader c-loader--primary" :aria-hidden false}))
(l/col {:width 3 :halign :center}
(dom/div #js {:className "c-loader c-loader--accent" :aria-hidden false}))
(l/col {:width 3 :halign :center}
(dom/button #js {:className "c-button c-button--raised c-button--primary" :type "button"}
(dom/span #js {:className "c-loader c-loader--inverted" :aria-hidden false}))
(dom/button #js {:className "c-button c-button--raised" :type "button"}
(dom/span #js {:className "c-loader" :aria-hidden false})))))
(def tabs-header
"# Tabs")
(defexample tabs
"### Basic"
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab is-active" :type "button"} "Widgets")
(dom/button #js {:className "c-tab" :type "button"} "Doodads")
(dom/button #js {:className "c-tab" :type "button"} "Apparatuses")
(dom/button #js {:className "c-tab" :type "button"} "Things")))
(defexample tabs-colors
"### Colors"
(dom/div nil
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab c-tab--primary is-active" :type "button"} "Widgets")
(dom/button #js {:className "c-tab c-tab--primary" :type "button"} "Doodads")
(dom/button #js {:className "c-tab c-tab--primary" :type "button"} "Apparatuses")
(dom/button #js {:className "c-tab c-tab--primary" :type "button"} "Things"))
(dom/div #js {:className "t-dark"}
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab c-tab--contrast is-active" :type "button"} "Widgets")
(dom/button #js {:className "c-tab c-tab--contrast" :type "button"} "Doodads")
(dom/button #js {:className "c-tab c-tab--contrast" :type "button"} "Apparatuses")
(dom/button #js {:className "c-tab c-tab--contrast" :type "button"} "Things")))))
(defexample tabs-dropdown
"### With Dropdowns"
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className "c-tab" :type "button"} "Widgets")
(dom/button #js {:className "c-tab" :type "button"} "Doodads")
(dom/button #js {:className "c-tab" :type "button"} "Apparatuses")
(dom/span #js {:className "has-menu"}
(dom/button #js {:className "c-tab is-active" :type "button"} "Things")
(dom/ul #js {:className "c-menu"}
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamabob"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamajig"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thinger")))
(dom/button #js {:className "c-tab" :type "button"} "Doodads")
(dom/button #js {:className "c-tab" :type "button"} "Apparatuses")
(dom/span #js {:className "has-menu"}
(dom/button #js {:className "c-tab is-active" :type "button"} "Things")
(dom/ul #js {:className "c-menu is-active"}
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamabob"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thingamajig"))
(dom/li #js {}
(dom/button #js {:className "c-menu__item" :type "button"} "Thinger")))))))
(def messages-header
"# Messages")
(defexample messages
"A basic message"
(dom/div #js {}
(dom/div #js {:className "c-message"} "This is a message")
(dom/div #js {:className "c-message c-message--primary"} "This is a primary message")
(dom/div #js {:className "c-message c-message--accent"} "This is an accent message")))
(defexample messages-raised
"Chat style messages"
(dom/div #js {}
(dom/div #js {:className ""}
(dom/span #js {:className "c-message c-message--raised c-message--large"} "This is a message"))
(dom/div #js {:className "u-center"}
(dom/div #js {:className "c-message c-message--expanded"} "Today maybe")
(dom/span #js {:className "c-message c-message--raised c-message--primary c-message--large"} "This is a primary message"))
(dom/div #js {:className "u-end"}
(dom/span #js {:className "c-message c-message--raised c-message--accent c-message--large"} "This is an accent message"))))
(def notification-header
"# Notifications
Used to communicate the state of your user's interactions as well as system status.
In general, use the positioning classes (e.g. `u-absolute--middle-center`) to place these in
the UI.")
(defexample notification
"### Basic"
(dom/div #js {:className "c-notification"}
(icons/icon :info)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Info Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-success
"### Success"
(dom/div #js {:className "c-notification"}
(icons/icon :check_circle :states [:positive])
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Successful Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-warning
"### Warning"
(dom/div #js {:className "c-notification c-notification--warning"}
(icons/icon :warning)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Warning Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-error
"### Error"
(dom/div #js {:className "c-notification c-notification--error"}
(icons/icon :error)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Error Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(defexample notification-wide
"## Wide"
(dom/div #js {:className "c-notification c-notification--wide c-notification--informative"}
(icons/icon :info)
(dom/div #js {:className "c-notification_content"}
(dom/h1 #js {:className "c-notification_heading"} "Wide Notification")
(dom/p #js {} "Communicate a meaningful message."))
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :close))))
(def progress-header
"# Progress")
(defexample progress-basic
"## Basic"
(dom/div #js {}
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Indeterminate")
(dom/progress #js {:className "c-progress" :aria-hidden false}))
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Indeterminate & Dense")
(dom/progress #js {:className "c-progress c-progress--dense" :aria-hidden false}))
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Value")
(dom/progress #js {:className "c-progress" :max "100" :value "70" :aria-hidden false}))
(dom/div #js {:className "u-trailer"}
(dom/h4 nil "Value & Small")
(dom/progress #js {:className "c-progress c-progress--dense" :max "100" :value "70" :aria-hidden false}))))
(def radio-header
"# Radio")
(defexample radio
"### Basic"
(let [selection (or (om/get-state this :selection) 1)
select (fn [n] (om/update-state! this assoc :selection n))]
(dom/div #js {}
(dom/div #js {:className "u-trailer--quarter"}
(dom/input #js {:id "r1" :type "radio" :className "c-radio c-radio--expanded" :name "radiogroup"
:checked (= 1 selection) :onClick #(select 1)})
(dom/label #js {:id "r1l" :htmlFor "r1"} "A"))
(dom/div #js {:className "u-trailer--quarter"}
(dom/input #js {:id "r2" :type "radio" :className "c-radio c-radio--expanded" :name "radiogroup"
:checked (= 2 selection) :onClick #(select 2)})
(dom/label #js {:id "r2l" :htmlFor "r2"} "B"))
(dom/div #js {:className "u-trailer--quarter"}
(dom/input #js {:id "r3" :type "radio" :className "c-radio c-radio--expanded" :name "radiogroup"
:checked (= 3 selection) :onClick #(select 3)})
(dom/label #js {:htmlFor "r3"} "C")))))
(defexample radio-stacked
"### Stacked"
(let [selection (or (om/get-state this :selection) 1)
select (fn [n] (om/update-state! this assoc :selection n))]
(dom/div #js {}
(dom/input #js {:id "sr1" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 1 selection) :onClick #(select 1)})
(dom/label #js {:id "sr1l" :htmlFor "sr1"} "1")
(dom/input #js {:id "sr2" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 2 selection) :onClick #(select 2)})
(dom/label #js {:id "sr2l" :htmlFor "sr2"} "2")
(dom/input #js {:id "sr3" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 3 selection) :onClick #(select 3)})
(dom/label #js {:htmlFor "sr3"} "3")
(dom/input #js {:id "sr4" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 4 selection) :onClick #(select 4)})
(dom/label #js {:htmlFor "sr4"} "4")
(dom/input #js {:id "sr5" :type "radio" :className "c-radio c-radio--stacked" :name "stackedradio"
:checked (= 5 selection) :onClick #(select 5)})
(dom/label #js {:htmlFor "sr5"} "5"))))
(def slider-header
"# Slider
A simple range input slider")
(defexample slider
"### Simple
"
(let [active (boolean (om/get-state this :active))
]
(dom/div nil
(dom/input #js {:className "c-slider"
:id "range-1"
:type "range"
:value 0})
(dom/input #js {:className "c-slider"
:id "range-1"
:type "range"
:value 25})
(dom/input #js {:className "c-slider"
:id "range-1"
:type "range" })
(dom/input #js {:className "c-slider"
:id "range-1"
:disabled true
:type "range"
:value 0})
(dom/input #js {:className "c-slider"
:id "range-1"
:disabled true
:type "range" })
)))
Switch
(def switch-header
"# Switch
A simple control to indicate if somehting is on or off.")
(defexample switch
"### Simple
Click this example to see it's active state which is a simple `:checked` attribute on `.c-switch__input`."
(let [active (boolean (om/get-state this :active))]
(dom/div #js {:className "c-switch"
:onClick #(om/update-state! this update :active not)}
(dom/input #js {:className "c-switch__input"
:id "h-switch-input-1"
:type "checkbox"
:checked (= active true)})
(dom/label #js {:className "c-switch__paddle"
:aria-hidden false
:htmlFor "h-switch-input-1"}))))
(defexample switch-icon
"### Icons
You can put up to 2 icons inside the `.c-switch__paddle` that represent what off and on actually do."
(let [active (boolean (om/get-state this :active))]
(dom/div #js {:className "c-switch"
:onClick #(om/update-state! this update :active not)}
(dom/input #js {:className "c-switch__input"
:id "h-switch-input-1"
:type "checkbox"
:checked (= active true)})
(dom/label #js {:className "c-switch__paddle"
:htmlFor "h-switch-input-1"}
(icons/icon :clear)
(icons/icon :done)))))
(def tables-header
"# Tables")
(defexample tables
"### Basic"
(let [kind (or (om/get-state this :kind))
set-kind (fn [k] (om/update-state! this assoc :kind k))]
(dom/div #js {}
(dom/div #js {}
(dom/span nil "View ")
(dom/button #js {:aria-label "Default" :onClick #(set-kind nil)
:type "button"
:className (str "c-button c-button--small " (when (= kind nil) "is-active"))}
(dom/span #js {:className "c-button__content"} "Default"))
(dom/button #js {:aria-label "Swipe View" :onClick #(set-kind "swipe")
:type "button"
:className (str "c-button c-button--small " (when (= kind "swipe") "is-active"))}
(icons/icon :view_headline)
(dom/span #js {:className "c-button__content"} "Swipe"))
(dom/button #js {:aria-label "Toggle View" :onClick #(set-kind "toggle")
:type "button"
:className (str "c-button c-button--small " (when (= kind "toggle") "is-active"))}
(icons/icon :view_week)
(dom/span #js {:className "c-button__content"} "Toggle"))
(dom/button #js {:aria-label "Stacked View" :onClick #(set-kind "stacked")
:type "button"
:className (str "c-button c-button--small " (when (= kind "stacked") "is-active"))}
(icons/icon :view_agenda)
(dom/span #js {:className "c-button__content"} "Stacked")))
(dom/table #js {:className (str "c-table c-table--" kind)}
(dom/caption nil "Table Example")
(dom/thead nil
(dom/tr #js {:className "c-table__week"}
(dom/th #js {:scope "col"} "Agent")
(dom/th #js {:scope "col" :className "c-table__priority-3"} "Opens")
(dom/th #js {:scope "col" :className "c-table__priority-2"} "Open %")
(dom/th #js {:scope "col" :className "c-table__priority-1"} "Clicks")
(dom/th #js {:scope "col" :className "c-table__priority-4"} "Click %")
(dom/th #js {:scope "col" :className "c-table__priority-5"} "Booked")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Attr Rev")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Bounce %")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Share %")
(dom/th #js {:scope "col" :className "c-table__priority-6"} "Unsub %")))
(dom/tbody #js {}
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "GMC"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "300"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "60"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "3000"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "12000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "32800"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "32")))
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "Dodge"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "100"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "54"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "1200"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "18"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "6000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "24000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "18"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "18"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "18")))
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "Volvo"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "600"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "72"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "960"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "42"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "3000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "1200"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "42"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "42"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "42")))
(dom/tr #js {}
(dom/td #js {}
(dom/span #js {:className "c-table__label"} "Agent")
(dom/span #js {:className "c-table__content"} "Audi"))
(dom/td #js {:className "c-table__priority-3"}
(dom/span #js {:className "c-table__label"} "Opens")
(dom/span #js {:className "c-table__content"} "300"))
(dom/td #js {:className "c-table__priority-2"}
(dom/span #js {:className "c-table__label"} "Open %")
(dom/span #js {:className "c-table__content"} "60"))
(dom/td #js {:className "c-table__priority-1"}
(dom/span #js {:className "c-table__label"} "Clicks")
(dom/span #js {:className "c-table__content"} "840"))
(dom/td #js {:className "c-table__priority-4"}
(dom/span #js {:className "c-table__label"} "Click %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-5"}
(dom/span #js {:className "c-table__label"} "Booked")
(dom/span #js {:className "c-table__content"} "12000"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Attr Rev")
(dom/span #js {:className "c-table__content"} "30800"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Bounce %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Share %")
(dom/span #js {:className "c-table__content"} "32"))
(dom/td #js {:className "c-table__priority-6"}
(dom/span #js {:className "c-table__label"} "Unsub %")
(dom/span #js {:className "c-table__content"} "32"))))))))
(def tooltips-header
"# Tooltips
Tool tips are based on `data` attributes.")
(defexample tooltips
"### Basic"
(dom/button #js {:data-tooltip "Hey!" :className "c-button" :type "button"} "Hover me!"))
(defexample tooltip-directions
"### Directions"
(dom/div #js {}
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "up" :className "c-button c-button--large" :type "button"} "Hover me!"))
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "left" :className "c-button c-button--large" :type "button"} "Hover me!"))
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "right" :className "c-button c-button--large" :type "button"} "Hover me!"))
(dom/div #js {:className "u-text-center"}
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-pos "down" :className "c-button c-button--large" :type "button"} "Hover me!"))))
(defexample tooltip-sizes
"### Sizes"
(dom/div #js {}
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "Hey!" :data-tooltip-length "small" :className "c-button c-button--large" :type "button"} "Small") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "Now that's a super big text we have over here right? Lorem ipsum dolor sit I'm done." :data-tooltip-length "medium" :className "c-button c-button--large" :type "button"} "Medium") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "What about something really big? This may surpass your window dimensions. Imagine you're on that boring class with that boring teacher and you didn't slept so well last night. Suddenly you're sleeping in class. Can you believe it?!" :data-tooltip-length "large" :className "c-button c-button--large" :type "button"} "Large") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "What about something really big? This may surpass your window dimensions. Imagine you're on that boring class with that boring teacher and you didn't slept so well last night. Suddenly you're sleeping in class. Can you believe it?!" :data-tooltip-length "xlarge" :className "c-button c-button--large" :type "button"} "X-Large") " ") " "
(dom/div #js {:className "u-text-center"} " "
(dom/button #js {:data-tooltip "What about something really big? This may surpass your window dimensions. Imagine you're on that boring class with that boring teacher and you didn't slept so well last night. Suddenly you're sleeping in class. Can you believe it?!" :data-tooltip-length "fit" :className "c-button c-button--large" :type "button"} "My width will fit to element") " ") " "))
(defn toggle-pause [this] (om/update-state! this update :pause not))
(defexample button-group
"# Button Group"
(let [pause (boolean (om/get-state this :pause))]
(dom/div #js {}
(dom/label #js {:htmlFor "target"} "Control")
(dom/div #js {:className "o-button-group--toggle" :id "target"}
(dom/button #js {:className (str "c-button " (if pause "" " c-button--raised c-button--primary"))
:type "button"
:onClick #(toggle-pause this)} "Play")
(dom/button #js {:className (str "c-button " (if (not pause) "" "c-button--raised c-button--primary"))
:type "button"
:onClick #(toggle-pause this)} "Pause")))))
(defexample postfix-group
"# Button Group Postfix Example
**Please Note** This does not work well on mobile with multiple buttons. To fix this we hacked out the second button. Use at your own risk.
"
(dom/div #js {}
(dom/div #js {:className "u-row u-row--collapse"}
(dom/div #js {:className "u-column--9"}
(dom/input #js {:type "text" :placeholder "Multiple buttons on the end" :className "c-input"}))
(dom/div #js {:className "u-column--3"}
(dom/div #js {:className "o-button-group"}
(dom/button #js {:className "c-button c-button--postfix"} "Go")
(dom/button #js {:className "c-button c-button--postfix u-hide@sm"} "Start"))))))
(defn render-calendar-week [lowerRange upperRange]
(for [x (range lowerRange (+ upperRange 1))
:let [y (dom/td #js {:key (str "id-" x) :className "c-calendar__day"} x)]]
y))
(defexample calendar-example
"### Calendar Example"
(dom/div #js {}
(dom/div #js {:className "u-wrapper"}
(dom/label #js {:className "is-optional" :htmlFor "dateInput"} " X Date")
(dom/div #js {:className "c-field"}
(dom/input #js {:readOnly true :value "January 19, 2017" :id "dateInput" :type "text" :className "c-field__input"}))
(dom/div #js {:className "c-calendar"}
(dom/header #js {:className "c-calendar__control u-middle"}
(dom/button #js {:title "Last Month" :className "c-button c-button--icon" :type "button"}
(icons/icon :keyboard_arrow_left))
(dom/span #js {} "January 2017")
(dom/button #js {:title "Today" :className "c-button c-button--icon" :type "button"}
(icons/icon :today))
(dom/button #js {:title "Next Month" :className "c-button c-button--icon" :type "button"}
(icons/icon :keyboard_arrow_right)))
(dom/div #js {:className "o-calendar__month"}
(dom/table #js {:role "presentation"}
(dom/tbody #js {}
(dom/tr #js {:className "c-calendar__week"}
(dom/td #js {} "Su")
(dom/td #js {} "M")
(dom/td #js {} "Tu")
(dom/td #js {} "W")
(dom/td #js {} "Th")
(dom/td #js {} "F")
(dom/td #js {} "Sa"))
(dom/tr #js {}
(dom/td #js {:className "c-calendar__day is-inactive"} "27")
(dom/td #js {:className "c-calendar__day is-inactive"} "28")
(dom/td #js {:className "c-calendar__day is-inactive"} "29")
(dom/td #js {:className "c-calendar__day is-inactive"} "30")
(dom/td #js {:className "c-calendar__day is-inactive"} "31")
(render-calendar-week 1 2))
(dom/tr #js {}
(render-calendar-week 3 9))
(dom/tr #js {}
(render-calendar-week 10 16))
(dom/tr #js {}
(render-calendar-week 17 18)
(dom/td #js {:className "c-calendar__day is-active"} "19")
(render-calendar-week 20 23))
(dom/tr #js {}
(render-calendar-week 24 30)
))))))))
(defn toggle-drawer [this] (om/update-state! this update :drawer not))
(defexample drawer
"# Drawer"
(let [drawer (boolean (om/get-state this :drawer))]
(e/ui-iframe {:width "100%" :height "480px"}
(dom/div #js {}
(dom/link #js {:rel "stylesheet" :href "css/untangled-ui.css"})
(dom/button #js {:className "c-button"
:onClick #(toggle-drawer this)} "Show/Hide Drawer Example")
(dom/div #js {:className (str "c-drawer c-drawer--right" (when drawer " is-open"))}
(dom/header #js {:className "c-drawer__header u-row u-middle"}
(dom/h1 #js {:className ""} "Just Another Drawer"))
(dom/div #js {:className "c-list"}
(dom/div #js {:className "c-drawer__group"}
(dom/div #js {:className "c-drawer__action"}
(icons/icon :games) "Games")
(dom/div #js {:className "c-drawer__action"}
(icons/icon :movie) "Movies")
(dom/div #js {:className "c-drawer__action"}
(icons/icon :book) "Books"))
(dom/div #js {:className "c-drawer__group"}
(dom/div #js {:className "c-drawer__subheader"} "Subheader")
(dom/div #js {:className "c-drawer__action"}
"Settings")
(dom/div #js {:className "c-drawer__action"}
"Help & Feedback"))
))
(dom/div #js {:className (str "c-backdrop" (when drawer " is-active"))
:onClick #(toggle-drawer this)})))))
(defexample icon-bar
"# Icon Bar"
(dom/div #js {}
(dom/nav #js {:className "c-iconbar"}
(dom/button #js {:className "c-iconbar__item is-active" :type "button"}
(icons/icon :home)
(dom/span #js {:className "c-iconbar__label"} "Home"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :description)
(dom/span #js {:className "c-iconbar__label"} "Docs"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :feedback)
(dom/span #js {:className "c-iconbar__label"} "Support"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(dom/span #js {:className "c-icon"}
(dom/svg #js {:width "24" :height "24" :xmlns "" :viewBox "0 0 24 24" :role "img"}
(dom/path #js {:d "M12 0c-6.627 0-12 5.406-12 12.073 0 5.335 3.438 9.859 8.207 11.455.6.111.819-.262.819-.581l-.017-2.247c-3.337.729-4.042-1.424-4.042-1.424-.546-1.394-1.332-1.765-1.332-1.765-1.091-.749.083-.734.083-.734 1.205.084 1.839 1.244 1.839 1.244 1.071 1.845 2.81 1.312 3.492 1.002.109-.778.42-1.312.762-1.612-2.664-.305-5.466-1.341-5.466-5.967 0-1.319.468-2.395 1.234-3.24-.122-.307-.535-1.535.119-3.196 0 0 1.006-.324 3.3 1.238.957-.269 1.983-.402 3.003-.406 1.02.004 2.046.139 3.004.407 2.29-1.564 3.297-1.238 3.297-1.238.656 1.663.243 2.89.12 3.195.769.845 1.233 1.921 1.233 3.24 0 4.638-2.807 5.659-5.48 5.958.432.374.814 1.108.814 2.234 0 1.614-.016 2.915-.016 3.313 0 .321.218.697.826.579 4.765-1.599 8.2-6.123 8.2-11.455 0-6.667-5.373-12.073-12-12.073z"})))
(dom/span #js {:className "c-iconbar__label"} "Github")))))
(defexample icon-rail
"# Icon Rail Example
Just add an extra modifier class `.c-iconbar--rail` and you'll get this effect.
"
(dom/div #js {}
(dom/nav #js {:className "c-iconbar c-iconbar--rail"}
(dom/button #js {:className "c-iconbar__item is-active" :type "button"}
(icons/icon :home)
(dom/span #js {:className "c-iconbar__label"} "Home"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :description)
(dom/span #js {:className "c-iconbar__label"} "Docs"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :feedback)
(dom/span #js {:className "c-iconbar__label"} "Support"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(dom/span #js {:className "c-icon"}
(dom/svg #js {:width "24" :height "24" :xmlns "" :viewBox "0 0 24 24" :role "img"}
(dom/path #js {:d "M12 0c-6.627 0-12 5.406-12 12.073 0 5.335 3.438 9.859 8.207 11.455.6.111.819-.262.819-.581l-.017-2.247c-3.337.729-4.042-1.424-4.042-1.424-.546-1.394-1.332-1.765-1.332-1.765-1.091-.749.083-.734.083-.734 1.205.084 1.839 1.244 1.839 1.244 1.071 1.845 2.81 1.312 3.492 1.002.109-.778.42-1.312.762-1.612-2.664-.305-5.466-1.341-5.466-5.967 0-1.319.468-2.395 1.234-3.24-.122-.307-.535-1.535.119-3.196 0 0 1.006-.324 3.3 1.238.957-.269 1.983-.402 3.003-.406 1.02.004 2.046.139 3.004.407 2.29-1.564 3.297-1.238 3.297-1.238.656 1.663.243 2.89.12 3.195.769.845 1.233 1.921 1.233 3.24 0 4.638-2.807 5.659-5.48 5.958.432.374.814 1.108.814 2.234 0 1.614-.016 2.915-.016 3.313 0 .321.218.697.826.579 4.765-1.599 8.2-6.123 8.2-11.455 0-6.667-5.373-12.073-12-12.073z"})))
(dom/span #js {:className "c-iconbar__label"} "Github")))))
(defexample icon-bar-shifting
"# Icon Bar Shifting Example
Just add an extra modifier class `.c-iconbar--shifting` and you'll get this effect.
"
(dom/div #js {}
(dom/nav #js {:className "c-iconbar c-iconbar--shifting is-mobile"}
(dom/button #js {:className "c-iconbar__item is-active" :type "button"}
(icons/icon :home)
(dom/span #js {:className "c-iconbar__label"} "Home"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :description)
(dom/span #js {:className "c-iconbar__label"} "Docs"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(icons/icon :feedback)
(dom/span #js {:className "c-iconbar__label"} "Support"))
(dom/button #js {:className "c-iconbar__item" :type "button"}
(dom/span #js {:className "c-icon"}
(dom/svg #js {:width "24" :height "24" :xmlns "" :viewBox "0 0 24 24" :role "img"}
(dom/path #js {:d "M12 0c-6.627 0-12 5.406-12 12.073 0 5.335 3.438 9.859 8.207 11.455.6.111.819-.262.819-.581l-.017-2.247c-3.337.729-4.042-1.424-4.042-1.424-.546-1.394-1.332-1.765-1.332-1.765-1.091-.749.083-.734.083-.734 1.205.084 1.839 1.244 1.839 1.244 1.071 1.845 2.81 1.312 3.492 1.002.109-.778.42-1.312.762-1.612-2.664-.305-5.466-1.341-5.466-5.967 0-1.319.468-2.395 1.234-3.24-.122-.307-.535-1.535.119-3.196 0 0 1.006-.324 3.3 1.238.957-.269 1.983-.402 3.003-.406 1.02.004 2.046.139 3.004.407 2.29-1.564 3.297-1.238 3.297-1.238.656 1.663.243 2.89.12 3.195.769.845 1.233 1.921 1.233 3.24 0 4.638-2.807 5.659-5.48 5.958.432.374.814 1.108.814 2.234 0 1.614-.016 2.915-.016 3.313 0 .321.218.697.826.579 4.765-1.599 8.2-6.123 8.2-11.455 0-6.667-5.373-12.073-12-12.073z"})))
(dom/span #js {:className "c-iconbar__label"} "Github")))))
(defexample modal-example
"# Modal
### Basic"
(dom/div #js {:style #js {:position "relative" :height "400px"}}
(dom/div #js {:className (str "c-dialog is-active") :style #js {:position "absolute"}}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-dialog__title"} "Dialog title")
(dom/div #js {:className "c-dialog__content"}
(dom/span #js {} "This is a card in a dialog, what will they think of next?")
)
(dom/div #js {:className "c-dialog__actions"}
(dom/button #js {:className "c-button c-button--primary"
:type "button"
:onClick #(om/update-state! this assoc :modal-visible false)} "Cancel")
(dom/button #js {:className "c-button c-button--primary"
:type "button"
:onClick #(om/update-state! this assoc :modal-visible false)} "Ok"))
))
(dom/div #js {:className (str "c-backdrop _is-active") :style #js {:position "absolute"}})))
(defviewport modal-fullscreen-1
"Fullscreen modal"
(dom/div #js {:className "c-dialog c-dialog--fullscreen"}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-toolbar c-toolbar--primary c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__row c-toolbar__row--expanded"}
(dom/div #js {:className "c-toolbar__view"}
(dom/button #js {:className "c-button c-button--icon"} (icons/icon :close))
(dom/span #js {:className "c-toolbar__label"} "Modal title"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button"} "Save"))))
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button c-button--wide"} ""))
(dom/div #js {:className "c-dialog__content"}
(dom/input #js {:className "c-field c-field--large u-trailer" :placeholder "Event name"})
(dom/input #js {:className "c-field" :placeholder "Location"})
(dom/label #js {:className "is-optional u-leader--half"} "Start time")
(dom/input #js {:className "c-field" :placeholder "12:00 AM"})
(dom/label #js {:className "is-optional u-leader--half"} "End time")
(dom/input #js {:className "c-field" :placeholder "1:00 PM"})
(dom/input #js {:className "c-field" :placeholder "Room"})))))
(defviewport modal-fullscreen-2
"Fullscreen modal with another modal"
(dom/div #js {:style #js {:position "relative" :height "570px"}}
(dom/div #js {:className (str "c-dialog is-active") :style #js {:position "absolute"}}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-dialog__content"}
(dom/span #js {} "Discard new event?"))
(dom/div #js {:className "c-dialog__actions"}
(dom/button #js {:className "c-button c-button--primary"
:onClick #(om/update-state! this assoc :modal-visible false)} "Cancel")
(dom/button #js {:className "c-button c-button--primary"
:onClick #(om/update-state! this assoc :modal-visible false)} "Erase"))))
(dom/div #js {:className (str "c-backdrop is-active") :style #js {:position "absolute"}})
(dom/div #js {:className "c-dialog c-dialog--fullscreen"}
(dom/div #js {:className "c-dialog__card"}
(dom/div #js {:className "c-toolbar c-toolbar--primary c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__row c-toolbar__row--expanded"}
(dom/div #js {:className "c-toolbar__view"}
(dom/button #js {:className "c-button c-button--icon"} (icons/icon :close))
(dom/span #js {:className "c-toolbar__label"} "Modal title"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button"} "Save"))))
(dom/div #js {:className "has-menu"}
(dom/button #js {:className "c-button c-button--wide"} ""))
(dom/div #js {:className "c-dialog__content"}
(dom/input #js {:className "c-field c-field--large u-trailer" :placeholder "Event name"})
(dom/input #js {:className "c-field" :placeholder "Location"})
(dom/label #js {:className "is-optional u-leader--half"} "Start time")
(dom/input #js {:className "c-field" :placeholder "12:00 AM"})
(dom/label #js {:className "is-optional u-leader--half"} "End time")
(dom/input #js {:className "c-field" :placeholder "1:00 PM"})
(dom/input #js {:className "c-field" :placeholder "Room"}))))))
(defexample toolbar
"# Toolbar Example"
(let [changed-menu (om/get-state this :changed-menu)
ui-menu-open (if (= (:id changed-menu) :ui) (:open-state changed-menu) nil)
lang-menu-open (if (= (:id changed-menu) :lang) (:open-state changed-menu) nil)
ui-menu-class (str "c-menu" (if ui-menu-open " is-active" ""))
lang-menu-class (str "c-menu c-menu--right " (if lang-menu-open " is-active" ""))
lang-item-selected (or (if (= (:id changed-menu) :lang) (:selected-item changed-menu) nil) "English-US")
menu-action (fn [menu opened item]
(om/update-state! this assoc :changed-menu {:id menu :open-state opened :selected-item item}))]
(e/ui-iframe {:width "100%" :height "300px"}
(dom/div #js { :style #js {:backgroundColor "#efefef" :height "300px"}}
(dom/div #js {:className "c-toolbar"}
(dom/link #js {:rel "stylesheet" :href "css/untangled-ui.css"})
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(e/ui-icon {:glyph :menu})))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"} (icons/icon :help))
(dom/button #js {:className "c-button c-button--icon"
:title "Kevin Mitnick" :type "button"}
(icons/icon :account_circle)))))))))
(defexample toolbar-colors
"### Colors"
(let [changed-menu (om/get-state this :changed-menu)
ui-menu-open (if (= (:id changed-menu) :ui) (:open-state changed-menu) nil)
lang-menu-open (if (= (:id changed-menu) :lang) (:open-state changed-menu) nil)
ui-menu-class (str "c-menu" (if ui-menu-open " is-active" ""))
lang-menu-class (str "c-menu c-menu--right " (if lang-menu-open " is-active" ""))
lang-item-selected (or (if (= (:id changed-menu) :lang) (:selected-item changed-menu) nil) "English-US")
menu-action (fn [menu opened item]
(om/update-state! this assoc :changed-menu {:id menu :open-state opened :selected-item item}))]
(dom/div nil
(dom/div #js {:className "c-toolbar c-toolbar--primary c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :menu)))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__view"}
(dom/span #js {:className "c-toolbar__label"} "Primary toolbar"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :help))
(dom/span #js {:title "Kevin Mitnick"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :account_circle))))))
(dom/p nil " ")
(dom/div #js {:className "c-toolbar c-toolbar--dark c-toolbar--raised"}
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :arrow_back)))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__view"}
(dom/span #js {:className "c-toolbar__label"} "Dark toolbar"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :filter_list))
(dom/span #js {:title "Kevin Mitnick"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :search)))))))))
(defexample toolbar-dense
"### Dense
This toolbar is mainly used for specific operations and navigation for the current app you are using.
"
(let [selected-item (or (om/get-state this :selected-item) :widgets)
get-class (fn [item] (str "c-tab c-tab--contrast " (if (= item selected-item) " is-active" "")))
select-item (fn [item] (om/update-state! this assoc :selected-item item))]
(e/ui-iframe {:width "100%"}
(dom/div #js {:className "c-toolbar c-toolbar--raised c-toolbar--dark"}
(dom/link #js {:rel "stylesheet" :href "css/untangled-ui.css"})
(dom/div #js {:className "c-toolbar__button"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :menu)))
(dom/div #js {:className "c-toolbar__row"}
(dom/div #js {:className "c-toolbar__view"}
(dom/span #js {:className "c-toolbar__label"} "Second row is dense"))
(dom/div #js {:className "c-toolbar__actions"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :help))
(dom/span #js {:title "Kevin Mitnick"}
(dom/button #js {:className "c-button c-button--icon" :type "button"}
(icons/icon :account_circle)))))
(dom/div #js {:className "c-toolbar__row c-toolbar__row--dense"}
(dom/div #js {:className "c-tabs"}
(dom/button #js {:className (get-class :widgets)
:type "button"
:onClick #(select-item :widgets)} "Widgets")
(dom/button #js {:className (get-class :doodads)
:type "button"
:onClick #(select-item :doodads)} "Doodads")
(dom/button #js {:className (get-class :apparatuses)
:type "button"
:onClick #(select-item :apparatuses)} "Apparatuses")
(dom/button #js {:className (get-class :things)
:type "button"
:onClick #(select-item :things)} "Things")))))))
(def sections
(vec (sort-by :title
[
First show the basic pattern , then modifiers , then elements .
{:id :avatar
:title "Avatar"
:documentation avatar-header
:examples [ avatar avatar-group avatar-customize ]}
{:id :badges
:title "Badges"
:documentation badge-header
:examples [ badge badge-button badge-icon badge-customize ]}
{:id :buttons
:title "Buttons"
:documentation button-header
:examples [ button button-shape button-color button-state button-state-raised button-icon button-group ]}
{:id :calendar-example :title "Calendar" :examples [calendar-example]
:documentation
"# Calendar
This is a month view calendar for overlaying on input fields that control date selection."}
{:id :card
:title "Card"
:documentation card-header
:examples [ card card-states card-transparent card-ruled ]}
{:id :checkboxes
:title "Checkboxes"
:documentation checkbox-header
:examples [ checkboxes ]}
{:id :drawer
:title "Drawer"
:examples [ drawer ]}
{:id :expanding_panel
:title "Expansion panels"
:documentation expansion-panel-header
:examples [ expansion-panel expansion-panel-survey ] }
{:id :fields
:title "Fields"
:documentation field-header
:examples [ field field-states field-sizes field-icon field-content textarea ]}
{:id :icons
:title "Icons"
:documentation icon-header
:examples [ icons icon-sizes icon-states icon-library ]}
{:id :icon-bar
:title "Icon Bar"
:examples [ icon-bar icon-rail icon-bar-shifting ]}
{:id :labels
:title "Labels"
:documentation label-header
:examples [ labels label-icons ]}
{:id :lists
:title "Lists"
:documentation lists-header
:examples [ lists ]}
{:id :loader
:title "Loader"
:documentation loader-header
:examples [ loader ]}
{:id :dropdowns
:title "Menus"
:documentation menus-header
:examples [ menus menus-shape menus-search-multi menus-data ]}
{:id :messages
:title "Messages"
:documentation messages-header
:examples [ messages messages-raised ]}
{:id :modal
:title "Dialog"
:examples [ modal-example modal-fullscreen-1 modal-fullscreen-2 ]}
{:id :notifications
:title "Notifications"
:documentation notification-header
:examples [ notification notification-success notification-warning notification-error notification-wide ]}
{:id :progressbar
:title "Progress"
:documentation progress-header
:examples [ progress-basic]}
{:id :radio
:title "Radio Buttons"
:documentation radio-header
:examples [ radio radio-stacked]}
{:id :slider
:title "Slider"
:documentation slider-header
:examples [ slider ]}
{:id :switch
:title "Switch"
:documentation switch-header
:examples [ switch switch-icon ]}
{:id :table
:title "Tables"
:documentation tables-header
:examples [ tables ]}
{:id :menus
:title "Tabs"
:documentation tabs-header
:examples [ tabs tabs-colors tabs-dropdown ]}
{:id :toolbar
:title "Toolbar"
:examples [ toolbar toolbar-colors toolbar-dense ]}
{:id :tooltip
:title "Tooltips"
:documentation tooltips-header
:examples [ tooltips tooltip-directions tooltip-sizes ]}])))
|
16552ed3163f744da08257580879630eb44f4e1f1b966184860c21b8b7266f14 | NorfairKing/sydtest | SpecifySpec.hs | module Test.Syd.SpecifySpec (spec) where
import Test.QuickCheck
import Test.Syd
spec :: Spec
spec = sequential $ do
describe "boolean" $ do
it "boolean" True
before (pure (2 :: Int)) $
it "boolean function (inner)" $ \i -> even i
beforeAll (pure (2 :: Int)) $ do
itWithOuter "boolean function (one outer)" $ \i -> even i
itWithBoth "boolean function (both inner and outer)" $ \i () -> even i
describe "IO action" $ do
it "IO action" True
before (pure (2 :: Int)) $
it "IO action function (inner)" $ \i -> i `shouldBe` 2
beforeAll (pure (1 :: Int)) $ do
itWithOuter "IO action function (one outer)" $ \i -> i `shouldBe` 1
itWithBoth "IO action function (both inner and outer)" $ \i () -> i `shouldBe` 1
describe "property test" $ do
it "property test" $ property $ \j -> j `shouldBe` (j :: Int)
before (pure (2 :: Int)) $
it "property test function (inner)" $ \i ->
property $ \j ->
i * j `shouldBe` 2 * (j :: Int)
beforeAll (pure (1 :: Int)) $ do
itWithOuter "property test function (one outer)" $ \i -> property $ \j ->
i * j `shouldBe` 1 * j
itWithBoth "property test function (both inner and outer)" $ \i () -> property $ \j ->
i * j `shouldBe` 1 * j
describe "pending tests" $ do
pending "this is a pending test"
pendingWith "this is another pending test" "with this reason"
| null | https://raw.githubusercontent.com/NorfairKing/sydtest/0fad471cee677a4018acbe1983385dfc9a1b49d2/sydtest/test/Test/Syd/SpecifySpec.hs | haskell | module Test.Syd.SpecifySpec (spec) where
import Test.QuickCheck
import Test.Syd
spec :: Spec
spec = sequential $ do
describe "boolean" $ do
it "boolean" True
before (pure (2 :: Int)) $
it "boolean function (inner)" $ \i -> even i
beforeAll (pure (2 :: Int)) $ do
itWithOuter "boolean function (one outer)" $ \i -> even i
itWithBoth "boolean function (both inner and outer)" $ \i () -> even i
describe "IO action" $ do
it "IO action" True
before (pure (2 :: Int)) $
it "IO action function (inner)" $ \i -> i `shouldBe` 2
beforeAll (pure (1 :: Int)) $ do
itWithOuter "IO action function (one outer)" $ \i -> i `shouldBe` 1
itWithBoth "IO action function (both inner and outer)" $ \i () -> i `shouldBe` 1
describe "property test" $ do
it "property test" $ property $ \j -> j `shouldBe` (j :: Int)
before (pure (2 :: Int)) $
it "property test function (inner)" $ \i ->
property $ \j ->
i * j `shouldBe` 2 * (j :: Int)
beforeAll (pure (1 :: Int)) $ do
itWithOuter "property test function (one outer)" $ \i -> property $ \j ->
i * j `shouldBe` 1 * j
itWithBoth "property test function (both inner and outer)" $ \i () -> property $ \j ->
i * j `shouldBe` 1 * j
describe "pending tests" $ do
pending "this is a pending test"
pendingWith "this is another pending test" "with this reason"
|
|
fa07f65b10344ac2cb3c36d52e34b06cafc2c5a7b99521ae0e61106fff9fa838 | gdamore/tree-sitter-d | helix-indents.scm | [
(parameters)
(template_parameters)
(expression_statement)
(aggregate_body)
(function_body)
(scope_statement)
(block_statement)
(case_statement)
] @indent
[
(case)
(default)
"}"
"]"
] @outdent
| null | https://raw.githubusercontent.com/gdamore/tree-sitter-d/0f0fdd68dc03931c0a718d2b98f0bf85caf574a3/queries/helix-indents.scm | scheme | [
(parameters)
(template_parameters)
(expression_statement)
(aggregate_body)
(function_body)
(scope_statement)
(block_statement)
(case_statement)
] @indent
[
(case)
(default)
"}"
"]"
] @outdent
|
|
1f4ffdc107b0e375b35467ec5c946426da1314575afabe74ebaad4ba67a11325 | cstar/ejabberd-old | mod_configure.erl | %%%----------------------------------------------------------------------
File :
Author : < >
%%% Purpose : Support for online configuration of ejabberd
Created : 19 Jan 2003 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2010 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. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
Implements most of XEP-0133 : Service Administration Version 1.1
( 2005 - 08 - 19 )
-module(mod_configure).
-author('').
-behaviour(gen_mod).
-export([start/2,
stop/1,
get_local_identity/5,
get_local_features/5,
get_local_items/5,
adhoc_local_items/4,
adhoc_local_commands/4,
get_sm_identity/5,
get_sm_features/5,
get_sm_items/5,
adhoc_sm_items/4,
adhoc_sm_commands/4]).
-include("ejabberd.hrl").
-include("jlib.hrl").
-include("adhoc.hrl").
-define(T(Lang, Text), translate:translate(Lang, Text)).
Copied from
-record(session, {sid, usr, us, priority, info}).
start(Host, _Opts) ->
ejabberd_hooks:add(disco_local_items, Host, ?MODULE, get_local_items, 50),
ejabberd_hooks:add(disco_local_features, Host, ?MODULE, get_local_features, 50),
ejabberd_hooks:add(disco_local_identity, Host, ?MODULE, get_local_identity, 50),
ejabberd_hooks:add(disco_sm_items, Host, ?MODULE, get_sm_items, 50),
ejabberd_hooks:add(disco_sm_features, Host, ?MODULE, get_sm_features, 50),
ejabberd_hooks:add(disco_sm_identity, Host, ?MODULE, get_sm_identity, 50),
ejabberd_hooks:add(adhoc_local_items, Host, ?MODULE, adhoc_local_items, 50),
ejabberd_hooks:add(adhoc_local_commands, Host, ?MODULE, adhoc_local_commands, 50),
ejabberd_hooks:add(adhoc_sm_items, Host, ?MODULE, adhoc_sm_items, 50),
ejabberd_hooks:add(adhoc_sm_commands, Host, ?MODULE, adhoc_sm_commands, 50),
ok.
stop(Host) ->
ejabberd_hooks:delete(adhoc_sm_commands, Host, ?MODULE, adhoc_sm_commands, 50),
ejabberd_hooks:delete(adhoc_sm_items, Host, ?MODULE, adhoc_sm_items, 50),
ejabberd_hooks:delete(adhoc_local_commands, Host, ?MODULE, adhoc_local_commands, 50),
ejabberd_hooks:delete(adhoc_local_items, Host, ?MODULE, adhoc_local_items, 50),
ejabberd_hooks:delete(disco_sm_identity, Host, ?MODULE, get_sm_identity, 50),
ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE, get_sm_features, 50),
ejabberd_hooks:delete(disco_sm_items, Host, ?MODULE, get_sm_items, 50),
ejabberd_hooks:delete(disco_local_identity, Host, ?MODULE, get_local_identity, 50),
ejabberd_hooks:delete(disco_local_features, Host, ?MODULE, get_local_features, 50),
ejabberd_hooks:delete(disco_local_items, Host, ?MODULE, get_local_items, 50),
gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_COMMANDS),
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_COMMANDS).
%%%-----------------------------------------------------------------------
-define(INFO_IDENTITY(Category, Type, Name, Lang),
[{xmlelement, "identity",
[{"category", Category},
{"type", Type},
{"name", ?T(Lang, Name)}], []}]).
-define(INFO_COMMAND(Name, Lang),
?INFO_IDENTITY("automation", "command-node", Name, Lang)).
-define(NODEJID(To, Name, Node),
{xmlelement, "item",
[{"jid", jlib:jid_to_string(To)},
{"name", ?T(Lang, Name)},
{"node", Node}], []}).
-define(NODE(Name, Node),
{xmlelement, "item",
[{"jid", Server},
{"name", ?T(Lang, Name)},
{"node", Node}], []}).
-define(NS_ADMINX(Sub), ?NS_ADMIN++"#"++Sub).
-define(NS_ADMINL(Sub), ["http:","jabber.org","protocol","admin", Sub]).
tokenize(Node) -> string:tokens(Node, "/#").
get_sm_identity(Acc, _From, _To, Node, Lang) ->
case Node of
"config" ->
?INFO_COMMAND("Configuration", Lang);
_ ->
Acc
end.
get_local_identity(Acc, _From, _To, Node, Lang) ->
LNode = tokenize(Node),
case LNode of
["running nodes", ENode] ->
?INFO_IDENTITY("ejabberd", "node", ENode, Lang);
["running nodes", _ENode, "DB"] ->
?INFO_COMMAND("Database", Lang);
["running nodes", _ENode, "modules", "start"] ->
?INFO_COMMAND("Start Modules", Lang);
["running nodes", _ENode, "modules", "stop"] ->
?INFO_COMMAND("Stop Modules", Lang);
["running nodes", _ENode, "backup", "backup"] ->
?INFO_COMMAND("Backup", Lang);
["running nodes", _ENode, "backup", "restore"] ->
?INFO_COMMAND("Restore", Lang);
["running nodes", _ENode, "backup", "textfile"] ->
?INFO_COMMAND("Dump to Text File", Lang);
["running nodes", _ENode, "import", "file"] ->
?INFO_COMMAND("Import File", Lang);
["running nodes", _ENode, "import", "dir"] ->
?INFO_COMMAND("Import Directory", Lang);
["running nodes", _ENode, "restart"] ->
?INFO_COMMAND("Restart Service", Lang);
["running nodes", _ENode, "shutdown"] ->
?INFO_COMMAND("Shut Down Service", Lang);
?NS_ADMINL("add-user") ->
?INFO_COMMAND("Add User", Lang);
?NS_ADMINL("delete-user") ->
?INFO_COMMAND("Delete User", Lang);
?NS_ADMINL("end-user-session") ->
?INFO_COMMAND("End User Session", Lang);
?NS_ADMINL("get-user-password") ->
?INFO_COMMAND("Get User Password", Lang);
?NS_ADMINL("change-user-password") ->
?INFO_COMMAND("Change User Password", Lang);
?NS_ADMINL("get-user-lastlogin") ->
?INFO_COMMAND("Get User Last Login Time", Lang);
?NS_ADMINL("user-stats") ->
?INFO_COMMAND("Get User Statistics", Lang);
?NS_ADMINL("get-registered-users-num") ->
?INFO_COMMAND("Get Number of Registered Users", Lang);
?NS_ADMINL("get-online-users-num") ->
?INFO_COMMAND("Get Number of Online Users", Lang);
["config", "acls"] ->
?INFO_COMMAND("Access Control Lists", Lang);
["config", "access"] ->
?INFO_COMMAND("Access Rules", Lang);
_ ->
Acc
end.
%%%-----------------------------------------------------------------------
-define(INFO_RESULT(Allow, Feats),
case Allow of
deny ->
{error, ?ERR_FORBIDDEN};
allow ->
{result, Feats}
end).
get_sm_features(Acc, From, #jid{lserver = LServer} = _To, Node, _Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
Allow = acl:match_rule(LServer, configure, From),
case Node of
"config" ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
_ ->
Acc
end
end.
get_local_features(Acc, From, #jid{lserver = LServer} = _To, Node, _Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
case LNode of
["config"] ->
?INFO_RESULT(Allow, []);
["user"] ->
?INFO_RESULT(Allow, []);
["online users"] ->
?INFO_RESULT(Allow, []);
["all users"] ->
?INFO_RESULT(Allow, []);
["all users", [$@ | _]] ->
?INFO_RESULT(Allow, []);
["outgoing s2s" | _] ->
?INFO_RESULT(Allow, []);
["running nodes"] ->
?INFO_RESULT(Allow, []);
["stopped nodes"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode] ->
?INFO_RESULT(Allow, [?NS_STATS]);
["running nodes", _ENode, "DB"] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "modules"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode, "modules", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "backup"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode, "backup", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "import"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode, "import", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "restart"] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "shutdown"] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["config", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["http:" | _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
_ ->
Acc
end
end.
%%%-----------------------------------------------------------------------
adhoc_sm_items(Acc, From, #jid{lserver = LServer} = To, Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Nodes = [{xmlelement, "item",
[{"jid", jlib:jid_to_string(To)},
{"name", ?T(Lang, "Configuration")},
{"node", "config"}], []}],
{result, Items ++ Nodes};
_ ->
Acc
end.
%%%-----------------------------------------------------------------------
get_sm_items(Acc, From,
#jid{user = User, server = Server, lserver = LServer} = To,
Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
case {acl:match_rule(LServer, configure, From), Node} of
{allow, ""} ->
Nodes = [?NODEJID(To, "Configuration", "config"),
?NODEJID(To, "User Management", "user")],
{result, Items ++ Nodes ++ get_user_resources(User, Server)};
{allow, "config"} ->
{result, []};
{_, "config"} ->
{error, ?ERR_FORBIDDEN};
_ ->
Acc
end
end.
get_user_resources(User, Server) ->
Rs = ejabberd_sm:get_user_resources(User, Server),
lists:map(fun(R) ->
{xmlelement, "item",
[{"jid", User ++ "@" ++ Server ++ "/" ++ R},
{"name", User}], []}
end, lists:sort(Rs)).
%%%-----------------------------------------------------------------------
adhoc_local_items(Acc, From, #jid{lserver = LServer, server = Server} = To,
Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
PermLev = get_permission_level(From),
%% Recursively get all configure commands
Nodes = recursively_get_local_items(PermLev, LServer, "", Server,
Lang),
Nodes1 = lists:filter(
fun(N) ->
Nd = xml:get_tag_attr_s("node", N),
F = get_local_features([], From, To, Nd, Lang),
case F of
{result, [?NS_COMMANDS]} ->
true;
_ ->
false
end
end, Nodes),
{result, Items ++ Nodes1};
_ ->
Acc
end.
recursively_get_local_items(_PermLev, _LServer, "online users", _Server, _Lang) ->
[];
recursively_get_local_items(_PermLev, _LServer, "all users", _Server, _Lang) ->
[];
recursively_get_local_items(PermLev, LServer, Node, Server, Lang) ->
LNode = tokenize(Node),
Items = case get_local_items({PermLev, LServer}, LNode, Server, Lang) of
{result, Res} ->
Res;
{error, _Error} ->
[]
end,
Nodes = lists:flatten(
lists:map(
fun(N) ->
S = xml:get_tag_attr_s("jid", N),
Nd = xml:get_tag_attr_s("node", N),
if (S /= Server) or (Nd == "") ->
[];
true ->
[N, recursively_get_local_items(
PermLev, LServer, Nd, Server, Lang)]
end
end, Items)),
Nodes.
get_permission_level(JID) ->
case acl:match_rule(global, configure, JID) of
allow -> global;
deny -> vhost
end.
%%%-----------------------------------------------------------------------
-define(ITEMS_RESULT(Allow, LNode, Fallback),
case Allow of
deny ->
Fallback;
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, LNode,
jlib:jid_to_string(To), Lang) of
{result, Res} ->
{result, Res};
{error, Error} ->
{error, Error}
end
end).
get_local_items(Acc, From, #jid{lserver = LServer} = To, "", Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Allow = acl:match_rule(LServer, configure, From),
case Allow of
deny ->
{result, Items};
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, [],
jlib:jid_to_string(To), Lang) of
{result, Res} ->
{result, Items ++ Res};
{error, _Error} ->
{result, Items}
end
end
end;
get_local_items(Acc, From, #jid{lserver = LServer} = To, Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
case LNode of
["config"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["user"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["online users"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["all users"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["all users", [$@ | _]] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["outgoing s2s" | _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["stopped nodes"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "DB"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "modules"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "modules", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "backup"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "backup", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "import"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "import", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "restart"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "shutdown"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["config", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
?NS_ADMINL(_) ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
_ ->
Acc
end
end.
%%%-----------------------------------------------------------------------
@spec ( { PermissionLevel , Host } , [ string ( ) ] , Server::string ( ) , )
%% -> {result, [xmlelement()]}
%% PermissionLevel = global | vhost
get_local_items(_Host, [], Server, Lang) ->
{result,
[?NODE("Configuration", "config"),
?NODE("User Management", "user"),
?NODE("Online Users", "online users"),
?NODE("All Users", "all users"),
?NODE("Outgoing s2s Connections", "outgoing s2s"),
?NODE("Running Nodes", "running nodes"),
?NODE("Stopped Nodes", "stopped nodes")
]};
get_local_items(_Host, ["config"], Server, Lang) ->
{result,
[?NODE("Access Control Lists", "config/acls"),
?NODE("Access Rules", "config/access")
]};
get_local_items(_Host, ["config", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["user"], Server, Lang) ->
{result,
[?NODE("Add User", ?NS_ADMINX("add-user")),
?NODE("Delete User", ?NS_ADMINX("delete-user")),
?NODE("End User Session", ?NS_ADMINX("end-user-session")),
?NODE("Get User Password", ?NS_ADMINX("get-user-password")),
?NODE("Change User Password",?NS_ADMINX("change-user-password")),
?NODE("Get User Last Login Time", ?NS_ADMINX("get-user-lastlogin")),
?NODE("Get User Statistics", ?NS_ADMINX("user-stats")),
?NODE("Get Number of Registered Users",?NS_ADMINX("get-registered-users-num")),
?NODE("Get Number of Online Users",?NS_ADMINX("get-online-users-num"))
]};
get_local_items(_Host, ["http:" | _], _Server, _Lang) ->
{result, []};
get_local_items({_, Host}, ["online users"], _Server, _Lang) ->
{result, get_online_vh_users(Host)};
get_local_items({_, Host}, ["all users"], _Server, _Lang) ->
{result, get_all_vh_users(Host)};
get_local_items({_, Host}, ["all users", [$@ | Diap]], _Server, _Lang) ->
case catch ejabberd_auth:get_vh_registered_users(Host) of
{'EXIT', _Reason} ->
?ERR_INTERNAL_SERVER_ERROR;
Users ->
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
case catch begin
{ok, [S1, S2]} = regexp:split(Diap, "-"),
N1 = list_to_integer(S1),
N2 = list_to_integer(S2),
Sub = lists:sublist(SUsers, N1, N2 - N1 + 1),
lists:map(fun({S, U}) ->
{xmlelement, "item",
[{"jid", U ++ "@" ++ S},
{"name", U ++ "@" ++ S}], []}
end, Sub)
end of
{'EXIT', _Reason} ->
?ERR_NOT_ACCEPTABLE;
Res ->
{result, Res}
end
end;
get_local_items({_, Host}, ["outgoing s2s"], _Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang)};
get_local_items({_, Host}, ["outgoing s2s", To], _Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang, To)};
get_local_items(_Host, ["running nodes"], Server, Lang) ->
{result, get_running_nodes(Server, Lang)};
get_local_items(_Host, ["stopped nodes"], _Server, Lang) ->
{result, get_stopped_nodes(Lang)};
get_local_items({global, _Host}, ["running nodes", ENode], Server, Lang) ->
{result,
[?NODE("Database", "running nodes/" ++ ENode ++ "/DB"),
?NODE("Modules", "running nodes/" ++ ENode ++ "/modules"),
?NODE("Backup Management", "running nodes/" ++ ENode ++ "/backup"),
?NODE("Import Users From jabberd14 Spool Files",
"running nodes/" ++ ENode ++ "/import"),
?NODE("Restart Service", "running nodes/" ++ ENode ++ "/restart"),
?NODE("Shut Down Service", "running nodes/" ++ ENode ++ "/shutdown")
]};
get_local_items({vhost, _Host}, ["running nodes", ENode], Server, Lang) ->
{result,
[?NODE("Modules", "running nodes/" ++ ENode ++ "/modules")
]};
get_local_items(_Host, ["running nodes", _ENode, "DB"], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", ENode, "modules"], Server, Lang) ->
{result,
[?NODE("Start Modules", "running nodes/" ++ ENode ++ "/modules/start"),
?NODE("Stop Modules", "running nodes/" ++ ENode ++ "/modules/stop")
]};
get_local_items(_Host, ["running nodes", _ENode, "modules", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", ENode, "backup"], Server, Lang) ->
{result,
[?NODE("Backup", "running nodes/" ++ ENode ++ "/backup/backup"),
?NODE("Restore", "running nodes/" ++ ENode ++ "/backup/restore"),
?NODE("Dump to Text File",
"running nodes/" ++ ENode ++ "/backup/textfile")
]};
get_local_items(_Host, ["running nodes", _ENode, "backup", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", ENode, "import"], Server, Lang) ->
{result,
[?NODE("Import File", "running nodes/" ++ ENode ++ "/import/file"),
?NODE("Import Directory", "running nodes/" ++ ENode ++ "/import/dir")
]};
get_local_items(_Host, ["running nodes", _ENode, "import", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", _ENode, "restart"], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", _ENode, "shutdown"], _Server, _Lang) ->
{result, []};
get_local_items(_Host, _, _Server, _Lang) ->
{error, ?ERR_ITEM_NOT_FOUND}.
get_online_vh_users(Host) ->
case catch ejabberd_sm:get_vh_session_list(Host) of
{'EXIT', _Reason} ->
[];
USRs ->
SURs = lists:sort([{S, U, R} || {U, S, R} <- USRs]),
lists:map(fun({S, U, R}) ->
{xmlelement, "item",
[{"jid", U ++ "@" ++ S ++ "/" ++ R},
{"name", U ++ "@" ++ S}], []}
end, SURs)
end.
get_all_vh_users(Host) ->
case catch ejabberd_auth:get_vh_registered_users(Host) of
{'EXIT', _Reason} ->
[];
Users ->
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
case length(SUsers) of
N when N =< 100 ->
lists:map(fun({S, U}) ->
{xmlelement, "item",
[{"jid", U ++ "@" ++ S},
{"name", U ++ "@" ++ S}], []}
end, SUsers);
N ->
NParts = trunc(math:sqrt(N * 0.618)) + 1,
M = trunc(N / NParts) + 1,
lists:map(fun(K) ->
L = K + M - 1,
Node =
"@" ++ integer_to_list(K) ++
"-" ++ integer_to_list(L),
{FS, FU} = lists:nth(K, SUsers),
{LS, LU} =
if L < N -> lists:nth(L, SUsers);
true -> lists:last(SUsers)
end,
Name =
FU ++ "@" ++ FS ++
" -- " ++
LU ++ "@" ++ LS,
{xmlelement, "item",
[{"jid", Host},
{"node", "all users/" ++ Node},
{"name", Name}], []}
end, lists:seq(1, N, M))
end
end.
get_outgoing_s2s(Host, Lang) ->
case catch ejabberd_s2s:dirty_get_connections() of
{'EXIT', _Reason} ->
[];
Connections ->
DotHost = "." ++ Host,
TConns = [TH || {FH, TH} <- Connections,
Host == FH orelse lists:suffix(DotHost, FH)],
lists:map(
fun(T) ->
{xmlelement, "item",
[{"jid", Host},
{"node", "outgoing s2s/" ++ T},
{"name",
lists:flatten(
io_lib:format(
?T(Lang, "To ~s"), [T]))}],
[]}
end, lists:usort(TConns))
end.
get_outgoing_s2s(Host, Lang, To) ->
case catch ejabberd_s2s:dirty_get_connections() of
{'EXIT', _Reason} ->
[];
Connections ->
lists:map(
fun({F, _T}) ->
{xmlelement, "item",
[{"jid", Host},
{"node", "outgoing s2s/" ++ To ++ "/" ++ F},
{"name",
lists:flatten(
io_lib:format(
?T(Lang, "From ~s"), [F]))}],
[]}
end, lists:keysort(1, lists:filter(fun(E) ->
element(2, E) == To
end, Connections)))
end.
get_running_nodes(Server, _Lang) ->
case catch mnesia:system_info(running_db_nodes) of
{'EXIT', _Reason} ->
[];
DBNodes ->
lists:map(
fun(N) ->
S = atom_to_list(N),
{xmlelement, "item",
[{"jid", Server},
{"node", "running nodes/" ++ S},
{"name", S}],
[]}
end, lists:sort(DBNodes))
end.
get_stopped_nodes(_Lang) ->
case catch (lists:usort(mnesia:system_info(db_nodes) ++
mnesia:system_info(extra_db_nodes)) --
mnesia:system_info(running_db_nodes)) of
{'EXIT', _Reason} ->
[];
DBNodes ->
lists:map(
fun(N) ->
S = atom_to_list(N),
{xmlelement, "item",
[{"jid", ?MYNAME},
{"node", "stopped nodes/" ++ S},
{"name", S}],
[]}
end, lists:sort(DBNodes))
end.
%%-------------------------------------------------------------------------
-define(COMMANDS_RESULT(LServerOrGlobal, From, To, Request),
case acl:match_rule(LServerOrGlobal, configure, From) of
deny ->
{error, ?ERR_FORBIDDEN};
allow ->
adhoc_local_commands(From, To, Request)
end).
adhoc_local_commands(Acc, From, #jid{lserver = LServer} = To,
#adhoc_request{node = Node} = Request) ->
LNode = tokenize(Node),
case LNode of
["running nodes", _ENode, "DB"] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "modules", _] ->
?COMMANDS_RESULT(LServer, From, To, Request);
["running nodes", _ENode, "backup", _] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "import", _] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "restart"] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "shutdown"] ->
?COMMANDS_RESULT(global, From, To, Request);
["config", _] ->
?COMMANDS_RESULT(LServer, From, To, Request);
?NS_ADMINL(_) ->
?COMMANDS_RESULT(LServer, From, To, Request);
_ ->
Acc
end.
adhoc_local_commands(From, #jid{lserver = LServer} = _To,
#adhoc_request{lang = Lang,
node = Node,
sessionid = SessionID,
action = Action,
xdata = XData} = Request) ->
LNode = tokenize(Node),
%% If the "action" attribute is not present, it is
%% understood as "execute". If there was no <actions/>
element in the first response ( which there is n't in our
%% case), "execute" and "complete" are equivalent.
ActionIsExecute = lists:member(Action,
["", "execute", "complete"]),
if Action == "cancel" ->
%% User cancels request
adhoc:produce_response(
Request,
#adhoc_response{status = canceled});
XData == false, ActionIsExecute ->
%% User requests form
case get_form(LServer, LNode, Lang) of
{result, Form} ->
adhoc:produce_response(
Request,
#adhoc_response{status = executing,
elements = Form});
{result, Status, Form} ->
adhoc:produce_response(
Request,
#adhoc_response{status = Status,
elements = Form});
{error, Error} ->
{error, Error}
end;
XData /= false, ActionIsExecute ->
%% User returns form.
case jlib:parse_xdata_submit(XData) of
invalid ->
{error, ?ERR_BAD_REQUEST};
Fields ->
case catch set_form(From, LServer, LNode, Lang, Fields) of
{result, Res} ->
adhoc:produce_response(
#adhoc_response{lang = Lang,
node = Node,
sessionid = SessionID,
elements = Res,
status = completed});
{'EXIT', _} ->
{error, ?ERR_BAD_REQUEST};
{error, Error} ->
{error, Error}
end
end;
true ->
{error, ?ERR_BAD_REQUEST}
end.
-define(TVFIELD(Type, Var, Val),
{xmlelement, "field", [{"type", Type},
{"var", Var}],
[{xmlelement, "value", [], [{xmlcdata, Val}]}]}).
-define(HFIELD(), ?TVFIELD("hidden", "FORM_TYPE", ?NS_ADMIN)).
-define(TLFIELD(Type, Label, Var),
{xmlelement, "field", [{"type", Type},
{"label", ?T(Lang, Label)},
{"var", Var}], []}).
-define(XFIELD(Type, Label, Var, Val),
{xmlelement, "field", [{"type", Type},
{"label", ?T(Lang, Label)},
{"var", Var}],
[{xmlelement, "value", [], [{xmlcdata, Val}]}]}).
-define(XMFIELD(Type, Label, Var, Vals),
{xmlelement, "field", [{"type", Type},
{"label", ?T(Lang, Label)},
{"var", Var}],
[{xmlelement, "value", [], [{xmlcdata,Val}]} || Val <- Vals]}).
-define(TABLEFIELD(Table, Val),
{xmlelement, "field", [{"type", "list-single"},
{"label", atom_to_list(Table)},
{"var", atom_to_list(Table)}],
[{xmlelement, "value", [], [{xmlcdata, atom_to_list(Val)}]},
{xmlelement, "option", [{"label",
?T(Lang, "RAM copy")}],
[{xmlelement, "value", [], [{xmlcdata, "ram_copies"}]}]},
{xmlelement, "option", [{"label",
?T(Lang,
"RAM and disc copy")}],
[{xmlelement, "value", [], [{xmlcdata, "disc_copies"}]}]},
{xmlelement, "option", [{"label",
?T(Lang,
"Disc only copy")}],
[{xmlelement, "value", [], [{xmlcdata, "disc_only_copies"}]}]},
{xmlelement, "option", [{"label",
?T(Lang, "Remote copy")}],
[{xmlelement, "value", [], [{xmlcdata, "unknown"}]}]}
]}).
get_form(_Host, ["running nodes", ENode, "DB"], Lang) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case rpc:call(Node, mnesia, system_info, [tables]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
Tables ->
STables = lists:sort(Tables),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Database Tables Configuration at ") ++
ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Choose storage type of tables")}]} |
lists:map(
fun(Table) ->
case rpc:call(Node,
mnesia,
table_info,
[Table, storage_type]) of
{badrpc, _} ->
?TABLEFIELD(Table, unknown);
Type ->
?TABLEFIELD(Table, Type)
end
end, STables)
]}]}
end
end;
get_form(Host, ["running nodes", ENode, "modules", "stop"], Lang) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case rpc:call(Node, gen_mod, loaded_modules, [Host]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
Modules ->
SModules = lists:sort(Modules),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Stop Modules at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Choose modules to stop")}]} |
lists:map(fun(M) ->
S = atom_to_list(M),
?XFIELD("boolean", S, S, "0")
end, SModules)
]}]}
end
end;
get_form(_Host, ["running nodes", ENode, "modules", "start"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Start Modules at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter list of {Module, [Options]}")}]},
?XFIELD("text-multi", "List of modules to start", "modules", "[].")
]}]};
get_form(_Host, ["running nodes", ENode, "backup", "backup"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Backup to File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to backup file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "backup", "restore"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Restore Backup from File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to backup file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "backup", "textfile"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Dump Backup to Text File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to text file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "import", "file"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Import User from File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to jabberd14 spool file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "import", "dir"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Import Users from Dir at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to jabberd14 spool dir")}]},
?XFIELD("text-single", "Path to Dir", "path", "")
]}]};
get_form(_Host, ["running nodes", _ENode, "restart"], Lang) ->
Make_option =
fun(LabelNum, LabelUnit, Value)->
{xmlelement, "option",
[{"label", LabelNum ++ ?T(Lang, LabelUnit)}],
[{xmlelement, "value", [], [{xmlcdata, Value}]}]}
end,
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Restart Service")}]},
{xmlelement, "field",
[{"type", "list-single"},
{"label", ?T(Lang, "Time delay")},
{"var", "delay"}],
[Make_option("", "immediately", "1"),
Make_option("15 ", "seconds", "15"),
Make_option("30 ", "seconds", "30"),
Make_option("60 ", "seconds", "60"),
Make_option("90 ", "seconds", "90"),
Make_option("2 ", "minutes", "120"),
Make_option("3 ", "minutes", "180"),
Make_option("4 ", "minutes", "240"),
Make_option("5 ", "minutes", "300"),
Make_option("10 ", "minutes", "600"),
Make_option("15 ", "minutes", "900"),
Make_option("30 ", "minutes", "1800"),
{xmlelement, "required", [], []}
]},
{xmlelement, "field",
[{"type", "fixed"},
{"label", ?T(Lang, "Send announcement to all online users on all hosts")}],
[]},
{xmlelement, "field",
[{"var", "subject"},
{"type", "text-single"},
{"label", ?T(Lang, "Subject")}],
[]},
{xmlelement, "field",
[{"var", "announcement"},
{"type", "text-multi"},
{"label", ?T(Lang, "Message body")}],
[]}
]}]};
get_form(_Host, ["running nodes", _ENode, "shutdown"], Lang) ->
Make_option =
fun(LabelNum, LabelUnit, Value)->
{xmlelement, "option",
[{"label", LabelNum ++ ?T(Lang, LabelUnit)}],
[{xmlelement, "value", [], [{xmlcdata, Value}]}]}
end,
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Shut Down Service")}]},
{xmlelement, "field",
[{"type", "list-single"},
{"label", ?T(Lang, "Time delay")},
{"var", "delay"}],
[Make_option("", "immediately", "1"),
Make_option("15 ", "seconds", "15"),
Make_option("30 ", "seconds", "30"),
Make_option("60 ", "seconds", "60"),
Make_option("90 ", "seconds", "90"),
Make_option("2 ", "minutes", "120"),
Make_option("3 ", "minutes", "180"),
Make_option("4 ", "minutes", "240"),
Make_option("5 ", "minutes", "300"),
Make_option("10 ", "minutes", "600"),
Make_option("15 ", "minutes", "900"),
Make_option("30 ", "minutes", "1800"),
{xmlelement, "required", [], []}
]},
{xmlelement, "field",
[{"type", "fixed"},
{"label", ?T(Lang, "Send announcement to all online users on all hosts")}],
[]},
{xmlelement, "field",
[{"var", "subject"},
{"type", "text-single"},
{"label", ?T(Lang, "Subject")}],
[]},
{xmlelement, "field",
[{"var", "announcement"},
{"type", "text-multi"},
{"label", ?T(Lang, "Message body")}],
[]}
]}]};
get_form(Host, ["config", "acls"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Access Control List Configuration")}]},
{xmlelement, "field", [{"type", "text-multi"},
{"label",
?T(
Lang, "Access control lists")},
{"var", "acls"}],
lists:map(fun(S) ->
{xmlelement, "value", [], [{xmlcdata, S}]}
end,
string:tokens(
lists:flatten(
io_lib:format(
"~p.",
[ets:select(acl,
[{{acl, {'$1', '$2'}, '$3'},
[{'==', '$2', Host}],
[{{acl, '$1', '$3'}}]}])
])),
"\n"))
}
]}]};
get_form(Host, ["config", "access"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Access Configuration")}]},
{xmlelement, "field", [{"type", "text-multi"},
{"label",
?T(
Lang, "Access rules")},
{"var", "access"}],
lists:map(fun(S) ->
{xmlelement, "value", [], [{xmlcdata, S}]}
end,
string:tokens(
lists:flatten(
io_lib:format(
"~p.",
[ets:select(config,
[{{config, {access, '$1', '$2'}, '$3'},
[{'==', '$2', Host}],
[{{access, '$1', '$3'}}]}])
])),
"\n"))
}
]}]};
get_form(_Host, ?NS_ADMINL("add-user"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Add User")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]},
{xmlelement, "field",
[{"type", "text-private"},
{"label", ?T(Lang, "Password")},
{"var", "password"}],
[{xmlelement, "required", [], []}]},
{xmlelement, "field",
[{"type", "text-private"},
{"label", ?T(Lang, "Password Verification")},
{"var", "password-verify"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("delete-user"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Delete User")}]},
{xmlelement, "field",
[{"type", "jid-multi"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjids"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("end-user-session"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "End User Session")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("get-user-password"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Password")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("change-user-password"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Password")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]},
{xmlelement, "field",
[{"type", "text-private"},
{"label", ?T(Lang, "Password")},
{"var", "password"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("get-user-lastlogin"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Last Login Time")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("user-stats"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Statistics")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(Host, ?NS_ADMINL("get-registered-users-num"), Lang) ->
[Num] = io_lib:format("~p", [ejabberd_auth:get_vh_registered_users_number(Host)]),
{result, completed,
[{xmlelement, "x",
[{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement,
"field",
[{"type", "text-single"},
{"label", ?T(Lang, "Number of registered users")},
{"var", "registeredusersnum"}],
[{xmlelement, "value", [], [{xmlcdata, Num}]}]
}]}]};
get_form(Host, ?NS_ADMINL("get-online-users-num"), Lang) ->
Num = io_lib:format("~p", [length(ejabberd_sm:get_vh_session_list(Host))]),
{result, completed,
[{xmlelement, "x",
[{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement,
"field",
[{"type", "text-single"},
{"label", ?T(Lang, "Number of online users")},
{"var", "onlineusersnum"}],
[{xmlelement, "value", [], [{xmlcdata, Num}]}]
}]}]};
get_form(_Host, _, _Lang) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
set_form(_From, _Host, ["running nodes", ENode, "DB"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
lists:foreach(
fun({SVar, SVals}) ->
%% We believe that this is allowed only for good people
Table = list_to_atom(SVar),
Type = case SVals of
["unknown"] -> unknown;
["ram_copies"] -> ram_copies;
["disc_copies"] -> disc_copies;
["disc_only_copies"] -> disc_only_copies;
_ -> false
end,
if
Type == false ->
ok;
Type == unknown ->
mnesia:del_table_copy(Table, Node);
true ->
case mnesia:add_table_copy(Table, Node, Type) of
{aborted, _} ->
mnesia:change_table_copy_type(
Table, Node, Type);
_ ->
ok
end
end
end, XData),
{result, []}
end;
set_form(_From, Host, ["running nodes", ENode, "modules", "stop"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
lists:foreach(
fun({Var, Vals}) ->
case Vals of
["1"] ->
Module = list_to_atom(Var),
rpc:call(Node, gen_mod, stop_module, [Host, Module]);
_ ->
ok
end
end, XData),
{result, []}
end;
set_form(_From, Host, ["running nodes", ENode, "modules", "start"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("modules", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, Strings}} ->
String = lists:foldl(fun(S, Res) ->
Res ++ S ++ "\n"
end, "", Strings),
case erl_scan:string(String) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, Modules} ->
lists:foreach(
fun({Module, Args}) ->
rpc:call(Node,
gen_mod,
start_module,
[Host, Module, Args])
end, Modules),
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "backup", "backup"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
case rpc:call(Node, mnesia, backup, [String]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
{error, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
_ ->
{result, []}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "backup", "restore"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
case rpc:call(Node, ejabberd_admin, restore, [String]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
{error, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
_ ->
{result, []}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "backup", "textfile"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
case rpc:call(Node, ejabberd_admin, dump_to_textfile, [String]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
{error, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
_ ->
{result, []}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "import", "file"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
rpc:call(Node, jd2ejd, import_file, [String]),
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "import", "dir"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
rpc:call(Node, jd2ejd, import_dir, [String]),
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(From, Host, ["running nodes", ENode, "restart"], _Lang, XData) ->
stop_node(From, Host, ENode, restart, XData);
set_form(From, Host, ["running nodes", ENode, "shutdown"], _Lang, XData) ->
stop_node(From, Host, ENode, stop, XData);
set_form(_From, Host, ["config", "acls"], _Lang, XData) ->
case lists:keysearch("acls", 1, XData) of
{value, {_, Strings}} ->
String = lists:foldl(fun(S, Res) ->
Res ++ S ++ "\n"
end, "", Strings),
case erl_scan:string(String) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, ACLs} ->
case acl:add_list(Host, ACLs, true) of
ok ->
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
set_form(_From, Host, ["config", "access"], _Lang, XData) ->
SetAccess =
fun(Rs) ->
mnesia:transaction(
fun() ->
Os = mnesia:select(config,
[{{config, {access, '$1', '$2'}, '$3'},
[{'==', '$2', Host}],
['$_']}]),
lists:foreach(fun(O) ->
mnesia:delete_object(O)
end, Os),
lists:foreach(
fun({access, Name, Rules}) ->
mnesia:write({config,
{access, Name, Host},
Rules})
end, Rs)
end)
end,
case lists:keysearch("access", 1, XData) of
{value, {_, Strings}} ->
String = lists:foldl(fun(S, Res) ->
Res ++ S ++ "\n"
end, "", Strings),
case erl_scan:string(String) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, Rs} ->
case SetAccess(Rs) of
{atomic, _} ->
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
set_form(From, Host, ?NS_ADMINL("add-user"), _Lang, XData) ->
AccountString = get_value("accountjid", XData),
Password = get_value("password", XData),
Password = get_value("password-verify", XData),
AccountJID = jlib:string_to_jid(AccountString),
User = AccountJID#jid.luser,
Server = AccountJID#jid.lserver,
true = lists:member(Server, ?MYHOSTS),
true = (Server == Host) orelse (get_permission_level(From) == global),
ejabberd_auth:try_register(User, Server, Password),
{result, []};
set_form(From, Host, ?NS_ADMINL("delete-user"), _Lang, XData) ->
AccountStringList = get_values("accountjids", XData),
[_|_] = AccountStringList,
ASL2 = lists:map(
fun(AccountString) ->
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
true = ejabberd_auth:is_user_exists(User, Server),
{User, Server}
end,
AccountStringList),
[ejabberd_auth:remove_user(User, Server) || {User, Server} <- ASL2],
{result, []};
set_form(From, Host, ?NS_ADMINL("end-user-session"), _Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
LUser = JID#jid.luser,
LServer = JID#jid.lserver,
true = (LServer == Host) orelse (get_permission_level(From) == global),
Code copied from
case JID#jid.lresource of
[] ->
SIDs = mnesia:dirty_select(session,
[{#session{sid = '$1', usr = {LUser, LServer, '_'}, _ = '_'}, [], ['$1']}]),
[Pid ! replaced || {_, Pid} <- SIDs];
R ->
[{_, Pid}] = mnesia:dirty_select(session,
[{#session{sid = '$1', usr = {LUser, LServer, R}, _ = '_'}, [], ['$1']}]),
Pid ! replaced
end,
{result, []};
set_form(From, Host, ?NS_ADMINL("get-user-password"), Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
Password = ejabberd_auth:get_password(User, Server),
true = is_list(Password),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
?XFIELD("jid-single", "Jabber ID", "accountjid", AccountString),
?XFIELD("text-single", "Password", "password", Password)
]}]};
set_form(From, Host, ?NS_ADMINL("change-user-password"), _Lang, XData) ->
AccountString = get_value("accountjid", XData),
Password = get_value("password", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
true = ejabberd_auth:is_user_exists(User, Server),
ejabberd_auth:set_password(User, Server, Password),
{result, []};
set_form(From, Host, ?NS_ADMINL("get-user-lastlogin"), Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
%% Code copied from web/ejabberd_web_admin.erl
TODO : Update time format to XEP-0202 : Entity Time
FLast =
case ejabberd_sm:get_user_resources(User, Server) of
[] ->
_US = {User, Server},
case get_last_info(User, Server) of
not_found ->
?T(Lang, "Never");
{ok, Timestamp, _Status} ->
Shift = Timestamp,
TimeStamp = {Shift div 1000000,
Shift rem 1000000,
0},
{{Year, Month, Day}, {Hour, Minute, Second}} =
calendar:now_to_local_time(TimeStamp),
lists:flatten(
io_lib:format(
"~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w",
[Year, Month, Day, Hour, Minute, Second]))
end;
_ ->
?T(Lang, "Online")
end,
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}, {"type", "result"}],
[?HFIELD(),
?XFIELD("jid-single", "Jabber ID", "accountjid", AccountString),
?XFIELD("text-single", "Last login", "lastlogin", FLast)
]}]};
set_form(From, Host, ?NS_ADMINL("user-stats"), Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
Resources = ejabberd_sm:get_user_resources(User, Server),
IPs1 = [ejabberd_sm:get_user_ip(User, Server, Resource) || Resource <- Resources],
IPs = [inet_parse:ntoa(IP)++":"++integer_to_list(Port) || {IP, Port} <- IPs1],
Items = ejabberd_hooks:run_fold(roster_get, Server, [], [{User, Server}]),
Rostersize = integer_to_list(erlang:length(Items)),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
?XFIELD("jid-single", "Jabber ID", "accountjid", AccountString),
?XFIELD("text-single", "Roster size", "rostersize", Rostersize),
?XMFIELD("text-multi", "IP addresses", "ipaddresses", IPs),
?XMFIELD("text-multi", "Resources", "onlineresources", Resources)
]}]};
set_form(_From, _Host, _, _Lang, _XData) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
get_value(Field, XData) ->
hd(get_values(Field, XData)).
get_values(Field, XData) ->
{value, {_, ValueList}} = lists:keysearch(Field, 1, XData),
ValueList.
search_running_node(SNode) ->
search_running_node(SNode, mnesia:system_info(running_db_nodes)).
search_running_node(_, []) ->
false;
search_running_node(SNode, [Node | Nodes]) ->
case atom_to_list(Node) of
SNode ->
Node;
_ ->
search_running_node(SNode, Nodes)
end.
stop_node(From, Host, ENode, Action, XData) ->
Delay = list_to_integer(get_value("delay", XData)),
Subject = case get_value("subject", XData) of
[] -> [];
S -> [{xmlelement, "field", [{"var","subject"}],
[{xmlelement,"value",[],[{xmlcdata,S}]}]}]
end,
Announcement = case get_values("announcement", XData) of
[] -> [];
As -> [{xmlelement, "field", [{"var","body"}],
[{xmlelement,"value",[],[{xmlcdata,Line}]} || Line <- As] }]
end,
case Subject ++ Announcement of
[] -> ok;
SubEls ->
Request = #adhoc_request{
node = ?NS_ADMINX("announce-allhosts"),
action = "complete",
xdata = {xmlelement, "x",
[{"xmlns","jabber:x:data"},{"type","submit"}],
SubEls},
others= [{xmlelement, "x",
[{"xmlns","jabber:x:data"},{"type","submit"}],
SubEls}]
},
To = jlib:make_jid("", Host, ""),
mod_announce:announce_commands(empty, From, To, Request)
end,
Time = timer:seconds(Delay),
Node = list_to_atom(ENode),
{ok, _} = timer:apply_after(Time, rpc, call, [Node, init, Action, []]),
{result, []}.
get_last_info(User, Server) ->
ML = lists:member(mod_last, gen_mod:loaded_modules(Server)),
MLO = lists:member(mod_last_odbc, gen_mod:loaded_modules(Server)),
case {ML, MLO} of
{true, _} -> mod_last:get_last_info(User, Server);
{false, true} -> mod_last_odbc:get_last_info(User, Server);
{false, false} -> not_found
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
adhoc_sm_commands(_Acc, From,
#jid{user = User, server = Server, lserver = LServer} = _To,
#adhoc_request{lang = Lang,
node = "config",
action = Action,
xdata = XData} = Request) ->
case acl:match_rule(LServer, configure, From) of
deny ->
{error, ?ERR_FORBIDDEN};
allow ->
%% If the "action" attribute is not present, it is
%% understood as "execute". If there was no <actions/>
element in the first response ( which there is n't in our
%% case), "execute" and "complete" are equivalent.
ActionIsExecute = lists:member(Action,
["", "execute", "complete"]),
if Action == "cancel" ->
%% User cancels request
adhoc:produce_response(
Request,
#adhoc_response{status = canceled});
XData == false, ActionIsExecute ->
%% User requests form
case get_sm_form(User, Server, "config", Lang) of
{result, Form} ->
adhoc:produce_response(
Request,
#adhoc_response{status = executing,
elements = Form});
{error, Error} ->
{error, Error}
end;
XData /= false, ActionIsExecute ->
%% User returns form.
case jlib:parse_xdata_submit(XData) of
invalid ->
{error, ?ERR_BAD_REQUEST};
Fields ->
set_sm_form(User, Server, "config", Request, Fields)
end;
true ->
{error, ?ERR_BAD_REQUEST}
end
end;
adhoc_sm_commands(Acc, _From, _To, _Request) ->
Acc.
get_sm_form(User, Server, "config", Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Administration of ") ++ User}]},
{xmlelement, "field",
[{"type", "list-single"},
{"label", ?T(Lang, "Action on user")},
{"var", "action"}],
[{xmlelement, "value", [], [{xmlcdata, "edit"}]},
{xmlelement, "option",
[{"label", ?T(Lang, "Edit Properties")}],
[{xmlelement, "value", [], [{xmlcdata, "edit"}]}]},
{xmlelement, "option",
[{"label", ?T(Lang, "Remove User")}],
[{xmlelement, "value", [], [{xmlcdata, "remove"}]}]}
]},
?XFIELD("text-private", "Password", "password",
ejabberd_auth:get_password_s(User, Server))
]}]};
get_sm_form(_User, _Server, _Node, _Lang) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
set_sm_form(User, Server, "config",
#adhoc_request{lang = Lang,
node = Node,
sessionid = SessionID}, XData) ->
Response = #adhoc_response{lang = Lang,
node = Node,
sessionid = SessionID,
status = completed},
case lists:keysearch("action", 1, XData) of
{value, {_, ["edit"]}} ->
case lists:keysearch("password", 1, XData) of
{value, {_, [Password]}} ->
ejabberd_auth:set_password(User, Server, Password),
adhoc:produce_response(Response);
_ ->
{error, ?ERR_NOT_ACCEPTABLE}
end;
{value, {_, ["remove"]}} ->
catch ejabberd_auth:remove_user(User, Server),
adhoc:produce_response(Response);
_ ->
{error, ?ERR_NOT_ACCEPTABLE}
end;
set_sm_form(_User, _Server, _Node, _Request, _Fields) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
| null | https://raw.githubusercontent.com/cstar/ejabberd-old/559f8b6b0a935710fe93e9afacb4270d6d6ea00f/src/mod_configure.erl | erlang | ----------------------------------------------------------------------
Purpose : Support for online configuration of ejabberd
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.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-----------------------------------------------------------------------
Recursively get all configure commands
-----------------------------------------------------------------------
-----------------------------------------------------------------------
-> {result, [xmlelement()]}
PermissionLevel = global | vhost
-------------------------------------------------------------------------
If the "action" attribute is not present, it is
understood as "execute". If there was no <actions/>
case), "execute" and "complete" are equivalent.
User cancels request
User requests form
User returns form.
We believe that this is allowed only for good people
Code copied from web/ejabberd_web_admin.erl
If the "action" attribute is not present, it is
understood as "execute". If there was no <actions/>
case), "execute" and "complete" are equivalent.
User cancels request
User requests form
User returns form. | File :
Author : < >
Created : 19 Jan 2003 by < >
ejabberd , Copyright ( C ) 2002 - 2010 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
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
Implements most of XEP-0133 : Service Administration Version 1.1
( 2005 - 08 - 19 )
-module(mod_configure).
-author('').
-behaviour(gen_mod).
-export([start/2,
stop/1,
get_local_identity/5,
get_local_features/5,
get_local_items/5,
adhoc_local_items/4,
adhoc_local_commands/4,
get_sm_identity/5,
get_sm_features/5,
get_sm_items/5,
adhoc_sm_items/4,
adhoc_sm_commands/4]).
-include("ejabberd.hrl").
-include("jlib.hrl").
-include("adhoc.hrl").
-define(T(Lang, Text), translate:translate(Lang, Text)).
Copied from
-record(session, {sid, usr, us, priority, info}).
start(Host, _Opts) ->
ejabberd_hooks:add(disco_local_items, Host, ?MODULE, get_local_items, 50),
ejabberd_hooks:add(disco_local_features, Host, ?MODULE, get_local_features, 50),
ejabberd_hooks:add(disco_local_identity, Host, ?MODULE, get_local_identity, 50),
ejabberd_hooks:add(disco_sm_items, Host, ?MODULE, get_sm_items, 50),
ejabberd_hooks:add(disco_sm_features, Host, ?MODULE, get_sm_features, 50),
ejabberd_hooks:add(disco_sm_identity, Host, ?MODULE, get_sm_identity, 50),
ejabberd_hooks:add(adhoc_local_items, Host, ?MODULE, adhoc_local_items, 50),
ejabberd_hooks:add(adhoc_local_commands, Host, ?MODULE, adhoc_local_commands, 50),
ejabberd_hooks:add(adhoc_sm_items, Host, ?MODULE, adhoc_sm_items, 50),
ejabberd_hooks:add(adhoc_sm_commands, Host, ?MODULE, adhoc_sm_commands, 50),
ok.
stop(Host) ->
ejabberd_hooks:delete(adhoc_sm_commands, Host, ?MODULE, adhoc_sm_commands, 50),
ejabberd_hooks:delete(adhoc_sm_items, Host, ?MODULE, adhoc_sm_items, 50),
ejabberd_hooks:delete(adhoc_local_commands, Host, ?MODULE, adhoc_local_commands, 50),
ejabberd_hooks:delete(adhoc_local_items, Host, ?MODULE, adhoc_local_items, 50),
ejabberd_hooks:delete(disco_sm_identity, Host, ?MODULE, get_sm_identity, 50),
ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE, get_sm_features, 50),
ejabberd_hooks:delete(disco_sm_items, Host, ?MODULE, get_sm_items, 50),
ejabberd_hooks:delete(disco_local_identity, Host, ?MODULE, get_local_identity, 50),
ejabberd_hooks:delete(disco_local_features, Host, ?MODULE, get_local_features, 50),
ejabberd_hooks:delete(disco_local_items, Host, ?MODULE, get_local_items, 50),
gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_COMMANDS),
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_COMMANDS).
-define(INFO_IDENTITY(Category, Type, Name, Lang),
[{xmlelement, "identity",
[{"category", Category},
{"type", Type},
{"name", ?T(Lang, Name)}], []}]).
-define(INFO_COMMAND(Name, Lang),
?INFO_IDENTITY("automation", "command-node", Name, Lang)).
-define(NODEJID(To, Name, Node),
{xmlelement, "item",
[{"jid", jlib:jid_to_string(To)},
{"name", ?T(Lang, Name)},
{"node", Node}], []}).
-define(NODE(Name, Node),
{xmlelement, "item",
[{"jid", Server},
{"name", ?T(Lang, Name)},
{"node", Node}], []}).
-define(NS_ADMINX(Sub), ?NS_ADMIN++"#"++Sub).
-define(NS_ADMINL(Sub), ["http:","jabber.org","protocol","admin", Sub]).
tokenize(Node) -> string:tokens(Node, "/#").
get_sm_identity(Acc, _From, _To, Node, Lang) ->
case Node of
"config" ->
?INFO_COMMAND("Configuration", Lang);
_ ->
Acc
end.
get_local_identity(Acc, _From, _To, Node, Lang) ->
LNode = tokenize(Node),
case LNode of
["running nodes", ENode] ->
?INFO_IDENTITY("ejabberd", "node", ENode, Lang);
["running nodes", _ENode, "DB"] ->
?INFO_COMMAND("Database", Lang);
["running nodes", _ENode, "modules", "start"] ->
?INFO_COMMAND("Start Modules", Lang);
["running nodes", _ENode, "modules", "stop"] ->
?INFO_COMMAND("Stop Modules", Lang);
["running nodes", _ENode, "backup", "backup"] ->
?INFO_COMMAND("Backup", Lang);
["running nodes", _ENode, "backup", "restore"] ->
?INFO_COMMAND("Restore", Lang);
["running nodes", _ENode, "backup", "textfile"] ->
?INFO_COMMAND("Dump to Text File", Lang);
["running nodes", _ENode, "import", "file"] ->
?INFO_COMMAND("Import File", Lang);
["running nodes", _ENode, "import", "dir"] ->
?INFO_COMMAND("Import Directory", Lang);
["running nodes", _ENode, "restart"] ->
?INFO_COMMAND("Restart Service", Lang);
["running nodes", _ENode, "shutdown"] ->
?INFO_COMMAND("Shut Down Service", Lang);
?NS_ADMINL("add-user") ->
?INFO_COMMAND("Add User", Lang);
?NS_ADMINL("delete-user") ->
?INFO_COMMAND("Delete User", Lang);
?NS_ADMINL("end-user-session") ->
?INFO_COMMAND("End User Session", Lang);
?NS_ADMINL("get-user-password") ->
?INFO_COMMAND("Get User Password", Lang);
?NS_ADMINL("change-user-password") ->
?INFO_COMMAND("Change User Password", Lang);
?NS_ADMINL("get-user-lastlogin") ->
?INFO_COMMAND("Get User Last Login Time", Lang);
?NS_ADMINL("user-stats") ->
?INFO_COMMAND("Get User Statistics", Lang);
?NS_ADMINL("get-registered-users-num") ->
?INFO_COMMAND("Get Number of Registered Users", Lang);
?NS_ADMINL("get-online-users-num") ->
?INFO_COMMAND("Get Number of Online Users", Lang);
["config", "acls"] ->
?INFO_COMMAND("Access Control Lists", Lang);
["config", "access"] ->
?INFO_COMMAND("Access Rules", Lang);
_ ->
Acc
end.
-define(INFO_RESULT(Allow, Feats),
case Allow of
deny ->
{error, ?ERR_FORBIDDEN};
allow ->
{result, Feats}
end).
get_sm_features(Acc, From, #jid{lserver = LServer} = _To, Node, _Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
Allow = acl:match_rule(LServer, configure, From),
case Node of
"config" ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
_ ->
Acc
end
end.
get_local_features(Acc, From, #jid{lserver = LServer} = _To, Node, _Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
case LNode of
["config"] ->
?INFO_RESULT(Allow, []);
["user"] ->
?INFO_RESULT(Allow, []);
["online users"] ->
?INFO_RESULT(Allow, []);
["all users"] ->
?INFO_RESULT(Allow, []);
["all users", [$@ | _]] ->
?INFO_RESULT(Allow, []);
["outgoing s2s" | _] ->
?INFO_RESULT(Allow, []);
["running nodes"] ->
?INFO_RESULT(Allow, []);
["stopped nodes"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode] ->
?INFO_RESULT(Allow, [?NS_STATS]);
["running nodes", _ENode, "DB"] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "modules"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode, "modules", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "backup"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode, "backup", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "import"] ->
?INFO_RESULT(Allow, []);
["running nodes", _ENode, "import", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "restart"] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["running nodes", _ENode, "shutdown"] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["config", _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
["http:" | _] ->
?INFO_RESULT(Allow, [?NS_COMMANDS]);
_ ->
Acc
end
end.
adhoc_sm_items(Acc, From, #jid{lserver = LServer} = To, Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Nodes = [{xmlelement, "item",
[{"jid", jlib:jid_to_string(To)},
{"name", ?T(Lang, "Configuration")},
{"node", "config"}], []}],
{result, Items ++ Nodes};
_ ->
Acc
end.
get_sm_items(Acc, From,
#jid{user = User, server = Server, lserver = LServer} = To,
Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
case {acl:match_rule(LServer, configure, From), Node} of
{allow, ""} ->
Nodes = [?NODEJID(To, "Configuration", "config"),
?NODEJID(To, "User Management", "user")],
{result, Items ++ Nodes ++ get_user_resources(User, Server)};
{allow, "config"} ->
{result, []};
{_, "config"} ->
{error, ?ERR_FORBIDDEN};
_ ->
Acc
end
end.
get_user_resources(User, Server) ->
Rs = ejabberd_sm:get_user_resources(User, Server),
lists:map(fun(R) ->
{xmlelement, "item",
[{"jid", User ++ "@" ++ Server ++ "/" ++ R},
{"name", User}], []}
end, lists:sort(Rs)).
adhoc_local_items(Acc, From, #jid{lserver = LServer, server = Server} = To,
Lang) ->
case acl:match_rule(LServer, configure, From) of
allow ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
PermLev = get_permission_level(From),
Nodes = recursively_get_local_items(PermLev, LServer, "", Server,
Lang),
Nodes1 = lists:filter(
fun(N) ->
Nd = xml:get_tag_attr_s("node", N),
F = get_local_features([], From, To, Nd, Lang),
case F of
{result, [?NS_COMMANDS]} ->
true;
_ ->
false
end
end, Nodes),
{result, Items ++ Nodes1};
_ ->
Acc
end.
recursively_get_local_items(_PermLev, _LServer, "online users", _Server, _Lang) ->
[];
recursively_get_local_items(_PermLev, _LServer, "all users", _Server, _Lang) ->
[];
recursively_get_local_items(PermLev, LServer, Node, Server, Lang) ->
LNode = tokenize(Node),
Items = case get_local_items({PermLev, LServer}, LNode, Server, Lang) of
{result, Res} ->
Res;
{error, _Error} ->
[]
end,
Nodes = lists:flatten(
lists:map(
fun(N) ->
S = xml:get_tag_attr_s("jid", N),
Nd = xml:get_tag_attr_s("node", N),
if (S /= Server) or (Nd == "") ->
[];
true ->
[N, recursively_get_local_items(
PermLev, LServer, Nd, Server, Lang)]
end
end, Items)),
Nodes.
get_permission_level(JID) ->
case acl:match_rule(global, configure, JID) of
allow -> global;
deny -> vhost
end.
-define(ITEMS_RESULT(Allow, LNode, Fallback),
case Allow of
deny ->
Fallback;
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, LNode,
jlib:jid_to_string(To), Lang) of
{result, Res} ->
{result, Res};
{error, Error} ->
{error, Error}
end
end).
get_local_items(Acc, From, #jid{lserver = LServer} = To, "", Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Allow = acl:match_rule(LServer, configure, From),
case Allow of
deny ->
{result, Items};
allow ->
PermLev = get_permission_level(From),
case get_local_items({PermLev, LServer}, [],
jlib:jid_to_string(To), Lang) of
{result, Res} ->
{result, Items ++ Res};
{error, _Error} ->
{result, Items}
end
end
end;
get_local_items(Acc, From, #jid{lserver = LServer} = To, Node, Lang) ->
case gen_mod:is_loaded(LServer, mod_adhoc) of
false ->
Acc;
_ ->
LNode = tokenize(Node),
Allow = acl:match_rule(LServer, configure, From),
case LNode of
["config"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["user"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["online users"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["all users"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["all users", [$@ | _]] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["outgoing s2s" | _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["stopped nodes"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "DB"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "modules"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "modules", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "backup"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "backup", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "import"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "import", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "restart"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["running nodes", _ENode, "shutdown"] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
["config", _] ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
?NS_ADMINL(_) ->
?ITEMS_RESULT(Allow, LNode, {error, ?ERR_FORBIDDEN});
_ ->
Acc
end
end.
@spec ( { PermissionLevel , Host } , [ string ( ) ] , Server::string ( ) , )
get_local_items(_Host, [], Server, Lang) ->
{result,
[?NODE("Configuration", "config"),
?NODE("User Management", "user"),
?NODE("Online Users", "online users"),
?NODE("All Users", "all users"),
?NODE("Outgoing s2s Connections", "outgoing s2s"),
?NODE("Running Nodes", "running nodes"),
?NODE("Stopped Nodes", "stopped nodes")
]};
get_local_items(_Host, ["config"], Server, Lang) ->
{result,
[?NODE("Access Control Lists", "config/acls"),
?NODE("Access Rules", "config/access")
]};
get_local_items(_Host, ["config", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["user"], Server, Lang) ->
{result,
[?NODE("Add User", ?NS_ADMINX("add-user")),
?NODE("Delete User", ?NS_ADMINX("delete-user")),
?NODE("End User Session", ?NS_ADMINX("end-user-session")),
?NODE("Get User Password", ?NS_ADMINX("get-user-password")),
?NODE("Change User Password",?NS_ADMINX("change-user-password")),
?NODE("Get User Last Login Time", ?NS_ADMINX("get-user-lastlogin")),
?NODE("Get User Statistics", ?NS_ADMINX("user-stats")),
?NODE("Get Number of Registered Users",?NS_ADMINX("get-registered-users-num")),
?NODE("Get Number of Online Users",?NS_ADMINX("get-online-users-num"))
]};
get_local_items(_Host, ["http:" | _], _Server, _Lang) ->
{result, []};
get_local_items({_, Host}, ["online users"], _Server, _Lang) ->
{result, get_online_vh_users(Host)};
get_local_items({_, Host}, ["all users"], _Server, _Lang) ->
{result, get_all_vh_users(Host)};
get_local_items({_, Host}, ["all users", [$@ | Diap]], _Server, _Lang) ->
case catch ejabberd_auth:get_vh_registered_users(Host) of
{'EXIT', _Reason} ->
?ERR_INTERNAL_SERVER_ERROR;
Users ->
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
case catch begin
{ok, [S1, S2]} = regexp:split(Diap, "-"),
N1 = list_to_integer(S1),
N2 = list_to_integer(S2),
Sub = lists:sublist(SUsers, N1, N2 - N1 + 1),
lists:map(fun({S, U}) ->
{xmlelement, "item",
[{"jid", U ++ "@" ++ S},
{"name", U ++ "@" ++ S}], []}
end, Sub)
end of
{'EXIT', _Reason} ->
?ERR_NOT_ACCEPTABLE;
Res ->
{result, Res}
end
end;
get_local_items({_, Host}, ["outgoing s2s"], _Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang)};
get_local_items({_, Host}, ["outgoing s2s", To], _Server, Lang) ->
{result, get_outgoing_s2s(Host, Lang, To)};
get_local_items(_Host, ["running nodes"], Server, Lang) ->
{result, get_running_nodes(Server, Lang)};
get_local_items(_Host, ["stopped nodes"], _Server, Lang) ->
{result, get_stopped_nodes(Lang)};
get_local_items({global, _Host}, ["running nodes", ENode], Server, Lang) ->
{result,
[?NODE("Database", "running nodes/" ++ ENode ++ "/DB"),
?NODE("Modules", "running nodes/" ++ ENode ++ "/modules"),
?NODE("Backup Management", "running nodes/" ++ ENode ++ "/backup"),
?NODE("Import Users From jabberd14 Spool Files",
"running nodes/" ++ ENode ++ "/import"),
?NODE("Restart Service", "running nodes/" ++ ENode ++ "/restart"),
?NODE("Shut Down Service", "running nodes/" ++ ENode ++ "/shutdown")
]};
get_local_items({vhost, _Host}, ["running nodes", ENode], Server, Lang) ->
{result,
[?NODE("Modules", "running nodes/" ++ ENode ++ "/modules")
]};
get_local_items(_Host, ["running nodes", _ENode, "DB"], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", ENode, "modules"], Server, Lang) ->
{result,
[?NODE("Start Modules", "running nodes/" ++ ENode ++ "/modules/start"),
?NODE("Stop Modules", "running nodes/" ++ ENode ++ "/modules/stop")
]};
get_local_items(_Host, ["running nodes", _ENode, "modules", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", ENode, "backup"], Server, Lang) ->
{result,
[?NODE("Backup", "running nodes/" ++ ENode ++ "/backup/backup"),
?NODE("Restore", "running nodes/" ++ ENode ++ "/backup/restore"),
?NODE("Dump to Text File",
"running nodes/" ++ ENode ++ "/backup/textfile")
]};
get_local_items(_Host, ["running nodes", _ENode, "backup", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", ENode, "import"], Server, Lang) ->
{result,
[?NODE("Import File", "running nodes/" ++ ENode ++ "/import/file"),
?NODE("Import Directory", "running nodes/" ++ ENode ++ "/import/dir")
]};
get_local_items(_Host, ["running nodes", _ENode, "import", _], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", _ENode, "restart"], _Server, _Lang) ->
{result, []};
get_local_items(_Host, ["running nodes", _ENode, "shutdown"], _Server, _Lang) ->
{result, []};
get_local_items(_Host, _, _Server, _Lang) ->
{error, ?ERR_ITEM_NOT_FOUND}.
get_online_vh_users(Host) ->
case catch ejabberd_sm:get_vh_session_list(Host) of
{'EXIT', _Reason} ->
[];
USRs ->
SURs = lists:sort([{S, U, R} || {U, S, R} <- USRs]),
lists:map(fun({S, U, R}) ->
{xmlelement, "item",
[{"jid", U ++ "@" ++ S ++ "/" ++ R},
{"name", U ++ "@" ++ S}], []}
end, SURs)
end.
get_all_vh_users(Host) ->
case catch ejabberd_auth:get_vh_registered_users(Host) of
{'EXIT', _Reason} ->
[];
Users ->
SUsers = lists:sort([{S, U} || {U, S} <- Users]),
case length(SUsers) of
N when N =< 100 ->
lists:map(fun({S, U}) ->
{xmlelement, "item",
[{"jid", U ++ "@" ++ S},
{"name", U ++ "@" ++ S}], []}
end, SUsers);
N ->
NParts = trunc(math:sqrt(N * 0.618)) + 1,
M = trunc(N / NParts) + 1,
lists:map(fun(K) ->
L = K + M - 1,
Node =
"@" ++ integer_to_list(K) ++
"-" ++ integer_to_list(L),
{FS, FU} = lists:nth(K, SUsers),
{LS, LU} =
if L < N -> lists:nth(L, SUsers);
true -> lists:last(SUsers)
end,
Name =
FU ++ "@" ++ FS ++
" -- " ++
LU ++ "@" ++ LS,
{xmlelement, "item",
[{"jid", Host},
{"node", "all users/" ++ Node},
{"name", Name}], []}
end, lists:seq(1, N, M))
end
end.
get_outgoing_s2s(Host, Lang) ->
case catch ejabberd_s2s:dirty_get_connections() of
{'EXIT', _Reason} ->
[];
Connections ->
DotHost = "." ++ Host,
TConns = [TH || {FH, TH} <- Connections,
Host == FH orelse lists:suffix(DotHost, FH)],
lists:map(
fun(T) ->
{xmlelement, "item",
[{"jid", Host},
{"node", "outgoing s2s/" ++ T},
{"name",
lists:flatten(
io_lib:format(
?T(Lang, "To ~s"), [T]))}],
[]}
end, lists:usort(TConns))
end.
get_outgoing_s2s(Host, Lang, To) ->
case catch ejabberd_s2s:dirty_get_connections() of
{'EXIT', _Reason} ->
[];
Connections ->
lists:map(
fun({F, _T}) ->
{xmlelement, "item",
[{"jid", Host},
{"node", "outgoing s2s/" ++ To ++ "/" ++ F},
{"name",
lists:flatten(
io_lib:format(
?T(Lang, "From ~s"), [F]))}],
[]}
end, lists:keysort(1, lists:filter(fun(E) ->
element(2, E) == To
end, Connections)))
end.
get_running_nodes(Server, _Lang) ->
case catch mnesia:system_info(running_db_nodes) of
{'EXIT', _Reason} ->
[];
DBNodes ->
lists:map(
fun(N) ->
S = atom_to_list(N),
{xmlelement, "item",
[{"jid", Server},
{"node", "running nodes/" ++ S},
{"name", S}],
[]}
end, lists:sort(DBNodes))
end.
get_stopped_nodes(_Lang) ->
case catch (lists:usort(mnesia:system_info(db_nodes) ++
mnesia:system_info(extra_db_nodes)) --
mnesia:system_info(running_db_nodes)) of
{'EXIT', _Reason} ->
[];
DBNodes ->
lists:map(
fun(N) ->
S = atom_to_list(N),
{xmlelement, "item",
[{"jid", ?MYNAME},
{"node", "stopped nodes/" ++ S},
{"name", S}],
[]}
end, lists:sort(DBNodes))
end.
-define(COMMANDS_RESULT(LServerOrGlobal, From, To, Request),
case acl:match_rule(LServerOrGlobal, configure, From) of
deny ->
{error, ?ERR_FORBIDDEN};
allow ->
adhoc_local_commands(From, To, Request)
end).
adhoc_local_commands(Acc, From, #jid{lserver = LServer} = To,
#adhoc_request{node = Node} = Request) ->
LNode = tokenize(Node),
case LNode of
["running nodes", _ENode, "DB"] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "modules", _] ->
?COMMANDS_RESULT(LServer, From, To, Request);
["running nodes", _ENode, "backup", _] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "import", _] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "restart"] ->
?COMMANDS_RESULT(global, From, To, Request);
["running nodes", _ENode, "shutdown"] ->
?COMMANDS_RESULT(global, From, To, Request);
["config", _] ->
?COMMANDS_RESULT(LServer, From, To, Request);
?NS_ADMINL(_) ->
?COMMANDS_RESULT(LServer, From, To, Request);
_ ->
Acc
end.
adhoc_local_commands(From, #jid{lserver = LServer} = _To,
#adhoc_request{lang = Lang,
node = Node,
sessionid = SessionID,
action = Action,
xdata = XData} = Request) ->
LNode = tokenize(Node),
element in the first response ( which there is n't in our
ActionIsExecute = lists:member(Action,
["", "execute", "complete"]),
if Action == "cancel" ->
adhoc:produce_response(
Request,
#adhoc_response{status = canceled});
XData == false, ActionIsExecute ->
case get_form(LServer, LNode, Lang) of
{result, Form} ->
adhoc:produce_response(
Request,
#adhoc_response{status = executing,
elements = Form});
{result, Status, Form} ->
adhoc:produce_response(
Request,
#adhoc_response{status = Status,
elements = Form});
{error, Error} ->
{error, Error}
end;
XData /= false, ActionIsExecute ->
case jlib:parse_xdata_submit(XData) of
invalid ->
{error, ?ERR_BAD_REQUEST};
Fields ->
case catch set_form(From, LServer, LNode, Lang, Fields) of
{result, Res} ->
adhoc:produce_response(
#adhoc_response{lang = Lang,
node = Node,
sessionid = SessionID,
elements = Res,
status = completed});
{'EXIT', _} ->
{error, ?ERR_BAD_REQUEST};
{error, Error} ->
{error, Error}
end
end;
true ->
{error, ?ERR_BAD_REQUEST}
end.
-define(TVFIELD(Type, Var, Val),
{xmlelement, "field", [{"type", Type},
{"var", Var}],
[{xmlelement, "value", [], [{xmlcdata, Val}]}]}).
-define(HFIELD(), ?TVFIELD("hidden", "FORM_TYPE", ?NS_ADMIN)).
-define(TLFIELD(Type, Label, Var),
{xmlelement, "field", [{"type", Type},
{"label", ?T(Lang, Label)},
{"var", Var}], []}).
-define(XFIELD(Type, Label, Var, Val),
{xmlelement, "field", [{"type", Type},
{"label", ?T(Lang, Label)},
{"var", Var}],
[{xmlelement, "value", [], [{xmlcdata, Val}]}]}).
-define(XMFIELD(Type, Label, Var, Vals),
{xmlelement, "field", [{"type", Type},
{"label", ?T(Lang, Label)},
{"var", Var}],
[{xmlelement, "value", [], [{xmlcdata,Val}]} || Val <- Vals]}).
-define(TABLEFIELD(Table, Val),
{xmlelement, "field", [{"type", "list-single"},
{"label", atom_to_list(Table)},
{"var", atom_to_list(Table)}],
[{xmlelement, "value", [], [{xmlcdata, atom_to_list(Val)}]},
{xmlelement, "option", [{"label",
?T(Lang, "RAM copy")}],
[{xmlelement, "value", [], [{xmlcdata, "ram_copies"}]}]},
{xmlelement, "option", [{"label",
?T(Lang,
"RAM and disc copy")}],
[{xmlelement, "value", [], [{xmlcdata, "disc_copies"}]}]},
{xmlelement, "option", [{"label",
?T(Lang,
"Disc only copy")}],
[{xmlelement, "value", [], [{xmlcdata, "disc_only_copies"}]}]},
{xmlelement, "option", [{"label",
?T(Lang, "Remote copy")}],
[{xmlelement, "value", [], [{xmlcdata, "unknown"}]}]}
]}).
get_form(_Host, ["running nodes", ENode, "DB"], Lang) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case rpc:call(Node, mnesia, system_info, [tables]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
Tables ->
STables = lists:sort(Tables),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Database Tables Configuration at ") ++
ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Choose storage type of tables")}]} |
lists:map(
fun(Table) ->
case rpc:call(Node,
mnesia,
table_info,
[Table, storage_type]) of
{badrpc, _} ->
?TABLEFIELD(Table, unknown);
Type ->
?TABLEFIELD(Table, Type)
end
end, STables)
]}]}
end
end;
get_form(Host, ["running nodes", ENode, "modules", "stop"], Lang) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case rpc:call(Node, gen_mod, loaded_modules, [Host]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
Modules ->
SModules = lists:sort(Modules),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Stop Modules at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Choose modules to stop")}]} |
lists:map(fun(M) ->
S = atom_to_list(M),
?XFIELD("boolean", S, S, "0")
end, SModules)
]}]}
end
end;
get_form(_Host, ["running nodes", ENode, "modules", "start"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Start Modules at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter list of {Module, [Options]}")}]},
?XFIELD("text-multi", "List of modules to start", "modules", "[].")
]}]};
get_form(_Host, ["running nodes", ENode, "backup", "backup"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Backup to File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to backup file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "backup", "restore"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Restore Backup from File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to backup file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "backup", "textfile"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Dump Backup to Text File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to text file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "import", "file"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Import User from File at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to jabberd14 spool file")}]},
?XFIELD("text-single", "Path to File", "path", "")
]}]};
get_form(_Host, ["running nodes", ENode, "import", "dir"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Import Users from Dir at ") ++ ENode}]},
{xmlelement, "instructions", [],
[{xmlcdata,
?T(
Lang, "Enter path to jabberd14 spool dir")}]},
?XFIELD("text-single", "Path to Dir", "path", "")
]}]};
get_form(_Host, ["running nodes", _ENode, "restart"], Lang) ->
Make_option =
fun(LabelNum, LabelUnit, Value)->
{xmlelement, "option",
[{"label", LabelNum ++ ?T(Lang, LabelUnit)}],
[{xmlelement, "value", [], [{xmlcdata, Value}]}]}
end,
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Restart Service")}]},
{xmlelement, "field",
[{"type", "list-single"},
{"label", ?T(Lang, "Time delay")},
{"var", "delay"}],
[Make_option("", "immediately", "1"),
Make_option("15 ", "seconds", "15"),
Make_option("30 ", "seconds", "30"),
Make_option("60 ", "seconds", "60"),
Make_option("90 ", "seconds", "90"),
Make_option("2 ", "minutes", "120"),
Make_option("3 ", "minutes", "180"),
Make_option("4 ", "minutes", "240"),
Make_option("5 ", "minutes", "300"),
Make_option("10 ", "minutes", "600"),
Make_option("15 ", "minutes", "900"),
Make_option("30 ", "minutes", "1800"),
{xmlelement, "required", [], []}
]},
{xmlelement, "field",
[{"type", "fixed"},
{"label", ?T(Lang, "Send announcement to all online users on all hosts")}],
[]},
{xmlelement, "field",
[{"var", "subject"},
{"type", "text-single"},
{"label", ?T(Lang, "Subject")}],
[]},
{xmlelement, "field",
[{"var", "announcement"},
{"type", "text-multi"},
{"label", ?T(Lang, "Message body")}],
[]}
]}]};
get_form(_Host, ["running nodes", _ENode, "shutdown"], Lang) ->
Make_option =
fun(LabelNum, LabelUnit, Value)->
{xmlelement, "option",
[{"label", LabelNum ++ ?T(Lang, LabelUnit)}],
[{xmlelement, "value", [], [{xmlcdata, Value}]}]}
end,
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Shut Down Service")}]},
{xmlelement, "field",
[{"type", "list-single"},
{"label", ?T(Lang, "Time delay")},
{"var", "delay"}],
[Make_option("", "immediately", "1"),
Make_option("15 ", "seconds", "15"),
Make_option("30 ", "seconds", "30"),
Make_option("60 ", "seconds", "60"),
Make_option("90 ", "seconds", "90"),
Make_option("2 ", "minutes", "120"),
Make_option("3 ", "minutes", "180"),
Make_option("4 ", "minutes", "240"),
Make_option("5 ", "minutes", "300"),
Make_option("10 ", "minutes", "600"),
Make_option("15 ", "minutes", "900"),
Make_option("30 ", "minutes", "1800"),
{xmlelement, "required", [], []}
]},
{xmlelement, "field",
[{"type", "fixed"},
{"label", ?T(Lang, "Send announcement to all online users on all hosts")}],
[]},
{xmlelement, "field",
[{"var", "subject"},
{"type", "text-single"},
{"label", ?T(Lang, "Subject")}],
[]},
{xmlelement, "field",
[{"var", "announcement"},
{"type", "text-multi"},
{"label", ?T(Lang, "Message body")}],
[]}
]}]};
get_form(Host, ["config", "acls"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Access Control List Configuration")}]},
{xmlelement, "field", [{"type", "text-multi"},
{"label",
?T(
Lang, "Access control lists")},
{"var", "acls"}],
lists:map(fun(S) ->
{xmlelement, "value", [], [{xmlcdata, S}]}
end,
string:tokens(
lists:flatten(
io_lib:format(
"~p.",
[ets:select(acl,
[{{acl, {'$1', '$2'}, '$3'},
[{'==', '$2', Host}],
[{{acl, '$1', '$3'}}]}])
])),
"\n"))
}
]}]};
get_form(Host, ["config", "access"], Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Access Configuration")}]},
{xmlelement, "field", [{"type", "text-multi"},
{"label",
?T(
Lang, "Access rules")},
{"var", "access"}],
lists:map(fun(S) ->
{xmlelement, "value", [], [{xmlcdata, S}]}
end,
string:tokens(
lists:flatten(
io_lib:format(
"~p.",
[ets:select(config,
[{{config, {access, '$1', '$2'}, '$3'},
[{'==', '$2', Host}],
[{{access, '$1', '$3'}}]}])
])),
"\n"))
}
]}]};
get_form(_Host, ?NS_ADMINL("add-user"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Add User")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]},
{xmlelement, "field",
[{"type", "text-private"},
{"label", ?T(Lang, "Password")},
{"var", "password"}],
[{xmlelement, "required", [], []}]},
{xmlelement, "field",
[{"type", "text-private"},
{"label", ?T(Lang, "Password Verification")},
{"var", "password-verify"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("delete-user"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Delete User")}]},
{xmlelement, "field",
[{"type", "jid-multi"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjids"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("end-user-session"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "End User Session")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("get-user-password"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Password")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("change-user-password"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Password")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]},
{xmlelement, "field",
[{"type", "text-private"},
{"label", ?T(Lang, "Password")},
{"var", "password"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("get-user-lastlogin"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Last Login Time")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(_Host, ?NS_ADMINL("user-stats"), Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata, ?T(Lang, "Get User Statistics")}]},
{xmlelement, "field",
[{"type", "jid-single"},
{"label", ?T(Lang, "Jabber ID")},
{"var", "accountjid"}],
[{xmlelement, "required", [], []}]}
]}]};
get_form(Host, ?NS_ADMINL("get-registered-users-num"), Lang) ->
[Num] = io_lib:format("~p", [ejabberd_auth:get_vh_registered_users_number(Host)]),
{result, completed,
[{xmlelement, "x",
[{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement,
"field",
[{"type", "text-single"},
{"label", ?T(Lang, "Number of registered users")},
{"var", "registeredusersnum"}],
[{xmlelement, "value", [], [{xmlcdata, Num}]}]
}]}]};
get_form(Host, ?NS_ADMINL("get-online-users-num"), Lang) ->
Num = io_lib:format("~p", [length(ejabberd_sm:get_vh_session_list(Host))]),
{result, completed,
[{xmlelement, "x",
[{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement,
"field",
[{"type", "text-single"},
{"label", ?T(Lang, "Number of online users")},
{"var", "onlineusersnum"}],
[{xmlelement, "value", [], [{xmlcdata, Num}]}]
}]}]};
get_form(_Host, _, _Lang) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
set_form(_From, _Host, ["running nodes", ENode, "DB"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
lists:foreach(
fun({SVar, SVals}) ->
Table = list_to_atom(SVar),
Type = case SVals of
["unknown"] -> unknown;
["ram_copies"] -> ram_copies;
["disc_copies"] -> disc_copies;
["disc_only_copies"] -> disc_only_copies;
_ -> false
end,
if
Type == false ->
ok;
Type == unknown ->
mnesia:del_table_copy(Table, Node);
true ->
case mnesia:add_table_copy(Table, Node, Type) of
{aborted, _} ->
mnesia:change_table_copy_type(
Table, Node, Type);
_ ->
ok
end
end
end, XData),
{result, []}
end;
set_form(_From, Host, ["running nodes", ENode, "modules", "stop"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
lists:foreach(
fun({Var, Vals}) ->
case Vals of
["1"] ->
Module = list_to_atom(Var),
rpc:call(Node, gen_mod, stop_module, [Host, Module]);
_ ->
ok
end
end, XData),
{result, []}
end;
set_form(_From, Host, ["running nodes", ENode, "modules", "start"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("modules", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, Strings}} ->
String = lists:foldl(fun(S, Res) ->
Res ++ S ++ "\n"
end, "", Strings),
case erl_scan:string(String) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, Modules} ->
lists:foreach(
fun({Module, Args}) ->
rpc:call(Node,
gen_mod,
start_module,
[Host, Module, Args])
end, Modules),
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "backup", "backup"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
case rpc:call(Node, mnesia, backup, [String]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
{error, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
_ ->
{result, []}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "backup", "restore"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
case rpc:call(Node, ejabberd_admin, restore, [String]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
{error, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
_ ->
{result, []}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "backup", "textfile"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
case rpc:call(Node, ejabberd_admin, dump_to_textfile, [String]) of
{badrpc, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
{error, _Reason} ->
{error, ?ERR_INTERNAL_SERVER_ERROR};
_ ->
{result, []}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "import", "file"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
rpc:call(Node, jd2ejd, import_file, [String]),
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(_From, _Host, ["running nodes", ENode, "import", "dir"], _Lang, XData) ->
case search_running_node(ENode) of
false ->
{error, ?ERR_ITEM_NOT_FOUND};
Node ->
case lists:keysearch("path", 1, XData) of
false ->
{error, ?ERR_BAD_REQUEST};
{value, {_, [String]}} ->
rpc:call(Node, jd2ejd, import_dir, [String]),
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end
end;
set_form(From, Host, ["running nodes", ENode, "restart"], _Lang, XData) ->
stop_node(From, Host, ENode, restart, XData);
set_form(From, Host, ["running nodes", ENode, "shutdown"], _Lang, XData) ->
stop_node(From, Host, ENode, stop, XData);
set_form(_From, Host, ["config", "acls"], _Lang, XData) ->
case lists:keysearch("acls", 1, XData) of
{value, {_, Strings}} ->
String = lists:foldl(fun(S, Res) ->
Res ++ S ++ "\n"
end, "", Strings),
case erl_scan:string(String) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, ACLs} ->
case acl:add_list(Host, ACLs, true) of
ok ->
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
set_form(_From, Host, ["config", "access"], _Lang, XData) ->
SetAccess =
fun(Rs) ->
mnesia:transaction(
fun() ->
Os = mnesia:select(config,
[{{config, {access, '$1', '$2'}, '$3'},
[{'==', '$2', Host}],
['$_']}]),
lists:foreach(fun(O) ->
mnesia:delete_object(O)
end, Os),
lists:foreach(
fun({access, Name, Rules}) ->
mnesia:write({config,
{access, Name, Host},
Rules})
end, Rs)
end)
end,
case lists:keysearch("access", 1, XData) of
{value, {_, Strings}} ->
String = lists:foldl(fun(S, Res) ->
Res ++ S ++ "\n"
end, "", Strings),
case erl_scan:string(String) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, Rs} ->
case SetAccess(Rs) of
{atomic, _} ->
{result, []};
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
_ ->
{error, ?ERR_BAD_REQUEST}
end;
set_form(From, Host, ?NS_ADMINL("add-user"), _Lang, XData) ->
AccountString = get_value("accountjid", XData),
Password = get_value("password", XData),
Password = get_value("password-verify", XData),
AccountJID = jlib:string_to_jid(AccountString),
User = AccountJID#jid.luser,
Server = AccountJID#jid.lserver,
true = lists:member(Server, ?MYHOSTS),
true = (Server == Host) orelse (get_permission_level(From) == global),
ejabberd_auth:try_register(User, Server, Password),
{result, []};
set_form(From, Host, ?NS_ADMINL("delete-user"), _Lang, XData) ->
AccountStringList = get_values("accountjids", XData),
[_|_] = AccountStringList,
ASL2 = lists:map(
fun(AccountString) ->
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
true = ejabberd_auth:is_user_exists(User, Server),
{User, Server}
end,
AccountStringList),
[ejabberd_auth:remove_user(User, Server) || {User, Server} <- ASL2],
{result, []};
set_form(From, Host, ?NS_ADMINL("end-user-session"), _Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
LUser = JID#jid.luser,
LServer = JID#jid.lserver,
true = (LServer == Host) orelse (get_permission_level(From) == global),
Code copied from
case JID#jid.lresource of
[] ->
SIDs = mnesia:dirty_select(session,
[{#session{sid = '$1', usr = {LUser, LServer, '_'}, _ = '_'}, [], ['$1']}]),
[Pid ! replaced || {_, Pid} <- SIDs];
R ->
[{_, Pid}] = mnesia:dirty_select(session,
[{#session{sid = '$1', usr = {LUser, LServer, R}, _ = '_'}, [], ['$1']}]),
Pid ! replaced
end,
{result, []};
set_form(From, Host, ?NS_ADMINL("get-user-password"), Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
Password = ejabberd_auth:get_password(User, Server),
true = is_list(Password),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
?XFIELD("jid-single", "Jabber ID", "accountjid", AccountString),
?XFIELD("text-single", "Password", "password", Password)
]}]};
set_form(From, Host, ?NS_ADMINL("change-user-password"), _Lang, XData) ->
AccountString = get_value("accountjid", XData),
Password = get_value("password", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
true = ejabberd_auth:is_user_exists(User, Server),
ejabberd_auth:set_password(User, Server, Password),
{result, []};
set_form(From, Host, ?NS_ADMINL("get-user-lastlogin"), Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
TODO : Update time format to XEP-0202 : Entity Time
FLast =
case ejabberd_sm:get_user_resources(User, Server) of
[] ->
_US = {User, Server},
case get_last_info(User, Server) of
not_found ->
?T(Lang, "Never");
{ok, Timestamp, _Status} ->
Shift = Timestamp,
TimeStamp = {Shift div 1000000,
Shift rem 1000000,
0},
{{Year, Month, Day}, {Hour, Minute, Second}} =
calendar:now_to_local_time(TimeStamp),
lists:flatten(
io_lib:format(
"~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w",
[Year, Month, Day, Hour, Minute, Second]))
end;
_ ->
?T(Lang, "Online")
end,
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}, {"type", "result"}],
[?HFIELD(),
?XFIELD("jid-single", "Jabber ID", "accountjid", AccountString),
?XFIELD("text-single", "Last login", "lastlogin", FLast)
]}]};
set_form(From, Host, ?NS_ADMINL("user-stats"), Lang, XData) ->
AccountString = get_value("accountjid", XData),
JID = jlib:string_to_jid(AccountString),
[_|_] = JID#jid.luser,
User = JID#jid.luser,
Server = JID#jid.lserver,
true = (Server == Host) orelse (get_permission_level(From) == global),
Resources = ejabberd_sm:get_user_resources(User, Server),
IPs1 = [ejabberd_sm:get_user_ip(User, Server, Resource) || Resource <- Resources],
IPs = [inet_parse:ntoa(IP)++":"++integer_to_list(Port) || {IP, Port} <- IPs1],
Items = ejabberd_hooks:run_fold(roster_get, Server, [], [{User, Server}]),
Rostersize = integer_to_list(erlang:length(Items)),
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
?XFIELD("jid-single", "Jabber ID", "accountjid", AccountString),
?XFIELD("text-single", "Roster size", "rostersize", Rostersize),
?XMFIELD("text-multi", "IP addresses", "ipaddresses", IPs),
?XMFIELD("text-multi", "Resources", "onlineresources", Resources)
]}]};
set_form(_From, _Host, _, _Lang, _XData) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
get_value(Field, XData) ->
hd(get_values(Field, XData)).
get_values(Field, XData) ->
{value, {_, ValueList}} = lists:keysearch(Field, 1, XData),
ValueList.
search_running_node(SNode) ->
search_running_node(SNode, mnesia:system_info(running_db_nodes)).
search_running_node(_, []) ->
false;
search_running_node(SNode, [Node | Nodes]) ->
case atom_to_list(Node) of
SNode ->
Node;
_ ->
search_running_node(SNode, Nodes)
end.
stop_node(From, Host, ENode, Action, XData) ->
Delay = list_to_integer(get_value("delay", XData)),
Subject = case get_value("subject", XData) of
[] -> [];
S -> [{xmlelement, "field", [{"var","subject"}],
[{xmlelement,"value",[],[{xmlcdata,S}]}]}]
end,
Announcement = case get_values("announcement", XData) of
[] -> [];
As -> [{xmlelement, "field", [{"var","body"}],
[{xmlelement,"value",[],[{xmlcdata,Line}]} || Line <- As] }]
end,
case Subject ++ Announcement of
[] -> ok;
SubEls ->
Request = #adhoc_request{
node = ?NS_ADMINX("announce-allhosts"),
action = "complete",
xdata = {xmlelement, "x",
[{"xmlns","jabber:x:data"},{"type","submit"}],
SubEls},
others= [{xmlelement, "x",
[{"xmlns","jabber:x:data"},{"type","submit"}],
SubEls}]
},
To = jlib:make_jid("", Host, ""),
mod_announce:announce_commands(empty, From, To, Request)
end,
Time = timer:seconds(Delay),
Node = list_to_atom(ENode),
{ok, _} = timer:apply_after(Time, rpc, call, [Node, init, Action, []]),
{result, []}.
get_last_info(User, Server) ->
ML = lists:member(mod_last, gen_mod:loaded_modules(Server)),
MLO = lists:member(mod_last_odbc, gen_mod:loaded_modules(Server)),
case {ML, MLO} of
{true, _} -> mod_last:get_last_info(User, Server);
{false, true} -> mod_last_odbc:get_last_info(User, Server);
{false, false} -> not_found
end.
adhoc_sm_commands(_Acc, From,
#jid{user = User, server = Server, lserver = LServer} = _To,
#adhoc_request{lang = Lang,
node = "config",
action = Action,
xdata = XData} = Request) ->
case acl:match_rule(LServer, configure, From) of
deny ->
{error, ?ERR_FORBIDDEN};
allow ->
element in the first response ( which there is n't in our
ActionIsExecute = lists:member(Action,
["", "execute", "complete"]),
if Action == "cancel" ->
adhoc:produce_response(
Request,
#adhoc_response{status = canceled});
XData == false, ActionIsExecute ->
case get_sm_form(User, Server, "config", Lang) of
{result, Form} ->
adhoc:produce_response(
Request,
#adhoc_response{status = executing,
elements = Form});
{error, Error} ->
{error, Error}
end;
XData /= false, ActionIsExecute ->
case jlib:parse_xdata_submit(XData) of
invalid ->
{error, ?ERR_BAD_REQUEST};
Fields ->
set_sm_form(User, Server, "config", Request, Fields)
end;
true ->
{error, ?ERR_BAD_REQUEST}
end
end;
adhoc_sm_commands(Acc, _From, _To, _Request) ->
Acc.
get_sm_form(User, Server, "config", Lang) ->
{result, [{xmlelement, "x", [{"xmlns", ?NS_XDATA}],
[?HFIELD(),
{xmlelement, "title", [],
[{xmlcdata,
?T(
Lang, "Administration of ") ++ User}]},
{xmlelement, "field",
[{"type", "list-single"},
{"label", ?T(Lang, "Action on user")},
{"var", "action"}],
[{xmlelement, "value", [], [{xmlcdata, "edit"}]},
{xmlelement, "option",
[{"label", ?T(Lang, "Edit Properties")}],
[{xmlelement, "value", [], [{xmlcdata, "edit"}]}]},
{xmlelement, "option",
[{"label", ?T(Lang, "Remove User")}],
[{xmlelement, "value", [], [{xmlcdata, "remove"}]}]}
]},
?XFIELD("text-private", "Password", "password",
ejabberd_auth:get_password_s(User, Server))
]}]};
get_sm_form(_User, _Server, _Node, _Lang) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
set_sm_form(User, Server, "config",
#adhoc_request{lang = Lang,
node = Node,
sessionid = SessionID}, XData) ->
Response = #adhoc_response{lang = Lang,
node = Node,
sessionid = SessionID,
status = completed},
case lists:keysearch("action", 1, XData) of
{value, {_, ["edit"]}} ->
case lists:keysearch("password", 1, XData) of
{value, {_, [Password]}} ->
ejabberd_auth:set_password(User, Server, Password),
adhoc:produce_response(Response);
_ ->
{error, ?ERR_NOT_ACCEPTABLE}
end;
{value, {_, ["remove"]}} ->
catch ejabberd_auth:remove_user(User, Server),
adhoc:produce_response(Response);
_ ->
{error, ?ERR_NOT_ACCEPTABLE}
end;
set_sm_form(_User, _Server, _Node, _Request, _Fields) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
|
bd2ab4d5bed85b1b13733f5b3b548497752e7696255d599991b5d5923dab0062 | alura-cursos/clojure-mutabilidade-atomos-e-refs | core.clj | (ns hospital.core
(:use [clojure pprint])
(:require [hospital.model :as h.model]))
espera ESPERA 3
; laboratorio1 3
; laboratorio2 2
; laboratorio3
(let [hospital-do-gui (h.model/novo-hospital)]
(pprint hospital-do-gui))
(pprint h.model/fila-vazia)
| null | https://raw.githubusercontent.com/alura-cursos/clojure-mutabilidade-atomos-e-refs/18c70bc13862df53377ac607b53b8f210f4239dd/aula6.2/hospital/src/hospital/core.clj | clojure | laboratorio1 3
laboratorio2 2
laboratorio3 | (ns hospital.core
(:use [clojure pprint])
(:require [hospital.model :as h.model]))
espera ESPERA 3
(let [hospital-do-gui (h.model/novo-hospital)]
(pprint hospital-do-gui))
(pprint h.model/fila-vazia)
|
59c9d1902868166d25770151e63e8f3ed531ed7a5e8e95deced9f754b00f77eb | erikd/hjsmin | hjsmin.hs | # LANGUAGE CPP #
#include "cabal_macros.h"
import qualified Data.ByteString.Lazy.Char8 as LBS
import Options.Applicative (Parser, ParserInfo, ParserPrefs)
import qualified Options.Applicative as Opt
import Text.Jasmine (minify)
import System.IO (hPutStrLn, stderr)
import System.Exit (exitFailure)
data Command
= Process FilePath (Maybe FilePath)
main :: IO ()
main =
Opt.customExecParser p opts >>= processFile
where
opts :: ParserInfo Command
opts = Opt.info (Opt.helper <*> pVersion <*> pProcess)
( Opt.fullDesc
<> Opt.header "hjsmin - Haskell implementation of a Javascript and JSON minifier"
)
p :: ParserPrefs
p = Opt.prefs Opt.showHelpOnEmpty
pVersion :: Parser (a -> a)
pVersion =
Opt.infoOption versionString
( Opt.long "version"
<> Opt.short 'v'
<> Opt.help "Print the version and exit"
)
pProcess :: Parser Command
pProcess =
Process <$> pInputFile <*> pMaybeOutputFile
where
pInputFile =
Opt.strOption
( Opt.long "input"
<> Opt.short 'i'
<> Opt.metavar "INPUT_FILE"
<> Opt.help "The original JavaScript file"
)
pMaybeOutputFile =
Opt.optional $ Opt.strOption
( Opt.long "output"
<> Opt.short 'o'
<> Opt.metavar "OUTPUT_FILE"
<> Opt.help "The minified output file. Default: stdout"
)
processFile :: Command -> IO ()
processFile (Process inputFile outputFile) = do
lbs <- LBS.readFile inputFile
if LBS.null lbs
then emptyFileError
else do
let minified = minify lbs
case outputFile of
Nothing -> LBS.putStrLn minified
Just f -> LBS.writeFile f minified
where
emptyFileError = do
hPutStrLn stderr $ "Error: input file '" ++ inputFile ++ "' is empty."
exitFailure
versionString :: String
versionString =
concat
[ "hjsmin version ", VERSION_hjsmin
, " (using language-javascript version ", VERSION_language_javascript, ")"
]
| null | https://raw.githubusercontent.com/erikd/hjsmin/2983d01c16f7a1d5659620b9b3cfc1ee883d2e81/main/hjsmin.hs | haskell | # LANGUAGE CPP #
#include "cabal_macros.h"
import qualified Data.ByteString.Lazy.Char8 as LBS
import Options.Applicative (Parser, ParserInfo, ParserPrefs)
import qualified Options.Applicative as Opt
import Text.Jasmine (minify)
import System.IO (hPutStrLn, stderr)
import System.Exit (exitFailure)
data Command
= Process FilePath (Maybe FilePath)
main :: IO ()
main =
Opt.customExecParser p opts >>= processFile
where
opts :: ParserInfo Command
opts = Opt.info (Opt.helper <*> pVersion <*> pProcess)
( Opt.fullDesc
<> Opt.header "hjsmin - Haskell implementation of a Javascript and JSON minifier"
)
p :: ParserPrefs
p = Opt.prefs Opt.showHelpOnEmpty
pVersion :: Parser (a -> a)
pVersion =
Opt.infoOption versionString
( Opt.long "version"
<> Opt.short 'v'
<> Opt.help "Print the version and exit"
)
pProcess :: Parser Command
pProcess =
Process <$> pInputFile <*> pMaybeOutputFile
where
pInputFile =
Opt.strOption
( Opt.long "input"
<> Opt.short 'i'
<> Opt.metavar "INPUT_FILE"
<> Opt.help "The original JavaScript file"
)
pMaybeOutputFile =
Opt.optional $ Opt.strOption
( Opt.long "output"
<> Opt.short 'o'
<> Opt.metavar "OUTPUT_FILE"
<> Opt.help "The minified output file. Default: stdout"
)
processFile :: Command -> IO ()
processFile (Process inputFile outputFile) = do
lbs <- LBS.readFile inputFile
if LBS.null lbs
then emptyFileError
else do
let minified = minify lbs
case outputFile of
Nothing -> LBS.putStrLn minified
Just f -> LBS.writeFile f minified
where
emptyFileError = do
hPutStrLn stderr $ "Error: input file '" ++ inputFile ++ "' is empty."
exitFailure
versionString :: String
versionString =
concat
[ "hjsmin version ", VERSION_hjsmin
, " (using language-javascript version ", VERSION_language_javascript, ")"
]
|
|
2210b483ae6a8bb0ad5019c2d4580a0ae7e092c73d37c9041251045809ba02fc | korya/efuns | test12.ml | let _ =
let x =
if Random.int 100 > -10 then 3
else 3
in
while x > 2 do
Printf.printf "bonjour"; print_newline ();
done | null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/inliner/tests/test12.ml | ocaml | let _ =
let x =
if Random.int 100 > -10 then 3
else 3
in
while x > 2 do
Printf.printf "bonjour"; print_newline ();
done |
|
13fce6cef65f799cca79affda8df76932567512724660d0ec101e4afa9d3b65f | portkey-cloud/aws-clj-sdk | codestar.clj | (ns portkey.aws.codestar (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope {:service "codestar", :region "ap-northeast-1"},
:ssl-common-name "codestar.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "codestar", :region "eu-west-1"},
:ssl-common-name "codestar.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "codestar", :region "us-east-2"},
:ssl-common-name "codestar.us-east-2.amazonaws.com",
:endpoint "-east-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope {:service "codestar", :region "ap-southeast-2"},
:ssl-common-name "codestar.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-1"
{:credential-scope {:service "codestar", :region "ap-southeast-1"},
:ssl-common-name "codestar.ap-southeast-1.amazonaws.com",
:endpoint "-southeast-1.amazonaws.com",
:signature-version :v4},
"ap-northeast-2"
{:credential-scope {:service "codestar", :region "ap-northeast-2"},
:ssl-common-name "codestar.ap-northeast-2.amazonaws.com",
:endpoint "-northeast-2.amazonaws.com",
:signature-version :v4},
"ca-central-1"
{:credential-scope {:service "codestar", :region "ca-central-1"},
:ssl-common-name "codestar.ca-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-central-1"
{:credential-scope {:service "codestar", :region "eu-central-1"},
:ssl-common-name "codestar.eu-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-west-2"
{:credential-scope {:service "codestar", :region "eu-west-2"},
:ssl-common-name "codestar.eu-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "codestar", :region "us-west-2"},
:ssl-common-name "codestar.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "codestar", :region "us-east-1"},
:ssl-common-name "codestar.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"us-west-1"
{:credential-scope {:service "codestar", :region "us-west-1"},
:ssl-common-name "codestar.us-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
| null | https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/codestar.clj | clojure | (ns portkey.aws.codestar (:require [portkey.aws]))
(def
endpoints
'{"ap-northeast-1"
{:credential-scope {:service "codestar", :region "ap-northeast-1"},
:ssl-common-name "codestar.ap-northeast-1.amazonaws.com",
:endpoint "-northeast-1.amazonaws.com",
:signature-version :v4},
"eu-west-1"
{:credential-scope {:service "codestar", :region "eu-west-1"},
:ssl-common-name "codestar.eu-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4},
"us-east-2"
{:credential-scope {:service "codestar", :region "us-east-2"},
:ssl-common-name "codestar.us-east-2.amazonaws.com",
:endpoint "-east-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-2"
{:credential-scope {:service "codestar", :region "ap-southeast-2"},
:ssl-common-name "codestar.ap-southeast-2.amazonaws.com",
:endpoint "-southeast-2.amazonaws.com",
:signature-version :v4},
"ap-southeast-1"
{:credential-scope {:service "codestar", :region "ap-southeast-1"},
:ssl-common-name "codestar.ap-southeast-1.amazonaws.com",
:endpoint "-southeast-1.amazonaws.com",
:signature-version :v4},
"ap-northeast-2"
{:credential-scope {:service "codestar", :region "ap-northeast-2"},
:ssl-common-name "codestar.ap-northeast-2.amazonaws.com",
:endpoint "-northeast-2.amazonaws.com",
:signature-version :v4},
"ca-central-1"
{:credential-scope {:service "codestar", :region "ca-central-1"},
:ssl-common-name "codestar.ca-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-central-1"
{:credential-scope {:service "codestar", :region "eu-central-1"},
:ssl-common-name "codestar.eu-central-1.amazonaws.com",
:endpoint "-central-1.amazonaws.com",
:signature-version :v4},
"eu-west-2"
{:credential-scope {:service "codestar", :region "eu-west-2"},
:ssl-common-name "codestar.eu-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-west-2"
{:credential-scope {:service "codestar", :region "us-west-2"},
:ssl-common-name "codestar.us-west-2.amazonaws.com",
:endpoint "-west-2.amazonaws.com",
:signature-version :v4},
"us-east-1"
{:credential-scope {:service "codestar", :region "us-east-1"},
:ssl-common-name "codestar.us-east-1.amazonaws.com",
:endpoint "-east-1.amazonaws.com",
:signature-version :v4},
"us-west-1"
{:credential-scope {:service "codestar", :region "us-west-1"},
:ssl-common-name "codestar.us-west-1.amazonaws.com",
:endpoint "-west-1.amazonaws.com",
:signature-version :v4}})
(comment TODO support "json")
|
|
ff11ca96410d81c10f42e7ebe39bbe29c8bd82340fd9bedc90227c8469f840a8 | jdevuyst/termcat | core_macros_cljs.clj | (ns termcat.core-macros-cljs
(:require [cljs.core.match.macros :refer (match)]
[clojure.core.reducers :as r]
[termcat.term :as t]
[termcat.rewrite :as rw]))
(defmacro with-cache [cache & body]
`(binding [rw/!*cache* ~cache]
~@body))
(defmacro window [init-state proj [& arg-list] & body]
(assert (or (nil? init-state) (map? init-state)))
(assert (reduce #(and %1 (symbol? %2)) true arg-list))
(assert (even? (count body)))
(let [argc (-> arg-list count dec)]
`(fn
([] ~init-state)
([state# input#]
(let [padded-input# (concat input# (repeat nil))
[~@arg-list] (cons state# (take ~argc padded-input#))]
(if-let [r# (match (->> padded-input#
(r/map ~proj)
(r/take ~argc)
(r/reduce conj [state#]))
~@body
:else nil)]
[(or (first r#) state#)
(concat (next r#)
(drop ~argc input#))]))))))
(defmacro defrule [fnname & rdecl]
(assert (symbol? fnname))
(let [[doc-str rdecl] (if (string? (first rdecl))
[(first rdecl) (next rdecl)]
["" rdecl])
[init-state rdecl] (if (vector? (first rdecl))
[nil rdecl]
[(first rdecl) (next rdecl)])
[[& args] body] [(first rdecl) (next rdecl)]]
(assert (>= (count args) 2))
`(def ~fnname ~doc-str
(-> (window ~init-state
t/tt
[~@args]
~@body)
rw/abstraction)))) | null | https://raw.githubusercontent.com/jdevuyst/termcat/5b4d89da67de89e6d62933c8c407e7a79ffdb0cb/src/clj/termcat/core_macros_cljs.clj | clojure | (ns termcat.core-macros-cljs
(:require [cljs.core.match.macros :refer (match)]
[clojure.core.reducers :as r]
[termcat.term :as t]
[termcat.rewrite :as rw]))
(defmacro with-cache [cache & body]
`(binding [rw/!*cache* ~cache]
~@body))
(defmacro window [init-state proj [& arg-list] & body]
(assert (or (nil? init-state) (map? init-state)))
(assert (reduce #(and %1 (symbol? %2)) true arg-list))
(assert (even? (count body)))
(let [argc (-> arg-list count dec)]
`(fn
([] ~init-state)
([state# input#]
(let [padded-input# (concat input# (repeat nil))
[~@arg-list] (cons state# (take ~argc padded-input#))]
(if-let [r# (match (->> padded-input#
(r/map ~proj)
(r/take ~argc)
(r/reduce conj [state#]))
~@body
:else nil)]
[(or (first r#) state#)
(concat (next r#)
(drop ~argc input#))]))))))
(defmacro defrule [fnname & rdecl]
(assert (symbol? fnname))
(let [[doc-str rdecl] (if (string? (first rdecl))
[(first rdecl) (next rdecl)]
["" rdecl])
[init-state rdecl] (if (vector? (first rdecl))
[nil rdecl]
[(first rdecl) (next rdecl)])
[[& args] body] [(first rdecl) (next rdecl)]]
(assert (>= (count args) 2))
`(def ~fnname ~doc-str
(-> (window ~init-state
t/tt
[~@args]
~@body)
rw/abstraction)))) |
|
479439efe783c812bdd87d018ac63e66779295c5ed311842dc772a04eb0f86b3 | haroldcarr/learn-haskell-coq-ml-etc | Lib.hs | {-# LANGUAGE OverloadedStrings #-}
module Lib
( scottyMain
) where
import Web.Scotty
import Data.Monoid (mconcat)
import Web.Scotty
import Network.Wai.Middleware.RequestLogger -- install wai-extra if you don't have this
import Control.Monad
import Control.Monad.Trans
import Data.Monoid
import System.Random (newStdGen, randomRs)
import Network.HTTP.Types (status302)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Data.String (fromString)
import Prelude
scottyMain :: IO ()
scottyMain = scotty 3000 $ do
-- Add any WAI middleware, they are run top-down.
middleware logStdoutDev
-- get (function $ \req -> Just [("version", T.pack $ show $ httpVersion req)]) $ do
-- v <- param "version"
-- text v
-- To demonstrate that routes are matched top-down.
get "/" $ text "foobar"
get "/" $ text "barfoo"
-- Using a parameter in the query string. If it has
not been given , a 500 page is generated .
get "/foo" $ do
v <- param "fooparam"
html $ mconcat ["<h1>", v, "</h1>"]
An uncaught error becomes a 500 page .
get "/raise" $ raise "some error here"
-- You can set status and headers directly.
get "/redirect-custom" $ do
status status302
setHeader "Location" ""
note first arg to header is NOT case - sensitive
-- redirects preempt execution
get "/redirect" $ do
void $ redirect ""
raise "this error is never reached"
-- Of course you can catch your own errors.
get "/rescue" $ do
(do void $ raise "a rescued error"; redirect "-never-go-here.com")
`rescue` (\m -> text $ "we recovered from " `mappend` m)
-- Parts of the URL that start with a colon match
-- any string, and capture that value as a parameter.
-- URL captures take precedence over query string parameters.
get "/foo/:bar/required" $ do
v <- param "bar"
html $ mconcat ["<h1>", v, "</h1>"]
-- Files are streamed directly to the client.
get "/404" $ file "404.html"
-- You can stop execution of this action and keep pattern matching routes.
get "/random" $ do
void next
redirect "-never-go-here.com"
-- You can do IO with liftIO, and you can return JSON content.
get "/random" $ do
g <- liftIO newStdGen
json $ take 20 $ randomRs (1::Int,100) g
get "/ints/:is" $ do
is <- param "is"
json $ [(1::Int)..10] ++ is
get "/setbody" $ do
html $ mconcat ["<form method=POST action=\"readbody\">"
,"<input type=text name=something>"
,"<input type=submit>"
,"</form>"
]
post "/readbody" $ do
b <- body
text $ decodeUtf8 b
get "/header" $ do
agent <- header "User-Agent"
maybe (raise "User-Agent header not found!") text agent
Make a request to this URI , then type a line in the terminal , which
-- will be the response. Using ctrl-c will cause getLine to fail.
This demonstrates that IO exceptions are lifted into ActionM exceptions .
get "/iofail" $ do
msg <- liftIO $ liftM fromString getLine
text msg
If you do n't want to use Warp as your webserver ,
you can use any WAI handler .
import Network . Wai . Handler . FastCGI ( run )
main = do
myApp < - scottyApp $ do
get " / " $ text " hello world "
run myApp
you can use any WAI handler.
import Network.Wai.Handler.FastCGI (run)
main = do
myApp <- scottyApp $ do
get "/" $ text "hello world"
run myApp
-}
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/topic/web/scotty/01-basic-example/src/Lib.hs | haskell | # LANGUAGE OverloadedStrings #
install wai-extra if you don't have this
Add any WAI middleware, they are run top-down.
get (function $ \req -> Just [("version", T.pack $ show $ httpVersion req)]) $ do
v <- param "version"
text v
To demonstrate that routes are matched top-down.
Using a parameter in the query string. If it has
You can set status and headers directly.
redirects preempt execution
Of course you can catch your own errors.
Parts of the URL that start with a colon match
any string, and capture that value as a parameter.
URL captures take precedence over query string parameters.
Files are streamed directly to the client.
You can stop execution of this action and keep pattern matching routes.
You can do IO with liftIO, and you can return JSON content.
will be the response. Using ctrl-c will cause getLine to fail. |
module Lib
( scottyMain
) where
import Web.Scotty
import Data.Monoid (mconcat)
import Web.Scotty
import Control.Monad
import Control.Monad.Trans
import Data.Monoid
import System.Random (newStdGen, randomRs)
import Network.HTTP.Types (status302)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Data.String (fromString)
import Prelude
scottyMain :: IO ()
scottyMain = scotty 3000 $ do
middleware logStdoutDev
get "/" $ text "foobar"
get "/" $ text "barfoo"
not been given , a 500 page is generated .
get "/foo" $ do
v <- param "fooparam"
html $ mconcat ["<h1>", v, "</h1>"]
An uncaught error becomes a 500 page .
get "/raise" $ raise "some error here"
get "/redirect-custom" $ do
status status302
setHeader "Location" ""
note first arg to header is NOT case - sensitive
get "/redirect" $ do
void $ redirect ""
raise "this error is never reached"
get "/rescue" $ do
(do void $ raise "a rescued error"; redirect "-never-go-here.com")
`rescue` (\m -> text $ "we recovered from " `mappend` m)
get "/foo/:bar/required" $ do
v <- param "bar"
html $ mconcat ["<h1>", v, "</h1>"]
get "/404" $ file "404.html"
get "/random" $ do
void next
redirect "-never-go-here.com"
get "/random" $ do
g <- liftIO newStdGen
json $ take 20 $ randomRs (1::Int,100) g
get "/ints/:is" $ do
is <- param "is"
json $ [(1::Int)..10] ++ is
get "/setbody" $ do
html $ mconcat ["<form method=POST action=\"readbody\">"
,"<input type=text name=something>"
,"<input type=submit>"
,"</form>"
]
post "/readbody" $ do
b <- body
text $ decodeUtf8 b
get "/header" $ do
agent <- header "User-Agent"
maybe (raise "User-Agent header not found!") text agent
Make a request to this URI , then type a line in the terminal , which
This demonstrates that IO exceptions are lifted into ActionM exceptions .
get "/iofail" $ do
msg <- liftIO $ liftM fromString getLine
text msg
If you do n't want to use Warp as your webserver ,
you can use any WAI handler .
import Network . Wai . Handler . FastCGI ( run )
main = do
myApp < - scottyApp $ do
get " / " $ text " hello world "
run myApp
you can use any WAI handler.
import Network.Wai.Handler.FastCGI (run)
main = do
myApp <- scottyApp $ do
get "/" $ text "hello world"
run myApp
-}
|
bdfdaf9e363cd39675f91050aaf5af1a4fac725f17c7dfa228c7cdf7c9751cbc | weblocks-framework/weblocks | twitter.lisp | ;;;; A quick demo hack of a twitter user and/or friends timeline feed
;;;; widget. Depends on cl-twitter (cl.net)
;;;;
;;;; You have to authenticate a user before the widget will work correctly.
(defwidget twitter-widget ()
((history :accessor twitter-history :initarg :history :initform nil)
(timeout :accessor twitter-timeout :initarg :timeout :initform 300)
(last-poll :accessor twitter-last-poll :initarg :last-poll :initform 0)
(maxcount :accessor twitter-max-count :initarg :max :initform 100)
(page :accessor twitter-page :initarg :page :initform 0)
(count :accessor twitter-count :initarg :count :initform 5)
(friends-p :accessor include-friends-p :initarg :friends-p :initform nil)))
(defmethod initialize-instance :after ((widget twitter-widget) &rest initargs)
(declare (ignore initargs))
(update-history widget))
(defun update-history (widget)
"Called on init or page change to cache tweets"
(with-slots (page count maxcount history) widget
(when (> page (max-page widget))
(setf page (max-page widget)))
(when (or (null history) (twitter-timed-out-p widget))
(setf history
(append (widget-latest widget)
history)))))
(defun widget-latest (widget)
(with-slots (history maxcount) widget
(sort
(if history
(append (twitter-op :user-timeline
:since-id (tweet-id (first history)))
(when (include-friends-p widget)
(twitter-op :friends-timeline
:since-id (tweet-id (first history)))))
(append (twitter-op :user-timeline
:count maxcount)
(when (include-friends-p widget)
(twitter-op :friends-timeline
:count maxcount))))
#'> :key #'tweet-id)))
(defun max-page (widget)
(with-slots (history maxcount count) widget
(/ (min (length history) maxcount) count)))
(defun twitter-timed-out-p (widget)
(with-slots (timeout last-poll) widget
(< timeout (- (get-universal-time) last-poll))))
(defun current-tweets (widget)
(with-slots (page count history) widget
(let ((page-entries (nthcdr (* page count) history)))
(subseq page-entries 0 (min count (length page-entries))))))
;;
;; Rendering
;;
(defmethod render-widget-body ((widget twitter-widget) &rest args)
(declare (ignore args))
(with-html
(render-link (f_% (update-history widget)) "Refresh")
" | "
(render-link (f_% (setf (include-friends-p widget)
(not (include-friends-p widget)))
(setf (twitter-history widget) nil)
(update-history widget))
(if (include-friends-p widget)
"User Only"
"Show Followed"))
(:table
(:tr (:th "Name") (:th "Time") (:th "Message"))
(dolist (tweet (current-tweets widget))
(with-html (:tr (:td (:img :src (twitter-user-profile-image-url (tweet-user tweet)))
(str (twitter-user-screen-name (tweet-user tweet))))
(:td (str (tweet-created-at tweet)))
(:td (str (tweet-text tweet)))))))
(twitter-page-nav widget)))
(defun twitter-page-nav (widget)
(with-slots (page count maxcount) widget
(with-html
(if (> page 0)
(render-link (f_% (decf page)
(update-history widget))
"Previous Page")
(str "Previous Page"))
(str " | ")
(if (< page (max-page widget))
(render-link (f_% (incf page)
(update-history widget))
"Next Page")
(str "Next Page")))))
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/contrib/ian/twitter.lisp | lisp | A quick demo hack of a twitter user and/or friends timeline feed
widget. Depends on cl-twitter (cl.net)
You have to authenticate a user before the widget will work correctly.
Rendering
|
(defwidget twitter-widget ()
((history :accessor twitter-history :initarg :history :initform nil)
(timeout :accessor twitter-timeout :initarg :timeout :initform 300)
(last-poll :accessor twitter-last-poll :initarg :last-poll :initform 0)
(maxcount :accessor twitter-max-count :initarg :max :initform 100)
(page :accessor twitter-page :initarg :page :initform 0)
(count :accessor twitter-count :initarg :count :initform 5)
(friends-p :accessor include-friends-p :initarg :friends-p :initform nil)))
(defmethod initialize-instance :after ((widget twitter-widget) &rest initargs)
(declare (ignore initargs))
(update-history widget))
(defun update-history (widget)
"Called on init or page change to cache tweets"
(with-slots (page count maxcount history) widget
(when (> page (max-page widget))
(setf page (max-page widget)))
(when (or (null history) (twitter-timed-out-p widget))
(setf history
(append (widget-latest widget)
history)))))
(defun widget-latest (widget)
(with-slots (history maxcount) widget
(sort
(if history
(append (twitter-op :user-timeline
:since-id (tweet-id (first history)))
(when (include-friends-p widget)
(twitter-op :friends-timeline
:since-id (tweet-id (first history)))))
(append (twitter-op :user-timeline
:count maxcount)
(when (include-friends-p widget)
(twitter-op :friends-timeline
:count maxcount))))
#'> :key #'tweet-id)))
(defun max-page (widget)
(with-slots (history maxcount count) widget
(/ (min (length history) maxcount) count)))
(defun twitter-timed-out-p (widget)
(with-slots (timeout last-poll) widget
(< timeout (- (get-universal-time) last-poll))))
(defun current-tweets (widget)
(with-slots (page count history) widget
(let ((page-entries (nthcdr (* page count) history)))
(subseq page-entries 0 (min count (length page-entries))))))
(defmethod render-widget-body ((widget twitter-widget) &rest args)
(declare (ignore args))
(with-html
(render-link (f_% (update-history widget)) "Refresh")
" | "
(render-link (f_% (setf (include-friends-p widget)
(not (include-friends-p widget)))
(setf (twitter-history widget) nil)
(update-history widget))
(if (include-friends-p widget)
"User Only"
"Show Followed"))
(:table
(:tr (:th "Name") (:th "Time") (:th "Message"))
(dolist (tweet (current-tweets widget))
(with-html (:tr (:td (:img :src (twitter-user-profile-image-url (tweet-user tweet)))
(str (twitter-user-screen-name (tweet-user tweet))))
(:td (str (tweet-created-at tweet)))
(:td (str (tweet-text tweet)))))))
(twitter-page-nav widget)))
(defun twitter-page-nav (widget)
(with-slots (page count maxcount) widget
(with-html
(if (> page 0)
(render-link (f_% (decf page)
(update-history widget))
"Previous Page")
(str "Previous Page"))
(str " | ")
(if (< page (max-page widget))
(render-link (f_% (incf page)
(update-history widget))
"Next Page")
(str "Next Page")))))
|
6d94218d002c73dbc635f333e9fc4a157dea81b16744a4027e3cf869bfe03cb3 | jhgarner/Xest-Window-Manager | ActionTypes.hs | {-# LANGUAGE DeriveAnyClass #-}
module Actions.ActionTypes where
import Dhall (Interpret)
import FocusList
import Standard
-- | Actions/events to be performed
data Action
= Insert
| ChangeNamed Text
| Move Direction
| RunCommand Text
| ChangeModeTo Mode
| ShowWindow Text
| HideWindow Text
| ZoomInInput
| ZoomOutInput
| ZoomInMonitor
| ZoomOutMonitor
| ZoomMonitorToInput
| ZoomInputToMonitor
| PopTiler
| PushTiler
| MakeEmpty
| MoveToLoc Natural
| KillActive
| ExitNow
| ToggleLogging
| ChangeToHorizontal
| ChangeToFloating
| ChangeToTwoCols
| SetRotate
| SetFull
| SetNoMod
| ToggleDocks
| ChangeActiveScreen Direction
deriving (Show, Generic, Interpret)
-- | Modes similar to modes in vim
data Mode = NewMode
{ modeName :: Text,
hasButtons :: Bool,
hasBorders :: Bool
}
deriving (Show, Generic, Interpret)
instance Eq Mode where
n1 == n2 = modeName n1 == modeName n2
| null | https://raw.githubusercontent.com/jhgarner/Xest-Window-Manager/d1e7640b70fea662508f99778535069e9c639517/src/Actions/ActionTypes.hs | haskell | # LANGUAGE DeriveAnyClass #
| Actions/events to be performed
| Modes similar to modes in vim |
module Actions.ActionTypes where
import Dhall (Interpret)
import FocusList
import Standard
data Action
= Insert
| ChangeNamed Text
| Move Direction
| RunCommand Text
| ChangeModeTo Mode
| ShowWindow Text
| HideWindow Text
| ZoomInInput
| ZoomOutInput
| ZoomInMonitor
| ZoomOutMonitor
| ZoomMonitorToInput
| ZoomInputToMonitor
| PopTiler
| PushTiler
| MakeEmpty
| MoveToLoc Natural
| KillActive
| ExitNow
| ToggleLogging
| ChangeToHorizontal
| ChangeToFloating
| ChangeToTwoCols
| SetRotate
| SetFull
| SetNoMod
| ToggleDocks
| ChangeActiveScreen Direction
deriving (Show, Generic, Interpret)
data Mode = NewMode
{ modeName :: Text,
hasButtons :: Bool,
hasBorders :: Bool
}
deriving (Show, Generic, Interpret)
instance Eq Mode where
n1 == n2 = modeName n1 == modeName n2
|
ff9ceeff628693f08ed13f05a34af1d36f4fa129aa9922b92699863497765a6e | jacquev6/General | Parsable.ml | #include "../Generated/Traits/Parsable.ml"
module Tests = struct
include Tests_
module MakeExamples(M: Testable.S0)(E: Examples.S0 with type t := M.t) = E
module MakeTests(M: Testable.S0)(E: Examples.S0 with type t := M.t) = struct
open Testing
open M
let tests = (
E.literals
|> List.flat_map ~f:(fun (s, expected) ->
[
~: "of_string %S" s (lazy (check ~repr ~equal ~expected (of_string s)));
~: "try_of_string %S" s (lazy (check_some ~repr ~equal ~expected (try_of_string s)));
]
)
)
end
include MakeMakers(MakeExamples)(MakeTests)
end
| null | https://raw.githubusercontent.com/jacquev6/General/5237123668e939c0cb83aa3e1c4756473336bc7e/src/Traits/Parsable.ml | ocaml | #include "../Generated/Traits/Parsable.ml"
module Tests = struct
include Tests_
module MakeExamples(M: Testable.S0)(E: Examples.S0 with type t := M.t) = E
module MakeTests(M: Testable.S0)(E: Examples.S0 with type t := M.t) = struct
open Testing
open M
let tests = (
E.literals
|> List.flat_map ~f:(fun (s, expected) ->
[
~: "of_string %S" s (lazy (check ~repr ~equal ~expected (of_string s)));
~: "try_of_string %S" s (lazy (check_some ~repr ~equal ~expected (try_of_string s)));
]
)
)
end
include MakeMakers(MakeExamples)(MakeTests)
end
|
|
5863dd6bcf3edf89b89e5a96f3d99de5f2681e5fcbbaf474652967f71efbd2c5 | ekmett/haskell | Relative.hs | module Relative
( Relative(..)
, RelativeSemigroup
, RelativeMonoid
) where
import Delta
import Unaligned.Internal (Rev(..))
--------------------------------------------------------------------------------
-- * Interface
--------------------------------------------------------------------------------
-- monoid action
class Relative a where
rel :: Delta -> a -> a
instance Relative a => Relative (Maybe a) where
rel = fmap . rel
-- | @rel d (a <> b) = rel d a <> rel d b@
class (Relative a, Semigroup a) => RelativeSemigroup a
| @rel d = mempty@
class (Relative a, RelativeSemigroup a, Monoid a) => RelativeMonoid a
instance Relative (f a) => Relative (Rev f a) where
rel d (Rev as) = Rev (rel d as)
| null | https://raw.githubusercontent.com/ekmett/haskell/37ad048531f5a3a13c6dfbf4772ee4325f0e4458/sequences/monoid-relative/Relative.hs | haskell | ------------------------------------------------------------------------------
* Interface
------------------------------------------------------------------------------
monoid action
| @rel d (a <> b) = rel d a <> rel d b@ | module Relative
( Relative(..)
, RelativeSemigroup
, RelativeMonoid
) where
import Delta
import Unaligned.Internal (Rev(..))
class Relative a where
rel :: Delta -> a -> a
instance Relative a => Relative (Maybe a) where
rel = fmap . rel
class (Relative a, Semigroup a) => RelativeSemigroup a
| @rel d = mempty@
class (Relative a, RelativeSemigroup a, Monoid a) => RelativeMonoid a
instance Relative (f a) => Relative (Rev f a) where
rel d (Rev as) = Rev (rel d as)
|
cc521e632661b4b6c13394827da8f36ddb949b7a31a8dad891c54a8b1553fa23 | haskell/cabal | Variable.hs | module Distribution.Solver.Types.Variable where
import Prelude (Eq, Show)
import Distribution.Solver.Types.OptionalStanza
import Distribution.PackageDescription (FlagName)
-- | Variables used by the dependency solver. This type is similar to the
internal ' Var ' type .
data Variable qpn =
PackageVar qpn
| FlagVar qpn FlagName
| StanzaVar qpn OptionalStanza
deriving (Eq, Show)
| null | https://raw.githubusercontent.com/haskell/cabal/6896c6aa0e4804913aaba0bbbe00649e18f17bb8/cabal-install-solver/src/Distribution/Solver/Types/Variable.hs | haskell | | Variables used by the dependency solver. This type is similar to the | module Distribution.Solver.Types.Variable where
import Prelude (Eq, Show)
import Distribution.Solver.Types.OptionalStanza
import Distribution.PackageDescription (FlagName)
internal ' Var ' type .
data Variable qpn =
PackageVar qpn
| FlagVar qpn FlagName
| StanzaVar qpn OptionalStanza
deriving (Eq, Show)
|
cd04adea15ad2258c0beab3d534f161f1a1d907e65d17777ecea24bd20cb6837 | juspay/atlas | FarePolicy.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : App . Routes .
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : App.Routes.FarePolicy
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module App.Routes.FarePolicy where
import Beckn.Types.Id (Id)
import Domain.Types.FarePolicy (FarePolicy)
import Environment
import Product.FarePolicy
import Servant
import Types.API.FarePolicy
import Utils.Auth
-- total
type FarePolicyAPI =
"org"
:> ( "farePolicy"
:> ( AdminTokenAuth :> Get '[JSON] ListFarePolicyRes
:<|> AdminTokenAuth
:> Capture "farePolicyId" (Id FarePolicy)
:> ReqBody '[JSON] UpdateFarePolicyReq
:> Post '[JSON] UpdateFarePolicyRes
)
)
farePolicyFlow :: FlowServer FarePolicyAPI
farePolicyFlow =
listFarePolicies
:<|> updateFarePolicy
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/driver-offer-bpp/src/App/Routes/FarePolicy.hs | haskell | total | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : App . Routes .
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : App.Routes.FarePolicy
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module App.Routes.FarePolicy where
import Beckn.Types.Id (Id)
import Domain.Types.FarePolicy (FarePolicy)
import Environment
import Product.FarePolicy
import Servant
import Types.API.FarePolicy
import Utils.Auth
type FarePolicyAPI =
"org"
:> ( "farePolicy"
:> ( AdminTokenAuth :> Get '[JSON] ListFarePolicyRes
:<|> AdminTokenAuth
:> Capture "farePolicyId" (Id FarePolicy)
:> ReqBody '[JSON] UpdateFarePolicyReq
:> Post '[JSON] UpdateFarePolicyRes
)
)
farePolicyFlow :: FlowServer FarePolicyAPI
farePolicyFlow =
listFarePolicies
:<|> updateFarePolicy
|
5f191bed393f4bf944ee75581a953ddf489435cf0cd2b94db906f3df0e488968 | ekmett/algebra | Class.hs | # LANGUAGE TypeOperators #
module Numeric.Additive.Class
(
-- * Additive Semigroups
Additive(..)
, sum1
* Additive Abelian semigroups
, Abelian
-- * Additive Monoids
, Idempotent
, sinnum1pIdempotent
-- * Partitionable semigroups
, Partitionable(..)
) where
import Data.Int
import Data.Word
import Data.Foldable hiding (concat)
import Data.Semigroup.Foldable
import Numeric.Natural
import Prelude ((-),Bool(..),($),id,(>>=),fromIntegral,(*),otherwise,quot,maybe,error,even,Maybe(..),(==),(.),($!),Integer,(||),pred)
import qualified Prelude
import Data.List.NonEmpty (NonEmpty(..), fromList)
infixl 6 +
-- |
-- > (a + b) + c = a + (b + c)
> sinnum 1 a = a
> sinnum ( 2 * n ) a = sinnum n a + sinnum n a
> sinnum ( 2 * n + 1 ) a = sinnum n a + sinnum n a + a
class Additive r where
(+) :: r -> r -> r
| sinnum1p n r = sinnum ( 1 + n ) r
sinnum1p :: Natural -> r -> r
sinnum1p y0 x0 = f x0 (1 Prelude.+ y0)
where
f x y
| even y = f (x + x) (y `quot` 2)
| y == 1 = x
| otherwise = g (x + x) (pred y `quot` 2) x
g x y z
| even y = g (x + x) (y `quot` 2) z
| y == 1 = x + z
| otherwise = g (x + x) (pred y `quot` 2) (x + z)
sumWith1 :: Foldable1 f => (a -> r) -> f a -> r
sumWith1 f = maybe (error "Numeric.Additive.Semigroup.sumWith1: empty structure") id . foldl' mf Nothing
where mf Nothing y = Just $! f y
mf (Just x) y = Just $! x + f y
sum1 :: (Foldable1 f, Additive r) => f r -> r
sum1 = sumWith1 id
instance Additive r => Additive (b -> r) where
f + g = \e -> f e + g e
sinnum1p n f e = sinnum1p n (f e)
sumWith1 f xs e = sumWith1 (`f` e) xs
instance Additive Bool where
(+) = (||)
sinnum1p _ a = a
instance Additive Natural where
(+) = (Prelude.+)
sinnum1p n r = (1 Prelude.+ fromIntegral n) * r
instance Additive Integer where
(+) = (Prelude.+)
sinnum1p n r = (1 Prelude.+ fromIntegral n) * r
instance Additive Int where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int8 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int16 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int32 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int64 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word8 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word16 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word32 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word64 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive () where
_ + _ = ()
sinnum1p _ _ = ()
sumWith1 _ _ = ()
instance (Additive a, Additive b) => Additive (a,b) where
(a,b) + (i,j) = (a + i, b + j)
sinnum1p n (a,b) = (sinnum1p n a, sinnum1p n b)
instance (Additive a, Additive b, Additive c) => Additive (a,b,c) where
(a,b,c) + (i,j,k) = (a + i, b + j, c + k)
sinnum1p n (a,b,c) = (sinnum1p n a, sinnum1p n b, sinnum1p n c)
instance (Additive a, Additive b, Additive c, Additive d) => Additive (a,b,c,d) where
(a,b,c,d) + (i,j,k,l) = (a + i, b + j, c + k, d + l)
sinnum1p n (a,b,c,d) = (sinnum1p n a, sinnum1p n b, sinnum1p n c, sinnum1p n d)
instance (Additive a, Additive b, Additive c, Additive d, Additive e) => Additive (a,b,c,d,e) where
(a,b,c,d,e) + (i,j,k,l,m) = (a + i, b + j, c + k, d + l, e + m)
sinnum1p n (a,b,c,d,e) = (sinnum1p n a, sinnum1p n b, sinnum1p n c, sinnum1p n d, sinnum1p n e)
concat :: NonEmpty (NonEmpty a) -> NonEmpty a
concat m = m >>= id
class Additive m => Partitionable m where
-- | partitionWith f c returns a list containing f a b for each a b such that a + b = c,
partitionWith :: (m -> m -> r) -> m -> NonEmpty r
instance Partitionable Bool where
partitionWith f False = f False False :| []
partitionWith f True = f False True :| [f True False, f True True]
instance Partitionable Natural where
partitionWith f n = fromList [ f k (n - k) | k <- [0..n] ]
instance Partitionable () where
partitionWith f () = f () () :| []
instance (Partitionable a, Partitionable b) => Partitionable (a,b) where
partitionWith f (a,b) = concat $ partitionWith (\ax ay ->
partitionWith (\bx by -> f (ax,bx) (ay,by)) b) a
instance (Partitionable a, Partitionable b, Partitionable c) => Partitionable (a,b,c) where
partitionWith f (a,b,c) = concat $ partitionWith (\ax ay ->
concat $ partitionWith (\bx by ->
partitionWith (\cx cy -> f (ax,bx,cx) (ay,by,cy)) c) b) a
instance (Partitionable a, Partitionable b, Partitionable c,Partitionable d ) => Partitionable (a,b,c,d) where
partitionWith f (a,b,c,d) = concat $ partitionWith (\ax ay ->
concat $ partitionWith (\bx by ->
concat $ partitionWith (\cx cy ->
partitionWith (\dx dy -> f (ax,bx,cx,dx) (ay,by,cy,dy)) d) c) b) a
instance (Partitionable a, Partitionable b, Partitionable c,Partitionable d, Partitionable e) => Partitionable (a,b,c,d,e) where
partitionWith f (a,b,c,d,e) = concat $ partitionWith (\ax ay ->
concat $ partitionWith (\bx by ->
concat $ partitionWith (\cx cy ->
concat $ partitionWith (\dx dy ->
partitionWith (\ex ey -> f (ax,bx,cx,dx,ex) (ay,by,cy,dy,ey)) e) d) c) b) a
-- | an additive abelian semigroup
--
-- a + b = b + a
class Additive r => Abelian r
instance Abelian r => Abelian (e -> r)
instance Abelian ()
instance Abelian Bool
instance Abelian Integer
instance Abelian Natural
instance Abelian Int
instance Abelian Int8
instance Abelian Int16
instance Abelian Int32
instance Abelian Int64
instance Abelian Word
instance Abelian Word8
instance Abelian Word16
instance Abelian Word32
instance Abelian Word64
instance (Abelian a, Abelian b) => Abelian (a,b)
instance (Abelian a, Abelian b, Abelian c) => Abelian (a,b,c)
instance (Abelian a, Abelian b, Abelian c, Abelian d) => Abelian (a,b,c,d)
instance (Abelian a, Abelian b, Abelian c, Abelian d, Abelian e) => Abelian (a,b,c,d,e)
-- | An additive semigroup with idempotent addition.
--
-- > a + a = a
--
class Additive r => Idempotent r
sinnum1pIdempotent :: Natural -> r -> r
sinnum1pIdempotent _ r = r
instance Idempotent ()
instance Idempotent Bool
instance Idempotent r => Idempotent (e -> r)
instance (Idempotent a, Idempotent b) => Idempotent (a,b)
instance (Idempotent a, Idempotent b, Idempotent c) => Idempotent (a,b,c)
instance (Idempotent a, Idempotent b, Idempotent c, Idempotent d) => Idempotent (a,b,c,d)
instance (Idempotent a, Idempotent b, Idempotent c, Idempotent d, Idempotent e) => Idempotent (a,b,c,d,e)
| null | https://raw.githubusercontent.com/ekmett/algebra/12dd33e848f406dd53d19b69b4f14c93ba6e352b/src/Numeric/Additive/Class.hs | haskell | * Additive Semigroups
* Additive Monoids
* Partitionable semigroups
|
> (a + b) + c = a + (b + c)
| partitionWith f c returns a list containing f a b for each a b such that a + b = c,
| an additive abelian semigroup
a + b = b + a
| An additive semigroup with idempotent addition.
> a + a = a
| # LANGUAGE TypeOperators #
module Numeric.Additive.Class
(
Additive(..)
, sum1
* Additive Abelian semigroups
, Abelian
, Idempotent
, sinnum1pIdempotent
, Partitionable(..)
) where
import Data.Int
import Data.Word
import Data.Foldable hiding (concat)
import Data.Semigroup.Foldable
import Numeric.Natural
import Prelude ((-),Bool(..),($),id,(>>=),fromIntegral,(*),otherwise,quot,maybe,error,even,Maybe(..),(==),(.),($!),Integer,(||),pred)
import qualified Prelude
import Data.List.NonEmpty (NonEmpty(..), fromList)
infixl 6 +
> sinnum 1 a = a
> sinnum ( 2 * n ) a = sinnum n a + sinnum n a
> sinnum ( 2 * n + 1 ) a = sinnum n a + sinnum n a + a
class Additive r where
(+) :: r -> r -> r
| sinnum1p n r = sinnum ( 1 + n ) r
sinnum1p :: Natural -> r -> r
sinnum1p y0 x0 = f x0 (1 Prelude.+ y0)
where
f x y
| even y = f (x + x) (y `quot` 2)
| y == 1 = x
| otherwise = g (x + x) (pred y `quot` 2) x
g x y z
| even y = g (x + x) (y `quot` 2) z
| y == 1 = x + z
| otherwise = g (x + x) (pred y `quot` 2) (x + z)
sumWith1 :: Foldable1 f => (a -> r) -> f a -> r
sumWith1 f = maybe (error "Numeric.Additive.Semigroup.sumWith1: empty structure") id . foldl' mf Nothing
where mf Nothing y = Just $! f y
mf (Just x) y = Just $! x + f y
sum1 :: (Foldable1 f, Additive r) => f r -> r
sum1 = sumWith1 id
instance Additive r => Additive (b -> r) where
f + g = \e -> f e + g e
sinnum1p n f e = sinnum1p n (f e)
sumWith1 f xs e = sumWith1 (`f` e) xs
instance Additive Bool where
(+) = (||)
sinnum1p _ a = a
instance Additive Natural where
(+) = (Prelude.+)
sinnum1p n r = (1 Prelude.+ fromIntegral n) * r
instance Additive Integer where
(+) = (Prelude.+)
sinnum1p n r = (1 Prelude.+ fromIntegral n) * r
instance Additive Int where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int8 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int16 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int32 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Int64 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word8 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word16 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word32 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive Word64 where
(+) = (Prelude.+)
sinnum1p n r = fromIntegral (1 Prelude.+ n) * r
instance Additive () where
_ + _ = ()
sinnum1p _ _ = ()
sumWith1 _ _ = ()
instance (Additive a, Additive b) => Additive (a,b) where
(a,b) + (i,j) = (a + i, b + j)
sinnum1p n (a,b) = (sinnum1p n a, sinnum1p n b)
instance (Additive a, Additive b, Additive c) => Additive (a,b,c) where
(a,b,c) + (i,j,k) = (a + i, b + j, c + k)
sinnum1p n (a,b,c) = (sinnum1p n a, sinnum1p n b, sinnum1p n c)
instance (Additive a, Additive b, Additive c, Additive d) => Additive (a,b,c,d) where
(a,b,c,d) + (i,j,k,l) = (a + i, b + j, c + k, d + l)
sinnum1p n (a,b,c,d) = (sinnum1p n a, sinnum1p n b, sinnum1p n c, sinnum1p n d)
instance (Additive a, Additive b, Additive c, Additive d, Additive e) => Additive (a,b,c,d,e) where
(a,b,c,d,e) + (i,j,k,l,m) = (a + i, b + j, c + k, d + l, e + m)
sinnum1p n (a,b,c,d,e) = (sinnum1p n a, sinnum1p n b, sinnum1p n c, sinnum1p n d, sinnum1p n e)
concat :: NonEmpty (NonEmpty a) -> NonEmpty a
concat m = m >>= id
class Additive m => Partitionable m where
partitionWith :: (m -> m -> r) -> m -> NonEmpty r
instance Partitionable Bool where
partitionWith f False = f False False :| []
partitionWith f True = f False True :| [f True False, f True True]
instance Partitionable Natural where
partitionWith f n = fromList [ f k (n - k) | k <- [0..n] ]
instance Partitionable () where
partitionWith f () = f () () :| []
instance (Partitionable a, Partitionable b) => Partitionable (a,b) where
partitionWith f (a,b) = concat $ partitionWith (\ax ay ->
partitionWith (\bx by -> f (ax,bx) (ay,by)) b) a
instance (Partitionable a, Partitionable b, Partitionable c) => Partitionable (a,b,c) where
partitionWith f (a,b,c) = concat $ partitionWith (\ax ay ->
concat $ partitionWith (\bx by ->
partitionWith (\cx cy -> f (ax,bx,cx) (ay,by,cy)) c) b) a
instance (Partitionable a, Partitionable b, Partitionable c,Partitionable d ) => Partitionable (a,b,c,d) where
partitionWith f (a,b,c,d) = concat $ partitionWith (\ax ay ->
concat $ partitionWith (\bx by ->
concat $ partitionWith (\cx cy ->
partitionWith (\dx dy -> f (ax,bx,cx,dx) (ay,by,cy,dy)) d) c) b) a
instance (Partitionable a, Partitionable b, Partitionable c,Partitionable d, Partitionable e) => Partitionable (a,b,c,d,e) where
partitionWith f (a,b,c,d,e) = concat $ partitionWith (\ax ay ->
concat $ partitionWith (\bx by ->
concat $ partitionWith (\cx cy ->
concat $ partitionWith (\dx dy ->
partitionWith (\ex ey -> f (ax,bx,cx,dx,ex) (ay,by,cy,dy,ey)) e) d) c) b) a
class Additive r => Abelian r
instance Abelian r => Abelian (e -> r)
instance Abelian ()
instance Abelian Bool
instance Abelian Integer
instance Abelian Natural
instance Abelian Int
instance Abelian Int8
instance Abelian Int16
instance Abelian Int32
instance Abelian Int64
instance Abelian Word
instance Abelian Word8
instance Abelian Word16
instance Abelian Word32
instance Abelian Word64
instance (Abelian a, Abelian b) => Abelian (a,b)
instance (Abelian a, Abelian b, Abelian c) => Abelian (a,b,c)
instance (Abelian a, Abelian b, Abelian c, Abelian d) => Abelian (a,b,c,d)
instance (Abelian a, Abelian b, Abelian c, Abelian d, Abelian e) => Abelian (a,b,c,d,e)
class Additive r => Idempotent r
sinnum1pIdempotent :: Natural -> r -> r
sinnum1pIdempotent _ r = r
instance Idempotent ()
instance Idempotent Bool
instance Idempotent r => Idempotent (e -> r)
instance (Idempotent a, Idempotent b) => Idempotent (a,b)
instance (Idempotent a, Idempotent b, Idempotent c) => Idempotent (a,b,c)
instance (Idempotent a, Idempotent b, Idempotent c, Idempotent d) => Idempotent (a,b,c,d)
instance (Idempotent a, Idempotent b, Idempotent c, Idempotent d, Idempotent e) => Idempotent (a,b,c,d,e)
|
253add24d2978b0e9ea39c271615e9074528582bacd11ad838f4a5c135853346 | codecrafters-io/build-your-own-grep | Parser.hs | module Parser (parse, astToMatcher, AST(..)) where
import qualified Text.Megaparsec as M
import Text.Megaparsec.Char (char, digitChar)
import Data.Void (Void)
import Data.Maybe (fromMaybe, isNothing)
import RegEx (M, posLit, negLit, emptyStrM, digitM, digitInverseM, alphaNumM, alphaNumInverseM, anyCharM, orM, andM, concatM, kleeneStarM, kleenePlusM)
type MParser = M.Parsec Void String
data AST a = PosLit a
| NegLit a
| DigitM
| DigitInverseM
| AlphaNumM
| AlphaNumInverseM
| AnyCharM
| OrM [AST a]
| AndM [AST a]
| ConcatM [AST a]
| KleeneStarM (AST a)
| KleenePlusM (AST a)
| EmptyStrM
deriving (Eq, Show)
astToMatcher :: AST Char -> M Char
astToMatcher (PosLit a) = posLit a
astToMatcher (NegLit a) = negLit a
astToMatcher DigitM = digitM
astToMatcher DigitInverseM = digitInverseM
astToMatcher AlphaNumM = alphaNumM
astToMatcher AlphaNumInverseM = alphaNumInverseM
astToMatcher AnyCharM = anyCharM
astToMatcher (OrM ms) = orM $ fmap astToMatcher ms
astToMatcher (AndM ms) = andM $ fmap astToMatcher ms
astToMatcher (ConcatM ms) = concatM $ fmap astToMatcher ms
astToMatcher (KleeneStarM m) = kleeneStarM $ astToMatcher m
astToMatcher (KleenePlusM m) = kleenePlusM $ astToMatcher m
astToMatcher EmptyStrM = emptyStrM
notChar :: Char -> MParser Char
notChar c = M.satisfy (/=c)
anyNotUsed :: String -> MParser Char
anyNotUsed s = M.satisfy $ not . (`elem` s)
-- | Inverts an AST Char
neg :: AST Char -> AST Char
neg DigitM = DigitInverseM
neg AlphaNumM = AlphaNumInverseM
neg (PosLit c) = NegLit c
neg _ = error "Unsupported input string"
-- The regex parser starts here
--
-- I had to adjust a few rules to support better parsing
pRegEx :: MParser (AST Char)
pRegEx = do
expression <- pExpression
return $ ConcatM [KleeneStarM AnyCharM, expression, KleeneStarM AnyCharM]
pExpression :: MParser (AST Char)
pExpression = pSubExpression
pSubExpression :: MParser (AST Char)
pSubExpression = do
subExp <- M.some $ M.try pMatch
return $ ConcatM subExp
pMatch :: MParser (AST Char)
pMatch = pMatchItem
pMatchItem :: MParser (AST Char)
pMatchItem = M.try pMatchCharacterClass M.<|> M.try pMatchCharacter
pMatchCharacterClass :: MParser (AST Char)
pMatchCharacterClass = M.try pCharacterGroup M.<|> M.try pCharacterClass
pMatchCharacter :: MParser (AST Char)
pMatchCharacter = do
c <- anyNotUsed "|()$"
return $ PosLit c
pCharacterGroup :: MParser (AST Char)
pCharacterGroup = M.try pPositiveCharacterGroup M.<|> M.try pNegativeCharacterGroup
pPositiveCharacterGroup :: MParser (AST Char)
pPositiveCharacterGroup = do
_ <- char '['
c <- anyNotUsed "^]"
cs <- M.many pCharacterGroupItem
let cs' = PosLit c : cs
_ <- char ']'
return $ OrM cs'
pNegativeCharacterGroup :: MParser (AST Char)
pNegativeCharacterGroup = do
_ <- char '['
_ <- char '^'
ms <- M.some pCharacterGroupItem
_ <- char ']'
return $ AndM $ fmap neg ms
pCharacterGroupItem :: MParser (AST Char)
pCharacterGroupItem = M.try pCharacterClass M.<|> M.try pChar
pCharacterClass :: MParser (AST Char)
pCharacterClass = M.try pCharacterClassAnyWord M.<|> M.try pCharacterClassAnyDecimal
pCharacterClassAnyWord :: MParser (AST a)
pCharacterClassAnyWord = do
_ <- char '\\'
_ <- char 'w'
return AlphaNumM
pCharacterClassAnyDecimal :: MParser (AST Char)
pCharacterClassAnyDecimal = do
_ <- char '\\'
_ <- char 'd'
return DigitM
pChar :: MParser (AST Char)
pChar = do
c <- notChar ']'
return $ PosLit c
parse :: String -> Maybe (AST Char)
parse = M.parseMaybe pRegEx
| null | https://raw.githubusercontent.com/codecrafters-io/build-your-own-grep/085a70404357c4abf11ff7c039cdf13181349e3c/solutions/haskell/06-combining_character_classes/code/src/Parser.hs | haskell | | Inverts an AST Char
The regex parser starts here
I had to adjust a few rules to support better parsing | module Parser (parse, astToMatcher, AST(..)) where
import qualified Text.Megaparsec as M
import Text.Megaparsec.Char (char, digitChar)
import Data.Void (Void)
import Data.Maybe (fromMaybe, isNothing)
import RegEx (M, posLit, negLit, emptyStrM, digitM, digitInverseM, alphaNumM, alphaNumInverseM, anyCharM, orM, andM, concatM, kleeneStarM, kleenePlusM)
type MParser = M.Parsec Void String
data AST a = PosLit a
| NegLit a
| DigitM
| DigitInverseM
| AlphaNumM
| AlphaNumInverseM
| AnyCharM
| OrM [AST a]
| AndM [AST a]
| ConcatM [AST a]
| KleeneStarM (AST a)
| KleenePlusM (AST a)
| EmptyStrM
deriving (Eq, Show)
astToMatcher :: AST Char -> M Char
astToMatcher (PosLit a) = posLit a
astToMatcher (NegLit a) = negLit a
astToMatcher DigitM = digitM
astToMatcher DigitInverseM = digitInverseM
astToMatcher AlphaNumM = alphaNumM
astToMatcher AlphaNumInverseM = alphaNumInverseM
astToMatcher AnyCharM = anyCharM
astToMatcher (OrM ms) = orM $ fmap astToMatcher ms
astToMatcher (AndM ms) = andM $ fmap astToMatcher ms
astToMatcher (ConcatM ms) = concatM $ fmap astToMatcher ms
astToMatcher (KleeneStarM m) = kleeneStarM $ astToMatcher m
astToMatcher (KleenePlusM m) = kleenePlusM $ astToMatcher m
astToMatcher EmptyStrM = emptyStrM
notChar :: Char -> MParser Char
notChar c = M.satisfy (/=c)
anyNotUsed :: String -> MParser Char
anyNotUsed s = M.satisfy $ not . (`elem` s)
neg :: AST Char -> AST Char
neg DigitM = DigitInverseM
neg AlphaNumM = AlphaNumInverseM
neg (PosLit c) = NegLit c
neg _ = error "Unsupported input string"
pRegEx :: MParser (AST Char)
pRegEx = do
expression <- pExpression
return $ ConcatM [KleeneStarM AnyCharM, expression, KleeneStarM AnyCharM]
pExpression :: MParser (AST Char)
pExpression = pSubExpression
pSubExpression :: MParser (AST Char)
pSubExpression = do
subExp <- M.some $ M.try pMatch
return $ ConcatM subExp
pMatch :: MParser (AST Char)
pMatch = pMatchItem
pMatchItem :: MParser (AST Char)
pMatchItem = M.try pMatchCharacterClass M.<|> M.try pMatchCharacter
pMatchCharacterClass :: MParser (AST Char)
pMatchCharacterClass = M.try pCharacterGroup M.<|> M.try pCharacterClass
pMatchCharacter :: MParser (AST Char)
pMatchCharacter = do
c <- anyNotUsed "|()$"
return $ PosLit c
pCharacterGroup :: MParser (AST Char)
pCharacterGroup = M.try pPositiveCharacterGroup M.<|> M.try pNegativeCharacterGroup
pPositiveCharacterGroup :: MParser (AST Char)
pPositiveCharacterGroup = do
_ <- char '['
c <- anyNotUsed "^]"
cs <- M.many pCharacterGroupItem
let cs' = PosLit c : cs
_ <- char ']'
return $ OrM cs'
pNegativeCharacterGroup :: MParser (AST Char)
pNegativeCharacterGroup = do
_ <- char '['
_ <- char '^'
ms <- M.some pCharacterGroupItem
_ <- char ']'
return $ AndM $ fmap neg ms
pCharacterGroupItem :: MParser (AST Char)
pCharacterGroupItem = M.try pCharacterClass M.<|> M.try pChar
pCharacterClass :: MParser (AST Char)
pCharacterClass = M.try pCharacterClassAnyWord M.<|> M.try pCharacterClassAnyDecimal
pCharacterClassAnyWord :: MParser (AST a)
pCharacterClassAnyWord = do
_ <- char '\\'
_ <- char 'w'
return AlphaNumM
pCharacterClassAnyDecimal :: MParser (AST Char)
pCharacterClassAnyDecimal = do
_ <- char '\\'
_ <- char 'd'
return DigitM
pChar :: MParser (AST Char)
pChar = do
c <- notChar ']'
return $ PosLit c
parse :: String -> Maybe (AST Char)
parse = M.parseMaybe pRegEx
|
870d15c1a7f84f60b7c7360caa2acc2aaa05d0b9a39fab4e23527ed65d6bcf08 | ivankelly/gambit | _num#.scm | ;;;============================================================================
File : " _ num#.scm " , Time - stamp : < 2008 - 10 - 30 16:53:55 feeley >
Copyright ( c ) 1994 - 2008 by , All Rights Reserved .
;;;============================================================================
;;; Representation of exceptions.
(define-library-type-of-exception range-exception
id: 10aa6857-6f27-45ab-ac38-2318ef2f277c
constructor: #f
opaque:
(procedure unprintable: read-only:)
(arguments unprintable: read-only:)
(arg-num unprintable: read-only:)
)
(define-library-type-of-exception divide-by-zero-exception
id: c4319ec5-29d5-43f3-bd16-fad15b238e82
constructor: #f
opaque:
(procedure unprintable: read-only:)
(arguments unprintable: read-only:)
)
(define-library-type-of-exception fixnum-overflow-exception
id: dd080472-485f-4f09-8e9e-924194042ff3
constructor: #f
opaque:
(procedure unprintable: read-only:)
(arguments unprintable: read-only:)
)
;;;----------------------------------------------------------------------------
;;; Define type checking macros.
(##define-macro (macro-index? var)
`(##not (##fixnum.negative? ,var)))
(##define-macro (macro-index-range? var lo hi)
`(macro-fixnum-range? ,var ,lo ,hi))
(##define-macro (macro-index-range-incl? var lo hi)
`(macro-fixnum-range-incl? ,var ,lo ,hi))
(##define-macro (macro-fixnum-range? var lo hi)
`(and (##not (##fixnum.< ,var ,lo))
(##fixnum.< ,var ,hi)))
(##define-macro (macro-fixnum-range-incl? var lo hi)
`(and (##not (##fixnum.< ,var ,lo))
(##not (##fixnum.< ,hi ,var))))
(##define-macro (macro-fixnum-and-fixnum-range-incl? var lo hi)
`(and (##fixnum? ,var)
(macro-fixnum-range-incl? ,var ,lo ,hi)))
(##define-macro (macro-range-incl? var lo hi)
`(and (macro-exact-int? ,var)
(##not (##< ,var ,lo))
(##not (##< ,hi ,var))))
(define-check-index-range-macro
index
macro-index?)
(define-check-index-range-macro
index-range
macro-index-range?
lo
hi)
(define-check-index-range-macro
index-range-incl
macro-index-range-incl?
lo
hi)
(define-check-index-range-macro
fixnum-range
macro-fixnum-range?
lo
hi)
(define-check-index-range-macro
fixnum-range-incl
macro-fixnum-range-incl?
lo
hi)
(define-check-type exact-signed-int8 'exact-signed-int8
macro-fixnum-and-fixnum-range-incl?
-128
127)
(define-check-type exact-signed-int8-list 'exact-signed-int8-list
macro-fixnum-and-fixnum-range-incl?
-128
127)
(define-check-type exact-unsigned-int8 'exact-unsigned-int8
macro-fixnum-and-fixnum-range-incl?
0
255)
(define-check-type exact-unsigned-int8-list 'exact-unsigned-int8-list
macro-fixnum-and-fixnum-range-incl?
0
255)
(define-check-type exact-signed-int16 'exact-signed-int16
macro-fixnum-and-fixnum-range-incl?
-32768
32767)
(define-check-type exact-signed-int16-list 'exact-signed-int16-list
macro-fixnum-and-fixnum-range-incl?
-32768
32767)
(define-check-type exact-unsigned-int16 'exact-unsigned-int16
macro-fixnum-and-fixnum-range-incl?
0
65535)
(define-check-type exact-unsigned-int16-list 'exact-unsigned-int16-list
macro-fixnum-and-fixnum-range-incl?
0
65535)
(define-check-type exact-signed-int32 'exact-signed-int32
macro-range-incl?
-2147483648
2147483647)
(define-check-type exact-signed-int32-list 'exact-signed-int32-list
macro-range-incl?
-2147483648
2147483647)
(define-check-type exact-unsigned-int32 'exact-unsigned-int32
macro-range-incl?
0
4294967295)
(define-check-type exact-unsigned-int32-list 'exact-unsigned-int32-list
macro-range-incl?
0
4294967295)
(define-check-type exact-signed-int64 'exact-signed-int64
macro-range-incl?
-9223372036854775808
9223372036854775807)
(define-check-type exact-signed-int64-list 'exact-signed-int64-list
macro-range-incl?
-9223372036854775808
9223372036854775807)
(define-check-type exact-unsigned-int64 'exact-unsigned-int64
macro-range-incl?
0
18446744073709551615)
(define-check-type exact-unsigned-int64-list 'exact-unsigned-int64-list
macro-range-incl?
0
18446744073709551615)
(define-check-type inexact-real 'inexact-real
##flonum?)
(define-check-type inexact-real-list 'inexact-real-list
##flonum?)
(define-check-type real 'real
##real?)
(define-check-type fixnum 'fixnum
##fixnum?)
(define-check-type flonum 'flonum
##flonum?)
;;;============================================================================
;;; Number representation.
There are 5 internal representations for numbers :
;;
fixnum , bignum , , flonum ,
;;
;; Fixnums and bignums form the class of exact-int.
;; Fixnums, bignums and ratnums form the class of exact-real.
;; Fixnums, bignums, ratnums and flonums form the class of noncpxnum.
;; The representation has some invariants:
;;
The numerator of a ratnum is a non - zero exact - int .
The denominator of a ratnum is an exact - int greater than 1 .
;; The numerator and denominator have no common divisors greater than 1.
;;
The real part of a cpxnum is a noncpxnum .
The imaginary part of a cpxnum is a noncpxnum ! = fixnum 0
;; The following table gives the mapping of the Scheme exact numbers to their
;; internal representation:
;;
;; type representation
;; exact integer = exact-int (fixnum, bignum)
exact rational = exact - real ( fixnum , bignum , )
exact real = exact - real ( fixnum , bignum , )
;; exact complex = exact-real or cpxnum with exact-real real and imag parts
;; For inexact numbers, the representation is not quite as straightforward.
;;
There are 3 special classes of inexact representation :
;; flonum-int : flonum with integer value
cpxnum - real : with imag part = flonum 0.0 or -0.0
;; cpxnum-int : cpxnum-real with exact-int or flonum-int real part
;;
;; Note: cpxnum-real and cpxnum-int only exist if
( macro - cpxnum - are - possibly - real ? ) returns # t.
;;
;; This gives the following table for Scheme's inexact numbers:
;;
;; type representation
;; inexact integer = flonum-int or cpxnum-int if it exists
;; inexact rational = flonum or cpxnum-real if it exists
;; inexact real = flonum or cpxnum-real if it exists
inexact complex = flonum or cpxnum with flonum real or imag part
( + -0 . 0)=-0 . ( * 4 .
(##define-macro (macro-cpxnum-are-possibly-real?) #f)
(##define-macro (macro-exact-int? obj) ;; obj can be any object
`(or (##fixnum? ,obj)
(##bignum? ,obj)))
(##define-macro (macro-exact-real? obj) ;; obj can be any object
`(or (macro-exact-int? ,obj)
(##ratnum? ,obj)))
(##define-macro (macro-flonum-int? obj) ;; obj must be a flonum
`(##flonum.integer? ,obj))
(##define-macro (macro-flonum-rational? obj) ;; obj must be a flonum
`(##flonum.finite? ,obj))
(##define-macro (macro-noncpxnum-int? obj) ;; obj must be in fixnum/bignum/ratnum/flonum
`(if (##flonum? ,obj)
(macro-flonum-int? ,obj)
(##not (##ratnum? ,obj))))
(##define-macro (macro-noncpxnum-rational? obj) ;; obj must be in fixnum/bignum/ratnum/flonum
`(or (##not (##flonum? ,obj))
(macro-flonum-rational? ,obj)))
(##define-macro (macro-cpxnum-int? obj) ;; obj must be a cpxnum
`(and (macro-cpxnum-are-possibly-real?)
(macro-cpxnum-real? ,obj)
(let ((real (macro-cpxnum-real ,obj)))
(macro-noncpxnum-int? real))))
(##define-macro (macro-cpxnum-rational? obj) ;; obj must be a cpxnum
`(and (macro-cpxnum-are-possibly-real?)
(let ((imag (macro-cpxnum-imag ,obj)))
(and (##flonum? imag)
(##flonum.zero? imag)
(let ((real (macro-cpxnum-real ,obj)))
(macro-noncpxnum-rational? real))))))
(##define-macro (macro-cpxnum-real? obj) ;; obj must be a cpxnum
`(and (macro-cpxnum-are-possibly-real?)
(let ((imag (macro-cpxnum-imag ,obj)))
(and (##flonum? imag)
(##flonum.zero? imag)))))
Dispatch for number representation
(##define-macro (macro-number-dispatch num err fix big rat flo cpx)
`(cond ((##fixnum? ,num) ,fix)
((##flonum? ,num) ,flo)
((##subtyped? ,num)
(let ((##s (##subtype ,num)))
(cond ((##fixnum.= ##s (macro-subtype-bignum)) ,big)
((##fixnum.= ##s (macro-subtype-ratnum)) ,rat)
((##fixnum.= ##s (macro-subtype-cpxnum)) ,cpx)
(else ,err))))
(else ,err)))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;; Miscellaneous constants.
(##define-macro (macro-inexact-+2) 2.0)
(##define-macro (macro-inexact--2) -2.0)
(##define-macro (macro-inexact-+1) 1.0)
(##define-macro (macro-inexact--1) -1.0)
(##define-macro (macro-inexact-+1/2) 0.5)
(##define-macro (macro-inexact-+0) 0.0)
(##define-macro (macro-inexact--0) -0.0)
(##define-macro (macro-inexact-+pi) 3.141592653589793)
(##define-macro (macro-inexact--pi) -3.141592653589793)
(##define-macro (macro-inexact-+pi/2) 1.5707963267948966)
(##define-macro (macro-inexact--pi/2) -1.5707963267948966)
(##define-macro (macro-inexact-+inf) (/ +1. 0.))
(##define-macro (macro-inexact--inf) (/ -1. 0.))
(##define-macro (macro-inexact-+nan) (/ 0. 0.))
(##define-macro (macro-cpxnum-+2i) +2i)
(##define-macro (macro-cpxnum--i) -i)
(##define-macro (macro-cpxnum-+i) +i)
(##define-macro (macro-cpxnum-+1/2+sqrt3/2i)
(make-rectangular 1/2 (/ (sqrt 3) 2)))
(##define-macro (macro-cpxnum-+1/2-sqrt3/2i)
(make-rectangular 1/2 (- (/ (sqrt 3) 2))))
(##define-macro (macro-cpxnum--1/2+sqrt3/2i)
(make-rectangular -1/2 (/ (sqrt 3) 2)))
(##define-macro (macro-cpxnum--1/2-sqrt3/2i)
(make-rectangular -1/2 (- (/ (sqrt 3) 2))))
(##define-macro (macro-cpxnum-+sqrt3/2+1/2i)
(make-rectangular (/ (sqrt 3) 2) 1/2))
(##define-macro (macro-cpxnum-+sqrt3/2-1/2i)
(make-rectangular (/ (sqrt 3) 2) -1/2))
(##define-macro (macro-cpxnum--sqrt3/2+1/2i)
(make-rectangular (- (/ (sqrt 3) 2)) 1/2))
(##define-macro (macro-cpxnum--sqrt3/2-1/2i)
(make-rectangular (- (/ (sqrt 3) 2)) -1/2))
(##define-macro (macro-inexact-exp-+1/2) (exp +1/2))
(##define-macro (macro-inexact-exp--1/2) (exp -1/2))
(##define-macro (macro-inexact-log-2) (log 2))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bignum related constants .
(##define-macro (macro-max-lines) 65536)
(##define-macro (macro-max-fixnum32-div-max-lines) 8191)
(##define-macro (macro-max-fixnum32) 536870911)
(##define-macro (macro-max-fixnum32-div-10) 53687091)
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
related constants .
(##define-macro (macro-flonum-m-bits)
52)
(##define-macro (macro-flonum-m-bits-plus-1)
53)
(##define-macro (macro-flonum-m-bits-plus-1*2)
106)
(##define-macro (macro-flonum-e-bits)
11)
( expt 2 ( + ( macro - flonum - e - bits ) ( macro - flonum - m - bits ) ) )
#x8000000000000000)
(##define-macro (macro-flonum-m-min) ;; (expt 2.0 (macro-flonum-m-bits))
4503599627370496.0)
( expt 2 ( macro - flonum - m - bits ) )
4503599627370496)
( expt 2 ( macro - flonum - m - bits - plus-1 ) )
9007199254740992)
( - ( macro - flonum-+m - max - plus-1 ) 1 )
9007199254740991)
(##define-macro (macro-flonum-+m-max-plus-1-inexact);; (exact->inexact (macro-flonum-+m-max-plus-1))
9007199254740992.0)
(##define-macro (macro-flonum-inverse-+m-max-plus-1-inexact);; (/ (macro-flonum-+m-max-plus-1-inexact))
(/ 9007199254740992.0))
(##define-macro (macro-flonum--m-min) ;; (- (macro-flonum-+m-min))
-4503599627370496)
(##define-macro (macro-flonum--m-max) ;; (- (macro-flonum-+m-max))
-9007199254740991)
( - ( expt 2 ( - ( macro - flonum - e - bits ) 1 ) ) 1 )
1023)
( + ( macro - flonum - e - bias ) 1 )
1024)
( - ( macro - flonum - e - bias ) 1 )
1022)
(##define-macro (macro-flonum-e-min) ;; (- (+ (macro-flonum-e-bias) (macro-flonum-m-bits) -1))
-1074)
(##define-macro (macro-flonum-min-normal) ;; (expt 2.0 (+ (macro-flonum-m-bits) (macro-flonum-e-min)))
(expt 2.0 (+ 52 -1074)))
( expt 2 ( - ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) 1 ) ) )
(expt 2 -513))
( expt 2.0 ( - ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) 1 ) ) )
(expt 2.0 -513))
( expt 2 ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) ( macro - flonum - m - bits - plus-1 ) ) )
(expt 2 565))
( expt 2.0 ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) ( macro - flonum - m - bits - plus-1 ) ) )
(expt 2.0 565))
(##define-macro (macro-inexact-radix) ;; (exact->inexact (macro-radix))
16384.0)
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
objects .
A ratnum is represented by an object vector of length 2
;; slot 0 = numerator
slot 1 = denominator
(##define-macro (macro-ratnum-make num den)
`(##subtype-set!
(##vector ,num ,den)
(macro-subtype-ratnum)))
(##define-macro (macro-ratnum-numerator r) `(macro-slot 0 ,r))
(##define-macro (macro-ratnum-numerator-set! r x) `(macro-slot 0 ,r ,x))
(##define-macro (macro-ratnum-denominator r) `(macro-slot 1 ,r))
(##define-macro (macro-ratnum-denominator-set! r x) `(macro-slot 1 ,r ,x))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
objects .
A is represented by an object vector of length 2
;; slot 0 = real
slot 1 = imag
(##define-macro (macro-cpxnum-make r i)
`(##subtype-set!
(##vector ,r ,i)
(macro-subtype-cpxnum)))
(##define-macro (macro-cpxnum-real c) `(macro-slot 0 ,c))
(##define-macro (macro-cpxnum-real-set! c x) `(macro-slot 0 ,c ,x))
(##define-macro (macro-cpxnum-imag c) `(macro-slot 1 ,c))
(##define-macro (macro-cpxnum-imag-set! c x) `(macro-slot 1 ,c ,x))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(##define-macro (macro-bignum-odd? x);;;;;;;;;;;;;;;;;;;;
`(##fixnum.odd? (##bignum.mdigit-ref ,x 0)))
(##define-macro (macro-real->inexact x)
`(let ((x ,x))
(if (##flonum? x)
x
(##exact->inexact
(if (macro-cpxnum-are-possibly-real?)
(##real-part x)
x)))))
;;;============================================================================
| null | https://raw.githubusercontent.com/ivankelly/gambit/7377246988d0982ceeb10f4249e96badf3ff9a8f/lib/_num%23.scm | scheme | ============================================================================
============================================================================
Representation of exceptions.
----------------------------------------------------------------------------
Define type checking macros.
============================================================================
Number representation.
Fixnums and bignums form the class of exact-int.
Fixnums, bignums and ratnums form the class of exact-real.
Fixnums, bignums, ratnums and flonums form the class of noncpxnum.
The representation has some invariants:
The numerator and denominator have no common divisors greater than 1.
The following table gives the mapping of the Scheme exact numbers to their
internal representation:
type representation
exact integer = exact-int (fixnum, bignum)
exact complex = exact-real or cpxnum with exact-real real and imag parts
For inexact numbers, the representation is not quite as straightforward.
flonum-int : flonum with integer value
cpxnum-int : cpxnum-real with exact-int or flonum-int real part
Note: cpxnum-real and cpxnum-int only exist if
This gives the following table for Scheme's inexact numbers:
type representation
inexact integer = flonum-int or cpxnum-int if it exists
inexact rational = flonum or cpxnum-real if it exists
inexact real = flonum or cpxnum-real if it exists
obj can be any object
obj can be any object
obj must be a flonum
obj must be a flonum
obj must be in fixnum/bignum/ratnum/flonum
obj must be in fixnum/bignum/ratnum/flonum
obj must be a cpxnum
obj must be a cpxnum
obj must be a cpxnum
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Miscellaneous constants.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(expt 2.0 (macro-flonum-m-bits))
(exact->inexact (macro-flonum-+m-max-plus-1))
(/ (macro-flonum-+m-max-plus-1-inexact))
(- (macro-flonum-+m-min))
(- (macro-flonum-+m-max))
(- (+ (macro-flonum-e-bias) (macro-flonum-m-bits) -1))
(expt 2.0 (+ (macro-flonum-m-bits) (macro-flonum-e-min)))
(exact->inexact (macro-radix))
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
slot 0 = numerator
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
slot 0 = real
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
============================================================================ |
File : " _ num#.scm " , Time - stamp : < 2008 - 10 - 30 16:53:55 feeley >
Copyright ( c ) 1994 - 2008 by , All Rights Reserved .
(define-library-type-of-exception range-exception
id: 10aa6857-6f27-45ab-ac38-2318ef2f277c
constructor: #f
opaque:
(procedure unprintable: read-only:)
(arguments unprintable: read-only:)
(arg-num unprintable: read-only:)
)
(define-library-type-of-exception divide-by-zero-exception
id: c4319ec5-29d5-43f3-bd16-fad15b238e82
constructor: #f
opaque:
(procedure unprintable: read-only:)
(arguments unprintable: read-only:)
)
(define-library-type-of-exception fixnum-overflow-exception
id: dd080472-485f-4f09-8e9e-924194042ff3
constructor: #f
opaque:
(procedure unprintable: read-only:)
(arguments unprintable: read-only:)
)
(##define-macro (macro-index? var)
`(##not (##fixnum.negative? ,var)))
(##define-macro (macro-index-range? var lo hi)
`(macro-fixnum-range? ,var ,lo ,hi))
(##define-macro (macro-index-range-incl? var lo hi)
`(macro-fixnum-range-incl? ,var ,lo ,hi))
(##define-macro (macro-fixnum-range? var lo hi)
`(and (##not (##fixnum.< ,var ,lo))
(##fixnum.< ,var ,hi)))
(##define-macro (macro-fixnum-range-incl? var lo hi)
`(and (##not (##fixnum.< ,var ,lo))
(##not (##fixnum.< ,hi ,var))))
(##define-macro (macro-fixnum-and-fixnum-range-incl? var lo hi)
`(and (##fixnum? ,var)
(macro-fixnum-range-incl? ,var ,lo ,hi)))
(##define-macro (macro-range-incl? var lo hi)
`(and (macro-exact-int? ,var)
(##not (##< ,var ,lo))
(##not (##< ,hi ,var))))
(define-check-index-range-macro
index
macro-index?)
(define-check-index-range-macro
index-range
macro-index-range?
lo
hi)
(define-check-index-range-macro
index-range-incl
macro-index-range-incl?
lo
hi)
(define-check-index-range-macro
fixnum-range
macro-fixnum-range?
lo
hi)
(define-check-index-range-macro
fixnum-range-incl
macro-fixnum-range-incl?
lo
hi)
(define-check-type exact-signed-int8 'exact-signed-int8
macro-fixnum-and-fixnum-range-incl?
-128
127)
(define-check-type exact-signed-int8-list 'exact-signed-int8-list
macro-fixnum-and-fixnum-range-incl?
-128
127)
(define-check-type exact-unsigned-int8 'exact-unsigned-int8
macro-fixnum-and-fixnum-range-incl?
0
255)
(define-check-type exact-unsigned-int8-list 'exact-unsigned-int8-list
macro-fixnum-and-fixnum-range-incl?
0
255)
(define-check-type exact-signed-int16 'exact-signed-int16
macro-fixnum-and-fixnum-range-incl?
-32768
32767)
(define-check-type exact-signed-int16-list 'exact-signed-int16-list
macro-fixnum-and-fixnum-range-incl?
-32768
32767)
(define-check-type exact-unsigned-int16 'exact-unsigned-int16
macro-fixnum-and-fixnum-range-incl?
0
65535)
(define-check-type exact-unsigned-int16-list 'exact-unsigned-int16-list
macro-fixnum-and-fixnum-range-incl?
0
65535)
(define-check-type exact-signed-int32 'exact-signed-int32
macro-range-incl?
-2147483648
2147483647)
(define-check-type exact-signed-int32-list 'exact-signed-int32-list
macro-range-incl?
-2147483648
2147483647)
(define-check-type exact-unsigned-int32 'exact-unsigned-int32
macro-range-incl?
0
4294967295)
(define-check-type exact-unsigned-int32-list 'exact-unsigned-int32-list
macro-range-incl?
0
4294967295)
(define-check-type exact-signed-int64 'exact-signed-int64
macro-range-incl?
-9223372036854775808
9223372036854775807)
(define-check-type exact-signed-int64-list 'exact-signed-int64-list
macro-range-incl?
-9223372036854775808
9223372036854775807)
(define-check-type exact-unsigned-int64 'exact-unsigned-int64
macro-range-incl?
0
18446744073709551615)
(define-check-type exact-unsigned-int64-list 'exact-unsigned-int64-list
macro-range-incl?
0
18446744073709551615)
(define-check-type inexact-real 'inexact-real
##flonum?)
(define-check-type inexact-real-list 'inexact-real-list
##flonum?)
(define-check-type real 'real
##real?)
(define-check-type fixnum 'fixnum
##fixnum?)
(define-check-type flonum 'flonum
##flonum?)
There are 5 internal representations for numbers :
fixnum , bignum , , flonum ,
The numerator of a ratnum is a non - zero exact - int .
The denominator of a ratnum is an exact - int greater than 1 .
The real part of a cpxnum is a noncpxnum .
The imaginary part of a cpxnum is a noncpxnum ! = fixnum 0
exact rational = exact - real ( fixnum , bignum , )
exact real = exact - real ( fixnum , bignum , )
There are 3 special classes of inexact representation :
cpxnum - real : with imag part = flonum 0.0 or -0.0
( macro - cpxnum - are - possibly - real ? ) returns # t.
inexact complex = flonum or cpxnum with flonum real or imag part
( + -0 . 0)=-0 . ( * 4 .
(##define-macro (macro-cpxnum-are-possibly-real?) #f)
`(or (##fixnum? ,obj)
(##bignum? ,obj)))
`(or (macro-exact-int? ,obj)
(##ratnum? ,obj)))
`(##flonum.integer? ,obj))
`(##flonum.finite? ,obj))
`(if (##flonum? ,obj)
(macro-flonum-int? ,obj)
(##not (##ratnum? ,obj))))
`(or (##not (##flonum? ,obj))
(macro-flonum-rational? ,obj)))
`(and (macro-cpxnum-are-possibly-real?)
(macro-cpxnum-real? ,obj)
(let ((real (macro-cpxnum-real ,obj)))
(macro-noncpxnum-int? real))))
`(and (macro-cpxnum-are-possibly-real?)
(let ((imag (macro-cpxnum-imag ,obj)))
(and (##flonum? imag)
(##flonum.zero? imag)
(let ((real (macro-cpxnum-real ,obj)))
(macro-noncpxnum-rational? real))))))
`(and (macro-cpxnum-are-possibly-real?)
(let ((imag (macro-cpxnum-imag ,obj)))
(and (##flonum? imag)
(##flonum.zero? imag)))))
Dispatch for number representation
(##define-macro (macro-number-dispatch num err fix big rat flo cpx)
`(cond ((##fixnum? ,num) ,fix)
((##flonum? ,num) ,flo)
((##subtyped? ,num)
(let ((##s (##subtype ,num)))
(cond ((##fixnum.= ##s (macro-subtype-bignum)) ,big)
((##fixnum.= ##s (macro-subtype-ratnum)) ,rat)
((##fixnum.= ##s (macro-subtype-cpxnum)) ,cpx)
(else ,err))))
(else ,err)))
(##define-macro (macro-inexact-+2) 2.0)
(##define-macro (macro-inexact--2) -2.0)
(##define-macro (macro-inexact-+1) 1.0)
(##define-macro (macro-inexact--1) -1.0)
(##define-macro (macro-inexact-+1/2) 0.5)
(##define-macro (macro-inexact-+0) 0.0)
(##define-macro (macro-inexact--0) -0.0)
(##define-macro (macro-inexact-+pi) 3.141592653589793)
(##define-macro (macro-inexact--pi) -3.141592653589793)
(##define-macro (macro-inexact-+pi/2) 1.5707963267948966)
(##define-macro (macro-inexact--pi/2) -1.5707963267948966)
(##define-macro (macro-inexact-+inf) (/ +1. 0.))
(##define-macro (macro-inexact--inf) (/ -1. 0.))
(##define-macro (macro-inexact-+nan) (/ 0. 0.))
(##define-macro (macro-cpxnum-+2i) +2i)
(##define-macro (macro-cpxnum--i) -i)
(##define-macro (macro-cpxnum-+i) +i)
(##define-macro (macro-cpxnum-+1/2+sqrt3/2i)
(make-rectangular 1/2 (/ (sqrt 3) 2)))
(##define-macro (macro-cpxnum-+1/2-sqrt3/2i)
(make-rectangular 1/2 (- (/ (sqrt 3) 2))))
(##define-macro (macro-cpxnum--1/2+sqrt3/2i)
(make-rectangular -1/2 (/ (sqrt 3) 2)))
(##define-macro (macro-cpxnum--1/2-sqrt3/2i)
(make-rectangular -1/2 (- (/ (sqrt 3) 2))))
(##define-macro (macro-cpxnum-+sqrt3/2+1/2i)
(make-rectangular (/ (sqrt 3) 2) 1/2))
(##define-macro (macro-cpxnum-+sqrt3/2-1/2i)
(make-rectangular (/ (sqrt 3) 2) -1/2))
(##define-macro (macro-cpxnum--sqrt3/2+1/2i)
(make-rectangular (- (/ (sqrt 3) 2)) 1/2))
(##define-macro (macro-cpxnum--sqrt3/2-1/2i)
(make-rectangular (- (/ (sqrt 3) 2)) -1/2))
(##define-macro (macro-inexact-exp-+1/2) (exp +1/2))
(##define-macro (macro-inexact-exp--1/2) (exp -1/2))
(##define-macro (macro-inexact-log-2) (log 2))
Bignum related constants .
(##define-macro (macro-max-lines) 65536)
(##define-macro (macro-max-fixnum32-div-max-lines) 8191)
(##define-macro (macro-max-fixnum32) 536870911)
(##define-macro (macro-max-fixnum32-div-10) 53687091)
related constants .
(##define-macro (macro-flonum-m-bits)
52)
(##define-macro (macro-flonum-m-bits-plus-1)
53)
(##define-macro (macro-flonum-m-bits-plus-1*2)
106)
(##define-macro (macro-flonum-e-bits)
11)
( expt 2 ( + ( macro - flonum - e - bits ) ( macro - flonum - m - bits ) ) )
#x8000000000000000)
4503599627370496.0)
( expt 2 ( macro - flonum - m - bits ) )
4503599627370496)
( expt 2 ( macro - flonum - m - bits - plus-1 ) )
9007199254740992)
( - ( macro - flonum-+m - max - plus-1 ) 1 )
9007199254740991)
9007199254740992.0)
(/ 9007199254740992.0))
-4503599627370496)
-9007199254740991)
( - ( expt 2 ( - ( macro - flonum - e - bits ) 1 ) ) 1 )
1023)
( + ( macro - flonum - e - bias ) 1 )
1024)
( - ( macro - flonum - e - bias ) 1 )
1022)
-1074)
(expt 2.0 (+ 52 -1074)))
( expt 2 ( - ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) 1 ) ) )
(expt 2 -513))
( expt 2.0 ( - ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) 1 ) ) )
(expt 2.0 -513))
( expt 2 ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) ( macro - flonum - m - bits - plus-1 ) ) )
(expt 2 565))
( expt 2.0 ( + ( quotient ( macro - flonum - e - bias - plus-1 ) 2 ) ( macro - flonum - m - bits - plus-1 ) ) )
(expt 2.0 565))
16384.0)
objects .
A ratnum is represented by an object vector of length 2
slot 1 = denominator
(##define-macro (macro-ratnum-make num den)
`(##subtype-set!
(##vector ,num ,den)
(macro-subtype-ratnum)))
(##define-macro (macro-ratnum-numerator r) `(macro-slot 0 ,r))
(##define-macro (macro-ratnum-numerator-set! r x) `(macro-slot 0 ,r ,x))
(##define-macro (macro-ratnum-denominator r) `(macro-slot 1 ,r))
(##define-macro (macro-ratnum-denominator-set! r x) `(macro-slot 1 ,r ,x))
objects .
A is represented by an object vector of length 2
slot 1 = imag
(##define-macro (macro-cpxnum-make r i)
`(##subtype-set!
(##vector ,r ,i)
(macro-subtype-cpxnum)))
(##define-macro (macro-cpxnum-real c) `(macro-slot 0 ,c))
(##define-macro (macro-cpxnum-real-set! c x) `(macro-slot 0 ,c ,x))
(##define-macro (macro-cpxnum-imag c) `(macro-slot 1 ,c))
(##define-macro (macro-cpxnum-imag-set! c x) `(macro-slot 1 ,c ,x))
`(##fixnum.odd? (##bignum.mdigit-ref ,x 0)))
(##define-macro (macro-real->inexact x)
`(let ((x ,x))
(if (##flonum? x)
x
(##exact->inexact
(if (macro-cpxnum-are-possibly-real?)
(##real-part x)
x)))))
|
358353bc7d6be8859c25f253df5931c793e3e498ebfc32318100888b3f3d0a10 | metabase/metabase | annotate_test.clj | (ns metabase.query-processor.middleware.annotate-test
(:require
[clojure.test :refer :all]
[medley.core :as m]
[metabase.driver :as driver]
[metabase.models :refer [Card Field]]
[metabase.query-processor :as qp]
[metabase.query-processor.middleware.annotate :as annotate]
[metabase.query-processor.store :as qp.store]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(set! *warn-on-reflection* true)
(defn- add-column-info [query metadata]
(mt/with-everything-store
(driver/with-driver :h2
((annotate/add-column-info query identity) metadata))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | column-info (:native) |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest native-column-info-test
(testing "native column info"
(testing "should still infer types even if the initial value(s) are `nil` (#4256, #6924)"
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
(concat (repeat 1000 [nil]) [[1] [2]])))))
(testing "should use default `base_type` of `type/*` if there are no non-nil values in the sample"
(is (= [:type/*]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
[[nil]]))))
(testing "should attempt to infer better base type if driver returns :type/* (#12150)"
;; `merged-column-info` handles merging info returned by driver & inferred by annotate
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{:base_type :type/*}]})
[[1] [2] [nil] [3]]))))
(testing "should disambiguate duplicate names"
(is (= [{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a" {:base-type :type/Integer}]}
{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a_2" {:base-type :type/Integer}]}]
(annotate/column-info
{:type :native}
{:cols [{:name "a" :base_type :type/Integer} {:name "a" :base_type :type/Integer}]
:rows [[1 nil]]}))))))
;;; +----------------------------------------------------------------------------------------------------------------+
| ( MBQL ) Col info for Field clauses |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- info-for-field
([field-id]
(into {} (db/select-one (into [Field] (disj (set @#'qp.store/field-columns-to-fetch) :database_type))
:id field-id)))
([table-key field-key]
(info-for-field (mt/id table-key field-key))))
(deftest col-info-field-ids-test
(testing {:base-type "make sure columns are comming back the way we'd expect for :field clauses"}
(mt/with-everything-store
(mt/$ids venues
(is (= [(merge (info-for-field :venues :price)
{:source :fields
:field_ref $price})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$price]}}
{:columns [:price]}))))))))
(deftest col-info-for-fks-and-joins-test
(mt/with-everything-store
(mt/$ids venues
(testing (str "when a `:field` with `:source-field` (implicit join) is used, we should add in `:fk_field_id` "
"info about the source Field")
(is (= [(merge (info-for-field :categories :name)
{:fk_field_id %category_id
:source :fields
:field_ref $category_id->categories.name})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$category_id->categories.name]}}
{:columns [:name]})))))
(testing "joins"
(testing (str "we should get `:fk_field_id` and information where possible when using joins; "
"display_name should include the display name of the FK field (for IMPLICIT JOINS)")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Category → Name"
:source :fields
:field_ref $category_id->categories.name
:fk_field_id %category_id
:source_alias "CATEGORIES__via__CATEGORY_ID"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&CATEGORIES__via__CATEGORY_ID.categories.name]
:joins [{:alias "CATEGORIES__via__CATEGORY_ID"
:source-table $$venues
:condition [:= $category_id &CATEGORIES__via__CATEGORY_ID.categories.id]
:strategy :left-join
:fk-field-id %category_id}]}}
{:columns [:name]})))))
(testing (str "for EXPLICIT JOINS (which do not include an `:fk-field-id` in the Join info) the returned "
"`:field_ref` should be have only `:join-alias`, and no `:source-field`")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Categories → Name"
:source :fields
:field_ref &Categories.categories.name
:source_alias "Categories"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&Categories.categories.name]
:joins [{:alias "Categories"
:source-table $$venues
:condition [:= $category_id &Categories.categories.id]
:strategy :left-join}]}}
{:columns [:name]})))))))))
(deftest col-info-for-field-with-temporal-unit-test
(mt/with-everything-store
(mt/$ids venues
(testing "when a `:field` with `:temporal-unit` is used, we should add in info about the `:unit`"
(is (= [(merge (info-for-field :venues :price)
{:unit :month
:source :fields
:field_ref !month.price})]
(doall
(annotate/column-info
{:type :query, :query {:fields (mt/$ids venues [!month.price])}}
{:columns [:price]})))))
(testing "datetime unit should work on field literals too"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:field_ref !month.*price/Number}]
(doall
(annotate/column-info
{:type :query, :query {:fields [[:field "price" {:base-type :type/Number, :temporal-unit :month}]]}}
{:columns [:price]}))))))
(testing "should add the correct info if the Field originally comes from a nested query"
(mt/$ids checkins
(is (= [{:name "DATE", :unit :month, :field_ref [:field %date {:temporal-unit :default}]}
{:name "LAST_LOGIN", :unit :month, :field_ref [:field
%users.last_login
{:temporal-unit :default
:join-alias "USERS__via__USER_ID"}]}]
(mapv
(fn [col]
(select-keys col [:name :unit :field_ref]))
(annotate/column-info
{:type :query
:query {:source-query {:source-table $$checkins
:breakout [[:field %date {:temporal-unit :month}]
[:field
%users.last_login
{:temporal-unit :month, :source-field %user_id}]]}
:source-metadata [{:name "DATE"
:id %date
:unit :month
:field_ref [:field %date {:temporal-unit :month}]}
{:name "LAST_LOGIN"
:id %users.last_login
:unit :month
:field_ref [:field %users.last_login {:temporal-unit :month
:source-field %user_id}]}]
:fields [[:field %date {:temporal-unit :default}]
[:field %users.last_login {:temporal-unit :default, :join-alias "USERS__via__USER_ID"}]]
:limit 1}}
nil))))))))
(deftest col-info-for-binning-strategy-test
(testing "when binning strategy is used, include `:binning_info`"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:binning_info {:num_bins 10, :bin_width 5, :min_value -100, :max_value 100, :binning_strategy :num-bins}
:field_ref [:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]}]
(doall
(annotate/column-info
{:type :query
:query {:fields [[:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]]}}
{:columns [:price]}))))))
(deftest col-info-combine-parent-field-names-test
(testing "For fields with parents we should return them with a combined name including parent's name"
(tt/with-temp* [Field [parent {:name "parent", :table_id (mt/id :venues)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
these two are a gross symptom . there 's some tension . sometimes it makes sense to have an effective
;; type: the db type is different and we have a way to convert. Othertimes, it doesn't make sense:
;; when the info is inferred. the solution to this might be quite extensive renaming
:coercion_strategy nil
:name "parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil])))))))
(testing "nested-nested fields should include grandparent name (etc)"
(tt/with-temp* [Field [grandparent {:name "grandparent", :table_id (mt/id :venues)}]
Field [parent {:name "parent", :table_id (mt/id :venues), :parent_id (u/the-id grandparent)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
:coercion_strategy nil
:name "grandparent.parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil]))))))))
(deftest col-info-field-literals-test
(testing "field literals should get the information from the matching `:source-metadata` if it was supplied"
(mt/with-everything-store
(is (= {:name "sum"
:display_name "sum of User ID"
:base_type :type/Integer
:field_ref [:field "sum" {:base-type :type/Integer}]
:semantic_type :type/FK}
(#'annotate/col-info-for-field-clause
{:source-metadata
[{:name "abc", :display_name "another Field", :base_type :type/Integer, :semantic_type :type/FK}
{:name "sum", :display_name "sum of User ID", :base_type :type/Integer, :semantic_type :type/FK}]}
[:field "sum" {:base-type :type/Integer}]))))))
(deftest col-info-expressions-test
(mt/with-everything-store
(testing "col info for an `expression` should work as expected"
(is (= {:base_type :type/Float
:name "double-price"
:display_name "double-price"
:expression_name "double-price"
:field_ref [:expression "double-price"]}
(mt/$ids venues
(#'annotate/col-info-for-field-clause
{:expressions {"double-price" [:* $price 2]}}
[:expression "double-price"])))))
(testing "col-info for convert-timezone should have a `converted_timezone` property"
(is (= {:converted_timezone "Asia/Ho_Chi_Minh",
:base_type :type/DateTime,
:name "last-login-converted",
:display_name "last-login-converted",
:expression_name "last-login-converted",
:field_ref [:expression "last-login-converted"]}
(mt/$ids users
(#'annotate/col-info-for-field-clause
{:expressions {"last-login-converted" [:convert-timezone $last_login "Asia/Ho_Chi_Minh" "UTC"]}}
[:expression "last-login-converted"]))))
(is (= {:converted_timezone "Asia/Ho_Chi_Minh",
:base_type :type/DateTime,
:name "last-login-converted",
:display_name "last-login-converted",
:expression_name "last-login-converted",
:field_ref [:expression "last-login-converted"]}
(mt/$ids users
(#'annotate/col-info-for-field-clause
{:expressions {"last-login-converted" [:datetime-add
[:convert-timezone $last_login "Asia/Ho_Chi_Minh" "UTC"] 2 :hour]}}
[:expression "last-login-converted"])))))
(testing "if there is no matching expression it should give a meaningful error message"
(is (= {:data {:expression-name "double-price"
:tried ["double-price" :double-price]
:found #{"one-hundred"}
:type :invalid-query}
:message "No expression named 'double-price'"}
(try
(mt/$ids venues
(#'annotate/col-info-for-field-clause {:expressions {"one-hundred" 100}} [:expression "double-price"]))
(catch Throwable e {:message (.getMessage e), :data (ex-data e)})))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | (MBQL) Col info for Aggregation clauses |
;;; +----------------------------------------------------------------------------------------------------------------+
;; test that added information about aggregations looks the way we'd expect
(defn- aggregation-names
([ag-clause]
(aggregation-names {} ag-clause))
([inner-query ag-clause]
(binding [driver/*driver* :h2]
(mt/with-everything-store
{:name (annotate/aggregation-name ag-clause)
:display_name (annotate/aggregation-display-name inner-query ag-clause)}))))
(deftest aggregation-names-test
(testing "basic aggregations"
(testing ":count"
(is (= {:name "count", :display_name "Count"}
(aggregation-names [:count]))))
(testing ":distinct"
(is (= {:name "count", :display_name "Distinct values of ID"}
(aggregation-names [:distinct [:field (mt/id :venues :id) nil]]))))
(testing ":sum"
(is (= {:name "sum", :display_name "Sum of ID"}
(aggregation-names [:sum [:field (mt/id :venues :id) nil]])))))
(testing "expressions"
(testing "simple expression"
(is (= {:name "expression", :display_name "Count + 1"}
(aggregation-names [:+ [:count] 1]))))
(testing "expression with nested expressions"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:* 2 [:avg [:field (mt/id :venues :price) nil]]]]))))
(testing "very complicated expression"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price * 3 * (Max of Category ID - 4))"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:*
2
[:avg [:field (mt/id :venues :price) nil]]
3
[:- [:max [:field (mt/id :venues :category_id) nil]] 4]]])))))
(testing "`aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:name "generated_name", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name", :display-name "User-specified Name"}]))))
(testing "`:name` only"
(is (= {:name "generated_name", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name"}]))))
(testing "`:display-name` only"
(is (= {:name "expression", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:display-name "User-specified Name"}]))))))
(defn- col-info-for-aggregation-clause
([clause]
(col-info-for-aggregation-clause {} clause))
([inner-query clause]
(binding [driver/*driver* :h2]
(#'annotate/col-info-for-aggregation-clause inner-query clause))))
(deftest col-info-for-aggregation-clause-test
(mt/with-everything-store
(testing "basic aggregation clauses"
(testing "`:count` (no field)"
(is (= {:base_type :type/Float, :name "expression", :display_name "Count / 2"}
(col-info-for-aggregation-clause [:/ [:count] 2]))))
(testing "`:sum`"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of Price + 1"}
(mt/$ids venues
(col-info-for-aggregation-clause [:sum [:+ $price 1]]))))))
(testing "`:aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "My custom name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:name "sum_2", :display-name "My custom name"}])))))
(testing "`:name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "Sum of Price"}
(mt/$ids venues
(col-info-for-aggregation-clause [:aggregation-options [:sum $price] {:name "sum_2"}])))))
(testing "`:display-name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum"
:display_name "My Custom Name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:display-name "My Custom Name"}]))))))
(testing (str "if a driver is kind enough to supply us with some information about the `:cols` that come back, we "
"should include that information in the results. Their information should be preferred over ours")
(is (= {:cols [{:name "metric"
:display_name "Total Events"
:base_type :type/Text
:effective_type :type/Text
:source :aggregation
:field_ref [:aggregation 0]}]}
(add-column-info
(mt/mbql-query venues {:aggregation [[:metric "ga:totalEvents"]]})
{:cols [{:name "totalEvents", :display_name "Total Events", :base_type :type/Text}]}))))
(testing "col info for an `expression` aggregation w/ a named expression should work as expected"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of double-price"}
(mt/$ids venues
(col-info-for-aggregation-clause {:expressions {"double-price" [:* $price 2]}} [:sum [:expression "double-price"]])))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Other MBQL col info tests |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- infered-col-type
[expr]
(-> (add-column-info (mt/mbql-query venues {:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
{})
:cols
first
(select-keys [:base_type :semantic_type])))
(deftest computed-columns-inference
(letfn [(infer [expr] (-> (mt/mbql-query venues
{:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
(add-column-info {})
:cols
first))]
(testing "Coalesce"
(testing "Uses the first clause"
(testing "Gets the type information from the field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "Does not contain a field id in its analysis (#18513)"
(is (false? (contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id)))))
(testing "Gets the type information from the literal"
(is (= {:base_type :type/Text,
:name "expr",
:display_name "expr",
:expression_name "expr",
:field_ref [:expression "expr"],
:source :fields}
(infer [:coalesce "bar" [:field (mt/id :venues :name) nil]]))))))
(testing "Case"
(testing "Uses first available type information"
(testing "From a field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "does not contain a field id in its analysis (#17512)"
(is (false?
(contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id))))))
(is (= {:base_type :type/Text}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] "big"]]])))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2]
[:+ [:field (mt/id :venues :price) nil] 1]]]])))
(testing "Make sure we skip nils when infering case return type"
(is (= {:base_type :type/Number}
(infered-col-type [:case [[[:< [:field (mt/id :venues :price) nil] 10] [:value nil {:base_type :type/Number}]]
[[:> [:field (mt/id :venues :price) nil] 2] 10]]]))))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] [:+ [:field (mt/id :venues :price) nil] 1]]]]))))))
(deftest ^:parallel datetime-arithmetics?-test
(is (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]))
(is (#'annotate/datetime-arithmetics? [:field (mt/id :checkins :date) {:temporal-unit :month}]))
(is (not (#'annotate/datetime-arithmetics? [:+ 1 [:temporal-extract
[:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]
:year]])))
(is (not (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] 3]))))
(deftest temporal-extract-test
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :month])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :hour])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :users :last_login) nil] 2 :month]))))
(deftest test-string-extracts
(is (= {:base_type :type/Text}
(infered-col-type [:trim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:ltrim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:rtrim "foo"])))
(is (= {:base_type :type/BigInteger}
(infered-col-type [:length "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:upper "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:lower "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:substring "foo" 2])))
(is (= {:base_type :type/Text}
(infered-col-type [:replace "foo" "f" "b"])))
(is (= {:base_type :type/Text}
(infered-col-type [:regex-match-first "foo" "f"])))
(is (= {:base_type :type/Text}
(infered-col-type [:concat "foo" "bar"])))
(is (= {:base_type :type/Text}
(infered-col-type [:coalesce "foo" "bar"])))
(is (= {:base_type :type/Text
:semantic_type :type/Name}
(infered-col-type [:coalesce [:field (mt/id :venues :name) nil] "bar"]))))
(deftest unique-name-key-test
(testing "Make sure `:cols` always come back with a unique `:name` key (#8759)"
(is (= {:cols
[{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 0]}
{:source :aggregation
:name "sum"
:display_name "sum"
:base_type :type/Number
:effective_type :type/Number
:field_ref [:aggregation 1]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_2"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 2]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_3"
:display_name "count_2"
:source :aggregation
:field_ref [:aggregation 3]}]}
(add-column-info
(mt/mbql-query venues
{:aggregation [[:count]
[:sum]
[:count]
[:aggregation-options [:count] {:display-name "count_2"}]]})
{:cols [{:name "count", :display_name "count", :base_type :type/Number}
{:name "sum", :display_name "sum", :base_type :type/Number}
{:name "count", :display_name "count", :base_type :type/Number}
{:name "count_2", :display_name "count_2", :base_type :type/Number}]})))))
(deftest expressions-keys-test
(testing "make sure expressions come back with the right set of keys, including `:expression_name` (#8854)"
(is (= {:name "discount_price"
:display_name "discount_price"
:base_type :type/Float
:expression_name "discount_price"
:source :fields
:field_ref [:expression "discount_price"]}
(-> (add-column-info
(mt/mbql-query venues
{:expressions {"discount_price" [:* 0.9 $price]}
:fields [$name [:expression "discount_price"]]
:limit 10})
{})
:cols
second)))))
(deftest deduplicate-expression-names-test
(testing "make sure multiple expressions come back with deduplicated names"
(testing "expressions in aggregations"
(is (= [{:base_type :type/Float, :name "expression", :display_name "0.9 * Average of Price", :source :aggregation, :field_ref [:aggregation 0]}
{:base_type :type/Float, :name "expression_2", :display_name "0.8 * Average of Price", :source :aggregation, :field_ref [:aggregation 1]}]
(:cols (add-column-info
(mt/mbql-query venues
{:aggregation [[:* 0.9 [:avg $price]] [:* 0.8 [:avg $price]]]
:limit 10})
{})))))
(testing "named :expressions"
(is (= [{:name "prev_month", :display_name "prev_month", :base_type :type/DateTime, :expression_name "prev_month", :source :fields, :field_ref [:expression "prev_month"]}]
(:cols (add-column-info
(mt/mbql-query users
{:expressions {:prev_month [:+ $last_login [:interval -1 :month]]}
:fields [[:expression "prev_month"]], :limit 10})
{})))))))
(deftest mbql-cols-nested-queries-test
(testing "Should be able to infer MBQL columns with nested queries"
(let [base-query (qp/preprocess
(mt/mbql-query venues
{:joins [{:fields :all
:source-table $$categories
:condition [:= $category_id &c.categories.id]
:alias "c"}]}))]
(doseq [level [0 1 2 3]]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids venues
[{:name "ID", :id %id, :field_ref $id}
{:name "NAME", :id %name, :field_ref $name}
{:name "CATEGORY_ID", :id %category_id, :field_ref $category_id}
{:name "LATITUDE", :id %latitude, :field_ref $latitude}
{:name "LONGITUDE", :id %longitude, :field_ref $longitude}
{:name "PRICE", :id %price, :field_ref $price}
{:name "ID_2", :id %categories.id, :field_ref &c.categories.id}
{:name "NAME_2", :id %categories.name, :field_ref &c.categories.name}])
(map #(select-keys % [:name :id :field_ref])
(:cols (add-column-info nested-query {})))))))))))
(testing "Aggregated question with source is an aggregated models should infer display_name correctly (#23248)"
(mt/dataset sample-dataset
(mt/with-temp* [Card [{card-id :id}
{:dataset true
:dataset_query
(mt/$ids :products
{:type :query
:database (mt/id)
:query {:source-table $$products
:aggregation
[[:aggregation-options
[:sum $price]
{:name "sum"}]
[:aggregation-options
[:max $rating]
{:name "max"}]]
:breakout $category
:order-by [[:asc $category]]}})}]]
(let [query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-id)
:aggregation [[:aggregation-options
[:sum
[:field
"sum"
{:base-type :type/Float}]]
{:name "sum"}]
[:aggregation-options
[:count]
{:name "count"}]]
:limit 1}))]
(is (= ["Sum of Sum of Price" "Count"]
(->> (add-column-info query {})
:cols
(map :display_name)))))))))
(deftest inception-test
(testing "Should return correct metadata for an 'inception-style' nesting of source > source > source with a join (#14745)"
(mt/dataset sample-dataset
these tests look at the metadata for just one column so it 's easier to spot the differences .
(letfn [(ean-metadata [result]
(as-> (:cols result) result
(m/index-by :name result)
(get result "EAN")
(select-keys result [:name :display_name :base_type :semantic_type :id :field_ref])))]
(testing "Make sure metadata is correct for the 'EAN' column with"
(let [base-query (qp/preprocess
(mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]
:limit 10}))]
(doseq [level (range 4)]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids products
{:name "EAN"
:display_name "Products → Ean"
:base_type :type/Text
:semantic_type nil
:id %ean
:field_ref &Products.ean})
(ean-metadata (add-column-info nested-query {}))))))))))))))
;; metabase#14787
(deftest col-info-for-fields-from-card-test
(mt/dataset sample-dataset
(let [card-1-query (mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]})]
(mt/with-temp* [Card [{card-1-id :id} {:dataset_query card-1-query}]
Card [{card-2-id :id} {:dataset_query (mt/mbql-query people)}]]
(testing "when a nested query is from a saved question, there should be no `:join-alias` on the left side"
(mt/$ids nil
(let [base-query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-1-id)
:joins [{:fields :all
:source-table (str "card__" card-2-id)
:condition [:= $orders.user_id &Products.products.id]
:alias "Q"}]
:limit 1}))
fields #{%orders.discount %products.title %people.source}]
(is (= [{:display_name "Discount" :field_ref [:field %orders.discount nil]}
{:display_name "Products → Title" :field_ref [:field %products.title nil]}
{:display_name "Q → Source" :field_ref [:field %people.source {:join-alias "Q"}]}]
(->> (:cols (add-column-info base-query {}))
(filter #(fields (:id %)))
(map #(select-keys % [:display_name :field_ref])))))))))))
(testing "Has the correct display names for joined fields from cards"
(letfn [(native [query] {:type :native
:native {:query query :template-tags {}}
:database (mt/id)})]
(mt/with-temp* [Card [{card1-id :id} {:dataset_query
(native "select 'foo' as A_COLUMN")}]
Card [{card2-id :id} {:dataset_query
(native "select 'foo' as B_COLUMN")}]]
(doseq [card-id [card1-id card2-id]]
;; populate metadata
(mt/user-http-request :rasta :post 202 (format "card/%d/query" card-id)))
(let [query {:database (mt/id)
:type :query
:query {:source-table (str "card__" card1-id)
:joins [{:fields "all"
:source-table (str "card__" card2-id)
:condition [:=
[:field "A_COLUMN" {:base-type :type/Text}]
[:field "B_COLUMN" {:base-type :type/Text
:join-alias "alias"}]]
:alias "alias"}]}}
results (qp/process-query query)]
(is (= "alias → B Column" (-> results :data :cols second :display_name))
"cols has wrong display name")
(is (= "alias → B Column" (-> results :data :results_metadata
:columns second :display_name))
"Results metadata cols has wrong display name"))))))
(deftest preserve-original-join-alias-test
(testing "The join alias for the `:field_ref` in results metadata should match the one originally specified (#27464)"
(mt/test-drivers (mt/normal-drivers-with-feature :left-join)
(mt/dataset sample-dataset
(let [join-alias "Products with a very long name - Product ID with a very long name"
results (mt/run-mbql-query orders
{:joins [{:source-table $$products
:condition [:= $product_id [:field %products.id {:join-alias join-alias}]]
:alias join-alias
:fields [[:field %products.title {:join-alias join-alias}]]}]
:fields [$orders.id
[:field %products.title {:join-alias join-alias}]]
:limit 4})]
(doseq [[location metadata] {"data.cols" (mt/cols results)
"data.results_metadata.columns" (get-in results [:data :results_metadata :columns])}]
(testing location
(is (= (mt/$ids
[{:display_name "ID"
:field_ref $orders.id}
(merge
{:display_name (str join-alias " → Title")
:field_ref [:field %products.title {:join-alias join-alias}]}
;; `source_alias` is only included in `data.cols`, but not in `results_metadata`
(when (= location "data.cols")
{:source_alias join-alias}))])
(map
#(select-keys % [:display_name :field_ref :source_alias])
metadata))))))))))
| null | https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/test/metabase/query_processor/middleware/annotate_test.clj | clojure | +----------------------------------------------------------------------------------------------------------------+
| column-info (:native) |
+----------------------------------------------------------------------------------------------------------------+
`merged-column-info` handles merging info returned by driver & inferred by annotate
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
type: the db type is different and we have a way to convert. Othertimes, it doesn't make sense:
when the info is inferred. the solution to this might be quite extensive renaming
+----------------------------------------------------------------------------------------------------------------+
| (MBQL) Col info for Aggregation clauses |
+----------------------------------------------------------------------------------------------------------------+
test that added information about aggregations looks the way we'd expect
+----------------------------------------------------------------------------------------------------------------+
| Other MBQL col info tests |
+----------------------------------------------------------------------------------------------------------------+
metabase#14787
populate metadata
`source_alias` is only included in `data.cols`, but not in `results_metadata` | (ns metabase.query-processor.middleware.annotate-test
(:require
[clojure.test :refer :all]
[medley.core :as m]
[metabase.driver :as driver]
[metabase.models :refer [Card Field]]
[metabase.query-processor :as qp]
[metabase.query-processor.middleware.annotate :as annotate]
[metabase.query-processor.store :as qp.store]
[metabase.test :as mt]
[metabase.util :as u]
[toucan.db :as db]
[toucan.util.test :as tt]))
(set! *warn-on-reflection* true)
(defn- add-column-info [query metadata]
(mt/with-everything-store
(driver/with-driver :h2
((annotate/add-column-info query identity) metadata))))
(deftest native-column-info-test
(testing "native column info"
(testing "should still infer types even if the initial value(s) are `nil` (#4256, #6924)"
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
(concat (repeat 1000 [nil]) [[1] [2]])))))
(testing "should use default `base_type` of `type/*` if there are no non-nil values in the sample"
(is (= [:type/*]
(transduce identity (#'annotate/base-type-inferer {:cols [{}]})
[[nil]]))))
(testing "should attempt to infer better base type if driver returns :type/* (#12150)"
(is (= [:type/Integer]
(transduce identity (#'annotate/base-type-inferer {:cols [{:base_type :type/*}]})
[[1] [2] [nil] [3]]))))
(testing "should disambiguate duplicate names"
(is (= [{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a" {:base-type :type/Integer}]}
{:name "a", :display_name "a", :base_type :type/Integer, :source :native, :field_ref [:field "a_2" {:base-type :type/Integer}]}]
(annotate/column-info
{:type :native}
{:cols [{:name "a" :base_type :type/Integer} {:name "a" :base_type :type/Integer}]
:rows [[1 nil]]}))))))
| ( MBQL ) Col info for Field clauses |
(defn- info-for-field
([field-id]
(into {} (db/select-one (into [Field] (disj (set @#'qp.store/field-columns-to-fetch) :database_type))
:id field-id)))
([table-key field-key]
(info-for-field (mt/id table-key field-key))))
(deftest col-info-field-ids-test
(testing {:base-type "make sure columns are comming back the way we'd expect for :field clauses"}
(mt/with-everything-store
(mt/$ids venues
(is (= [(merge (info-for-field :venues :price)
{:source :fields
:field_ref $price})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$price]}}
{:columns [:price]}))))))))
(deftest col-info-for-fks-and-joins-test
(mt/with-everything-store
(mt/$ids venues
(testing (str "when a `:field` with `:source-field` (implicit join) is used, we should add in `:fk_field_id` "
"info about the source Field")
(is (= [(merge (info-for-field :categories :name)
{:fk_field_id %category_id
:source :fields
:field_ref $category_id->categories.name})]
(doall
(annotate/column-info
{:type :query, :query {:fields [$category_id->categories.name]}}
{:columns [:name]})))))
(testing "joins"
(testing (str "we should get `:fk_field_id` and information where possible when using joins; "
"display_name should include the display name of the FK field (for IMPLICIT JOINS)")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Category → Name"
:source :fields
:field_ref $category_id->categories.name
:fk_field_id %category_id
:source_alias "CATEGORIES__via__CATEGORY_ID"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&CATEGORIES__via__CATEGORY_ID.categories.name]
:joins [{:alias "CATEGORIES__via__CATEGORY_ID"
:source-table $$venues
:condition [:= $category_id &CATEGORIES__via__CATEGORY_ID.categories.id]
:strategy :left-join
:fk-field-id %category_id}]}}
{:columns [:name]})))))
(testing (str "for EXPLICIT JOINS (which do not include an `:fk-field-id` in the Join info) the returned "
"`:field_ref` should be have only `:join-alias`, and no `:source-field`")
(is (= [(merge (info-for-field :categories :name)
{:display_name "Categories → Name"
:source :fields
:field_ref &Categories.categories.name
:source_alias "Categories"})]
(doall
(annotate/column-info
{:type :query
:query {:fields [&Categories.categories.name]
:joins [{:alias "Categories"
:source-table $$venues
:condition [:= $category_id &Categories.categories.id]
:strategy :left-join}]}}
{:columns [:name]})))))))))
(deftest col-info-for-field-with-temporal-unit-test
(mt/with-everything-store
(mt/$ids venues
(testing "when a `:field` with `:temporal-unit` is used, we should add in info about the `:unit`"
(is (= [(merge (info-for-field :venues :price)
{:unit :month
:source :fields
:field_ref !month.price})]
(doall
(annotate/column-info
{:type :query, :query {:fields (mt/$ids venues [!month.price])}}
{:columns [:price]})))))
(testing "datetime unit should work on field literals too"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:field_ref !month.*price/Number}]
(doall
(annotate/column-info
{:type :query, :query {:fields [[:field "price" {:base-type :type/Number, :temporal-unit :month}]]}}
{:columns [:price]}))))))
(testing "should add the correct info if the Field originally comes from a nested query"
(mt/$ids checkins
(is (= [{:name "DATE", :unit :month, :field_ref [:field %date {:temporal-unit :default}]}
{:name "LAST_LOGIN", :unit :month, :field_ref [:field
%users.last_login
{:temporal-unit :default
:join-alias "USERS__via__USER_ID"}]}]
(mapv
(fn [col]
(select-keys col [:name :unit :field_ref]))
(annotate/column-info
{:type :query
:query {:source-query {:source-table $$checkins
:breakout [[:field %date {:temporal-unit :month}]
[:field
%users.last_login
{:temporal-unit :month, :source-field %user_id}]]}
:source-metadata [{:name "DATE"
:id %date
:unit :month
:field_ref [:field %date {:temporal-unit :month}]}
{:name "LAST_LOGIN"
:id %users.last_login
:unit :month
:field_ref [:field %users.last_login {:temporal-unit :month
:source-field %user_id}]}]
:fields [[:field %date {:temporal-unit :default}]
[:field %users.last_login {:temporal-unit :default, :join-alias "USERS__via__USER_ID"}]]
:limit 1}}
nil))))))))
(deftest col-info-for-binning-strategy-test
(testing "when binning strategy is used, include `:binning_info`"
(is (= [{:name "price"
:base_type :type/Number
:display_name "Price"
:unit :month
:source :fields
:binning_info {:num_bins 10, :bin_width 5, :min_value -100, :max_value 100, :binning_strategy :num-bins}
:field_ref [:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]}]
(doall
(annotate/column-info
{:type :query
:query {:fields [[:field "price" {:base-type :type/Number
:temporal-unit :month
:binning {:strategy :num-bins
:num-bins 10
:bin-width 5
:min-value -100
:max-value 100}}]]}}
{:columns [:price]}))))))
(deftest col-info-combine-parent-field-names-test
(testing "For fields with parents we should return them with a combined name including parent's name"
(tt/with-temp* [Field [parent {:name "parent", :table_id (mt/id :venues)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
these two are a gross symptom . there 's some tension . sometimes it makes sense to have an effective
:coercion_strategy nil
:name "parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil])))))))
(testing "nested-nested fields should include grandparent name (etc)"
(tt/with-temp* [Field [grandparent {:name "grandparent", :table_id (mt/id :venues)}]
Field [parent {:name "parent", :table_id (mt/id :venues), :parent_id (u/the-id grandparent)}]
Field [child {:name "child", :table_id (mt/id :venues), :parent_id (u/the-id parent)}]]
(mt/with-everything-store
(is (= {:description nil
:table_id (mt/id :venues)
:semantic_type nil
:effective_type nil
:coercion_strategy nil
:name "grandparent.parent.child"
:settings nil
:field_ref [:field (u/the-id child) nil]
:nfc_path nil
:parent_id (u/the-id parent)
:id (u/the-id child)
:visibility_type :normal
:display_name "Child"
:fingerprint nil
:base_type :type/Text}
(into {} (#'annotate/col-info-for-field-clause {} [:field (u/the-id child) nil]))))))))
(deftest col-info-field-literals-test
(testing "field literals should get the information from the matching `:source-metadata` if it was supplied"
(mt/with-everything-store
(is (= {:name "sum"
:display_name "sum of User ID"
:base_type :type/Integer
:field_ref [:field "sum" {:base-type :type/Integer}]
:semantic_type :type/FK}
(#'annotate/col-info-for-field-clause
{:source-metadata
[{:name "abc", :display_name "another Field", :base_type :type/Integer, :semantic_type :type/FK}
{:name "sum", :display_name "sum of User ID", :base_type :type/Integer, :semantic_type :type/FK}]}
[:field "sum" {:base-type :type/Integer}]))))))
(deftest col-info-expressions-test
(mt/with-everything-store
(testing "col info for an `expression` should work as expected"
(is (= {:base_type :type/Float
:name "double-price"
:display_name "double-price"
:expression_name "double-price"
:field_ref [:expression "double-price"]}
(mt/$ids venues
(#'annotate/col-info-for-field-clause
{:expressions {"double-price" [:* $price 2]}}
[:expression "double-price"])))))
(testing "col-info for convert-timezone should have a `converted_timezone` property"
(is (= {:converted_timezone "Asia/Ho_Chi_Minh",
:base_type :type/DateTime,
:name "last-login-converted",
:display_name "last-login-converted",
:expression_name "last-login-converted",
:field_ref [:expression "last-login-converted"]}
(mt/$ids users
(#'annotate/col-info-for-field-clause
{:expressions {"last-login-converted" [:convert-timezone $last_login "Asia/Ho_Chi_Minh" "UTC"]}}
[:expression "last-login-converted"]))))
(is (= {:converted_timezone "Asia/Ho_Chi_Minh",
:base_type :type/DateTime,
:name "last-login-converted",
:display_name "last-login-converted",
:expression_name "last-login-converted",
:field_ref [:expression "last-login-converted"]}
(mt/$ids users
(#'annotate/col-info-for-field-clause
{:expressions {"last-login-converted" [:datetime-add
[:convert-timezone $last_login "Asia/Ho_Chi_Minh" "UTC"] 2 :hour]}}
[:expression "last-login-converted"])))))
(testing "if there is no matching expression it should give a meaningful error message"
(is (= {:data {:expression-name "double-price"
:tried ["double-price" :double-price]
:found #{"one-hundred"}
:type :invalid-query}
:message "No expression named 'double-price'"}
(try
(mt/$ids venues
(#'annotate/col-info-for-field-clause {:expressions {"one-hundred" 100}} [:expression "double-price"]))
(catch Throwable e {:message (.getMessage e), :data (ex-data e)})))))))
(defn- aggregation-names
([ag-clause]
(aggregation-names {} ag-clause))
([inner-query ag-clause]
(binding [driver/*driver* :h2]
(mt/with-everything-store
{:name (annotate/aggregation-name ag-clause)
:display_name (annotate/aggregation-display-name inner-query ag-clause)}))))
(deftest aggregation-names-test
(testing "basic aggregations"
(testing ":count"
(is (= {:name "count", :display_name "Count"}
(aggregation-names [:count]))))
(testing ":distinct"
(is (= {:name "count", :display_name "Distinct values of ID"}
(aggregation-names [:distinct [:field (mt/id :venues :id) nil]]))))
(testing ":sum"
(is (= {:name "sum", :display_name "Sum of ID"}
(aggregation-names [:sum [:field (mt/id :venues :id) nil]])))))
(testing "expressions"
(testing "simple expression"
(is (= {:name "expression", :display_name "Count + 1"}
(aggregation-names [:+ [:count] 1]))))
(testing "expression with nested expressions"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:* 2 [:avg [:field (mt/id :venues :price) nil]]]]))))
(testing "very complicated expression"
(is (= {:name "expression", :display_name "Min of ID + (2 * Average of Price * 3 * (Max of Category ID - 4))"}
(aggregation-names
[:+
[:min [:field (mt/id :venues :id) nil]]
[:*
2
[:avg [:field (mt/id :venues :price) nil]]
3
[:- [:max [:field (mt/id :venues :category_id) nil]] 4]]])))))
(testing "`aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:name "generated_name", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name", :display-name "User-specified Name"}]))))
(testing "`:name` only"
(is (= {:name "generated_name", :display_name "Min of ID + (2 * Average of Price)"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:name "generated_name"}]))))
(testing "`:display-name` only"
(is (= {:name "expression", :display_name "User-specified Name"}
(aggregation-names
[:aggregation-options
[:+ [:min [:field (mt/id :venues :id) nil]] [:* 2 [:avg [:field (mt/id :venues :price) nil]]]]
{:display-name "User-specified Name"}]))))))
(defn- col-info-for-aggregation-clause
([clause]
(col-info-for-aggregation-clause {} clause))
([inner-query clause]
(binding [driver/*driver* :h2]
(#'annotate/col-info-for-aggregation-clause inner-query clause))))
(deftest col-info-for-aggregation-clause-test
(mt/with-everything-store
(testing "basic aggregation clauses"
(testing "`:count` (no field)"
(is (= {:base_type :type/Float, :name "expression", :display_name "Count / 2"}
(col-info-for-aggregation-clause [:/ [:count] 2]))))
(testing "`:sum`"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of Price + 1"}
(mt/$ids venues
(col-info-for-aggregation-clause [:sum [:+ $price 1]]))))))
(testing "`:aggregation-options`"
(testing "`:name` and `:display-name`"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "My custom name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:name "sum_2", :display-name "My custom name"}])))))
(testing "`:name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum_2"
:display_name "Sum of Price"}
(mt/$ids venues
(col-info-for-aggregation-clause [:aggregation-options [:sum $price] {:name "sum_2"}])))))
(testing "`:display-name` only"
(is (= {:base_type :type/Integer
:semantic_type :type/Category
:settings nil
:name "sum"
:display_name "My Custom Name"}
(mt/$ids venues
(col-info-for-aggregation-clause
[:aggregation-options [:sum $price] {:display-name "My Custom Name"}]))))))
(testing (str "if a driver is kind enough to supply us with some information about the `:cols` that come back, we "
"should include that information in the results. Their information should be preferred over ours")
(is (= {:cols [{:name "metric"
:display_name "Total Events"
:base_type :type/Text
:effective_type :type/Text
:source :aggregation
:field_ref [:aggregation 0]}]}
(add-column-info
(mt/mbql-query venues {:aggregation [[:metric "ga:totalEvents"]]})
{:cols [{:name "totalEvents", :display_name "Total Events", :base_type :type/Text}]}))))
(testing "col info for an `expression` aggregation w/ a named expression should work as expected"
(is (= {:base_type :type/Float, :name "sum", :display_name "Sum of double-price"}
(mt/$ids venues
(col-info-for-aggregation-clause {:expressions {"double-price" [:* $price 2]}} [:sum [:expression "double-price"]])))))))
(defn- infered-col-type
[expr]
(-> (add-column-info (mt/mbql-query venues {:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
{})
:cols
first
(select-keys [:base_type :semantic_type])))
(deftest computed-columns-inference
(letfn [(infer [expr] (-> (mt/mbql-query venues
{:expressions {"expr" expr}
:fields [[:expression "expr"]]
:limit 10})
(add-column-info {})
:cols
first))]
(testing "Coalesce"
(testing "Uses the first clause"
(testing "Gets the type information from the field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "Does not contain a field id in its analysis (#18513)"
(is (false? (contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id)))))
(testing "Gets the type information from the literal"
(is (= {:base_type :type/Text,
:name "expr",
:display_name "expr",
:expression_name "expr",
:field_ref [:expression "expr"],
:source :fields}
(infer [:coalesce "bar" [:field (mt/id :venues :name) nil]]))))))
(testing "Case"
(testing "Uses first available type information"
(testing "From a field"
(is (= {:semantic_type :type/Name,
:coercion_strategy nil,
:name "expr",
:expression_name "expr",
:source :fields,
:field_ref [:expression "expr"],
:effective_type :type/Text,
:display_name "expr",
:base_type :type/Text}
(infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])))
(testing "does not contain a field id in its analysis (#17512)"
(is (false?
(contains? (infer [:coalesce [:field (mt/id :venues :name) nil] "bar"])
:id))))))
(is (= {:base_type :type/Text}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] "big"]]])))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2]
[:+ [:field (mt/id :venues :price) nil] 1]]]])))
(testing "Make sure we skip nils when infering case return type"
(is (= {:base_type :type/Number}
(infered-col-type [:case [[[:< [:field (mt/id :venues :price) nil] 10] [:value nil {:base_type :type/Number}]]
[[:> [:field (mt/id :venues :price) nil] 2] 10]]]))))
(is (= {:base_type :type/Float}
(infered-col-type [:case [[[:> [:field (mt/id :venues :price) nil] 2] [:+ [:field (mt/id :venues :price) nil] 1]]]]))))))
(deftest ^:parallel datetime-arithmetics?-test
(is (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]))
(is (#'annotate/datetime-arithmetics? [:field (mt/id :checkins :date) {:temporal-unit :month}]))
(is (not (#'annotate/datetime-arithmetics? [:+ 1 [:temporal-extract
[:+ [:field (mt/id :checkins :date) nil] [:interval -1 :month]]
:year]])))
(is (not (#'annotate/datetime-arithmetics? [:+ [:field (mt/id :checkins :date) nil] 3]))))
(deftest temporal-extract-test
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :month])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :checkins :date) nil] 2 :hour])))
(is (= {:base_type :type/DateTime}
(infered-col-type [:datetime-add [:field (mt/id :users :last_login) nil] 2 :month]))))
(deftest test-string-extracts
(is (= {:base_type :type/Text}
(infered-col-type [:trim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:ltrim "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:rtrim "foo"])))
(is (= {:base_type :type/BigInteger}
(infered-col-type [:length "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:upper "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:lower "foo"])))
(is (= {:base_type :type/Text}
(infered-col-type [:substring "foo" 2])))
(is (= {:base_type :type/Text}
(infered-col-type [:replace "foo" "f" "b"])))
(is (= {:base_type :type/Text}
(infered-col-type [:regex-match-first "foo" "f"])))
(is (= {:base_type :type/Text}
(infered-col-type [:concat "foo" "bar"])))
(is (= {:base_type :type/Text}
(infered-col-type [:coalesce "foo" "bar"])))
(is (= {:base_type :type/Text
:semantic_type :type/Name}
(infered-col-type [:coalesce [:field (mt/id :venues :name) nil] "bar"]))))
(deftest unique-name-key-test
(testing "Make sure `:cols` always come back with a unique `:name` key (#8759)"
(is (= {:cols
[{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 0]}
{:source :aggregation
:name "sum"
:display_name "sum"
:base_type :type/Number
:effective_type :type/Number
:field_ref [:aggregation 1]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_2"
:display_name "count"
:source :aggregation
:field_ref [:aggregation 2]}
{:base_type :type/Number
:effective_type :type/Number
:semantic_type :type/Quantity
:name "count_3"
:display_name "count_2"
:source :aggregation
:field_ref [:aggregation 3]}]}
(add-column-info
(mt/mbql-query venues
{:aggregation [[:count]
[:sum]
[:count]
[:aggregation-options [:count] {:display-name "count_2"}]]})
{:cols [{:name "count", :display_name "count", :base_type :type/Number}
{:name "sum", :display_name "sum", :base_type :type/Number}
{:name "count", :display_name "count", :base_type :type/Number}
{:name "count_2", :display_name "count_2", :base_type :type/Number}]})))))
(deftest expressions-keys-test
(testing "make sure expressions come back with the right set of keys, including `:expression_name` (#8854)"
(is (= {:name "discount_price"
:display_name "discount_price"
:base_type :type/Float
:expression_name "discount_price"
:source :fields
:field_ref [:expression "discount_price"]}
(-> (add-column-info
(mt/mbql-query venues
{:expressions {"discount_price" [:* 0.9 $price]}
:fields [$name [:expression "discount_price"]]
:limit 10})
{})
:cols
second)))))
(deftest deduplicate-expression-names-test
(testing "make sure multiple expressions come back with deduplicated names"
(testing "expressions in aggregations"
(is (= [{:base_type :type/Float, :name "expression", :display_name "0.9 * Average of Price", :source :aggregation, :field_ref [:aggregation 0]}
{:base_type :type/Float, :name "expression_2", :display_name "0.8 * Average of Price", :source :aggregation, :field_ref [:aggregation 1]}]
(:cols (add-column-info
(mt/mbql-query venues
{:aggregation [[:* 0.9 [:avg $price]] [:* 0.8 [:avg $price]]]
:limit 10})
{})))))
(testing "named :expressions"
(is (= [{:name "prev_month", :display_name "prev_month", :base_type :type/DateTime, :expression_name "prev_month", :source :fields, :field_ref [:expression "prev_month"]}]
(:cols (add-column-info
(mt/mbql-query users
{:expressions {:prev_month [:+ $last_login [:interval -1 :month]]}
:fields [[:expression "prev_month"]], :limit 10})
{})))))))
(deftest mbql-cols-nested-queries-test
(testing "Should be able to infer MBQL columns with nested queries"
(let [base-query (qp/preprocess
(mt/mbql-query venues
{:joins [{:fields :all
:source-table $$categories
:condition [:= $category_id &c.categories.id]
:alias "c"}]}))]
(doseq [level [0 1 2 3]]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids venues
[{:name "ID", :id %id, :field_ref $id}
{:name "NAME", :id %name, :field_ref $name}
{:name "CATEGORY_ID", :id %category_id, :field_ref $category_id}
{:name "LATITUDE", :id %latitude, :field_ref $latitude}
{:name "LONGITUDE", :id %longitude, :field_ref $longitude}
{:name "PRICE", :id %price, :field_ref $price}
{:name "ID_2", :id %categories.id, :field_ref &c.categories.id}
{:name "NAME_2", :id %categories.name, :field_ref &c.categories.name}])
(map #(select-keys % [:name :id :field_ref])
(:cols (add-column-info nested-query {})))))))))))
(testing "Aggregated question with source is an aggregated models should infer display_name correctly (#23248)"
(mt/dataset sample-dataset
(mt/with-temp* [Card [{card-id :id}
{:dataset true
:dataset_query
(mt/$ids :products
{:type :query
:database (mt/id)
:query {:source-table $$products
:aggregation
[[:aggregation-options
[:sum $price]
{:name "sum"}]
[:aggregation-options
[:max $rating]
{:name "max"}]]
:breakout $category
:order-by [[:asc $category]]}})}]]
(let [query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-id)
:aggregation [[:aggregation-options
[:sum
[:field
"sum"
{:base-type :type/Float}]]
{:name "sum"}]
[:aggregation-options
[:count]
{:name "count"}]]
:limit 1}))]
(is (= ["Sum of Sum of Price" "Count"]
(->> (add-column-info query {})
:cols
(map :display_name)))))))))
(deftest inception-test
(testing "Should return correct metadata for an 'inception-style' nesting of source > source > source with a join (#14745)"
(mt/dataset sample-dataset
these tests look at the metadata for just one column so it 's easier to spot the differences .
(letfn [(ean-metadata [result]
(as-> (:cols result) result
(m/index-by :name result)
(get result "EAN")
(select-keys result [:name :display_name :base_type :semantic_type :id :field_ref])))]
(testing "Make sure metadata is correct for the 'EAN' column with"
(let [base-query (qp/preprocess
(mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]
:limit 10}))]
(doseq [level (range 4)]
(testing (format "%d level(s) of nesting" level)
(let [nested-query (mt/nest-query base-query level)]
(testing (format "\nQuery = %s" (u/pprint-to-str nested-query))
(is (= (mt/$ids products
{:name "EAN"
:display_name "Products → Ean"
:base_type :type/Text
:semantic_type nil
:id %ean
:field_ref &Products.ean})
(ean-metadata (add-column-info nested-query {}))))))))))))))
(deftest col-info-for-fields-from-card-test
(mt/dataset sample-dataset
(let [card-1-query (mt/mbql-query orders
{:joins [{:fields :all
:source-table $$products
:condition [:= $product_id &Products.products.id]
:alias "Products"}]})]
(mt/with-temp* [Card [{card-1-id :id} {:dataset_query card-1-query}]
Card [{card-2-id :id} {:dataset_query (mt/mbql-query people)}]]
(testing "when a nested query is from a saved question, there should be no `:join-alias` on the left side"
(mt/$ids nil
(let [base-query (qp/preprocess
(mt/mbql-query nil
{:source-table (str "card__" card-1-id)
:joins [{:fields :all
:source-table (str "card__" card-2-id)
:condition [:= $orders.user_id &Products.products.id]
:alias "Q"}]
:limit 1}))
fields #{%orders.discount %products.title %people.source}]
(is (= [{:display_name "Discount" :field_ref [:field %orders.discount nil]}
{:display_name "Products → Title" :field_ref [:field %products.title nil]}
{:display_name "Q → Source" :field_ref [:field %people.source {:join-alias "Q"}]}]
(->> (:cols (add-column-info base-query {}))
(filter #(fields (:id %)))
(map #(select-keys % [:display_name :field_ref])))))))))))
(testing "Has the correct display names for joined fields from cards"
(letfn [(native [query] {:type :native
:native {:query query :template-tags {}}
:database (mt/id)})]
(mt/with-temp* [Card [{card1-id :id} {:dataset_query
(native "select 'foo' as A_COLUMN")}]
Card [{card2-id :id} {:dataset_query
(native "select 'foo' as B_COLUMN")}]]
(doseq [card-id [card1-id card2-id]]
(mt/user-http-request :rasta :post 202 (format "card/%d/query" card-id)))
(let [query {:database (mt/id)
:type :query
:query {:source-table (str "card__" card1-id)
:joins [{:fields "all"
:source-table (str "card__" card2-id)
:condition [:=
[:field "A_COLUMN" {:base-type :type/Text}]
[:field "B_COLUMN" {:base-type :type/Text
:join-alias "alias"}]]
:alias "alias"}]}}
results (qp/process-query query)]
(is (= "alias → B Column" (-> results :data :cols second :display_name))
"cols has wrong display name")
(is (= "alias → B Column" (-> results :data :results_metadata
:columns second :display_name))
"Results metadata cols has wrong display name"))))))
(deftest preserve-original-join-alias-test
(testing "The join alias for the `:field_ref` in results metadata should match the one originally specified (#27464)"
(mt/test-drivers (mt/normal-drivers-with-feature :left-join)
(mt/dataset sample-dataset
(let [join-alias "Products with a very long name - Product ID with a very long name"
results (mt/run-mbql-query orders
{:joins [{:source-table $$products
:condition [:= $product_id [:field %products.id {:join-alias join-alias}]]
:alias join-alias
:fields [[:field %products.title {:join-alias join-alias}]]}]
:fields [$orders.id
[:field %products.title {:join-alias join-alias}]]
:limit 4})]
(doseq [[location metadata] {"data.cols" (mt/cols results)
"data.results_metadata.columns" (get-in results [:data :results_metadata :columns])}]
(testing location
(is (= (mt/$ids
[{:display_name "ID"
:field_ref $orders.id}
(merge
{:display_name (str join-alias " → Title")
:field_ref [:field %products.title {:join-alias join-alias}]}
(when (= location "data.cols")
{:source_alias join-alias}))])
(map
#(select-keys % [:display_name :field_ref :source_alias])
metadata))))))))))
|
6b02bf482b579776860a6975f167c515ef885d3464b07d59a6cc908bd1c594f4 | nibbula/yew | where.lisp | ;;;
;;; where.lisp - Where command.
;;;
(defpackage :where
(:documentation "Where command.")
(:use :cl :dlib :collections #| :where-is |#)
(:export
#:where
))
(in-package :where)
(defun where (predicate sequence)
"Return the items from sequence for which predicate returns true.
Predicate can be a function of one argument, or a list which which is the body
of a function of the argument ‘_’. If sequence is NIL, do where like a verb
invoking where-is:what-where."
(flet ((where-what (p s)
(when (find-package :where-is)
(symbol-call :where-is :where-what p s))))
(if sequence
(etypecase predicate
(cons
(dbugf :where "List predicate ~s~%" predicate)
(opick (eval `(lambda (_)
(declare (ignorable _))
,predicate))
sequence))
(function
(dbugf :where "function predicate ~s~%" predicate)
(opick predicate sequence))
(symbol
(dbugf :where "symbol predicate ~s~%" predicate)
(case (intern (string predicate) :where)
((is am)
(dbugf :where "-> ~s ~s~%" (make-symbol (symbol-name predicate))
sequence)
(where-what predicate sequence))
(otherwise
(opick predicate sequence)))))
(where-what predicate sequence))))
;; End
| null | https://raw.githubusercontent.com/nibbula/yew/a62473dae637fb33a92aa75f260bf77b34cdbcfd/los/where.lisp | lisp |
where.lisp - Where command.
:where-is
End |
(defpackage :where
(:documentation "Where command.")
(:export
#:where
))
(in-package :where)
(defun where (predicate sequence)
"Return the items from sequence for which predicate returns true.
Predicate can be a function of one argument, or a list which which is the body
of a function of the argument ‘_’. If sequence is NIL, do where like a verb
invoking where-is:what-where."
(flet ((where-what (p s)
(when (find-package :where-is)
(symbol-call :where-is :where-what p s))))
(if sequence
(etypecase predicate
(cons
(dbugf :where "List predicate ~s~%" predicate)
(opick (eval `(lambda (_)
(declare (ignorable _))
,predicate))
sequence))
(function
(dbugf :where "function predicate ~s~%" predicate)
(opick predicate sequence))
(symbol
(dbugf :where "symbol predicate ~s~%" predicate)
(case (intern (string predicate) :where)
((is am)
(dbugf :where "-> ~s ~s~%" (make-symbol (symbol-name predicate))
sequence)
(where-what predicate sequence))
(otherwise
(opick predicate sequence)))))
(where-what predicate sequence))))
|
e01490fe0c689575b79bceffe05ff11dd7552dcc9f59836c3754d54284ed8fca | souenzzo/souenzzo.github.io | rgt.cljc | (ns br.com.souenzzo.rgt
(:require [clojure.string :as string])
#?(:clj (:import (clojure.lang Keyword))))
(defn render-properties
[attr]
(let [kvs (for [[k v] (dissoc attr :key :on-click)
:when (some? v)]
[(name k) (pr-str v)])]
(when (seq kvs)
(string/join " " (cons ""
(for [[k v] kvs]
(str k "=" v)))))))
(defn render-to-static-markup
[v]
(cond
(coll? v) (let [[tag & [attr & others :as raw-body]] v
attr? (map? attr)
body (if attr?
others
raw-body)]
(cond
(keyword? tag) (let [tag (name tag)]
(string/join
(concat
["<" tag
(render-properties (when attr?
attr))
">"]
(map render-to-static-markup body)
["</" tag ">"])))
(fn? tag) (render-to-static-markup (apply tag raw-body))
:else (string/join (map render-to-static-markup v))))
:else (str v)))
| null | https://raw.githubusercontent.com/souenzzo/souenzzo.github.io/30a811c4e5633ad07bba1d58d19eb091dac222e9/projects/rgt/src/br/com/souenzzo/rgt.cljc | clojure | (ns br.com.souenzzo.rgt
(:require [clojure.string :as string])
#?(:clj (:import (clojure.lang Keyword))))
(defn render-properties
[attr]
(let [kvs (for [[k v] (dissoc attr :key :on-click)
:when (some? v)]
[(name k) (pr-str v)])]
(when (seq kvs)
(string/join " " (cons ""
(for [[k v] kvs]
(str k "=" v)))))))
(defn render-to-static-markup
[v]
(cond
(coll? v) (let [[tag & [attr & others :as raw-body]] v
attr? (map? attr)
body (if attr?
others
raw-body)]
(cond
(keyword? tag) (let [tag (name tag)]
(string/join
(concat
["<" tag
(render-properties (when attr?
attr))
">"]
(map render-to-static-markup body)
["</" tag ">"])))
(fn? tag) (render-to-static-markup (apply tag raw-body))
:else (string/join (map render-to-static-markup v))))
:else (str v)))
|
|
139c3538e98ac737c2a1bc4f6d5f05bf3f57c42f270970a7004dad9d2d938227 | weyrick/roadsend-php | php-skeleton.scm | ;; ***** BEGIN LICENSE BLOCK *****
Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2008 Roadsend , Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation ; either version 2.1
of the License , or ( at your option ) any later version .
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
;;
You should have received a copy of the GNU Lesser General Public License
;; along with this program; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
;; ***** END LICENSE BLOCK *****
(module php-skeleton-lib
; required
(include "../phpoo-extension.sch")
(library profiler)
; import any required modules here, e.g. c bindings
(import
(skeleton-c-bindings "c-bindings.scm"))
;
list of exports . should include all defbuiltin and defconstant
;
(export
(init-php-skeleton-lib)
;
SKELETON_CONST
;
(skel_hello_world var1)
(skel_hash str int)
;
))
;
; this procedure needs to exist, but it need not
do much ( normally just returns 1 ) .
;
(define (init-php-skeleton-lib) 1)
; all top level statements are run on module initialization
; here we will initalize our builtin class
(create-skeleton-class)
; register the extension. required. note: version is not checked anywhere right now
extension title , shown in e.g. ( )
"1.0.0" ; version
"skeleton") ; library name. make sure this matches LIBNAME in Makefile
;
; this is how you can define a PHP resource. these are
; opaque objects in PHP, like a socket or database connection
; defresource is mostly a wrapper for define-struct.
" Sample Resource " is the string this object coerces to
; in php land, if you try to print it
;
( - resource " Sample Resource "
; field1
field2 )
;
; if you use resources, you should use some code like that below
; which handles resource finalization. see the mysql extension,
; for example
;
; (define *resource-counter* 0)
; (define (make-finalized-resource)
( when ( > * resource - counter * 255 ) ; an arbitrary constant which may be a php.ini entry
( gc - force - finalization ( lambda ( ) ( < = * resource - counter * 255 ) ) ) )
; (let ((new-resource (php-skel-resource 1 2)))
( set ! * resource - counter * ( + fx * resource - counter * 1 ) )
; (register-finalizer! new-resource (lambda (res)
; ; some theoretical procedure that closes the resource properly
; (resource-cleanup res)
( set ! * resource - counter * ( - * resource - counter * 1 ) ) ) ) )
; new-resource)
PHP TYPES ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
;
; Bigloo itself supports a variety of types, but the only ones we
; use in PHP land are: string, boolean, onum, php-hash and php-object
;
; You can use the normal bigloo functions for dealing with strings
; and booleans:
;
; string?
; boolean?
; make-string
; string=?
; substring
; ... etc
;
; Otherwise we have to do type juggling. If a bigloo type winds up
; in php land (such as a fixnum (bint) or #unspecified), it will
; show up strange when coerced to a string (i.e. ":ufo:") and may cause
; calculations to fail in general.
;
; "onum" is an "opaque number" and represents all numbers in php land.
; it follows zend's semantics for overflowing an integer into a float. you
; can use: onum-long? and onum-float? to see which it is
;
; You should use php versions of some normal scheme functions when
; dealing with php types. See runtime/php-types.scm and runtime/php-operators.scm
;
; Some commonly used functions:
;
; php-null? php-empty? php-hash? php-object? php-number?
;
php-+ php-- php-= php- * php-%
;
;
; There are a few constants that should be used as well:
;
; NULL
; TRUE
; FALSE
* zero *
* one *
;
;;;;;;;;;;;;
;
; NOTE: You should coerce all input variables and return values to the required PHP type
;
; convert-to-number - returns an onum, may be long or float depending on input
; convert-to-float - returns an onum, forces float
; convert-to-integer - returns an onum, forces integer
; convert-to-boolean - returns boolean
convert - to - string - returns string ( also see )
;
;;;;;
;;;;;;;;;;;;;;;;;;;;;;; LOCAL FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Normal scheme procedures created with define are not callable by
; PHP scripts.
;
;
; here we have a scheme procedure that's run on init, which creates
; a builtin php object
;
(define (create-skeleton-class)
; define a "builtin" class or interface. interfaces are simply abstract
; classes, but the 'interface flag should be used so the object system
; knows it is implementable
;
; a builtin class means it is always available while this extension is loaded,
; and it doesn't disappear at runtime reset
; note that for class/interface names, property names and method names, case
; will be kept but only properties are actually case sensitive
; class or interface defition. note that parent classes and interfaces should be defined
; first if the class will extend any
(define-builtin-php-class 'Skeleton ; class name. a symbol
extends , a list of one entry , a symbol
'() ; implements, a list of symbols
'() ; flags: abstract, interface, final
)
; define a class property
(define-php-property 'Skeleton ; the class name. a symbol.
"message" ; the property name. a string.
"default message" ; default value, a string or other php type (e.g. NULL)
visibility , one of : public , private , protected
#f ; static?
)
; define a php class method
(define-php-method 'Skeleton ; the class name, a symbol.
"__construct" ; method name, a string.
'(public) ; flags: public, private, protected, final, abstract
Skeleton:__construct ; scheme procedure that implements this method (see below)
)
)
;
Skeleton::__construct
;
; This is the scheme procedure that implements the "__construct" method for
the Skeleton class , as defined in define - php - method above . The procedure
name is arbitrary , but the arguments must be handled as shown . The first
; parameter will always be $this, which will always be a php-object or NULL
; for static methods.
;
; optional-args is a list of possible arguments that were passed into the method.
this method looks for two arguments , message and code .
;
(define (Skeleton:__construct this-unboxed . optional-args)
(let ((message '())
(code '()))
; do we have arguments passed in?
(when (pair? optional-args)
yes , the first is message . save it and shift the argument list .
(set! message
(maybe-unbox (car optional-args)))
(set! optional-args (cdr optional-args)))
; do we have another argument?
(when (pair? optional-args)
; yes, save it as code. we aren't looking for any more,
; so don't bother with a shift
(set! code
(maybe-unbox (car optional-args))))
;
; if the arguments now have a value, set our local properties
; note that 'all means we don't do a visibility check
;
(when message
(php-object-property-set!/string this-unboxed "message" message 'all))
(when code
(php-object-property-set!/string this-unboxed "code" code 'all))))
;;;;;;;;;;;;;;;
; a little function to compute x^n. not we don't do type conversion
here , we assume it 's done by our defbuiltin caller . that means
we 're just using 's fixnums here . we 've added type annotation
to that effect (: : )
(define (my-little-expt x::bint n::bint)
(expt x n))
;;;;;;;;;;;;;;;; PHP VISIBLE BUILTIN FUNCTIONS ;;;;;;;;;;;;;;;;;;;
;
Functions created with the defbuiltin macro are visible to
; PHP scripts
;
;
defbuiltin creates a builtin php function
;
take one parameter , echo it with a worldly greeting
(defbuiltin (skel_hello_world var1)
one way to do debugging : add a debug - trace . the first parameter
; is the required debug level for the output to be shown (via -d)
;
(debug-trace 1 "this is a debug message, shown at level 1. var1 is: " var1)
;
(echo (mkstr "hello world" var1)))
take two parameters and return a hash with two entries ,
; one for each parameter. we'll force str to be a string,
; and int to be a number
(defbuiltin (skel_hash str int)
(let ((result (make-php-hash)))
; :next is a special key which will use the next available int key
; mkstr coerces to a string
; convert-to-number coerces to a php number (onum)
(php-hash-insert! result :next (mkstr str))
(php-hash-insert! result :next (convert-to-number str))
; we can also specify a string key
(php-hash-insert! result "somekey" "some value")
result))
; this function uses our help scheme function above
; note that we do the type conversions here, and there is no
type annotation for defbuiltin parameters . also , we have to
; not only convert the parameters, but the return value!
(defbuiltin (skel_expt x n)
; mkfixnum makes a bigloo fixnum (bint)
; it should only be used be calling bigloo functions
; that require it, otherwise stick with onum (php numbers)
or
(let ((real-x (mkfixnum x))
(real-n (mkfixnum n)))
; convert-to-number ensures we return a php number (onum)
; see definition on my-little-expt in LOCAL FUNCTIONS section above
(convert-to-number (my-little-expt real-x real-n))))
;;;;;;;;;;;;;;;;;;;;; PHP VISIBLE CONSTANTS ;;;;;;;;;;;;;;;;;;;;;
;
; Constants created with the defconstant macro are visible to
; PHP scripts
;
;
; defconstant creates a builtin constant
; note, values are automatically coerced to php types
;
(defconstant SKELETON_CONST 0)
| null | https://raw.githubusercontent.com/weyrick/roadsend-php/d6301a897b1a02d7a85bdb915bea91d0991eb158/runtime/ext/skeleton/php-skeleton.scm | scheme | ***** BEGIN LICENSE BLOCK *****
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
either version 2.1
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program; if not, write to the Free Software
***** END LICENSE BLOCK *****
required
import any required modules here, e.g. c bindings
this procedure needs to exist, but it need not
all top level statements are run on module initialization
here we will initalize our builtin class
register the extension. required. note: version is not checked anywhere right now
version
library name. make sure this matches LIBNAME in Makefile
this is how you can define a PHP resource. these are
opaque objects in PHP, like a socket or database connection
defresource is mostly a wrapper for define-struct.
in php land, if you try to print it
field1
if you use resources, you should use some code like that below
which handles resource finalization. see the mysql extension,
for example
(define *resource-counter* 0)
(define (make-finalized-resource)
an arbitrary constant which may be a php.ini entry
(let ((new-resource (php-skel-resource 1 2)))
(register-finalizer! new-resource (lambda (res)
; some theoretical procedure that closes the resource properly
(resource-cleanup res)
new-resource)
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
Bigloo itself supports a variety of types, but the only ones we
use in PHP land are: string, boolean, onum, php-hash and php-object
You can use the normal bigloo functions for dealing with strings
and booleans:
string?
boolean?
make-string
string=?
substring
... etc
Otherwise we have to do type juggling. If a bigloo type winds up
in php land (such as a fixnum (bint) or #unspecified), it will
show up strange when coerced to a string (i.e. ":ufo:") and may cause
calculations to fail in general.
"onum" is an "opaque number" and represents all numbers in php land.
it follows zend's semantics for overflowing an integer into a float. you
can use: onum-long? and onum-float? to see which it is
You should use php versions of some normal scheme functions when
dealing with php types. See runtime/php-types.scm and runtime/php-operators.scm
Some commonly used functions:
php-null? php-empty? php-hash? php-object? php-number?
There are a few constants that should be used as well:
NULL
TRUE
FALSE
NOTE: You should coerce all input variables and return values to the required PHP type
convert-to-number - returns an onum, may be long or float depending on input
convert-to-float - returns an onum, forces float
convert-to-integer - returns an onum, forces integer
convert-to-boolean - returns boolean
LOCAL FUNCTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;
Normal scheme procedures created with define are not callable by
PHP scripts.
here we have a scheme procedure that's run on init, which creates
a builtin php object
define a "builtin" class or interface. interfaces are simply abstract
classes, but the 'interface flag should be used so the object system
knows it is implementable
a builtin class means it is always available while this extension is loaded,
and it doesn't disappear at runtime reset
note that for class/interface names, property names and method names, case
will be kept but only properties are actually case sensitive
class or interface defition. note that parent classes and interfaces should be defined
first if the class will extend any
class name. a symbol
implements, a list of symbols
flags: abstract, interface, final
define a class property
the class name. a symbol.
the property name. a string.
default value, a string or other php type (e.g. NULL)
static?
define a php class method
the class name, a symbol.
method name, a string.
flags: public, private, protected, final, abstract
scheme procedure that implements this method (see below)
This is the scheme procedure that implements the "__construct" method for
parameter will always be $this, which will always be a php-object or NULL
for static methods.
optional-args is a list of possible arguments that were passed into the method.
do we have arguments passed in?
do we have another argument?
yes, save it as code. we aren't looking for any more,
so don't bother with a shift
if the arguments now have a value, set our local properties
note that 'all means we don't do a visibility check
a little function to compute x^n. not we don't do type conversion
PHP VISIBLE BUILTIN FUNCTIONS ;;;;;;;;;;;;;;;;;;;
PHP scripts
is the required debug level for the output to be shown (via -d)
one for each parameter. we'll force str to be a string,
and int to be a number
:next is a special key which will use the next available int key
mkstr coerces to a string
convert-to-number coerces to a php number (onum)
we can also specify a string key
this function uses our help scheme function above
note that we do the type conversions here, and there is no
not only convert the parameters, but the return value!
mkfixnum makes a bigloo fixnum (bint)
it should only be used be calling bigloo functions
that require it, otherwise stick with onum (php numbers)
convert-to-number ensures we return a php number (onum)
see definition on my-little-expt in LOCAL FUNCTIONS section above
PHP VISIBLE CONSTANTS ;;;;;;;;;;;;;;;;;;;;;
Constants created with the defconstant macro are visible to
PHP scripts
defconstant creates a builtin constant
note, values are automatically coerced to php types
| Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2008 Roadsend , Inc.
of the License , or ( at your option ) any later version .
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
(module php-skeleton-lib
(include "../phpoo-extension.sch")
(library profiler)
(import
(skeleton-c-bindings "c-bindings.scm"))
list of exports . should include all defbuiltin and defconstant
(export
(init-php-skeleton-lib)
SKELETON_CONST
(skel_hello_world var1)
(skel_hash str int)
))
do much ( normally just returns 1 ) .
(define (init-php-skeleton-lib) 1)
(create-skeleton-class)
extension title , shown in e.g. ( )
" Sample Resource " is the string this object coerces to
( - resource " Sample Resource "
field2 )
( gc - force - finalization ( lambda ( ) ( < = * resource - counter * 255 ) ) ) )
( set ! * resource - counter * ( + fx * resource - counter * 1 ) )
( set ! * resource - counter * ( - * resource - counter * 1 ) ) ) ) )
php-+ php-- php-= php- * php-%
* zero *
* one *
convert - to - string - returns string ( also see )
(define (create-skeleton-class)
extends , a list of one entry , a symbol
)
visibility , one of : public , private , protected
)
)
)
Skeleton::__construct
the Skeleton class , as defined in define - php - method above . The procedure
name is arbitrary , but the arguments must be handled as shown . The first
this method looks for two arguments , message and code .
(define (Skeleton:__construct this-unboxed . optional-args)
(let ((message '())
(code '()))
(when (pair? optional-args)
yes , the first is message . save it and shift the argument list .
(set! message
(maybe-unbox (car optional-args)))
(set! optional-args (cdr optional-args)))
(when (pair? optional-args)
(set! code
(maybe-unbox (car optional-args))))
(when message
(php-object-property-set!/string this-unboxed "message" message 'all))
(when code
(php-object-property-set!/string this-unboxed "code" code 'all))))
here , we assume it 's done by our defbuiltin caller . that means
we 're just using 's fixnums here . we 've added type annotation
to that effect (: : )
(define (my-little-expt x::bint n::bint)
(expt x n))
Functions created with the defbuiltin macro are visible to
defbuiltin creates a builtin php function
take one parameter , echo it with a worldly greeting
(defbuiltin (skel_hello_world var1)
one way to do debugging : add a debug - trace . the first parameter
(debug-trace 1 "this is a debug message, shown at level 1. var1 is: " var1)
(echo (mkstr "hello world" var1)))
take two parameters and return a hash with two entries ,
(defbuiltin (skel_hash str int)
(let ((result (make-php-hash)))
(php-hash-insert! result :next (mkstr str))
(php-hash-insert! result :next (convert-to-number str))
(php-hash-insert! result "somekey" "some value")
result))
type annotation for defbuiltin parameters . also , we have to
(defbuiltin (skel_expt x n)
or
(let ((real-x (mkfixnum x))
(real-n (mkfixnum n)))
(convert-to-number (my-little-expt real-x real-n))))
(defconstant SKELETON_CONST 0)
|
fa0c671a6efc81c4d7a6cf1b95dfb1f97e98ba0b0ea3aee3b119ee59a17eef74 | aeden/learn-you-some-erlang | event.erl | -module(event).
-compile(export_all).
-record(state, {server,
name="",
to_go=0}).
loop(S = #state{server=Server, to_go=[T|Next]}) ->
receive
{Server, Ref, cancel} ->
Server ! {Ref, ok}
after T*1000 ->
if Next =:= [] ->
Server ! {done, S#state.name};
Next =/= [] ->
loop(S#state{to_go=Next})
end
end.
normalize(N) ->
Limit = 49*24*60*60,
[N rem Limit | lists:duplicate(N div Limit, Limit)].
start(EventName, Delay) ->
spawn(?MODULE, init, [self(), EventName, Delay]).
start_link(EventName, Delay) ->
spawn_link(?MODULE, init, [self(), EventName, Delay]).
cancel(Pid) ->
Ref = erlang:monitor(process, Pid),
Pid ! {self(), Ref, cancel},
receive
{Ref, ok} ->
erlang:demonitor(Ref, [flush]),
ok;
{'DOWN', Ref, process, Pid, _Reason} ->
ok
end.
%%% Event's innards
init(Server, EventName, DateTime) ->
loop(#state{server=Server,
name=EventName,
to_go=time_to_go(DateTime)}).
time_to_go(TimeOut={{_, _, _}, {_,_,_}}) ->
Now = calendar:local_time(),
ToGo = calendar:datetime_to_gregorian_seconds(TimeOut) - calendar:datetime_to_gregorian_seconds(Now),
Secs = if ToGo > 0 -> ToGo;
ToGo =< 0 -> 0
end,
normalize(Secs).
| null | https://raw.githubusercontent.com/aeden/learn-you-some-erlang/b72efc8617de7ec129cc31e5d504aa0bac7964ea/event_app/src/event.erl | erlang | Event's innards | -module(event).
-compile(export_all).
-record(state, {server,
name="",
to_go=0}).
loop(S = #state{server=Server, to_go=[T|Next]}) ->
receive
{Server, Ref, cancel} ->
Server ! {Ref, ok}
after T*1000 ->
if Next =:= [] ->
Server ! {done, S#state.name};
Next =/= [] ->
loop(S#state{to_go=Next})
end
end.
normalize(N) ->
Limit = 49*24*60*60,
[N rem Limit | lists:duplicate(N div Limit, Limit)].
start(EventName, Delay) ->
spawn(?MODULE, init, [self(), EventName, Delay]).
start_link(EventName, Delay) ->
spawn_link(?MODULE, init, [self(), EventName, Delay]).
cancel(Pid) ->
Ref = erlang:monitor(process, Pid),
Pid ! {self(), Ref, cancel},
receive
{Ref, ok} ->
erlang:demonitor(Ref, [flush]),
ok;
{'DOWN', Ref, process, Pid, _Reason} ->
ok
end.
init(Server, EventName, DateTime) ->
loop(#state{server=Server,
name=EventName,
to_go=time_to_go(DateTime)}).
time_to_go(TimeOut={{_, _, _}, {_,_,_}}) ->
Now = calendar:local_time(),
ToGo = calendar:datetime_to_gregorian_seconds(TimeOut) - calendar:datetime_to_gregorian_seconds(Now),
Secs = if ToGo > 0 -> ToGo;
ToGo =< 0 -> 0
end,
normalize(Secs).
|
6ae1a0d35b9880b8ee23a590845f1ead13c11e448b03cf2d1c4e1054305433bc | kloimhardt/clj-tiles | tutorials_advent1.cljs | (ns cljtiles.tutorials-advent1
(:require [cljtiles.codeexplode :as explode]
[clojure.string :as str]
[cljtiles.utils :as utils]
[cljs.reader :as edn]
[clojure.walk :as walk]))
(defn read-tuts [txt]
(let [src-split-1 (str/split (str txt "\n") #"\#\+end_src")
re-merge (fn [txtvec inter]
(map #(apply str %)
(partition-all 2 (interpose inter txtvec))))
descriptions (re-merge src-split-1 "#+end_src")
src-split (map #(str/split % #"\#\+begin_src clojure")
src-split-1)
names (->> src-split
(map first)
(map #(some-> (second (str/split % #"\#\+name: ")) str/trim)))
headers-code (->> src-split
(map last)
(map #(utils/twosplit % "\n"))
(butlast))]
(map (fn [name [header src] desc]
{:name name :header header :src src :description desc})
names headers-code descriptions)))
(defn normal-read-string [s]
(edn/read-string (str "[" s "]")))
(defn extended-read-string [s]
(let [nl #{:n1956214 :n2176543} ;;some random keywords used as marker
nls (str " " (apply str (interpose " " nl)) " ")
a (str/replace s #";.*?\n" "") ;;remove comment lines
b (str/replace a #"\n" nls)
c (normal-read-string b)]
(->> (into [] (remove nl c)) ;;remove last newline
(walk/postwalk (fn [x]
(if (and (coll? x) (some nl x))
(list :tiles/vert
(utils/list-into-same-coll x
(remove nl x)))
x))))))
(defn tuts-edn [tuts-txt]
(map #(assoc % :code (extended-read-string (:src %))) tuts-txt))
(defn replace-reference [tuts-edn]
(let [name-map (into {}
(comp (filter :name)
(map (juxt :name identity)))
tuts-edn)
middle (fn [s] (subs (subs s 2) 0 (- (count s) 4)))]
(map #(let [frs (str (first (:code %)))]
(if (str/starts-with? frs "<<")
(let [ref (get name-map (middle frs))]
(-> %
(assoc :code (:code ref))
(assoc :src (:src ref))))
%))
tuts-edn)))
(defn smuggle-shadow [tuts-map]
(butlast
(reduce (fn [acc {:keys [header src description] :as tut}]
(let [last (peek acc)
vcoll (pop acc)]
(if (str/ends-with? header ":exports none")
(conj vcoll (-> last
(update :shadow #((fnil conj []) % src))
(update :shadow-description #((fnil conj []) % description))))
(-> vcoll
(conj (merge last tut))
(conj {})))))
[{}] tuts-map)))
(defn replace-inline-tex [s]
(let [new-str-fn #(str (first %) "\\(" (subs (subs % 2) 0 (- (count %) 4)) "\\)" (last %))]
(-> s
(str/replace #"[\. ,\n]\$\S+?\$[\. ,\n:]" new-str-fn)
(str/replace #"[\. ,\n]\$\S+ = \S+?\$[\. ,\n:]" new-str-fn)
(str/replace #"[\. ,\n]\$\S+ \S+?\$[\. ,\n:]" new-str-fn))))
(defn format-description [tuts-mapvec]
(let [descvec (->> tuts-mapvec
(map (fn [d]
(str (apply str (:shadow-description d))
(:description d)))))
pre-and-p (->> descvec
(map #(str/split % #"\n\n"))
(map #(into [:div]
(map (fn [[previ prg]]
(cond
(str/starts-with? prg "#+RESULTS") nil
(str/starts-with? prg "#+STARTUP") nil
(str/starts-with? prg "#+PROPERTY") nil
(str/starts-with? prg "#+begin_src clojure :exports none") nil
(and (str/starts-with? previ "#+begin_src clojure :exports none")
(str/starts-with? (last (str/split prg #"\n")) "#+end_src"))
nil
(str/starts-with? prg "#+") [:pre prg]
(str/starts-with? (last (str/split prg #"\n")) "#+") [:pre prg]
(str/starts-with? prg "* ")
[:h1 (replace-inline-tex (subs (first (str/split prg #"\n")) 2))]
(str/starts-with? prg "** ")
[:h2 (replace-inline-tex (subs (first (str/split prg #"\n")) 3))]
:else
[:p (replace-inline-tex prg)]))
(partition 2 1 (cons "" %))))))]
(map #(assoc %1 :description %2) tuts-mapvec pre-and-p)))
(defn calc-y-for-solution [edn-code]
(let [summit (fn [xs]
(reduce (fn [acc x]
(conj acc (+ (peek acc) x)))
[] xs))]
(->> edn-code
(map (fn [cd]
(inc (count (filter #{:tiles/vert} (flatten cd))))))
(cons 0)
summit
(map (fn [y] [(* y 75) 0])))))
(defn explode-all [tuts-mapvec]
(map #(-> %
(assoc :solpos-yx (calc-y-for-solution (:code %)))
(assoc :solution (:code %))
(dissoc :name)
(dissoc :header)
(merge (explode/explode (:code %) nil)))
tuts-mapvec))
(defn generate-content [txt chapname]
(let [tuts (->> txt
(read-tuts)
(tuts-edn)
(replace-reference)
(smuggle-shadow)
(format-description)
(explode-all))
tuts-with-end (concat tuts [{:description [:p "End of chapter"] :solution ["End of Chapter"] :code ["End of Chapter"]}])]
{:tutorials tuts-with-end :chapnames [chapname] :chaps [(count tuts-with-end)]}))
| null | https://raw.githubusercontent.com/kloimhardt/clj-tiles/18c2e06886cc8131ef694ec92dcabf2c78af2462/src/cljtiles/tutorials_advent1.cljs | clojure | some random keywords used as marker
remove comment lines
remove last newline | (ns cljtiles.tutorials-advent1
(:require [cljtiles.codeexplode :as explode]
[clojure.string :as str]
[cljtiles.utils :as utils]
[cljs.reader :as edn]
[clojure.walk :as walk]))
(defn read-tuts [txt]
(let [src-split-1 (str/split (str txt "\n") #"\#\+end_src")
re-merge (fn [txtvec inter]
(map #(apply str %)
(partition-all 2 (interpose inter txtvec))))
descriptions (re-merge src-split-1 "#+end_src")
src-split (map #(str/split % #"\#\+begin_src clojure")
src-split-1)
names (->> src-split
(map first)
(map #(some-> (second (str/split % #"\#\+name: ")) str/trim)))
headers-code (->> src-split
(map last)
(map #(utils/twosplit % "\n"))
(butlast))]
(map (fn [name [header src] desc]
{:name name :header header :src src :description desc})
names headers-code descriptions)))
(defn normal-read-string [s]
(edn/read-string (str "[" s "]")))
(defn extended-read-string [s]
nls (str " " (apply str (interpose " " nl)) " ")
b (str/replace a #"\n" nls)
c (normal-read-string b)]
(walk/postwalk (fn [x]
(if (and (coll? x) (some nl x))
(list :tiles/vert
(utils/list-into-same-coll x
(remove nl x)))
x))))))
(defn tuts-edn [tuts-txt]
(map #(assoc % :code (extended-read-string (:src %))) tuts-txt))
(defn replace-reference [tuts-edn]
(let [name-map (into {}
(comp (filter :name)
(map (juxt :name identity)))
tuts-edn)
middle (fn [s] (subs (subs s 2) 0 (- (count s) 4)))]
(map #(let [frs (str (first (:code %)))]
(if (str/starts-with? frs "<<")
(let [ref (get name-map (middle frs))]
(-> %
(assoc :code (:code ref))
(assoc :src (:src ref))))
%))
tuts-edn)))
(defn smuggle-shadow [tuts-map]
(butlast
(reduce (fn [acc {:keys [header src description] :as tut}]
(let [last (peek acc)
vcoll (pop acc)]
(if (str/ends-with? header ":exports none")
(conj vcoll (-> last
(update :shadow #((fnil conj []) % src))
(update :shadow-description #((fnil conj []) % description))))
(-> vcoll
(conj (merge last tut))
(conj {})))))
[{}] tuts-map)))
(defn replace-inline-tex [s]
(let [new-str-fn #(str (first %) "\\(" (subs (subs % 2) 0 (- (count %) 4)) "\\)" (last %))]
(-> s
(str/replace #"[\. ,\n]\$\S+?\$[\. ,\n:]" new-str-fn)
(str/replace #"[\. ,\n]\$\S+ = \S+?\$[\. ,\n:]" new-str-fn)
(str/replace #"[\. ,\n]\$\S+ \S+?\$[\. ,\n:]" new-str-fn))))
(defn format-description [tuts-mapvec]
(let [descvec (->> tuts-mapvec
(map (fn [d]
(str (apply str (:shadow-description d))
(:description d)))))
pre-and-p (->> descvec
(map #(str/split % #"\n\n"))
(map #(into [:div]
(map (fn [[previ prg]]
(cond
(str/starts-with? prg "#+RESULTS") nil
(str/starts-with? prg "#+STARTUP") nil
(str/starts-with? prg "#+PROPERTY") nil
(str/starts-with? prg "#+begin_src clojure :exports none") nil
(and (str/starts-with? previ "#+begin_src clojure :exports none")
(str/starts-with? (last (str/split prg #"\n")) "#+end_src"))
nil
(str/starts-with? prg "#+") [:pre prg]
(str/starts-with? (last (str/split prg #"\n")) "#+") [:pre prg]
(str/starts-with? prg "* ")
[:h1 (replace-inline-tex (subs (first (str/split prg #"\n")) 2))]
(str/starts-with? prg "** ")
[:h2 (replace-inline-tex (subs (first (str/split prg #"\n")) 3))]
:else
[:p (replace-inline-tex prg)]))
(partition 2 1 (cons "" %))))))]
(map #(assoc %1 :description %2) tuts-mapvec pre-and-p)))
(defn calc-y-for-solution [edn-code]
(let [summit (fn [xs]
(reduce (fn [acc x]
(conj acc (+ (peek acc) x)))
[] xs))]
(->> edn-code
(map (fn [cd]
(inc (count (filter #{:tiles/vert} (flatten cd))))))
(cons 0)
summit
(map (fn [y] [(* y 75) 0])))))
(defn explode-all [tuts-mapvec]
(map #(-> %
(assoc :solpos-yx (calc-y-for-solution (:code %)))
(assoc :solution (:code %))
(dissoc :name)
(dissoc :header)
(merge (explode/explode (:code %) nil)))
tuts-mapvec))
(defn generate-content [txt chapname]
(let [tuts (->> txt
(read-tuts)
(tuts-edn)
(replace-reference)
(smuggle-shadow)
(format-description)
(explode-all))
tuts-with-end (concat tuts [{:description [:p "End of chapter"] :solution ["End of Chapter"] :code ["End of Chapter"]}])]
{:tutorials tuts-with-end :chapnames [chapname] :chaps [(count tuts-with-end)]}))
|
e09f1dfbb4e10a932cb42dd6a3c5bb0ba13da6595efbeeb066493f9d5649f279 | wdebeaum/step | boxer.lisp | ;;;;
;;;; w::boxer
;;;;
(define-words :pos W::n
:words (
((w::boxer w::shorts)
(senses
((LF-PARENT ONT::attire)
(meta-data :origin caloy3 :entry-date 20070330 :change-date nil :comments nil)
;(TEMPL mass-PRED-TEMPL)
(TEMPL COUNT-PRED-3p-TEMPL)
(syntax (W::morph (:forms (-none))))
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/boxer.lisp | lisp |
w::boxer
(TEMPL mass-PRED-TEMPL) |
(define-words :pos W::n
:words (
((w::boxer w::shorts)
(senses
((LF-PARENT ONT::attire)
(meta-data :origin caloy3 :entry-date 20070330 :change-date nil :comments nil)
(TEMPL COUNT-PRED-3p-TEMPL)
(syntax (W::morph (:forms (-none))))
)
)
)
))
|
a1a1b93d9b3488c806b22ee576b91a2a46da2fc8c381b80e8d2d046704e90f64 | rescript-lang/rescript-compiler | belt_Option.mli | Copyright ( C ) 2017 Authors of ReScript
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
*
In Belt we represent the existence and nonexistence of a value by wrapping it
with the ` option ` type . In order to make it a bit more convenient to work with
option - types , Belt provides utility - functions for it .
The ` option ` type is a part of the standard library which is defined like this :
` ` ` res sig
type option<'a > = None | Some('a )
` ` `
` ` ` res example
let someString : option < string > = Some("hello " )
` ` `
In Belt we represent the existence and nonexistence of a value by wrapping it
with the `option` type. In order to make it a bit more convenient to work with
option-types, Belt provides utility-functions for it.
The `option` type is a part of the ReScript standard library which is defined like this:
```res sig
type option<'a> = None | Some('a)
```
```res example
let someString: option<string> = Some("hello")
```
*)
val keepU : 'a option -> ('a -> bool [@bs]) -> 'a option
* version of ` keep `
val keep : 'a option -> ('a -> bool) -> 'a option
*
If ` optionValue ` is ` Some(value ) ` and ` p(value ) = true ` , it returns ` Some(value ) ` ; otherwise returns ` None `
` ` ` res example
Belt . Option.keep(Some(10 ) , x = > x > 5 ) / * returns ` Some(10 ) ` * /
Belt . ) , x = > x > 5 ) / * returns ` None ` * /
Belt . Option.keep(None , x = > x > 5 ) / * returns ` None ` * /
` ` `
If `optionValue` is `Some(value)` and `p(value) = true`, it returns `Some(value)`; otherwise returns `None`
```res example
Belt.Option.keep(Some(10), x => x > 5) /* returns `Some(10)` */
Belt.Option.keep(Some(4), x => x > 5) /* returns `None` */
Belt.Option.keep(None, x => x > 5) /* returns `None` */
```
*)
val forEachU : 'a option -> ('a -> unit [@bs]) -> unit
* version of ` forEach `
val forEach : 'a option -> ('a -> unit) -> unit
*
If ` optionValue ` is ` Some(value ` ) , it calls ` f(value ) ` ; otherwise returns ` ( ) `
` ` ` res example
Belt . Option.forEach(Some("thing " ) , x = > Js.log(x ) ) / * logs " thing " * /
Belt . Option.forEach(None , x = > Js.log(x ) ) / * returns ( ) * /
` ` `
If `optionValue` is `Some(value`), it calls `f(value)`; otherwise returns `()`
```res example
Belt.Option.forEach(Some("thing"), x => Js.log(x)) /* logs "thing" */
Belt.Option.forEach(None, x => Js.log(x)) /* returns () */
```
*)
val getExn : 'a option -> 'a
*
Raises an Error in case ` None ` is provided . Use with care .
` ` ` res example
Belt . Option.getExn(Some(3 ) ) / * 3 * /
Belt . Option.getExn(None ) / * Raises an Error * /
` ` `
Raises an Error in case `None` is provided. Use with care.
```res example
Belt.Option.getExn(Some(3)) /* 3 */
Belt.Option.getExn(None) /* Raises an Error */
```
*)
external getUnsafe :
'a option -> 'a = "%identity"
(**
`getUnsafe(x)` returns `x`
This is an unsafe operation, it assumes `x` is neither `None`
nor `Some(None(...)))`
*)
val mapWithDefaultU : 'a option -> 'b -> ('a -> 'b [@bs]) -> 'b
* version of ` mapWithDefault `
val mapWithDefault : 'a option -> 'b -> ('a -> 'b) -> 'b
*
If ` optionValue ` is of ` Some(value ) ` ,
this function returns that value applied with ` f ` , in other words ` f(value ) ` .
If ` optionValue ` is ` None ` , the default is returned .
` ` ` res example
let someValue = Some(3 )
someValue->Belt . Option.mapWithDefault(0 , x = > x + 5 ) / * 8 * /
let noneValue = None
noneValue->Belt . Option.mapWithDefault(0 , x = > x + 5 ) / * 0 * /
` ` `
If `optionValue` is of `Some(value)`,
this function returns that value applied with `f`, in other words `f(value)`.
If `optionValue` is `None`, the default is returned.
```res example
let someValue = Some(3)
someValue->Belt.Option.mapWithDefault(0, x => x + 5) /* 8 */
let noneValue = None
noneValue->Belt.Option.mapWithDefault(0, x => x + 5) /* 0 */
```
*)
val mapU : 'a option -> ('a -> 'b [@bs]) -> 'b option
* version of ` map `
val map : 'a option -> ('a -> 'b) -> 'b option
*
If ` optionValue ` is ` Some(value ) ` this returns ` f(value ) ` , otherwise it returns ` None ` .
` ` ` res example
Belt . ) , x = > x * x ) / * Some(9 ) * /
Belt . Option.map(None , x = > x * x ) / * None * /
` ` `
If `optionValue` is `Some(value)` this returns `f(value)`, otherwise it returns `None`.
```res example
Belt.Option.map(Some(3), x => x * x) /* Some(9) */
Belt.Option.map(None, x => x * x) /* None */
```
*)
val flatMapU : 'a option -> ('a -> 'b option [@bs]) -> 'b option
* version of ` flatMap `
val flatMap : 'a option -> ('a -> 'b option) -> 'b option
*
If ` optionValue ` is ` Some(value ) ` , returns ` f(value ) ` , otherwise returns
` None`.<br/ >
The function ` f ` must have a return type of ` option<'b > ` .
` ` ` res example
let addIfAboveOne = value = >
if ( value > 1 ) {
Some(value + 1 )
} else {
None
}
Belt . Option.flatMap(Some(2 ) , addIfAboveOne ) / * ) * /
Belt . Option.flatMap(Some(-4 ) , addIfAboveOne ) / * None * /
Belt . Option.flatMap(None , addIfAboveOne ) / * None * /
` ` `
If `optionValue` is `Some(value)`, returns `f(value)`, otherwise returns
`None`.<br/>
The function `f` must have a return type of `option<'b>`.
```res example
let addIfAboveOne = value =>
if (value > 1) {
Some(value + 1)
} else {
None
}
Belt.Option.flatMap(Some(2), addIfAboveOne) /* Some(3) */
Belt.Option.flatMap(Some(-4), addIfAboveOne) /* None */
Belt.Option.flatMap(None, addIfAboveOne) /* None */
```
*)
val getWithDefault : 'a option -> 'a -> 'a
*
If ` optionalValue ` is ` Some(value ) ` , returns ` value ` , otherwise default .
` ` ` res example
Belt . Option.getWithDefault(None , " Banana " ) / * Banana * /
Belt . Option.getWithDefault(Some("Apple " ) , " Banana " ) / * Apple * /
` ` `
` ` ` res example
let greet = ( firstName : option < string > ) = >
" Greetings " + + firstName->Belt . Option.getWithDefault("Anonymous " )
Some("Jane")->greet / * " Greetings " * /
None->greet / * " Greetings Anonymous " * /
` ` `
If `optionalValue` is `Some(value)`, returns `value`, otherwise default.
```res example
Belt.Option.getWithDefault(None, "Banana") /* Banana */
Belt.Option.getWithDefault(Some("Apple"), "Banana") /* Apple */
```
```res example
let greet = (firstName: option<string>) =>
"Greetings " ++ firstName->Belt.Option.getWithDefault("Anonymous")
Some("Jane")->greet /* "Greetings Jane" */
None->greet /* "Greetings Anonymous" */
```
*)
val orElse : 'a option -> 'a option -> 'a option
*
` orElse optionalValue otherOptional `
If ` optionalValue ` is ` Some value ` , returns ` Some value ` , otherwise ` otherOptional `
` ` `
orElse ( Some 1812 ) ( Some 1066 ) = Some 1812 ; ;
orElse None ( Some 1066 ) = Some 1066 ; ;
orElse None None = None ; ;
` ` `
`orElse optionalValue otherOptional`
If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOptional`
```
orElse (Some 1812) (Some 1066) = Some 1812;;
orElse None (Some 1066) = Some 1066;;
orElse None None = None;;
```
*)
val isSome : 'a option -> bool
(**
Returns `true` if the argument is `Some(value)`, `false` otherwise.
```res example
Belt.Option.isSome(None) /* false */
Belt.Option.isSome(Some(1)) /* true */
```
*)
val isNone : 'a option -> bool
*
Returns ` true ` if the argument is ` None ` , ` false ` otherwise .
` ` ` res example
Belt . Option.isNone(None ) / * true * /
Belt . ) ) / * false * /
` ` `
Returns `true` if the argument is `None`, `false` otherwise.
```res example
Belt.Option.isNone(None) /* true */
Belt.Option.isNone(Some(1)) /* false */
```
*)
val eqU : 'a option -> 'b option -> ('a -> 'b -> bool [@bs]) -> bool
*
version of ` eq `
Uncurried version of `eq`
*)
val eq : 'a option -> 'b option -> ('a -> 'b -> bool) -> bool
*
Evaluates two optional values for equality with respect to a predicate
function . If both ` optValue1 ` and ` optValue2 ` are ` None ` , returns ` true ` .
If one of the arguments is ` Some(value ) ` and the other is ` None ` , returns
` false ` .
If arguments are ` Some(value1 ) ` and ` Some(value2 ) ` , returns the result of
` predicate(value1 , ) ` ; the predicate function must return a bool .
` ` ` res example
let clockEqual = ( a , b ) = > mod(a , 12 ) = = mod(b , 12 )
open Belt . Option
eq(Some(3 ) , Some(15 ) , clockEqual ) / * true * /
eq(Some(3 ) , None , clockEqual ) / * false * /
eq(None , Some(3 ) , clockEqual ) / * false * /
eq(None , None , clockEqual ) / * true * /
` ` `
Evaluates two optional values for equality with respect to a predicate
function. If both `optValue1` and `optValue2` are `None`, returns `true`.
If one of the arguments is `Some(value)` and the other is `None`, returns
`false`.
If arguments are `Some(value1)` and `Some(value2)`, returns the result of
`predicate(value1, value2)`; the predicate function must return a bool.
```res example
let clockEqual = (a, b) => mod(a, 12) == mod(b, 12)
open Belt.Option
eq(Some(3), Some(15), clockEqual) /* true */
eq(Some(3), None, clockEqual) /* false */
eq(None, Some(3), clockEqual) /* false */
eq(None, None, clockEqual) /* true */
```
*)
val cmpU : 'a option -> 'b option -> ('a -> 'b -> int [@bs]) -> int
* version of ` cmp `
val cmp : 'a option -> 'b option -> ('a -> 'b -> int) -> int
*
` cmp(optValue1 , optValue2 , comparisonFunction ) ` compares two optional values
with respect to given ` comparisonFunction ` .
If both ` optValue1 ` and ` optValue2 ` are ` None ` , it returns ` 0 ` .
If the first argument is ` Some(value1 ) ` and the second is ` None ` , returns ` 1 `
( something is greater than nothing ) .
If the first argument is ` None ` and the second is ` Some(value2 ) ` , returns ` -1 `
( nothing is less than something ) .
If the arguments are ` Some(value1 ) ` and ` Some(value2 ) ` , returns the result of
` comparisonFunction(value1 , value2 ) ` ; comparisonFunction takes two arguments
and returns ` -1 ` if the first argument is less than the second , ` 0 ` if the
arguments are equal , and ` 1 ` if the first argument is greater than the second .
` ` ` res example
let clockCompare = ( a , b ) = > compare(mod(a , 12 ) , mod(b , 12 ) )
open Belt . Option
cmp(Some(3 ) , Some(15 ) , clockCompare ) / * 0 * /
cmp(Some(3 ) , Some(14 ) , clockCompare ) / * 1 * /
cmp(Some(2 ) , Some(15 ) , clockCompare ) / * ( -1 ) * /
cmp(None , Some(15 ) , clockCompare ) / * ( -1 ) * /
cmp(Some(14 ) , None , clockCompare ) / * 1 * /
cmp(None , None , clockCompare ) / * 0 * /
` ` `
`cmp(optValue1, optValue2, comparisonFunction)` compares two optional values
with respect to given `comparisonFunction`.
If both `optValue1` and `optValue2` are `None`, it returns `0`.
If the first argument is `Some(value1)` and the second is `None`, returns `1`
(something is greater than nothing).
If the first argument is `None` and the second is `Some(value2)`, returns `-1`
(nothing is less than something).
If the arguments are `Some(value1)` and `Some(value2)`, returns the result of
`comparisonFunction(value1, value2)`; comparisonFunction takes two arguments
and returns `-1` if the first argument is less than the second, `0` if the
arguments are equal, and `1` if the first argument is greater than the second.
```res example
let clockCompare = (a, b) => compare(mod(a, 12), mod(b, 12))
open Belt.Option
cmp(Some(3), Some(15), clockCompare) /* 0 */
cmp(Some(3), Some(14), clockCompare) /* 1 */
cmp(Some(2), Some(15), clockCompare) /* (-1) */
cmp(None, Some(15), clockCompare) /* (-1) */
cmp(Some(14), None, clockCompare) /* 1 */
cmp(None, None, clockCompare) /* 0 */
```
*)
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/c3fcc430360079546a6aabd2b2770303480f8486/jscomp/others/belt_Option.mli | ocaml | *
`getUnsafe(x)` returns `x`
This is an unsafe operation, it assumes `x` is neither `None`
nor `Some(None(...)))`
*
Returns `true` if the argument is `Some(value)`, `false` otherwise.
```res example
Belt.Option.isSome(None) /* false */
Belt.Option.isSome(Some(1)) /* true */
```
| Copyright ( C ) 2017 Authors of ReScript
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
*
In Belt we represent the existence and nonexistence of a value by wrapping it
with the ` option ` type . In order to make it a bit more convenient to work with
option - types , Belt provides utility - functions for it .
The ` option ` type is a part of the standard library which is defined like this :
` ` ` res sig
type option<'a > = None | Some('a )
` ` `
` ` ` res example
let someString : option < string > = Some("hello " )
` ` `
In Belt we represent the existence and nonexistence of a value by wrapping it
with the `option` type. In order to make it a bit more convenient to work with
option-types, Belt provides utility-functions for it.
The `option` type is a part of the ReScript standard library which is defined like this:
```res sig
type option<'a> = None | Some('a)
```
```res example
let someString: option<string> = Some("hello")
```
*)
val keepU : 'a option -> ('a -> bool [@bs]) -> 'a option
* version of ` keep `
val keep : 'a option -> ('a -> bool) -> 'a option
*
If ` optionValue ` is ` Some(value ) ` and ` p(value ) = true ` , it returns ` Some(value ) ` ; otherwise returns ` None `
` ` ` res example
Belt . Option.keep(Some(10 ) , x = > x > 5 ) / * returns ` Some(10 ) ` * /
Belt . ) , x = > x > 5 ) / * returns ` None ` * /
Belt . Option.keep(None , x = > x > 5 ) / * returns ` None ` * /
` ` `
If `optionValue` is `Some(value)` and `p(value) = true`, it returns `Some(value)`; otherwise returns `None`
```res example
Belt.Option.keep(Some(10), x => x > 5) /* returns `Some(10)` */
Belt.Option.keep(Some(4), x => x > 5) /* returns `None` */
Belt.Option.keep(None, x => x > 5) /* returns `None` */
```
*)
val forEachU : 'a option -> ('a -> unit [@bs]) -> unit
* version of ` forEach `
val forEach : 'a option -> ('a -> unit) -> unit
*
If ` optionValue ` is ` Some(value ` ) , it calls ` f(value ) ` ; otherwise returns ` ( ) `
` ` ` res example
Belt . Option.forEach(Some("thing " ) , x = > Js.log(x ) ) / * logs " thing " * /
Belt . Option.forEach(None , x = > Js.log(x ) ) / * returns ( ) * /
` ` `
If `optionValue` is `Some(value`), it calls `f(value)`; otherwise returns `()`
```res example
Belt.Option.forEach(Some("thing"), x => Js.log(x)) /* logs "thing" */
Belt.Option.forEach(None, x => Js.log(x)) /* returns () */
```
*)
val getExn : 'a option -> 'a
*
Raises an Error in case ` None ` is provided . Use with care .
` ` ` res example
Belt . Option.getExn(Some(3 ) ) / * 3 * /
Belt . Option.getExn(None ) / * Raises an Error * /
` ` `
Raises an Error in case `None` is provided. Use with care.
```res example
Belt.Option.getExn(Some(3)) /* 3 */
Belt.Option.getExn(None) /* Raises an Error */
```
*)
external getUnsafe :
'a option -> 'a = "%identity"
val mapWithDefaultU : 'a option -> 'b -> ('a -> 'b [@bs]) -> 'b
* version of ` mapWithDefault `
val mapWithDefault : 'a option -> 'b -> ('a -> 'b) -> 'b
*
If ` optionValue ` is of ` Some(value ) ` ,
this function returns that value applied with ` f ` , in other words ` f(value ) ` .
If ` optionValue ` is ` None ` , the default is returned .
` ` ` res example
let someValue = Some(3 )
someValue->Belt . Option.mapWithDefault(0 , x = > x + 5 ) / * 8 * /
let noneValue = None
noneValue->Belt . Option.mapWithDefault(0 , x = > x + 5 ) / * 0 * /
` ` `
If `optionValue` is of `Some(value)`,
this function returns that value applied with `f`, in other words `f(value)`.
If `optionValue` is `None`, the default is returned.
```res example
let someValue = Some(3)
someValue->Belt.Option.mapWithDefault(0, x => x + 5) /* 8 */
let noneValue = None
noneValue->Belt.Option.mapWithDefault(0, x => x + 5) /* 0 */
```
*)
val mapU : 'a option -> ('a -> 'b [@bs]) -> 'b option
* version of ` map `
val map : 'a option -> ('a -> 'b) -> 'b option
*
If ` optionValue ` is ` Some(value ) ` this returns ` f(value ) ` , otherwise it returns ` None ` .
` ` ` res example
Belt . ) , x = > x * x ) / * Some(9 ) * /
Belt . Option.map(None , x = > x * x ) / * None * /
` ` `
If `optionValue` is `Some(value)` this returns `f(value)`, otherwise it returns `None`.
```res example
Belt.Option.map(Some(3), x => x * x) /* Some(9) */
Belt.Option.map(None, x => x * x) /* None */
```
*)
val flatMapU : 'a option -> ('a -> 'b option [@bs]) -> 'b option
* version of ` flatMap `
val flatMap : 'a option -> ('a -> 'b option) -> 'b option
*
If ` optionValue ` is ` Some(value ) ` , returns ` f(value ) ` , otherwise returns
` None`.<br/ >
The function ` f ` must have a return type of ` option<'b > ` .
` ` ` res example
let addIfAboveOne = value = >
if ( value > 1 ) {
Some(value + 1 )
} else {
None
}
Belt . Option.flatMap(Some(2 ) , addIfAboveOne ) / * ) * /
Belt . Option.flatMap(Some(-4 ) , addIfAboveOne ) / * None * /
Belt . Option.flatMap(None , addIfAboveOne ) / * None * /
` ` `
If `optionValue` is `Some(value)`, returns `f(value)`, otherwise returns
`None`.<br/>
The function `f` must have a return type of `option<'b>`.
```res example
let addIfAboveOne = value =>
if (value > 1) {
Some(value + 1)
} else {
None
}
Belt.Option.flatMap(Some(2), addIfAboveOne) /* Some(3) */
Belt.Option.flatMap(Some(-4), addIfAboveOne) /* None */
Belt.Option.flatMap(None, addIfAboveOne) /* None */
```
*)
val getWithDefault : 'a option -> 'a -> 'a
*
If ` optionalValue ` is ` Some(value ) ` , returns ` value ` , otherwise default .
` ` ` res example
Belt . Option.getWithDefault(None , " Banana " ) / * Banana * /
Belt . Option.getWithDefault(Some("Apple " ) , " Banana " ) / * Apple * /
` ` `
` ` ` res example
let greet = ( firstName : option < string > ) = >
" Greetings " + + firstName->Belt . Option.getWithDefault("Anonymous " )
Some("Jane")->greet / * " Greetings " * /
None->greet / * " Greetings Anonymous " * /
` ` `
If `optionalValue` is `Some(value)`, returns `value`, otherwise default.
```res example
Belt.Option.getWithDefault(None, "Banana") /* Banana */
Belt.Option.getWithDefault(Some("Apple"), "Banana") /* Apple */
```
```res example
let greet = (firstName: option<string>) =>
"Greetings " ++ firstName->Belt.Option.getWithDefault("Anonymous")
Some("Jane")->greet /* "Greetings Jane" */
None->greet /* "Greetings Anonymous" */
```
*)
val orElse : 'a option -> 'a option -> 'a option
*
` orElse optionalValue otherOptional `
If ` optionalValue ` is ` Some value ` , returns ` Some value ` , otherwise ` otherOptional `
` ` `
orElse ( Some 1812 ) ( Some 1066 ) = Some 1812 ; ;
orElse None ( Some 1066 ) = Some 1066 ; ;
orElse None None = None ; ;
` ` `
`orElse optionalValue otherOptional`
If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOptional`
```
orElse (Some 1812) (Some 1066) = Some 1812;;
orElse None (Some 1066) = Some 1066;;
orElse None None = None;;
```
*)
val isSome : 'a option -> bool
val isNone : 'a option -> bool
*
Returns ` true ` if the argument is ` None ` , ` false ` otherwise .
` ` ` res example
Belt . Option.isNone(None ) / * true * /
Belt . ) ) / * false * /
` ` `
Returns `true` if the argument is `None`, `false` otherwise.
```res example
Belt.Option.isNone(None) /* true */
Belt.Option.isNone(Some(1)) /* false */
```
*)
val eqU : 'a option -> 'b option -> ('a -> 'b -> bool [@bs]) -> bool
*
version of ` eq `
Uncurried version of `eq`
*)
val eq : 'a option -> 'b option -> ('a -> 'b -> bool) -> bool
*
Evaluates two optional values for equality with respect to a predicate
function . If both ` optValue1 ` and ` optValue2 ` are ` None ` , returns ` true ` .
If one of the arguments is ` Some(value ) ` and the other is ` None ` , returns
` false ` .
If arguments are ` Some(value1 ) ` and ` Some(value2 ) ` , returns the result of
` predicate(value1 , ) ` ; the predicate function must return a bool .
` ` ` res example
let clockEqual = ( a , b ) = > mod(a , 12 ) = = mod(b , 12 )
open Belt . Option
eq(Some(3 ) , Some(15 ) , clockEqual ) / * true * /
eq(Some(3 ) , None , clockEqual ) / * false * /
eq(None , Some(3 ) , clockEqual ) / * false * /
eq(None , None , clockEqual ) / * true * /
` ` `
Evaluates two optional values for equality with respect to a predicate
function. If both `optValue1` and `optValue2` are `None`, returns `true`.
If one of the arguments is `Some(value)` and the other is `None`, returns
`false`.
If arguments are `Some(value1)` and `Some(value2)`, returns the result of
`predicate(value1, value2)`; the predicate function must return a bool.
```res example
let clockEqual = (a, b) => mod(a, 12) == mod(b, 12)
open Belt.Option
eq(Some(3), Some(15), clockEqual) /* true */
eq(Some(3), None, clockEqual) /* false */
eq(None, Some(3), clockEqual) /* false */
eq(None, None, clockEqual) /* true */
```
*)
val cmpU : 'a option -> 'b option -> ('a -> 'b -> int [@bs]) -> int
* version of ` cmp `
val cmp : 'a option -> 'b option -> ('a -> 'b -> int) -> int
*
` cmp(optValue1 , optValue2 , comparisonFunction ) ` compares two optional values
with respect to given ` comparisonFunction ` .
If both ` optValue1 ` and ` optValue2 ` are ` None ` , it returns ` 0 ` .
If the first argument is ` Some(value1 ) ` and the second is ` None ` , returns ` 1 `
( something is greater than nothing ) .
If the first argument is ` None ` and the second is ` Some(value2 ) ` , returns ` -1 `
( nothing is less than something ) .
If the arguments are ` Some(value1 ) ` and ` Some(value2 ) ` , returns the result of
` comparisonFunction(value1 , value2 ) ` ; comparisonFunction takes two arguments
and returns ` -1 ` if the first argument is less than the second , ` 0 ` if the
arguments are equal , and ` 1 ` if the first argument is greater than the second .
` ` ` res example
let clockCompare = ( a , b ) = > compare(mod(a , 12 ) , mod(b , 12 ) )
open Belt . Option
cmp(Some(3 ) , Some(15 ) , clockCompare ) / * 0 * /
cmp(Some(3 ) , Some(14 ) , clockCompare ) / * 1 * /
cmp(Some(2 ) , Some(15 ) , clockCompare ) / * ( -1 ) * /
cmp(None , Some(15 ) , clockCompare ) / * ( -1 ) * /
cmp(Some(14 ) , None , clockCompare ) / * 1 * /
cmp(None , None , clockCompare ) / * 0 * /
` ` `
`cmp(optValue1, optValue2, comparisonFunction)` compares two optional values
with respect to given `comparisonFunction`.
If both `optValue1` and `optValue2` are `None`, it returns `0`.
If the first argument is `Some(value1)` and the second is `None`, returns `1`
(something is greater than nothing).
If the first argument is `None` and the second is `Some(value2)`, returns `-1`
(nothing is less than something).
If the arguments are `Some(value1)` and `Some(value2)`, returns the result of
`comparisonFunction(value1, value2)`; comparisonFunction takes two arguments
and returns `-1` if the first argument is less than the second, `0` if the
arguments are equal, and `1` if the first argument is greater than the second.
```res example
let clockCompare = (a, b) => compare(mod(a, 12), mod(b, 12))
open Belt.Option
cmp(Some(3), Some(15), clockCompare) /* 0 */
cmp(Some(3), Some(14), clockCompare) /* 1 */
cmp(Some(2), Some(15), clockCompare) /* (-1) */
cmp(None, Some(15), clockCompare) /* (-1) */
cmp(Some(14), None, clockCompare) /* 1 */
cmp(None, None, clockCompare) /* 0 */
```
*)
|
c2cc902a3650ddbda6ed6fa4d6b442677616281614c47ade7be2205eabfbaa5f | the-little-typer/pie | pie-err.rkt | #lang racket/base
(require racket/string racket/port racket/match)
(require "locations.rkt")
(require "resugar.rkt")
(require "pretty.rkt")
(provide (all-defined-out))
(struct exn:fail:pie exn:fail (where)
#:property prop:exn:srclocs
(lambda (e)
(match (exn:fail:pie-where e)
[(list raw-src line col pos span)
highlights more consistently if we
;; return an actual path for the source when
;; the source string corresponds to a valid
;; file on the user's machine.
(define src (if (and (string? raw-src)
(file-exists? raw-src))
(string->path raw-src)
raw-src))
(list (srcloc src line col pos span))]))
#:transparent)
(define (raise-pie-error where msg)
(raise (exn:fail:pie (with-output-to-string
(lambda ()
(pprint-message msg)))
(current-continuation-marks)
(location->srcloc where))))
| null | https://raw.githubusercontent.com/the-little-typer/pie/a698d4cacd6823b5161221596d34bd17ce5282b8/pie-err.rkt | racket | return an actual path for the source when
the source string corresponds to a valid
file on the user's machine. | #lang racket/base
(require racket/string racket/port racket/match)
(require "locations.rkt")
(require "resugar.rkt")
(require "pretty.rkt")
(provide (all-defined-out))
(struct exn:fail:pie exn:fail (where)
#:property prop:exn:srclocs
(lambda (e)
(match (exn:fail:pie-where e)
[(list raw-src line col pos span)
highlights more consistently if we
(define src (if (and (string? raw-src)
(file-exists? raw-src))
(string->path raw-src)
raw-src))
(list (srcloc src line col pos span))]))
#:transparent)
(define (raise-pie-error where msg)
(raise (exn:fail:pie (with-output-to-string
(lambda ()
(pprint-message msg)))
(current-continuation-marks)
(location->srcloc where))))
|
bafc6e59005d7b4b98e72bc27f95560fa8e16060a486e2f0271c8e15c07ceba3 | dakrone/clj-http | core_old.clj | (ns clj-http.core-old
"Core HTTP request/response implementation."
(:require [clj-http.conn-mgr :as conn]
[clj-http.headers :as headers]
[clj-http.multipart :as mp]
[clj-http.util :refer [opt]]
clojure.pprint)
(:import [java.io ByteArrayOutputStream FilterInputStream InputStream]
java.net.URI
[org.apache.http HeaderIterator HttpEntity HttpEntityEnclosingRequest HttpHost HttpResponseInterceptor]
[org.apache.http.auth AuthScope NTCredentials UsernamePasswordCredentials]
[org.apache.http.client HttpClient HttpRequestRetryHandler]
[org.apache.http.client.methods HttpDelete HttpEntityEnclosingRequestBase HttpGet HttpHead HttpOptions HttpPatch HttpPost HttpPut HttpUriRequest]
[org.apache.http.client.params ClientPNames CookiePolicy]
org.apache.http.conn.ClientConnectionManager
org.apache.http.conn.params.ConnRoutePNames
org.apache.http.conn.routing.HttpRoute
org.apache.http.cookie.CookieSpecFactory
org.apache.http.cookie.params.CookieSpecPNames
[org.apache.http.entity ByteArrayEntity StringEntity]
org.apache.http.impl.client.DefaultHttpClient
org.apache.http.impl.conn.ProxySelectorRoutePlanner
org.apache.http.impl.cookie.BrowserCompatSpec
org.apache.http.params.CoreConnectionPNames))
(defn parse-headers
"Takes a HeaderIterator and returns a map of names to values.
If a name appears more than once (like `set-cookie`) then the value
will be a vector containing the values in the order they appeared
in the headers."
[^HeaderIterator headers & [use-header-maps-in-response?]]
(if-not use-header-maps-in-response?
(->> (headers/header-iterator-seq headers)
(map (fn [[k v]]
[(.toLowerCase ^String k) v]))
(reduce (fn [hs [k v]]
(headers/assoc-join hs k v))
{}))
(->> (headers/header-iterator-seq headers)
(reduce (fn [hs [k v]]
(headers/assoc-join hs k v))
(headers/header-map)))))
(defn set-client-param [^HttpClient client key val]
(when-not (nil? val)
(-> client
(.getParams)
(.setParameter key val))))
(defn make-proxy-method-with-body
[method]
(fn [^String url]
(doto (proxy [HttpEntityEnclosingRequestBase] []
(getMethod [] (.toUpperCase (name method))))
(.setURI (URI. url)))))
(def proxy-delete-with-body (make-proxy-method-with-body :delete))
(def proxy-get-with-body (make-proxy-method-with-body :get))
(def proxy-copy-with-body (make-proxy-method-with-body :copy))
(def proxy-move-with-body (make-proxy-method-with-body :move))
(def proxy-patch-with-body (make-proxy-method-with-body :patch))
(def ^:dynamic *cookie-store* nil)
(defn- set-routing
"Use ProxySelectorRoutePlanner to choose proxy sensible based on
http.nonProxyHosts"
[^DefaultHttpClient client]
(.setRoutePlanner client
(ProxySelectorRoutePlanner.
(.. client getConnectionManager getSchemeRegistry) nil))
client)
(defn maybe-force-proxy [^DefaultHttpClient client
^HttpEntityEnclosingRequestBase request
proxy-host proxy-port proxy-ignore-hosts]
(let [uri (.getURI request)]
(when (and (nil? ((set proxy-ignore-hosts) (.getHost uri))) proxy-host)
(let [target (HttpHost. (.getHost uri) (.getPort uri) (.getScheme uri))
route (HttpRoute. target nil (HttpHost. ^String proxy-host
(int proxy-port))
(.. client getConnectionManager getSchemeRegistry
(getScheme target) isLayered))]
(set-client-param client ConnRoutePNames/FORCED_ROUTE route)))
request))
(defn cookie-spec
"Create an instance of a
org.apache.http.impl.cookie.BrowserCompatSpec with a validate
function that you pass in. This function takes two parameters, a
cookie and an origin."
[f]
(proxy [BrowserCompatSpec] []
(validate [cookie origin] (f cookie origin))))
(defn cookie-spec-factory
"Create an instance of a org.apache.http.cookie.CookieSpecFactory
with a newInstance implementation that returns a cookie
specification with a validate function that you pass in. The
function takes two parameters: cookie and origin."
[f]
(proxy
[CookieSpecFactory] []
(newInstance [params] (cookie-spec f))))
(defn add-client-params!
"Add various client params to the http-client object, if needed."
[^DefaultHttpClient http-client kvs]
(let [cookie-policy (:cookie-policy kvs)
cookie-policy-name (str (type cookie-policy))
kvs (dissoc kvs :cookie-policy)]
(when cookie-policy
(-> http-client
.getCookieSpecs
(.register cookie-policy-name (cookie-spec-factory cookie-policy))))
(doto http-client
(set-client-param ClientPNames/COOKIE_POLICY
(if cookie-policy
cookie-policy-name
CookiePolicy/BROWSER_COMPATIBILITY))
(set-client-param CookieSpecPNames/SINGLE_COOKIE_HEADER true)
(set-client-param ClientPNames/HANDLE_REDIRECTS false))
(doseq [[k v] kvs]
(set-client-param http-client
k (cond
(and (not= ClientPNames/CONN_MANAGER_TIMEOUT k)
(instance? Long v))
(Integer. ^Long v)
true v)))))
(defn- coerce-body-entity
"Coerce the http-entity from an HttpResponse to either a byte-array, or a
stream that closes itself and the connection manager when closed."
[{:keys [as]} ^HttpEntity http-entity ^ClientConnectionManager conn-mgr]
(if http-entity
(proxy [FilterInputStream]
[^InputStream (.getContent http-entity)]
(close []
(try
;; Eliminate the reflection warning from proxy-super
(let [^InputStream this this]
(proxy-super close))
(finally
(when-not (conn/reusable? conn-mgr)
(conn/shutdown-manager conn-mgr))))))
(when-not (conn/reusable? conn-mgr)
(conn/shutdown-manager conn-mgr))))
(defn- print-debug!
"Print out debugging information to *out* for a given request."
[{:keys [debug-body body] :as req} http-req]
(println "Request:" (type body))
(clojure.pprint/pprint
(assoc req
:body (if (opt req :debug-body)
(cond
(isa? (type body) String)
body
(isa? (type body) HttpEntity)
(let [baos (ByteArrayOutputStream.)]
(.writeTo ^HttpEntity body baos)
(.toString baos "UTF-8"))
:else nil)
(if (isa? (type body) String)
(format "... %s bytes ..."
(count body))
(and body (bean body))))
:body-type (type body)))
(println "HttpRequest:")
(clojure.pprint/pprint (bean http-req)))
(defn http-request-for
"Provides the HttpRequest object for a particular request-method and url"
[request-method ^String http-url body]
(case request-method
:get (if body
(proxy-get-with-body http-url)
(HttpGet. http-url))
:head (HttpHead. http-url)
:put (HttpPut. http-url)
:post (HttpPost. http-url)
:options (HttpOptions. http-url)
:delete (if body
(proxy-delete-with-body http-url)
(HttpDelete. http-url))
:copy (proxy-copy-with-body http-url)
:move (proxy-move-with-body http-url)
:patch (if body
(proxy-patch-with-body http-url)
(HttpPatch. http-url))
(throw (IllegalArgumentException.
(str "Invalid request method " request-method)))))
(defn request
"Executes the HTTP request corresponding to the given Ring request map and
returns the Ring response map corresponding to the resulting HTTP response.
Note that where Ring uses InputStreams for the request and response bodies,
the clj-http uses ByteArrays for the bodies."
[{:keys [request-method scheme server-name server-port uri query-string
headers body multipart socket-timeout connection-timeout proxy-host
proxy-ignore-hosts proxy-port proxy-user proxy-pass as cookie-store
retry-handler response-interceptor digest-auth ntlm-auth
connection-manager client-params
; deprecated
conn-timeout
]
:as req}]
(let [^ClientConnectionManager conn-mgr
(or connection-manager
conn/*connection-manager*
(conn/make-regular-conn-manager req))
^DefaultHttpClient http-client (set-routing
(DefaultHttpClient. conn-mgr))
scheme (name scheme)]
(when-let [cookie-store (or cookie-store *cookie-store*)]
(.setCookieStore http-client cookie-store))
(when retry-handler
(.setHttpRequestRetryHandler
http-client
(proxy [HttpRequestRetryHandler] []
(retryRequest [e cnt context]
(retry-handler e cnt context)))))
(add-client-params!
http-client
;; merge in map of specified timeouts, to
;; support backward compatibility.
(merge {CoreConnectionPNames/SO_TIMEOUT socket-timeout
CoreConnectionPNames/CONNECTION_TIMEOUT (or connection-timeout
conn-timeout)}
client-params))
(when-let [[user pass] digest-auth]
(.setCredentials
(.getCredentialsProvider http-client)
(AuthScope. nil -1 nil)
(UsernamePasswordCredentials. user pass)))
(when-let [[user password host domain] ntlm-auth]
(.setCredentials
(.getCredentialsProvider http-client)
(AuthScope. nil -1 nil)
(NTCredentials. user password host domain)))
(when (and proxy-user proxy-pass)
(let [authscope (AuthScope. proxy-host proxy-port)
creds (UsernamePasswordCredentials. proxy-user proxy-pass)]
(.setCredentials (.getCredentialsProvider http-client)
authscope creds)))
(let [http-url (str scheme "://" server-name
(when server-port (str ":" server-port))
uri
(when query-string (str "?" query-string)))
req (assoc req :http-url http-url)
proxy-ignore-hosts (or proxy-ignore-hosts
#{"localhost" "127.0.0.1"})
^HttpUriRequest http-req (maybe-force-proxy
http-client
(http-request-for request-method
http-url body)
proxy-host
proxy-port
proxy-ignore-hosts)]
(when response-interceptor
(.addResponseInterceptor
http-client
(proxy [HttpResponseInterceptor] []
(process [resp ctx]
(response-interceptor resp ctx)))))
(when-not (conn/reusable? conn-mgr)
(.addHeader http-req "Connection" "close"))
(doseq [[header-n header-v] headers]
(if (coll? header-v)
(doseq [header-vth header-v]
(.addHeader http-req header-n header-vth))
(.addHeader http-req header-n (str header-v))))
(if multipart
(.setEntity ^HttpEntityEnclosingRequest http-req
(mp/create-multipart-entity multipart req))
(when (and body (instance? HttpEntityEnclosingRequest http-req))
(if (instance? HttpEntity body)
(.setEntity ^HttpEntityEnclosingRequest http-req body)
(.setEntity ^HttpEntityEnclosingRequest http-req
(if (string? body)
(StringEntity. ^String body "UTF-8")
(ByteArrayEntity. body))))))
(when (opt req :debug) (print-debug! req http-req))
(try
(let [http-resp (.execute http-client http-req)
http-entity (.getEntity http-resp)
resp {:status (.getStatusCode (.getStatusLine http-resp))
:headers (parse-headers
(.headerIterator http-resp)
(opt req :use-header-maps-in-response))
:body (coerce-body-entity req http-entity conn-mgr)}]
(if (opt req :save-request)
(-> resp
(assoc :request req)
(assoc-in [:request :body-type] (type body))
(update-in [:request]
#(if (opt req :debug-body)
(assoc % :body-content
(cond
(isa? (type (:body %)) String)
(:body %)
(isa? (type (:body %)) HttpEntity)
(let [baos (ByteArrayOutputStream.)]
(.writeTo ^HttpEntity (:body %) baos)
(.toString baos "UTF-8"))
:else nil))
%))
(assoc-in [:request :http-req] http-req)
(dissoc :save-request?))
resp))
(catch Throwable e
(when-not (conn/reusable? conn-mgr)
(conn/shutdown-manager conn-mgr))
(throw e))))))
| null | https://raw.githubusercontent.com/dakrone/clj-http/dd15359451645f677b3e294164cf70330b92241d/src/clj_http/core_old.clj | clojure | Eliminate the reflection warning from proxy-super
deprecated
merge in map of specified timeouts, to
support backward compatibility. | (ns clj-http.core-old
"Core HTTP request/response implementation."
(:require [clj-http.conn-mgr :as conn]
[clj-http.headers :as headers]
[clj-http.multipart :as mp]
[clj-http.util :refer [opt]]
clojure.pprint)
(:import [java.io ByteArrayOutputStream FilterInputStream InputStream]
java.net.URI
[org.apache.http HeaderIterator HttpEntity HttpEntityEnclosingRequest HttpHost HttpResponseInterceptor]
[org.apache.http.auth AuthScope NTCredentials UsernamePasswordCredentials]
[org.apache.http.client HttpClient HttpRequestRetryHandler]
[org.apache.http.client.methods HttpDelete HttpEntityEnclosingRequestBase HttpGet HttpHead HttpOptions HttpPatch HttpPost HttpPut HttpUriRequest]
[org.apache.http.client.params ClientPNames CookiePolicy]
org.apache.http.conn.ClientConnectionManager
org.apache.http.conn.params.ConnRoutePNames
org.apache.http.conn.routing.HttpRoute
org.apache.http.cookie.CookieSpecFactory
org.apache.http.cookie.params.CookieSpecPNames
[org.apache.http.entity ByteArrayEntity StringEntity]
org.apache.http.impl.client.DefaultHttpClient
org.apache.http.impl.conn.ProxySelectorRoutePlanner
org.apache.http.impl.cookie.BrowserCompatSpec
org.apache.http.params.CoreConnectionPNames))
(defn parse-headers
"Takes a HeaderIterator and returns a map of names to values.
If a name appears more than once (like `set-cookie`) then the value
will be a vector containing the values in the order they appeared
in the headers."
[^HeaderIterator headers & [use-header-maps-in-response?]]
(if-not use-header-maps-in-response?
(->> (headers/header-iterator-seq headers)
(map (fn [[k v]]
[(.toLowerCase ^String k) v]))
(reduce (fn [hs [k v]]
(headers/assoc-join hs k v))
{}))
(->> (headers/header-iterator-seq headers)
(reduce (fn [hs [k v]]
(headers/assoc-join hs k v))
(headers/header-map)))))
(defn set-client-param [^HttpClient client key val]
(when-not (nil? val)
(-> client
(.getParams)
(.setParameter key val))))
(defn make-proxy-method-with-body
[method]
(fn [^String url]
(doto (proxy [HttpEntityEnclosingRequestBase] []
(getMethod [] (.toUpperCase (name method))))
(.setURI (URI. url)))))
(def proxy-delete-with-body (make-proxy-method-with-body :delete))
(def proxy-get-with-body (make-proxy-method-with-body :get))
(def proxy-copy-with-body (make-proxy-method-with-body :copy))
(def proxy-move-with-body (make-proxy-method-with-body :move))
(def proxy-patch-with-body (make-proxy-method-with-body :patch))
(def ^:dynamic *cookie-store* nil)
(defn- set-routing
"Use ProxySelectorRoutePlanner to choose proxy sensible based on
http.nonProxyHosts"
[^DefaultHttpClient client]
(.setRoutePlanner client
(ProxySelectorRoutePlanner.
(.. client getConnectionManager getSchemeRegistry) nil))
client)
(defn maybe-force-proxy [^DefaultHttpClient client
^HttpEntityEnclosingRequestBase request
proxy-host proxy-port proxy-ignore-hosts]
(let [uri (.getURI request)]
(when (and (nil? ((set proxy-ignore-hosts) (.getHost uri))) proxy-host)
(let [target (HttpHost. (.getHost uri) (.getPort uri) (.getScheme uri))
route (HttpRoute. target nil (HttpHost. ^String proxy-host
(int proxy-port))
(.. client getConnectionManager getSchemeRegistry
(getScheme target) isLayered))]
(set-client-param client ConnRoutePNames/FORCED_ROUTE route)))
request))
(defn cookie-spec
"Create an instance of a
org.apache.http.impl.cookie.BrowserCompatSpec with a validate
function that you pass in. This function takes two parameters, a
cookie and an origin."
[f]
(proxy [BrowserCompatSpec] []
(validate [cookie origin] (f cookie origin))))
(defn cookie-spec-factory
"Create an instance of a org.apache.http.cookie.CookieSpecFactory
with a newInstance implementation that returns a cookie
specification with a validate function that you pass in. The
function takes two parameters: cookie and origin."
[f]
(proxy
[CookieSpecFactory] []
(newInstance [params] (cookie-spec f))))
(defn add-client-params!
"Add various client params to the http-client object, if needed."
[^DefaultHttpClient http-client kvs]
(let [cookie-policy (:cookie-policy kvs)
cookie-policy-name (str (type cookie-policy))
kvs (dissoc kvs :cookie-policy)]
(when cookie-policy
(-> http-client
.getCookieSpecs
(.register cookie-policy-name (cookie-spec-factory cookie-policy))))
(doto http-client
(set-client-param ClientPNames/COOKIE_POLICY
(if cookie-policy
cookie-policy-name
CookiePolicy/BROWSER_COMPATIBILITY))
(set-client-param CookieSpecPNames/SINGLE_COOKIE_HEADER true)
(set-client-param ClientPNames/HANDLE_REDIRECTS false))
(doseq [[k v] kvs]
(set-client-param http-client
k (cond
(and (not= ClientPNames/CONN_MANAGER_TIMEOUT k)
(instance? Long v))
(Integer. ^Long v)
true v)))))
(defn- coerce-body-entity
"Coerce the http-entity from an HttpResponse to either a byte-array, or a
stream that closes itself and the connection manager when closed."
[{:keys [as]} ^HttpEntity http-entity ^ClientConnectionManager conn-mgr]
(if http-entity
(proxy [FilterInputStream]
[^InputStream (.getContent http-entity)]
(close []
(try
(let [^InputStream this this]
(proxy-super close))
(finally
(when-not (conn/reusable? conn-mgr)
(conn/shutdown-manager conn-mgr))))))
(when-not (conn/reusable? conn-mgr)
(conn/shutdown-manager conn-mgr))))
(defn- print-debug!
"Print out debugging information to *out* for a given request."
[{:keys [debug-body body] :as req} http-req]
(println "Request:" (type body))
(clojure.pprint/pprint
(assoc req
:body (if (opt req :debug-body)
(cond
(isa? (type body) String)
body
(isa? (type body) HttpEntity)
(let [baos (ByteArrayOutputStream.)]
(.writeTo ^HttpEntity body baos)
(.toString baos "UTF-8"))
:else nil)
(if (isa? (type body) String)
(format "... %s bytes ..."
(count body))
(and body (bean body))))
:body-type (type body)))
(println "HttpRequest:")
(clojure.pprint/pprint (bean http-req)))
(defn http-request-for
"Provides the HttpRequest object for a particular request-method and url"
[request-method ^String http-url body]
(case request-method
:get (if body
(proxy-get-with-body http-url)
(HttpGet. http-url))
:head (HttpHead. http-url)
:put (HttpPut. http-url)
:post (HttpPost. http-url)
:options (HttpOptions. http-url)
:delete (if body
(proxy-delete-with-body http-url)
(HttpDelete. http-url))
:copy (proxy-copy-with-body http-url)
:move (proxy-move-with-body http-url)
:patch (if body
(proxy-patch-with-body http-url)
(HttpPatch. http-url))
(throw (IllegalArgumentException.
(str "Invalid request method " request-method)))))
(defn request
"Executes the HTTP request corresponding to the given Ring request map and
returns the Ring response map corresponding to the resulting HTTP response.
Note that where Ring uses InputStreams for the request and response bodies,
the clj-http uses ByteArrays for the bodies."
[{:keys [request-method scheme server-name server-port uri query-string
headers body multipart socket-timeout connection-timeout proxy-host
proxy-ignore-hosts proxy-port proxy-user proxy-pass as cookie-store
retry-handler response-interceptor digest-auth ntlm-auth
connection-manager client-params
conn-timeout
]
:as req}]
(let [^ClientConnectionManager conn-mgr
(or connection-manager
conn/*connection-manager*
(conn/make-regular-conn-manager req))
^DefaultHttpClient http-client (set-routing
(DefaultHttpClient. conn-mgr))
scheme (name scheme)]
(when-let [cookie-store (or cookie-store *cookie-store*)]
(.setCookieStore http-client cookie-store))
(when retry-handler
(.setHttpRequestRetryHandler
http-client
(proxy [HttpRequestRetryHandler] []
(retryRequest [e cnt context]
(retry-handler e cnt context)))))
(add-client-params!
http-client
(merge {CoreConnectionPNames/SO_TIMEOUT socket-timeout
CoreConnectionPNames/CONNECTION_TIMEOUT (or connection-timeout
conn-timeout)}
client-params))
(when-let [[user pass] digest-auth]
(.setCredentials
(.getCredentialsProvider http-client)
(AuthScope. nil -1 nil)
(UsernamePasswordCredentials. user pass)))
(when-let [[user password host domain] ntlm-auth]
(.setCredentials
(.getCredentialsProvider http-client)
(AuthScope. nil -1 nil)
(NTCredentials. user password host domain)))
(when (and proxy-user proxy-pass)
(let [authscope (AuthScope. proxy-host proxy-port)
creds (UsernamePasswordCredentials. proxy-user proxy-pass)]
(.setCredentials (.getCredentialsProvider http-client)
authscope creds)))
(let [http-url (str scheme "://" server-name
(when server-port (str ":" server-port))
uri
(when query-string (str "?" query-string)))
req (assoc req :http-url http-url)
proxy-ignore-hosts (or proxy-ignore-hosts
#{"localhost" "127.0.0.1"})
^HttpUriRequest http-req (maybe-force-proxy
http-client
(http-request-for request-method
http-url body)
proxy-host
proxy-port
proxy-ignore-hosts)]
(when response-interceptor
(.addResponseInterceptor
http-client
(proxy [HttpResponseInterceptor] []
(process [resp ctx]
(response-interceptor resp ctx)))))
(when-not (conn/reusable? conn-mgr)
(.addHeader http-req "Connection" "close"))
(doseq [[header-n header-v] headers]
(if (coll? header-v)
(doseq [header-vth header-v]
(.addHeader http-req header-n header-vth))
(.addHeader http-req header-n (str header-v))))
(if multipart
(.setEntity ^HttpEntityEnclosingRequest http-req
(mp/create-multipart-entity multipart req))
(when (and body (instance? HttpEntityEnclosingRequest http-req))
(if (instance? HttpEntity body)
(.setEntity ^HttpEntityEnclosingRequest http-req body)
(.setEntity ^HttpEntityEnclosingRequest http-req
(if (string? body)
(StringEntity. ^String body "UTF-8")
(ByteArrayEntity. body))))))
(when (opt req :debug) (print-debug! req http-req))
(try
(let [http-resp (.execute http-client http-req)
http-entity (.getEntity http-resp)
resp {:status (.getStatusCode (.getStatusLine http-resp))
:headers (parse-headers
(.headerIterator http-resp)
(opt req :use-header-maps-in-response))
:body (coerce-body-entity req http-entity conn-mgr)}]
(if (opt req :save-request)
(-> resp
(assoc :request req)
(assoc-in [:request :body-type] (type body))
(update-in [:request]
#(if (opt req :debug-body)
(assoc % :body-content
(cond
(isa? (type (:body %)) String)
(:body %)
(isa? (type (:body %)) HttpEntity)
(let [baos (ByteArrayOutputStream.)]
(.writeTo ^HttpEntity (:body %) baos)
(.toString baos "UTF-8"))
:else nil))
%))
(assoc-in [:request :http-req] http-req)
(dissoc :save-request?))
resp))
(catch Throwable e
(when-not (conn/reusable? conn-mgr)
(conn/shutdown-manager conn-mgr))
(throw e))))))
|
49532febd25b0f449530a06c88dbcedd353abb530ec75f23f028a0d9c06b780b | owainlewis/clojure-mail | message_test.clj | (ns clojure-mail.message-test
(:require [clojure.test :refer :all]
[clojure-mail.message :refer :all]
[clojure-mail.core :refer [file->message]]
[clojure.java.io :as io]))
(defn load-fixture [fixture]
(->> (str "emails/" fixture) io/resource io/file file->message))
(def fixture (load-fixture "25"))
(deftest mime-types-test
(testing "should parse correct mime-type on email message"
(let [types {:plain "TEXT/PLAIN; charset=utf-8; format=fixed"
:html "TEXT/HTML; charset=utf-8"}]
(is (= :plain (mime-type (:plain types))))
(is (= :html (mime-type (:html types)))))))
(deftest message-to-test
(testing "should return a sequence of message receievers"
(is (= (count (to fixture)) 1))
(is (= (first (to fixture)) {:address "" :name nil}))))
(deftest message-subject-test
(testing "should return an email message subject"
(is (= (subject fixture) "Request to share ContractsBuilder"))))
(deftest message-from-test
(testing "should return the message sender"))
(deftest message-content-type-test
(testing "should return the message content-type")
(is (= (mime-type (content-type fixture)) :multipart)))
| null | https://raw.githubusercontent.com/owainlewis/clojure-mail/8e792f5fdda2d38d5ce1fe90082c7859e66ab9a7/test/clojure_mail/message_test.clj | clojure | (ns clojure-mail.message-test
(:require [clojure.test :refer :all]
[clojure-mail.message :refer :all]
[clojure-mail.core :refer [file->message]]
[clojure.java.io :as io]))
(defn load-fixture [fixture]
(->> (str "emails/" fixture) io/resource io/file file->message))
(def fixture (load-fixture "25"))
(deftest mime-types-test
(testing "should parse correct mime-type on email message"
(let [types {:plain "TEXT/PLAIN; charset=utf-8; format=fixed"
:html "TEXT/HTML; charset=utf-8"}]
(is (= :plain (mime-type (:plain types))))
(is (= :html (mime-type (:html types)))))))
(deftest message-to-test
(testing "should return a sequence of message receievers"
(is (= (count (to fixture)) 1))
(is (= (first (to fixture)) {:address "" :name nil}))))
(deftest message-subject-test
(testing "should return an email message subject"
(is (= (subject fixture) "Request to share ContractsBuilder"))))
(deftest message-from-test
(testing "should return the message sender"))
(deftest message-content-type-test
(testing "should return the message content-type")
(is (= (mime-type (content-type fixture)) :multipart)))
|
|
bdd8c1c988644ebd8ab5eeecbc2d57bd5091238371518c367f06a8ebbeb6ef48 | tanders/cluster-engine | bugs.lisp |
;;; Examples that seem to show bugs
| null | https://raw.githubusercontent.com/tanders/cluster-engine/064ad4fd107f8d9a3dfcaf260524c2ab034c6d3f/test_files/bugs.lisp | lisp | Examples that seem to show bugs | |
c0f212025f2c65a4868dff0ab9df255f140f2a9c4783233feaf6024e5eb6a622 | ocaml-community/ocamlscript | calc.ml | Ocaml.sources := ["parser.mly"; "lexer.mll"]
--
(* Calculator example from the Objective Caml reference manual *)
(* File calc.ml *)
let _ =
try
let lexbuf = Lexing.from_channel stdin in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
| null | https://raw.githubusercontent.com/ocaml-community/ocamlscript/df0f04d7e41655944bd14e6989dd695425e5f871/examples/calc.ml | ocaml | Calculator example from the Objective Caml reference manual
File calc.ml | Ocaml.sources := ["parser.mly"; "lexer.mll"]
--
let _ =
try
let lexbuf = Lexing.from_channel stdin in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
|
10d8ca2142630b99025398d88cc224e16948ed1f855ab0c15148d24ea5d80eda | janestreet/bonsai | bonsai_web_ui_query_box.mli | open! Core
open Bonsai_web
* A textbox with suggested results , modeled off of Chrome 's address bar .
- " Enter " invokes [ on_select ] with the selected suggestion . If the suggestion
list is closed , the callback is not invoked , because of course nothing is
selected ; instead the suggestion list is opened .
- " Clicking " on the suggestion list invokes [ on_select ] .
- Focusing the the text input opens the suggestion list
- " Escape " or unfocusing the text input closes the suggestion list
- " Tab " and " Down Arrow " move the selected item down . If the suggestion
list is closed , it gets opened , and the selected item is set to the top
item .
- " Shift - Tab " and " Up Arrow " move the selected item up . Again , if the list
is closed , it gets opened , but selection is sent to the bottom item .
- Editing the textbox content re - filters the items .
- Changing the selected suggestion has no effect on the textbox content ,
since there might not be a string which exactly selects an item .
Only [ max_visible_items ] are rendered at once , so even with thousands of
suggestions , DOM updates should be very quick .
- "Enter" invokes [on_select] with the selected suggestion. If the suggestion
list is closed, the callback is not invoked, because of course nothing is
selected; instead the suggestion list is opened.
- "Clicking" on the suggestion list invokes [on_select].
- Focusing the the text input opens the suggestion list
- "Escape" or unfocusing the text input closes the suggestion list
- "Tab" and "Down Arrow" move the selected item down. If the suggestion
list is closed, it gets opened, and the selected item is set to the top
item.
- "Shift-Tab" and "Up Arrow" move the selected item up. Again, if the list
is closed, it gets opened, but selection is sent to the bottom item.
- Editing the textbox content re-filters the items.
- Changing the selected suggestion has no effect on the textbox content,
since there might not be a string which exactly selects an item.
Only [max_visible_items] are rendered at once, so even with thousands of
suggestions, DOM updates should be very quick.
*)
module Suggestion_list_kind : sig
type t =
| Transient_overlay
(** When set to Transient, the suggestion-list only shows up when the
textbox is focused, and the list will float over other items on the
page.*)
| Permanent_fixture
(** Permanent will make the suggestion-list always present, and it
will take up space during the layout of the application. *)
[@@deriving sexp, compare, enumerate, equal]
end
module Expand_direction : sig
type t =
| Down
* Autocomplete options appear below the textbox , with the first item at
the top of the list .
the top of the list. *)
| Up
* Autocomplete options appear above the textbox , with the first item at
the bottom of the list .
the bottom of the list. *)
[@@deriving sexp, compare, enumerate, equal]
end
type 'k t =
{ selected_item : 'k option
; view : Vdom.Node.t
; query : string
}
[@@deriving fields]
val create
: ('k, 'cmp) Bonsai.comparator
-> ?initial_query:string
-> ?max_visible_items:int Value.t
(** The value defaults to Transient. Read doc comment on the type for
more info. *)
-> ?suggestion_list_kind:Suggestion_list_kind.t Value.t
(** The value defaults to Down. Read doc comment on the type for more info. *)
-> ?expand_direction:Expand_direction.t Value.t
* If provided , the attributes in this value will be attached to
the vdom node representing the currently selected item in the list .
the vdom node representing the currently selected item in the list. *)
-> ?selected_item_attr:Vdom.Attr.t Value.t
(** If provided, [extra_list_container_attr] will be added to the
vdom node containing the list of suggestions. *)
-> ?extra_list_container_attr:Vdom.Attr.t Value.t
(** If provided, [extra_input_attr] will be added to the query text input. *)
-> ?extra_input_attr:Vdom.Attr.t Value.t
(** If provided [extra_attr] will be added to the outermost div of this component. *)
-> ?extra_attr:Vdom.Attr.t Value.t
(** [f] generates the set of completion options by returning
a map from a user-provided key ['k] to the view for that element
in the dropdown list. The currently entered filter from the textbox
part of the component is provided as an argument to the function
and it is expected that you use this to do your own filtering and
return the filtered map. *)
-> f:(string Value.t -> ('k, Vdom.Node.t, 'cmp) Map.t Computation.t)
(** [on_select] is called when [enter] is hit when an item is
selected. *)
-> on_select:('k -> unit Effect.t) Value.t
-> unit
-> 'k t Computation.t
(** [stringable] is like [create] but takes a map with possible completion options,
instead of a function to generate them. Completion options will be displayed if their
string representation [Fuzzy_match]es the current query. *)
val stringable
: ('k, 'cmp) Bonsai.comparator
-> ?initial_query:string
-> ?max_visible_items:int Value.t
-> ?suggestion_list_kind:Suggestion_list_kind.t Value.t
-> ?expand_direction:Expand_direction.t Value.t
-> ?selected_item_attr:Vdom.Attr.t Value.t
-> ?extra_list_container_attr:Vdom.Attr.t Value.t
-> ?extra_input_attr:Vdom.Attr.t Value.t
-> ?extra_attr:Vdom.Attr.t Value.t
-> ?to_view:('k -> string -> Vdom.Node.t)
-> on_select:('k -> unit Effect.t) Value.t
-> ('k, string, 'cmp) Map.t Value.t
-> 'k t Computation.t
module Collate_map_with_score : sig
module Scored_key : sig
type 'k t = int * 'k
include Comparator.S1 with type 'a t := 'a t
module M (T : T) : sig
type nonrec t = T.t t [@@deriving sexp]
include
Comparator.S with type t := t and type comparator_witness = comparator_witness
end
module Map : sig
type nonrec ('k, 'v) t = ('k t, 'v, comparator_witness) Map.t
end
end
* [ collate ] sorts and filters the input map according to a [ score ] function
( filtering a result out is done by returning 0 from [ score ] , and
transforms the data in the map according to a [ to_result ] function .
The performance trade - off is specific : we assume that the input map
does n't change very often so that we can pre - process all the items in the
map ahead of time . Thus , the goal of this function is not to be as
incremental as possible , but rather to have as low of constants as
possible .
[ query_is_as_strict ] is used to determine whether a new query will filter
out at least as many items as the previous query . If so , then we can skip
running [ score ] on items that have already been filtered away .
Each time the query changes , we remember a previous query and which
items have been filtered away by that query . However , if the previous
query limits the input to fewer than [ stop_trimming_input_at_count ] , then
we do n't update the previous query . This allows the user to specify that
when the number of results is small enough that it is more worthwhile to
cache a more general query in order to allow backtracking through
previous queries without abandoning caching altogether .
(filtering a result out is done by returning 0 from [score], and
transforms the data in the map according to a [to_result] function.
The performance trade-off is specific: we assume that the input map
doesn't change very often so that we can pre-process all the items in the
map ahead of time. Thus, the goal of this function is not to be as
incremental as possible, but rather to have as low of constants as
possible.
[query_is_as_strict] is used to determine whether a new query will filter
out at least as many items as the previous query. If so, then we can skip
running [score] on items that have already been filtered away.
Each time the query changes, we remember a previous query and which
items have been filtered away by that query. However, if the previous
query limits the input to fewer than [stop_trimming_input_at_count], then
we don't update the previous query. This allows the user to specify that
when the number of results is small enough that it is more worthwhile to
cache a more general query in order to allow backtracking through
previous queries without abandoning caching altogether. *)
val collate
: preprocess:(key:'k -> data:'v -> 'preprocessed)
-> score:('query -> 'preprocessed -> int)
-> query_is_as_strict:('query -> as_:'query -> bool)
-> to_result:('preprocessed -> key:'k -> data:'v -> 'result)
-> ('k, 'v, 'cmp) Map.t Value.t
-> 'query Value.t
-> ('k, 'result) Scored_key.Map.t Computation.t
end
| null | https://raw.githubusercontent.com/janestreet/bonsai/34430405574a4de68835f1010c22f9ac18dfffb6/web_ui/query_box/src/bonsai_web_ui_query_box.mli | ocaml | * When set to Transient, the suggestion-list only shows up when the
textbox is focused, and the list will float over other items on the
page.
* Permanent will make the suggestion-list always present, and it
will take up space during the layout of the application.
* The value defaults to Transient. Read doc comment on the type for
more info.
* The value defaults to Down. Read doc comment on the type for more info.
* If provided, [extra_list_container_attr] will be added to the
vdom node containing the list of suggestions.
* If provided, [extra_input_attr] will be added to the query text input.
* If provided [extra_attr] will be added to the outermost div of this component.
* [f] generates the set of completion options by returning
a map from a user-provided key ['k] to the view for that element
in the dropdown list. The currently entered filter from the textbox
part of the component is provided as an argument to the function
and it is expected that you use this to do your own filtering and
return the filtered map.
* [on_select] is called when [enter] is hit when an item is
selected.
* [stringable] is like [create] but takes a map with possible completion options,
instead of a function to generate them. Completion options will be displayed if their
string representation [Fuzzy_match]es the current query. | open! Core
open Bonsai_web
* A textbox with suggested results , modeled off of Chrome 's address bar .
- " Enter " invokes [ on_select ] with the selected suggestion . If the suggestion
list is closed , the callback is not invoked , because of course nothing is
selected ; instead the suggestion list is opened .
- " Clicking " on the suggestion list invokes [ on_select ] .
- Focusing the the text input opens the suggestion list
- " Escape " or unfocusing the text input closes the suggestion list
- " Tab " and " Down Arrow " move the selected item down . If the suggestion
list is closed , it gets opened , and the selected item is set to the top
item .
- " Shift - Tab " and " Up Arrow " move the selected item up . Again , if the list
is closed , it gets opened , but selection is sent to the bottom item .
- Editing the textbox content re - filters the items .
- Changing the selected suggestion has no effect on the textbox content ,
since there might not be a string which exactly selects an item .
Only [ max_visible_items ] are rendered at once , so even with thousands of
suggestions , DOM updates should be very quick .
- "Enter" invokes [on_select] with the selected suggestion. If the suggestion
list is closed, the callback is not invoked, because of course nothing is
selected; instead the suggestion list is opened.
- "Clicking" on the suggestion list invokes [on_select].
- Focusing the the text input opens the suggestion list
- "Escape" or unfocusing the text input closes the suggestion list
- "Tab" and "Down Arrow" move the selected item down. If the suggestion
list is closed, it gets opened, and the selected item is set to the top
item.
- "Shift-Tab" and "Up Arrow" move the selected item up. Again, if the list
is closed, it gets opened, but selection is sent to the bottom item.
- Editing the textbox content re-filters the items.
- Changing the selected suggestion has no effect on the textbox content,
since there might not be a string which exactly selects an item.
Only [max_visible_items] are rendered at once, so even with thousands of
suggestions, DOM updates should be very quick.
*)
module Suggestion_list_kind : sig
type t =
| Transient_overlay
| Permanent_fixture
[@@deriving sexp, compare, enumerate, equal]
end
module Expand_direction : sig
type t =
| Down
* Autocomplete options appear below the textbox , with the first item at
the top of the list .
the top of the list. *)
| Up
* Autocomplete options appear above the textbox , with the first item at
the bottom of the list .
the bottom of the list. *)
[@@deriving sexp, compare, enumerate, equal]
end
type 'k t =
{ selected_item : 'k option
; view : Vdom.Node.t
; query : string
}
[@@deriving fields]
val create
: ('k, 'cmp) Bonsai.comparator
-> ?initial_query:string
-> ?max_visible_items:int Value.t
-> ?suggestion_list_kind:Suggestion_list_kind.t Value.t
-> ?expand_direction:Expand_direction.t Value.t
* If provided , the attributes in this value will be attached to
the vdom node representing the currently selected item in the list .
the vdom node representing the currently selected item in the list. *)
-> ?selected_item_attr:Vdom.Attr.t Value.t
-> ?extra_list_container_attr:Vdom.Attr.t Value.t
-> ?extra_input_attr:Vdom.Attr.t Value.t
-> ?extra_attr:Vdom.Attr.t Value.t
-> f:(string Value.t -> ('k, Vdom.Node.t, 'cmp) Map.t Computation.t)
-> on_select:('k -> unit Effect.t) Value.t
-> unit
-> 'k t Computation.t
val stringable
: ('k, 'cmp) Bonsai.comparator
-> ?initial_query:string
-> ?max_visible_items:int Value.t
-> ?suggestion_list_kind:Suggestion_list_kind.t Value.t
-> ?expand_direction:Expand_direction.t Value.t
-> ?selected_item_attr:Vdom.Attr.t Value.t
-> ?extra_list_container_attr:Vdom.Attr.t Value.t
-> ?extra_input_attr:Vdom.Attr.t Value.t
-> ?extra_attr:Vdom.Attr.t Value.t
-> ?to_view:('k -> string -> Vdom.Node.t)
-> on_select:('k -> unit Effect.t) Value.t
-> ('k, string, 'cmp) Map.t Value.t
-> 'k t Computation.t
module Collate_map_with_score : sig
module Scored_key : sig
type 'k t = int * 'k
include Comparator.S1 with type 'a t := 'a t
module M (T : T) : sig
type nonrec t = T.t t [@@deriving sexp]
include
Comparator.S with type t := t and type comparator_witness = comparator_witness
end
module Map : sig
type nonrec ('k, 'v) t = ('k t, 'v, comparator_witness) Map.t
end
end
* [ collate ] sorts and filters the input map according to a [ score ] function
( filtering a result out is done by returning 0 from [ score ] , and
transforms the data in the map according to a [ to_result ] function .
The performance trade - off is specific : we assume that the input map
does n't change very often so that we can pre - process all the items in the
map ahead of time . Thus , the goal of this function is not to be as
incremental as possible , but rather to have as low of constants as
possible .
[ query_is_as_strict ] is used to determine whether a new query will filter
out at least as many items as the previous query . If so , then we can skip
running [ score ] on items that have already been filtered away .
Each time the query changes , we remember a previous query and which
items have been filtered away by that query . However , if the previous
query limits the input to fewer than [ stop_trimming_input_at_count ] , then
we do n't update the previous query . This allows the user to specify that
when the number of results is small enough that it is more worthwhile to
cache a more general query in order to allow backtracking through
previous queries without abandoning caching altogether .
(filtering a result out is done by returning 0 from [score], and
transforms the data in the map according to a [to_result] function.
The performance trade-off is specific: we assume that the input map
doesn't change very often so that we can pre-process all the items in the
map ahead of time. Thus, the goal of this function is not to be as
incremental as possible, but rather to have as low of constants as
possible.
[query_is_as_strict] is used to determine whether a new query will filter
out at least as many items as the previous query. If so, then we can skip
running [score] on items that have already been filtered away.
Each time the query changes, we remember a previous query and which
items have been filtered away by that query. However, if the previous
query limits the input to fewer than [stop_trimming_input_at_count], then
we don't update the previous query. This allows the user to specify that
when the number of results is small enough that it is more worthwhile to
cache a more general query in order to allow backtracking through
previous queries without abandoning caching altogether. *)
val collate
: preprocess:(key:'k -> data:'v -> 'preprocessed)
-> score:('query -> 'preprocessed -> int)
-> query_is_as_strict:('query -> as_:'query -> bool)
-> to_result:('preprocessed -> key:'k -> data:'v -> 'result)
-> ('k, 'v, 'cmp) Map.t Value.t
-> 'query Value.t
-> ('k, 'result) Scored_key.Map.t Computation.t
end
|
253fb9a601e4d298bc5163a79d4f78dddea81225c2746890cd4b3cb06165e863 | erlang/otp | beam_validator.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2004 - 2023 . 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.
%%
%% %CopyrightEnd%
-module(beam_validator).
-include("beam_asm.hrl").
-define(UNICODE_MAX, (16#10FFFF)).
%% When an instruction throws an exception it does so by branching (branch/4)
%% to this label, following the {f,0} convention used in BIFs.
%%
%% Instructions that have fail labels but cannot throw exceptions should guard
%% themselves with assert_no_exception/1, and instructions that are statically
%% guaranteed not to fail should simply skip branching.
-define(EXCEPTION_LABEL, 0).
-compile({no_auto_import,[min/2]}).
Avoid warning for local function error/1 clashing with autoimported BIF .
-compile({no_auto_import,[error/1]}).
Interface for compiler .
-export([validate/2, format_error/1]).
-import(lists, [dropwhile/2,foldl/3,member/2,reverse/2,zip/2]).
%% To be called by the compiler.
-spec validate(Code, Level) -> Result when
Code :: beam_utils:module_code(),
Level :: strong | weak,
Result :: ok | {error, [{atom(), list()}]}.
validate({Mod,Exp,Attr,Fs,Lc}, Level) when is_atom(Mod),
is_list(Exp),
is_list(Attr),
is_integer(Lc) ->
Ft = build_function_table(Fs, #{}),
case validate_0(Fs, Mod, Level, Ft) of
[] ->
ok;
Es0 ->
Es = [{1,?MODULE,E} || E <- Es0],
{error,[{atom_to_list(Mod),Es}]}
end.
-spec format_error(term()) -> iolist().
format_error({{_M,F,A},{I,Off,limit}}) ->
io_lib:format(
"function ~p/~p+~p:~n"
" An implementation limit was reached.~n"
" Try reducing the complexity of this function.~n~n"
" Instruction: ~p~n", [F,A,Off,I]);
format_error({{_M,F,A},{undef_labels,Lbls}}) ->
io_lib:format(
"function ~p/~p:~n"
" Internal consistency check failed - please report this bug.~n"
" The following label(s) were referenced but not defined:~n", [F,A]) ++
" " ++ [[integer_to_list(L)," "] || L <- Lbls] ++ "\n";
format_error({{_M,F,A},{I,Off,Desc}}) ->
io_lib:format(
"function ~p/~p+~p:~n"
" Internal consistency check failed - please report this bug.~n"
" Instruction: ~p~n"
" Error: ~p:~n", [F,A,Off,I,Desc]);
format_error(Error) ->
io_lib:format("~p~n", [Error]).
%%%
%%% Local functions follow.
%%%
%%%
%%% The validator follows.
%%%
%%% The purpose of the validator is to find errors in the generated
%%% code that may cause the emulator to crash or behave strangely.
%%% We don't care about type errors in the user's code that will
%%% cause a proper exception at run-time.
%%%
%%% Things currently not checked. XXX
%%%
%%% - Heap allocation for binaries.
%%%
%% validate(Module, Level, [Function], Ft) -> [] | [Error]
%% A list of functions with their code. The code is in the same
format as used in the compiler and in .S files .
validate_0([], _Module, _Level, _Ft) ->
[];
validate_0([{function, Name, Arity, Entry, Code} | Fs], Module, Level, Ft) ->
MFA = {Module, Name, Arity},
try validate_1(Code, MFA, Entry, Level, Ft) of
_ ->
validate_0(Fs, Module, Level, Ft)
catch
throw:Error ->
%% Controlled error.
[Error | validate_0(Fs, Module, Level, Ft)];
Class:Error:Stack ->
%% Crash.
io:fwrite("Function: ~w/~w\n", [Name,Arity]),
erlang:raise(Class, Error, Stack)
end.
-record(t_abstract, {kind}).
%% The types are the same as in 'beam_types.hrl', with the addition of:
%%
%% * `#t_abstract{}` which describes tuples under construction, match context
%% positions, and so on.
%% * `(fun(values()) -> type())` that defers figuring out the type until it's
%% actually used. Mainly used to coax more type information out of
` get_tuple_element ` where a test on one element ( e.g. record tag ) may
%% affect the type of another.
-type validator_type() :: #t_abstract{} | fun((values()) -> type()) | type().
-record(value_ref, {id :: index()}).
-record(value, {op :: term(), args :: [argument()], type :: validator_type()}).
-type argument() :: #value_ref{} | beam_literal().
-type values() :: #{ #value_ref{} => #value{} }.
-type index() :: non_neg_integer().
Register tags describe the state of the register rather than the value they
%% contain (if any).
%%
%% initialized The register has been initialized with some valid term
%% so that it is safe to pass to the garbage collector.
%% NOT safe to use in any other way (will not crash the
%% emulator, but clearly points to a bug in the compiler).
%%
%% uninitialized The register contains any old garbage and can not be
%% passed to the garbage collector.
%%
%% {catchtag,[Lbl]} A special term used within a catch. Must only be used
%% by the catch instructions; NOT safe to use in other
%% instructions.
%%
%% {trytag,[Lbl]} A special term used within a try block. Must only be
%% used by the catch instructions; NOT safe to use in other
%% instructions.
-type tag() :: initialized |
uninitialized |
{catchtag, ordsets:ordset(label())} |
{trytag, ordsets:ordset(label())}.
-type x_regs() :: #{ {x, index()} => #value_ref{} }.
-type y_regs() :: #{ {y, index()} => tag() | #value_ref{} }.
%% Emulation state
-record(st,
{%% All known values.
vs=#{} :: values(),
Register states .
xs=#{} :: x_regs(),
ys=#{} :: y_regs(),
f=init_fregs(),
%% A set of all registers containing "fragile" terms. That is, terms
%% that don't exist on our process heap and would be destroyed by a
GC .
fragile=sets:new([{version, 2}]) :: sets:set(),
%% Number of Y registers.
%%
%% Note that this may be 0 if there's a frame without saved values,
%% such as on a body-recursive call.
numy=none :: none | {undecided,index()} | index(),
%% Available heap size.
h=0,
%% Available heap size for funs (aka lambdas).
hl=0,
%%Available heap size for floats.
hf=0,
%% List of hot catch/try tags
ct=[],
Previous instruction was setelement/3 .
setelem=false,
put/1 instructions left .
puts_left=none,
%% Current receive state:
%%
%% * 'none' - Not in a receive loop.
* ' marked_position ' - We 've used a marker prior to .
%% * 'entered_loop' - We're in a receive loop.
%% * 'undecided'
recv_state=none :: none | undecided | marked_position | entered_loop,
%% Holds the current saved position for each `#t_bs_context{}`, in the
%% sense that the position is equal to that of their context. They are
%% invalidated whenever their context advances.
%%
%% These are used to update the unit of saved positions after
%% operations that test the incoming unit, such as bs_test_unit and
%% bs_get_binary2 with {atom,all}.
ms_positions=#{} :: #{ Ctx :: #value_ref{} => Pos :: #value_ref{} }
}).
-type label() :: integer().
-type state() :: #st{} | 'none'.
%% Validator state
-record(vst,
{%% Current state
current=none :: state(),
%% Validation level
level :: strong | weak,
%% States at labels
branched=#{} :: #{ label() => state() },
%% All defined labels
labels=sets:new([{version, 2}]) :: sets:set(),
%% Information of other functions in the module
ft=#{} :: #{ label() => map() },
%% Counter for #value_ref{} creation
ref_ctr=0 :: index()
}).
build_function_table([{function,Name,Arity,Entry,Code0}|Fs], Acc) ->
Code = dropwhile(fun({label,L}) when L =:= Entry ->
false;
(_) ->
true
end, Code0),
case Code of
[{label,Entry} | Is] ->
Info = #{ name => Name,
arity => Arity,
parameter_info => find_parameter_info(Is, #{}),
always_fails => always_fails(Is) },
build_function_table(Fs, Acc#{ Entry => Info });
_ ->
%% Something is seriously wrong. Ignore it for now.
%% It will be detected and diagnosed later.
build_function_table(Fs, Acc)
end;
build_function_table([], Acc) ->
Acc.
' , { var_info , , Info } } | Is ] , Acc ) - >
find_parameter_info(Is, Acc#{ Reg => Info });
find_parameter_info([{'%', _} | Is], Acc) ->
find_parameter_info(Is, Acc);
find_parameter_info(_, Acc) ->
Acc.
always_fails([{jump,_}|_]) -> true;
always_fails(_) -> false.
validate_1(Is, MFA0, Entry, Level, Ft) ->
{Offset, MFA, Header, Body} = extract_header(Is, MFA0, Entry, 1, []),
Vst0 = init_vst(MFA, Level, Ft),
%% We validate the header after the body as the latter may jump to the
%% former to raise 'function_clause' exceptions.
Vst1 = validate_instrs(Body, MFA, Offset, Vst0),
Vst = validate_instrs(Header, MFA, 1, Vst1),
validate_branches(MFA, Vst).
extract_header([{func_info, {atom,Mod}, {atom,Name}, Arity}=I | Is],
MFA0, Entry, Offset, Acc) ->
{_, Name, Arity} = MFA0, %Assertion.
MFA = {Mod, Name, Arity},
case Is of
[{label, Entry} | _] ->
Header = reverse(Acc, [I]),
{Offset + 1, MFA, Header, Is};
_ ->
error({MFA, no_entry_label})
end;
extract_header([{label,_}=I | Is], MFA, Entry, Offset, Acc) ->
extract_header(Is, MFA, Entry, Offset + 1, [I | Acc]);
extract_header([{line,_}=I | Is], MFA, Entry, Offset, Acc) ->
extract_header(Is, MFA, Entry, Offset + 1, [I | Acc]);
extract_header(_Is, MFA, _Entry, _Offset, _Acc) ->
error({MFA, invalid_function_header}).
init_vst({_, _, Arity}, Level, Ft) ->
Vst = #vst{branched=#{},
current=#st{},
ft=Ft,
labels=sets:new([{version, 2}]),
level=Level},
init_function_args(Arity - 1, Vst).
init_function_args(-1, Vst) ->
Vst;
init_function_args(X, Vst) ->
init_function_args(X - 1, create_term(any, argument, [], {x,X}, Vst)).
kill_heap_allocation(#vst{current=St0}=Vst) ->
St = St0#st{h=0,hl=0,hf=0},
Vst#vst{current=St}.
validate_branches(MFA, Vst) ->
#vst{ branched=Targets0, labels=Labels0 } = Vst,
Targets = maps:keys(Targets0),
Labels = sets:to_list(Labels0),
case Targets -- Labels of
[_|_]=Undef ->
Error = {undef_labels, Undef},
error({MFA, Error});
[] ->
Vst
end.
validate_instrs([I|Is], MFA, Offset, Vst0) ->
validate_instrs(Is, MFA, Offset+1,
try
Vst = validate_mutation(I, Vst0),
vi(I, Vst)
catch Error ->
error({MFA, {I, Offset, Error}})
end);
validate_instrs([], _MFA, _Offset, Vst) ->
Vst.
vi({label,Lbl}, #vst{current=St0,
ref_ctr=Counter0,
branched=Branched0,
labels=Labels0}=Vst) ->
{St, Counter} = merge_states(Lbl, St0, Branched0, Counter0),
Branched = Branched0#{ Lbl => St },
Labels = sets:add_element(Lbl, Labels0),
Vst#vst{current=St,
ref_ctr=Counter,
branched=Branched,
labels=Labels};
vi(_I, #vst{current=none}=Vst) ->
%% Ignore all unreachable code.
Vst;
%%
%% Misc annotations
%%
' , { var_info , , Info } } , ) - >
validate_var_info(Info, Reg, Vst);
' , { remove_fragility , } } , ) - >
%% This is a hack to make prim_eval:'receive'/2 work.
%%
%% Normally it's illegal to pass fragile terms as a function argument as we
%% have no way of knowing what the callee will do with it, but we know that
prim_eval:'receive'/2 wo n't leak the term , nor cause a GC since it 's
%% disabled while matching messages.
remove_fragility(Reg, Vst);
' , _ } , ) - >
Vst;
vi({line,_}, Vst) ->
Vst;
vi(nif_start, Vst) ->
Vst;
%%
%% Moves
%%
vi({move,Src,Dst}, Vst) ->
assign(Src, Dst, Vst);
vi({swap,RegA,RegB}, Vst0) ->
assert_movable(RegA, Vst0),
assert_movable(RegB, Vst0),
%% We don't expect fragile registers to be swapped.
%% Therefore, we can conservatively make both registers
fragile if one of the register is fragile instead of
%% swapping the fragility of the registers.
Sources = [RegA,RegB],
Vst1 = propagate_fragility(RegA, Sources, Vst0),
Vst2 = propagate_fragility(RegB, Sources, Vst1),
%% Swap the value references.
VrefA = get_reg_vref(RegA, Vst2),
VrefB = get_reg_vref(RegB, Vst2),
Vst = set_reg_vref(VrefB, RegA, Vst2),
set_reg_vref(VrefA, RegB, Vst);
vi({fmove,Src,{fr,_}=Dst}, Vst) ->
assert_type(#t_float{}, Src, Vst),
set_freg(Dst, Vst);
vi({fmove,{fr,_}=Src,Dst}, Vst0) ->
assert_freg_set(Src, Vst0),
Vst = eat_heap_float(Vst0),
create_term(#t_float{}, fmove, [], Dst, Vst);
vi({kill,Reg}, Vst) ->
create_tag(initialized, kill, [], Reg, Vst);
vi({init,Reg}, Vst) ->
create_tag(initialized, init, [], Reg, Vst);
vi({init_yregs,{list,Yregs}}, Vst0) ->
case ordsets:from_list(Yregs) of
[] -> error(empty_list);
Yregs -> ok;
_ -> error(not_ordset)
end,
foldl(fun(Y, Vst) ->
create_tag(initialized, init, [], Y, Vst)
end, Vst0, Yregs);
%%
%% Matching and test instructions.
%%
vi({jump,{f,Lbl}}, Vst) ->
assert_no_exception(Lbl),
%% The next instruction is never executed.
branch(Lbl, Vst, fun kill_state/1);
vi({select_val,Src0,{f,Fail},{list,Choices}}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
assert_choices(Choices),
validate_select_val(Fail, Choices, Src, Vst);
vi({select_tuple_arity,Tuple0,{f,Fail},{list,Choices}}, Vst) ->
Tuple = unpack_typed_arg(Tuple0, Vst),
assert_type(#t_tuple{}, Tuple, Vst),
assert_arities(Choices),
validate_select_tuple_arity(Fail, Choices, Tuple, Vst);
vi({test,has_map_fields,{f,Lbl},Src,{list,List}}, Vst) ->
verify_has_map_fields(Lbl, Src, List, Vst);
vi({test,is_atom,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_atom{}, Src, Vst);
vi({test,is_binary,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_bitstring{size_unit=8}, Src, Vst);
vi({test,is_bitstr,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_bitstring{}, Src, Vst);
vi({test,is_boolean,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, beam_types:make_boolean(), Src, Vst);
vi({test,is_float,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_float{}, Src, Vst);
vi({test,is_function,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_fun{}, Src, Vst);
vi({test,is_function2,{f,Lbl},[Src,{integer,Arity}]}, Vst)
when Arity >= 0, Arity =< ?MAX_FUNC_ARGS ->
type_test(Lbl, #t_fun{arity=Arity}, Src, Vst);
vi({test,is_function2,{f,Lbl},[Src0,_Arity]}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
%% We cannot subtract the function type when the arity is
%% unknown: `Src` may still be a function if the arity is
%% outside the allowed range.
FailVst
end,
fun(SuccVst) ->
update_type(fun meet/2, #t_fun{}, Src, SuccVst)
end);
vi({test,is_tuple,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_tuple{}, Src, Vst);
vi({test,is_integer,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_integer{}, Src, Vst);
vi({test,is_nonempty_list,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_cons{}, Src, Vst);
vi({test,is_number,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_number{}, Src, Vst);
vi({test,is_list,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_list{}, Src, Vst);
vi({test,is_map,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_map{}, Src, Vst);
vi({test,is_nil,{f,Lbl},[Src0]}, Vst) ->
%% is_nil is an exact check against the 'nil' value, and should not be
%% treated as a simple type test.
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
update_ne_types(Src, nil, FailVst)
end,
fun(SuccVst) ->
update_eq_types(Src, nil, SuccVst)
end);
vi({test,is_pid,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, pid, Src, Vst);
vi({test,is_port,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, port, Src, Vst);
vi({test,is_reference,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, reference, Src, Vst);
vi({test,test_arity,{f,Lbl},[Tuple,Sz]}, Vst) when is_integer(Sz) ->
assert_type(#t_tuple{}, Tuple, Vst),
Type = #t_tuple{exact=true,size=Sz},
type_test(Lbl, Type, Tuple, Vst);
vi({test,is_tagged_tuple,{f,Lbl},[Src0,Sz,Atom]}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
Es = #{ 1 => get_literal_type(Atom) },
Type = #t_tuple{exact=true,size=Sz,elements=Es},
type_test(Lbl, Type, Src, Vst);
vi({test,is_eq_exact,{f,Lbl},[Src0,Val0]}, Vst) ->
assert_no_exception(Lbl),
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
Val = unpack_typed_arg(Val0, Vst),
assert_term(Val, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
update_ne_types(Src, Val, FailVst)
end,
fun(SuccVst) ->
update_eq_types(Src, Val, SuccVst)
end);
vi({test,is_ne_exact,{f,Lbl},[Src0,Val0]}, Vst) ->
assert_no_exception(Lbl),
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
Val = unpack_typed_arg(Val0, Vst),
assert_term(Val, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
update_eq_types(Src, Val, FailVst)
end,
fun(SuccVst) ->
update_ne_types(Src, Val, SuccVst)
end);
%%
%% Simple getters that can't fail.
%%
vi({get_list,Src,D1,D2}, Vst0) ->
assert_not_literal(Src),
assert_type(#t_cons{}, Src, Vst0),
SrcType = get_term_type(Src, Vst0),
{HeadType, _, _} = beam_call_types:types(erlang, hd, [SrcType]),
{TailType, _, _} = beam_call_types:types(erlang, tl, [SrcType]),
Vst = extract_term(HeadType, get_hd, [Src], D1, Vst0),
extract_term(TailType, get_tl, [Src], D2, Vst, Vst0);
vi({get_hd,Src,Dst}, Vst) ->
assert_not_literal(Src),
assert_type(#t_cons{}, Src, Vst),
SrcType = get_term_type(Src, Vst),
{HeadType, _, _} = beam_call_types:types(erlang, hd, [SrcType]),
extract_term(HeadType, get_hd, [Src], Dst, Vst);
vi({get_tl,Src,Dst}, Vst) ->
assert_not_literal(Src),
assert_type(#t_cons{}, Src, Vst),
SrcType = get_term_type(Src, Vst),
{TailType, _, _} = beam_call_types:types(erlang, tl, [SrcType]),
extract_term(TailType, get_tl, [Src], Dst, Vst);
vi({get_tuple_element,Src,N,Dst}, Vst) ->
Index = N+1,
assert_not_literal(Src),
assert_type(#t_tuple{size=Index}, Src, Vst),
VRef = get_reg_vref(Src, Vst),
Type = fun(Vs) ->
#value{type=T} = map_get(VRef, Vs),
#t_tuple{elements=Es} = normalize(concrete_type(T, Vs)),
beam_types:get_tuple_element(Index, Es)
end,
extract_term(Type, {bif,element}, [{integer,Index}, Src], Dst, Vst);
%%
%% Allocate, deallocate, et.al.
%%
vi({test_heap,Heap,Live}, Vst) ->
test_heap(Heap, Live, Vst);
vi({allocate,Stk,Live}, Vst) ->
allocate(uninitialized, Stk, 0, Live, Vst);
vi({allocate_heap,Stk,Heap,Live}, Vst) ->
allocate(uninitialized, Stk, Heap, Live, Vst);
vi({allocate_zero,Stk,Live}, Vst) ->
allocate(initialized, Stk, 0, Live, Vst);
vi({allocate_heap_zero,Stk,Heap,Live}, Vst) ->
allocate(initialized, Stk, Heap, Live, Vst);
vi({deallocate,StkSize}, #vst{current=#st{numy=StkSize}}=Vst) ->
verify_no_ct(Vst),
deallocate(Vst);
vi({deallocate,_}, #vst{current=#st{numy=NumY}}) ->
error({allocated,NumY});
vi({trim,N,Remaining}, #vst{current=St0}=Vst) ->
#st{numy=NumY} = St0,
if
N =< NumY, N+Remaining =:= NumY ->
Vst#vst{current=trim_stack(N, 0, NumY, St0)};
N > NumY; N+Remaining =/= NumY ->
error({trim,N,Remaining,allocated,NumY})
end;
%%
%% Term-building instructions
%%
vi({put_list,A,B,Dst}, Vst0) ->
Vst = eat_heap(2, Vst0),
Head = get_term_type(A, Vst),
Tail = get_term_type(B, Vst),
create_term(beam_types:make_cons(Head, Tail), put_list, [A, B], Dst, Vst);
vi({put_tuple2,Dst,{list,Elements}}, Vst0) ->
_ = [assert_term(El, Vst0) || El <- Elements],
Size = length(Elements),
Vst = eat_heap(Size+1, Vst0),
{Es,_} = foldl(fun(Val, {Es0, Index}) ->
Type = get_term_type(Val, Vst0),
Es = beam_types:set_tuple_element(Index, Type, Es0),
{Es, Index + 1}
end, {#{}, 1}, Elements),
Type = #t_tuple{exact=true,size=Size,elements=Es},
create_term(Type, put_tuple2, [], Dst, Vst);
vi({set_tuple_element,Src,Tuple,N}, Vst) ->
%% This instruction never fails, though it may be invalid in some contexts;
%% see validate_mutation/2
I = N + 1,
assert_term(Src, Vst),
assert_type(#t_tuple{size=I}, Tuple, Vst),
%% Manually update the tuple type; we can't rely on the ordinary update
%% helpers as we must support overwriting (rather than just widening or
%% narrowing) known elements, and we can't use extract_term either since
%% the source tuple may be aliased.
TupleType0 = get_term_type(Tuple, Vst),
ArgType = get_term_type(Src, Vst),
TupleType = beam_types:update_tuple(TupleType0, [{I, ArgType}]),
override_type(TupleType, Tuple, Vst);
vi({update_record,_Hint,Size,Src,Dst,{list,Ss}}, Vst) ->
verify_update_record(Size, Src, Dst, Ss, Vst);
%%
%% Calls
%%
vi({apply,Live}, Vst) ->
validate_body_call(apply, Live+2, Vst);
vi({apply_last,Live,N}, Vst) ->
validate_tail_call(N, apply, Live+2, Vst);
vi({call,Live,Func}, Vst) ->
validate_body_call(Func, Live, Vst);
vi({call_ext,Live,Func}, Vst) ->
validate_body_call(Func, Live, Vst);
vi({call_only,Live,Func}, Vst) ->
validate_tail_call(none, Func, Live, Vst);
vi({call_ext_only,Live,Func}, Vst) ->
validate_tail_call(none, Func, Live, Vst);
vi({call_last,Live,Func,N}, Vst) ->
validate_tail_call(N, Func, Live, Vst);
vi({call_ext_last,Live,Func,N}, Vst) ->
validate_tail_call(N, Func, Live, Vst);
vi({call_fun2,{f,Lbl},Live,Fun0}, #vst{ft=Ft}=Vst) ->
%% Fun call with known target. Verify that the target exists, agrees with
%% the type annotation for `Fun`, and that it has environment variables.
%%
%% Direct fun calls without environment variables must be expressed as
%% local fun calls.
#{ name := Name, arity := TotalArity } = map_get(Lbl, Ft),
#tr{t=#t_fun{target={Name,TotalArity}},r=Fun} = Fun0, %Assertion.
true = Live < TotalArity, %Assertion.
assert_term(Fun, Vst),
validate_body_call('fun', Live, Vst);
vi({call_fun2,Tag,Live,Fun0}, Vst) ->
Fun = unpack_typed_arg(Fun0, Vst),
assert_term(Fun, Vst),
case Tag of
{atom,safe} -> ok;
{atom,unsafe} -> ok;
_ -> error({invalid_tag,Tag})
end,
branch(?EXCEPTION_LABEL, Vst,
fun(SuccVst0) ->
SuccVst = update_type(fun meet/2, #t_fun{arity=Live},
Fun, SuccVst0),
validate_body_call('fun', Live, SuccVst)
end);
vi({call_fun,Live}, Vst) ->
Fun = {x,Live},
assert_term(Fun, Vst),
branch(?EXCEPTION_LABEL, Vst,
fun(SuccVst0) ->
SuccVst = update_type(fun meet/2, #t_fun{arity=Live},
Fun, SuccVst0),
validate_body_call('fun', Live+1, SuccVst)
end);
vi({make_fun2,{f,Lbl},_,_,NumFree}, #vst{ft=Ft}=Vst0) ->
#{ name := Name, arity := TotalArity } = map_get(Lbl, Ft),
Arity = TotalArity - NumFree,
true = Arity >= 0, %Assertion.
Vst = prune_x_regs(NumFree, Vst0),
verify_call_args(make_fun, NumFree, Vst),
verify_y_init(Vst),
Type = #t_fun{target={Name,TotalArity},arity=Arity},
create_term(Type, make_fun, [], {x,0}, Vst);
vi({make_fun3,{f,Lbl},_,_,Dst,{list,Env}}, #vst{ft=Ft}=Vst0) ->
_ = [assert_term(E, Vst0) || E <- Env],
NumFree = length(Env),
#{ name := Name, arity := TotalArity } = map_get(Lbl, Ft),
Arity = TotalArity - NumFree,
true = Arity >= 0, %Assertion.
Vst = eat_heap_fun(Vst0),
Type = #t_fun{target={Name,TotalArity},arity=Arity},
create_term(Type, make_fun, [], Dst, Vst);
vi(return, Vst) ->
assert_durable_term({x,0}, Vst),
verify_return(Vst);
%%
BIF calls
%%
vi({bif,Op,{f,Fail},Ss0,Dst0}, Vst0) ->
Ss = [unpack_typed_arg(Arg, Vst0) || Arg <- Ss0],
Dst = unpack_typed_arg(Dst0, Vst0),
case is_float_arith_bif(Op, Ss) of
true ->
?EXCEPTION_LABEL = Fail, %Assertion.
validate_float_arith_bif(Ss, Dst, Vst0);
false ->
validate_src(Ss, Vst0),
validate_bif(bif, Op, Fail, Ss, Dst, Vst0, Vst0)
end;
vi({gc_bif,Op,{f,Fail},Live,Ss0,Dst0}, Vst0) ->
Ss = [unpack_typed_arg(Arg, Vst0) || Arg <- Ss0],
Dst = unpack_typed_arg(Dst0, Vst0),
validate_src(Ss, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
Heap allocations and X registers are killed regardless of whether we
fail or not , as we may fail after GC .
Vst1 = kill_heap_allocation(Vst0),
Vst = prune_x_regs(Live, Vst1),
validate_bif(gc_bif, Op, Fail, Ss, Dst, Vst0, Vst);
%%
%% Message instructions
%%
vi(send, Vst) ->
validate_body_call(send, 2, Vst);
vi({loop_rec,{f,Fail},Dst}, Vst0) ->
assert_no_exception(Fail),
Vst = update_receive_state(entered_loop, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
%% This term may not be part of the root set until
%% remove_message/0 is executed. If control transfers to the
%% loop_rec_end/1 instruction, no part of this term must be
%% stored in a Y register.
{Ref, SuccVst} = new_value(any, loop_rec, [], SuccVst0),
mark_fragile(Dst, set_reg_vref(Ref, Dst, SuccVst))
end);
vi({loop_rec_end,Lbl}, Vst) ->
assert_no_exception(Lbl),
verify_y_init(Vst),
kill_state(Vst);
vi({recv_marker_reserve=Op, Dst}, Vst) ->
create_term(#t_abstract{kind=receive_marker}, Op, [], Dst, Vst);
vi({recv_marker_bind, Marker, Ref}, Vst) ->
assert_type(#t_abstract{kind=receive_marker}, Marker, Vst),
assert_durable_term(Ref, Vst),
assert_not_literal(Ref),
Vst;
vi({recv_marker_clear, Ref}, Vst) ->
assert_durable_term(Ref, Vst),
assert_not_literal(Ref),
Vst;
vi({recv_marker_use, Ref}, Vst) ->
assert_durable_term(Ref, Vst),
assert_not_literal(Ref),
update_receive_state(marked_position, Vst);
vi(remove_message, Vst0) ->
Vst = update_receive_state(none, Vst0),
%% The message term is no longer fragile. It can be used
%% without restrictions.
remove_fragility(Vst);
vi(timeout, Vst0) ->
Vst = update_receive_state(none, Vst0),
prune_x_regs(0, Vst);
vi({wait,{f,Lbl}}, Vst) ->
assert_no_exception(Lbl),
verify_y_init(Vst),
branch(Lbl, Vst, fun kill_state/1);
vi({wait_timeout,{f,Lbl},Src}, Vst0) ->
assert_no_exception(Lbl),
assert_term(Src, Vst0),
verify_y_init(Vst0),
Vst = branch(Lbl, schedule_out(0, Vst0)),
branch(?EXCEPTION_LABEL, Vst);
%%
%% Catch & try.
%%
vi({'catch',Dst,{f,Fail}}, Vst) when Fail =/= none ->
init_try_catch_branch(catchtag, Dst, Fail, Vst);
vi({'try',Dst,{f,Fail}}, Vst) when Fail =/= none ->
init_try_catch_branch(trytag, Dst, Fail, Vst);
vi({catch_end,Reg}, #vst{current=#st{ct=[Tag|_]}}=Vst0) ->
case get_tag_type(Reg, Vst0) of
{catchtag,_Fail}=Tag ->
Vst = kill_catch_tag(Reg, Vst0),
%% {x,0} contains the caught term, if any.
create_term(any, catch_end, [], {x,0}, Vst);
Type ->
error({wrong_tag_type,Type})
end;
vi({try_end,Reg}, #vst{current=#st{ct=[Tag|_]}}=Vst) ->
case get_tag_type(Reg, Vst) of
{trytag,_Fail}=Tag ->
%% Kill the catch tag without affecting X registers.
kill_catch_tag(Reg, Vst);
Type ->
error({wrong_tag_type,Type})
end;
vi({try_case,Reg}, #vst{current=#st{ct=[Tag|_]}}=Vst0) ->
case get_tag_type(Reg, Vst0) of
{trytag,_Fail}=Tag ->
%% Kill the catch tag and all other state (as if we've been
%% scheduled out with no live registers). Only previously allocated
%% Y registers are alive at this point.
Vst1 = kill_catch_tag(Reg, Vst0),
Vst2 = schedule_out(0, Vst1),
%% Class:Error:Stacktrace
ClassType = #t_atom{elements=[error,exit,throw]},
Vst3 = create_term(ClassType, try_case, [], {x,0}, Vst2),
Vst = create_term(any, try_case, [], {x,1}, Vst3),
create_term(any, try_case, [], {x,2}, Vst);
Type ->
error({wrong_tag_type,Type})
end;
vi(build_stacktrace, Vst0) ->
verify_y_init(Vst0),
verify_live(1, Vst0),
Vst = prune_x_regs(1, Vst0),
Reg = {x,0},
assert_durable_term(Reg, Vst),
create_term(#t_list{}, build_stacktrace, [], Reg, Vst);
%%
%% Map instructions.
%%
vi({get_map_elements,{f,Fail},Src0,{list,List}}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
verify_get_map(Fail, Src, List, Vst);
vi({put_map_assoc=Op,{f,Fail},Src,Dst,Live,{list,List}}, Vst) ->
verify_put_map(Op, Fail, Src, Dst, Live, List, Vst);
vi({put_map_exact=Op,{f,Fail},Src,Dst,Live,{list,List}}, Vst) ->
verify_put_map(Op, Fail, Src, Dst, Live, List, Vst);
%%
%% Bit syntax matching
%%
vi({bs_match,{f,Fail},Ctx0,{commands,List}}, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
verify_y_init(Vst),
branch(Fail, Vst,
fun(FailVst) ->
validate_failed_bs_match(List, Ctx, FailVst)
end,
fun(SuccVst) ->
validate_bs_match(List, Ctx, 1, SuccVst)
end);
vi({bs_get_tail,Ctx,Dst,Live}, Vst0) ->
assert_type(#t_bs_context{}, Ctx, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
#t_bs_context{tail_unit=Unit} = get_concrete_type(Ctx, Vst0),
Vst = prune_x_regs(Live, Vst0),
extract_term(#t_bitstring{size_unit=Unit}, bs_get_tail, [Ctx], Dst,
Vst, Vst0);
vi({bs_start_match4,Fail,Live,Src,Dst}, Vst) ->
validate_bs_start_match(Fail, Live, Src, Dst, Vst);
vi({test,bs_start_match3,{f,_}=Fail,Live,[Src],Dst}, Vst) ->
validate_bs_start_match(Fail, Live, Src, Dst, Vst);
vi({test,bs_match_string,{f,Fail},[Ctx,Stride,{string,String}]}, Vst) ->
true = is_bitstring(String), %Assertion.
validate_bs_skip(Fail, Ctx, Stride, Vst);
vi({test,bs_skip_bits2,{f,Fail},[Ctx,Size0,Unit,_Flags]}, Vst) ->
Size = unpack_typed_arg(Size0, Vst),
assert_term(Size, Vst),
Stride = case get_concrete_type(Size, Vst) of
#t_integer{elements={Same,Same}} -> Same * Unit;
_ -> Unit
end,
validate_bs_skip(Fail, Ctx, Stride, Vst);
vi({test,bs_test_tail2,{f,Fail},[Ctx,_Size]}, Vst) ->
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
branch(Fail, Vst);
vi({test,bs_test_unit,{f,Fail},[Ctx,Unit]}, Vst) ->
assert_type(#t_bs_context{}, Ctx, Vst),
Type = #t_bs_context{tail_unit=Unit},
branch(Fail, Vst,
fun(FailVst) ->
update_type(fun subtract/2, Type, Ctx, FailVst)
end,
fun(SuccVst0) ->
SuccVst = update_bs_unit(Ctx, Unit, SuccVst0),
update_type(fun meet/2, Type, Ctx, SuccVst)
end);
vi({test,bs_skip_utf8,{f,Fail},[Ctx,Live,_]}, Vst) ->
validate_bs_skip(Fail, Ctx, 8, Live, Vst);
vi({test,bs_skip_utf16,{f,Fail},[Ctx,Live,_]}, Vst) ->
validate_bs_skip(Fail, Ctx, 16, Live, Vst);
vi({test,bs_skip_utf32,{f,Fail},[Ctx,Live,_]}, Vst) ->
validate_bs_skip(Fail, Ctx, 32, Live, Vst);
vi({test,bs_get_binary2=Op,{f,Fail},Live,[Ctx,{atom,all},Unit,_],Dst}, Vst) ->
Type = #t_bitstring{size_unit=Unit},
validate_bs_get_all(Op, Fail, Ctx, Live, Unit, Type, Dst, Vst);
vi({test,bs_get_binary2=Op,{f,Fail},Live,[Ctx,Size,Unit,_],Dst}, Vst) ->
Type = #t_bitstring{size_unit=bsm_size_unit(Size, Unit)},
Stride = bsm_stride(Size, Unit),
validate_bs_get(Op, Fail, Ctx, Live, Stride, Type, Dst, Vst);
vi({test,bs_get_integer2=Op,{f,Fail},Live,
[Ctx,{integer,Size},Unit,{field_flags,Flags}],Dst},Vst) ->
Type = bs_integer_type({Size, Size}, Unit, Flags),
Stride = Unit * Size,
validate_bs_get(Op, Fail, Ctx, Live, Stride, Type, Dst, Vst);
vi({test,bs_get_integer2=Op,{f,Fail},Live,[Ctx,Sz0,Unit,{field_flags,Flags}],Dst},Vst) ->
Sz = unpack_typed_arg(Sz0, Vst),
Type = case meet(get_term_type(Sz, Vst), #t_integer{}) of
#t_integer{elements=Bounds} ->
bs_integer_type(Bounds, Unit, Flags);
none ->
none
end,
validate_bs_get(Op, Fail, Ctx, Live, Unit, Type, Dst, Vst);
vi({test,bs_get_float2=Op,{f,Fail},Live,[Ctx,Size,Unit,_],Dst},Vst) ->
Stride = bsm_stride(Size, Unit),
validate_bs_get(Op, Fail, Ctx, Live, Stride, #t_float{}, Dst, Vst);
vi({test,bs_get_utf8=Op,{f,Fail},Live,[Ctx,_],Dst}, Vst) ->
Type = beam_types:make_integer(0, ?UNICODE_MAX),
validate_bs_get(Op, Fail, Ctx, Live, 8, Type, Dst, Vst);
vi({test,bs_get_utf16=Op,{f,Fail},Live,[Ctx,_],Dst}, Vst) ->
Type = beam_types:make_integer(0, ?UNICODE_MAX),
validate_bs_get(Op, Fail, Ctx, Live, 16, Type, Dst, Vst);
vi({test,bs_get_utf32=Op,{f,Fail},Live,[Ctx,_],Dst}, Vst) ->
Type = beam_types:make_integer(0, ?UNICODE_MAX),
validate_bs_get(Op, Fail, Ctx, Live, 32, Type, Dst, Vst);
vi({test,is_lt,{f,Fail},Args0}, Vst) ->
Args = [unpack_typed_arg(Arg, Vst) || Arg <- Args0],
validate_src(Args, Vst),
Types = [get_term_type(Arg, Vst) || Arg <- Args],
branch(Fail, Vst,
fun(FailVst) ->
infer_relop_types('>=', Args, Types, FailVst)
end,
fun(SuccVst) ->
infer_relop_types('<', Args, Types, SuccVst)
end);
vi({test,is_ge,{f,Fail},Args0}, Vst) ->
Args = [unpack_typed_arg(Arg, Vst) || Arg <- Args0],
validate_src(Args, Vst),
Types = [get_term_type(Arg, Vst) || Arg <- Args],
branch(Fail, Vst,
fun(FailVst) ->
infer_relop_types('<', Args, Types, FailVst)
end,
fun(SuccVst) ->
infer_relop_types('>=', Args, Types, SuccVst)
end);
vi({test,_Op,{f,Lbl},Ss}, Vst) ->
validate_src([unpack_typed_arg(Arg, Vst) || Arg <- Ss], Vst),
branch(Lbl, Vst);
%%
%% Bit syntax positioning
%%
vi({bs_get_position, Ctx, Dst, Live}, Vst0) ->
assert_type(#t_bs_context{}, Ctx, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
#t_bs_context{tail_unit=Unit} = get_concrete_type(Ctx, Vst0),
Vst1 = prune_x_regs(Live, Vst0),
Vst = create_term(#t_abstract{kind={ms_position, Unit}},
bs_get_position, [Ctx], Dst, Vst1, Vst0),
mark_current_ms_position(Ctx, Dst, Vst);
vi({bs_set_position, Ctx, Pos}, Vst0) ->
assert_type(#t_bs_context{}, Ctx, Vst0),
assert_type(#t_abstract{kind={ms_position,1}}, Pos, Vst0),
#t_abstract{kind={ms_position,Unit}} = get_concrete_type(Pos, Vst0),
Vst = override_type(#t_bs_context{tail_unit=Unit}, Ctx, Vst0),
mark_current_ms_position(Ctx, Pos, Vst);
%%
%% Floating-point instructions (excluding BIFs)
%%
vi({fconv,Src0,{fr,_}=Dst}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst,
fun(SuccVst0) ->
SuccVst = update_type(fun meet/2, #t_number{}, Src, SuccVst0),
set_freg(Dst, SuccVst)
end);
%%
%% Exception-raising instructions
%%
vi({func_info, {atom, _Mod}, {atom, _Name}, Arity}, Vst) ->
#vst{current=#st{numy=NumY}} = Vst,
if
NumY =:= none ->
verify_live(Arity, Vst),
verify_call_args(func_info, Arity, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
NumY =/= none ->
error({allocated, NumY})
end;
vi({badmatch,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi({case_end,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi(if_end, Vst) ->
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi({try_case_end,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi({badrecord,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi(raw_raise=I, Vst0) ->
validate_body_call(I, 3, Vst0);
%%
%% Binary construction
%%
vi(bs_init_writable=I, Vst) ->
validate_body_call(I, 1, Vst);
vi({bs_create_bin,{f,Fail},Heap,Live,Unit,Dst,{list,List0}}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
List = [unpack_typed_arg(Arg, Vst0) || Arg <- List0],
verify_create_bin_list(List, Vst0),
Vst = prune_x_regs(Live, Vst0),
branch(Fail, Vst,
fun(FailVst0) ->
heap_alloc(0, FailVst0)
end,
fun(SuccVst0) ->
SuccVst1 = update_create_bin_list(List, SuccVst0),
SuccVst = heap_alloc(Heap, SuccVst1),
create_term(#t_bitstring{size_unit=Unit}, bs_create_bin, [], Dst,
SuccVst)
end);
vi({bs_init2,{f,Fail},Sz,Heap,Live,_,Dst}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
if
is_integer(Sz) -> ok;
true -> assert_term(Sz, Vst0)
end,
Vst = heap_alloc(Heap, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
create_term(#t_bitstring{size_unit=8}, bs_init2, [], Dst,
SuccVst, SuccVst0)
end);
vi({bs_init_bits,{f,Fail},Sz,Heap,Live,_,Dst}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
if
is_integer(Sz) -> ok;
true -> assert_term(Sz, Vst0)
end,
Vst = heap_alloc(Heap, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
create_term(#t_bitstring{}, bs_init_bits, [], Dst, SuccVst)
end);
vi({bs_add,{f,Fail},[A,B,_],Dst}, Vst) ->
assert_term(A, Vst),
assert_term(B, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_integer{}, bs_add, [A, B], Dst, SuccVst)
end);
vi({bs_utf8_size,{f,Fail},A,Dst}, Vst) ->
assert_term(A, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_integer{}, bs_utf8_size, [A], Dst, SuccVst)
end);
vi({bs_utf16_size,{f,Fail},A,Dst}, Vst) ->
assert_term(A, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_integer{}, bs_utf16_size, [A], Dst, SuccVst)
end);
vi({bs_append,{f,Fail},Bits,Heap,Live,Unit,Bin,_Flags,Dst}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
assert_term(Bits, Vst0),
assert_term(Bin, Vst0),
Vst = heap_alloc(Heap, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
create_term(#t_bitstring{size_unit=Unit}, bs_append,
[Bin], Dst, SuccVst, SuccVst0)
end);
vi({bs_private_append,{f,Fail},Bits,Unit,Bin,_Flags,Dst}, Vst) ->
assert_term(Bits, Vst),
assert_term(Bin, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_bitstring{size_unit=Unit}, bs_private_append,
[Bin], Dst, SuccVst)
end);
vi({bs_put_string,Sz,_}, Vst) when is_integer(Sz) ->
Vst;
vi({bs_put_binary,{f,Fail},Sz,_,_,Src}, Vst) ->
assert_term(Sz, Vst),
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_bitstring{}, Src, SuccVst)
end);
vi({bs_put_float,{f,Fail},Sz,_,_,Src}, Vst) ->
assert_term(Sz, Vst),
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_float{}, Src, SuccVst)
end);
vi({bs_put_integer,{f,Fail},Sz,_,_,Src}, Vst) ->
assert_term(Sz, Vst),
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi({bs_put_utf8,{f,Fail},_,Src}, Vst) ->
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi({bs_put_utf16,{f,Fail},_,Src}, Vst) ->
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi({bs_put_utf32,{f,Fail},_,Src}, Vst) ->
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi(_, _) ->
error(unknown_instruction).
infer_relop_types(Op, Args, Types, Vst) ->
case infer_relop_types(Op, Types) of
[] ->
Vst;
Infer ->
Zipped = zip(Args, Infer),
foldl(fun({V,T}, Acc) ->
update_type(fun meet/2, T, V, Acc)
end, Vst, Zipped)
end.
infer_relop_types(Op, [#t_integer{elements=R1},
#t_integer{elements=R2}]) ->
case beam_bounds:infer_relop_types(Op, R1, R2) of
{NewR1,NewR2} ->
NewType1 = #t_integer{elements=NewR1},
NewType2 = #t_integer{elements=NewR2},
[NewType1,NewType2];
none ->
[none, none];
any ->
[]
end;
infer_relop_types(Op0, [Type1,Type2]) ->
Op = case Op0 of
'<' -> '=<';
'>' -> '>=';
_ -> Op0
end,
case {infer_get_range(Type1),infer_get_range(Type2)} of
{none,_}=R ->
[infer_relop_any(Op, R, Type1),Type2];
{_,none}=R ->
[Type1,infer_relop_any(Op, R, Type2)];
{R1,R2} ->
case beam_bounds:infer_relop_types(Op, R1, R2) of
{NewR1,NewR2} ->
NewType1 = meet(#t_number{elements=NewR1}, Type1),
NewType2 = meet(#t_number{elements=NewR2}, Type2),
[NewType1,NewType2];
none ->
[none, none];
any ->
[]
end
end;
infer_relop_types(_, _) ->
[].
infer_relop_any('=<', {none,any}, Type) ->
N = #t_number{},
meet(N, Type);
infer_relop_any('=<', {none,{_,Max}}, Type) ->
N = infer_make_number({'-inf',Max}),
meet(N, Type);
infer_relop_any('>=', {any,none}, Type) ->
N = #t_number{},
meet(N, Type);
infer_relop_any('>=', {{_,Max},none}, Type) ->
N = infer_make_number({'-inf',Max}),
meet(N, Type);
infer_relop_any('>=', {none,{Min,_}}, Type) when is_integer(Min) ->
N = #t_number{elements={'-inf',Min}},
meet(subtract(any, N), Type);
infer_relop_any('=<', {{Min,_},none}, Type) when is_integer(Min) ->
N = #t_number{elements={'-inf',Min}},
meet(subtract(any, N), Type);
infer_relop_any(_, _, Type) ->
Type.
infer_make_number({'-inf','+inf'}) ->
#t_number{};
infer_make_number({_,_}=R) ->
#t_number{elements=R}.
infer_get_range(#t_integer{elements=R}) -> R;
infer_get_range(#t_number{elements=R}) -> R;
infer_get_range(_) -> none.
validate_var_info([{fun_type, Type} | Info], Reg, Vst0) ->
%% Explicit type information inserted after make_fun2 instructions to mark
%% the return type of the created fun.
Vst = update_type(fun meet/2, #t_fun{type=Type}, Reg, Vst0),
validate_var_info(Info, Reg, Vst);
validate_var_info([{type, none} | _Info], _Reg, Vst) ->
Unreachable code , typically after a call that never returns .
kill_state(Vst);
validate_var_info([{type, Type} | Info], Reg, Vst0) ->
%% Explicit type information inserted by optimization passes to indicate
that has a certain type , so that we can accept cross - function type
%% optimizations.
Vst = update_type(fun meet/2, Type, Reg, Vst0),
validate_var_info(Info, Reg, Vst);
validate_var_info([_ | Info], Reg, Vst) ->
validate_var_info(Info, Reg, Vst);
validate_var_info([], _Reg, Vst) ->
Vst.
%% Tail call.
%% The stackframe must have a known size and be initialized.
%% Does not return to the instruction following the call.
validate_tail_call(Deallocate, Func, Live, #vst{current=#st{numy=NumY}}=Vst0) ->
verify_y_init(Vst0),
verify_live(Live, Vst0),
verify_call_args(Func, Live, Vst0),
case will_call_succeed(Func, Live, Vst0) of
yes when Deallocate =:= NumY ->
%% The call cannot fail; we don't need to handle exceptions
Vst = deallocate(Vst0),
verify_return(Vst);
'maybe' when Deallocate =:= NumY ->
%% The call may fail; make sure we update exception state
Vst = deallocate(Vst0),
branch(?EXCEPTION_LABEL, Vst, fun verify_return/1);
no ->
The compiler is allowed to emit garbage values for " "
%% as we know that it will not be used in this case.
branch(?EXCEPTION_LABEL, Vst0, fun kill_state/1);
_ when Deallocate =/= NumY ->
error({allocated, NumY})
end.
%% A "plain" call.
%% The stackframe must be initialized.
%% The instruction will return to the instruction following the call.
validate_body_call(Func, Live,
#vst{current=#st{numy=NumY}}=Vst) when is_integer(NumY)->
verify_y_init(Vst),
verify_live(Live, Vst),
verify_call_args(Func, Live, Vst),
SuccFun = fun(SuccVst0) ->
%% Note that we don't try to infer anything from the
%% argument types, as that may cause types to become
%% concrete "too early."
%%
%% See beam_types_SUITE:premature_concretization/1 for
%% details.
{RetType, _, _} = call_types(Func, Live, SuccVst0),
true = RetType =/= none, %Assertion.
SuccVst = schedule_out(0, SuccVst0),
create_term(RetType, call, [], {x,0}, SuccVst)
end,
case will_call_succeed(Func, Live, Vst) of
yes ->
SuccFun(Vst);
'maybe' ->
branch(?EXCEPTION_LABEL, Vst, SuccFun);
no ->
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1)
end;
validate_body_call(_, _, #vst{current=#st{numy=NumY}}) ->
error({allocated, NumY}).
init_try_catch_branch(Kind, Dst, Fail, Vst0) ->
assert_no_exception(Fail),
Tag = {Kind, [Fail]},
Vst = create_tag(Tag, 'try_catch', [], Dst, Vst0),
#vst{current=St0} = Vst,
#st{ct=Tags}=St0,
St = St0#st{ct=[Tag|Tags]},
Vst#vst{current=St}.
verify_has_map_fields(Lbl, Src, List, Vst) ->
assert_type(#t_map{}, Src, Vst),
assert_unique_map_keys(List),
verify_map_fields(List, Src, Lbl, Vst).
verify_map_fields([Key | Keys], Map, Lbl, Vst) ->
assert_term(Key, Vst),
case bif_types(map_get, [Key, Map], Vst) of
{none, _, _} -> kill_state(Vst);
{_, _, _} -> verify_map_fields(Keys, Map, Lbl, Vst)
end;
verify_map_fields([], _Map, Lbl, Vst) ->
branch(Lbl, Vst).
verify_get_map(Fail, Src, List, Vst0) ->
assert_no_exception(Fail),
OTP 22 .
assert_type(#t_map{}, Src, Vst0),
branch(Fail, Vst0,
fun(FailVst) ->
clobber_map_vals(List, Src, FailVst)
end,
fun(SuccVst) ->
Keys = extract_map_keys(List, SuccVst),
assert_unique_map_keys(Keys),
extract_map_vals(List, Src, SuccVst)
end).
%% get_map_elements may leave its destinations in an inconsistent state when
%% the fail label is taken. Consider the following:
%%
{ , a},{x,1},{atom , b},{x,2 } ] } } .
%%
%% If 'a' exists but not 'b', {x,1} is overwritten when we jump to {f,7}.
%%
%% We must be careful to preserve the uninitialized status for Y registers
%% that have been allocated but not yet defined.
clobber_map_vals([Key0, Dst | T], Map, Vst0) ->
Key = unpack_typed_arg(Key0, Vst0),
case is_reg_initialized(Dst, Vst0) of
true ->
Vst = extract_term(any, {bif,map_get}, [Key, Map], Dst, Vst0),
clobber_map_vals(T, Map, Vst);
false ->
clobber_map_vals(T, Map, Vst0)
end;
clobber_map_vals([], _Map, Vst) ->
Vst.
is_reg_initialized({x,_}=Reg, #vst{current=#st{xs=Xs}}) ->
is_map_key(Reg, Xs);
is_reg_initialized({y,_}=Reg, #vst{current=#st{ys=Ys}}) ->
case Ys of
#{Reg:=Val} ->
Val =/= uninitialized;
#{} ->
false
end;
is_reg_initialized(V, #vst{}) -> error({not_a_register, V}).
extract_map_keys([Key,_Val | T], Vst) ->
[unpack_typed_arg(Key, Vst) | extract_map_keys(T, Vst)];
extract_map_keys([], _Vst) ->
[].
extract_map_vals(List, Src, SuccVst) ->
Seen = sets:new([{version, 2}]),
extract_map_vals(List, Src, Seen, SuccVst, SuccVst).
extract_map_vals([Key0, Dst | Vs], Map, Seen0, Vst0, Vsti0) ->
case sets:is_element(Dst, Seen0) of
true ->
%% The destinations must not overwrite each other.
error(conflicting_destinations);
false ->
Key = unpack_typed_arg(Key0, Vsti0),
assert_term(Key, Vst0),
case bif_types(map_get, [Key, Map], Vst0) of
{none, _, _} ->
kill_state(Vsti0);
{DstType, _, _} ->
Vsti = extract_term(DstType, {bif,map_get},
[Key, Map], Dst, Vsti0),
Seen = sets:add_element(Dst, Seen0),
extract_map_vals(Vs, Map, Seen, Vst0, Vsti)
end
end;
extract_map_vals([], _Map, _Seen, _Vst0, Vst) ->
Vst.
verify_put_map(Op, Fail, Src, Dst, Live, List, Vst0) ->
assert_type(#t_map{}, Src, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
_ = [assert_term(Term, Vst0) || Term <- List],
Vst = heap_alloc(0, Vst0),
SuccFun = fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
Keys = extract_map_keys(List, SuccVst),
assert_unique_map_keys(Keys),
Type = put_map_type(Src, List, Vst),
create_term(Type, Op, [Src], Dst, SuccVst, SuccVst0)
end,
case Op of
put_map_exact ->
branch(Fail, Vst, SuccFun);
put_map_assoc ->
%% This instruction cannot fail.
?EXCEPTION_LABEL = Fail, %Assertion.
SuccFun(Vst)
end.
put_map_type(Map0, List, Vst) ->
Map = get_term_type(Map0, Vst),
pmt_1(List, Vst, Map).
pmt_1([Key0, Value0 | List], Vst, Acc0) ->
Key = get_term_type(Key0, Vst),
Value = get_term_type(Value0, Vst),
{Acc, _, _} = beam_call_types:types(maps, put, [Key, Value, Acc0]),
pmt_1(List, Vst, Acc);
pmt_1([], _Vst, Acc) ->
Acc.
verify_update_record(Size, Src, Dst, List, Vst0) ->
assert_type(#t_tuple{exact=true,size=Size}, Src, Vst0),
verify_y_init(Vst0),
Vst = eat_heap(Size + 1, Vst0),
case update_tuple_type(List, Src, Vst) of
none -> error(invalid_index);
Type -> create_term(Type, update_record, [], Dst, Vst)
end.
update_tuple_type([_|_]=Updates0, Src, Vst) ->
Filter = #t_tuple{size=update_tuple_highest_index(Updates0, -1)},
case meet(get_term_type(Src, Vst), Filter) of
none ->
none;
TupleType ->
Updates = update_tuple_type_1(Updates0, Vst),
beam_types:update_tuple(TupleType, Updates)
end.
update_tuple_type_1([Index, Value | Updates], Vst) ->
[{Index, get_term_type(Value, Vst)} | update_tuple_type_1(Updates, Vst)];
update_tuple_type_1([], _Vst) ->
[].
update_tuple_highest_index([Index, _Val | List], Acc) when is_integer(Index) ->
update_tuple_highest_index(List, max(Index, Acc));
update_tuple_highest_index([], Acc) when Acc >= 1 ->
Acc.
verify_create_bin_list([{atom,string},_Seg,Unit,Flags,Val,Size|Args], Vst) ->
assert_bs_unit({atom,string}, Unit),
assert_term(Flags, Vst),
case Val of
{string,Bs} when is_binary(Bs) -> ok;
_ -> error({not_string,Val})
end,
assert_term(Flags, Vst),
assert_term(Size, Vst),
verify_create_bin_list(Args, Vst);
verify_create_bin_list([Type,_Seg,Unit,Flags,Val,Size|Args], Vst) ->
assert_term(Type, Vst),
assert_bs_unit(Type, Unit),
assert_term(Flags, Vst),
assert_term(Val, Vst),
assert_term(Size, Vst),
verify_create_bin_list(Args, Vst);
verify_create_bin_list([], _Vst) -> ok.
update_create_bin_list([{atom,string},_Seg,_Unit,_Flags,_Val,_Size|T], Vst) ->
update_create_bin_list(T, Vst);
update_create_bin_list([{atom,Op},_Seg,_Unit,_Flags,Val,_Size|T], Vst0) ->
Type = update_create_bin_type(Op),
Vst = update_type(fun meet/2, Type, Val, Vst0),
update_create_bin_list(T, Vst);
update_create_bin_list([], Vst) -> Vst.
update_create_bin_type(append) -> #t_bitstring{};
update_create_bin_type(private_append) -> #t_bitstring{};
update_create_bin_type(binary) -> #t_bitstring{};
update_create_bin_type(float) -> #t_float{};
update_create_bin_type(integer) -> #t_integer{};
update_create_bin_type(utf8) -> #t_integer{};
update_create_bin_type(utf16) -> #t_integer{};
update_create_bin_type(utf32) -> #t_integer{}.
assert_bs_unit({atom,Type}, 0) ->
case Type of
utf8 -> ok;
utf16 -> ok;
utf32 -> ok;
_ -> error({zero_unit_invalid_for_type,Type})
end;
assert_bs_unit({atom,_Type}, Unit) when is_integer(Unit), 0 < Unit, Unit =< 256 ->
ok;
assert_bs_unit(_, Unit) ->
error({invalid,Unit}).
%%
%% Common code for validating returns, whether naked or as part of a tail call.
%%
verify_return(#vst{current=#st{numy=NumY}}) when NumY =/= none ->
error({stack_frame,NumY});
verify_return(#vst{current=#st{recv_state=State}}) when State =/= none ->
%% Returning in the middle of a receive loop will ruin the next receive.
error({return_in_receive,State});
verify_return(Vst) ->
verify_no_ct(Vst),
kill_state(Vst).
%%
%% Common code for validating BIFs.
%%
%% OrigVst is the state we entered the instruction with, which is needed for
%% gc_bifs as X registers are pruned prior to calling this function, which may
%% have clobbered the sources.
%%
validate_bif(Kind, Op, Fail, Ss, Dst, OrigVst, Vst) ->
case will_bif_succeed(Op, Ss, Vst) of
yes ->
This BIF can not fail ( neither throw nor branch ) , make sure it 's
%% handled without updating exception state.
validate_bif_1(Kind, Op, cannot_fail, Ss, Dst, OrigVst, Vst);
no ->
This BIF always fails ; jump directly to the fail block or
%% exception handler.
branch(Fail, Vst, fun kill_state/1);
'maybe' ->
validate_bif_1(Kind, Op, Fail, Ss, Dst, OrigVst, Vst)
end.
validate_bif_1(Kind, Op, cannot_fail, Ss, Dst, OrigVst, Vst0) ->
This BIF explicitly can not fail ; it will not jump to a guard nor throw
%% an exception. Validation will fail if it returns 'none' or has a type
%% conflict on one of its arguments.
{Type, ArgTypes, _CanSubtract} = bif_types(Op, Ss, Vst0),
ZippedArgs = zip(Ss, ArgTypes),
Vst = foldl(fun({A, T}, V) ->
update_type(fun meet/2, T, A, V)
end, Vst0, ZippedArgs),
true = Type =/= none, %Assertion.
extract_term(Type, {Kind, Op}, Ss, Dst, Vst, OrigVst);
validate_bif_1(Kind, Op, Fail, Ss, Dst, OrigVst, Vst) ->
{Type, ArgTypes, CanSubtract} = bif_types(Op, Ss, Vst),
ZippedArgs = zip(Ss, ArgTypes),
FailFun = case CanSubtract of
true ->
fun(FailVst0) ->
foldl(fun({A, T}, V) ->
update_type(fun subtract/2, T, A, V)
end, FailVst0, ZippedArgs)
end;
false ->
fun(S) -> S end
end,
SuccFun = fun(SuccVst0) ->
SuccVst = foldl(fun({A, T}, V) ->
update_type(fun meet/2, T, A, V)
end, SuccVst0, ZippedArgs),
extract_term(Type, {Kind, Op}, Ss, Dst, SuccVst, OrigVst)
end,
branch(Fail, Vst, FailFun, SuccFun).
%%
%% Common code for validating bs_start_match* instructions.
%%
validate_bs_start_match({atom,resume}, Live, Src, Dst, Vst0) ->
assert_type(#t_bs_context{}, Src, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
Vst = assign(Src, Dst, Vst0),
prune_x_regs(Live, Vst);
validate_bs_start_match({atom,no_fail}, Live, Src, Dst, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
Vst1 = update_type(fun meet/2, #t_bs_matchable{}, Src, Vst0),
%% Retain the current unit, if known.
SrcType = get_movable_term_type(Src, Vst1),
TailUnit = beam_types:get_bs_matchable_unit(SrcType),
Vst = prune_x_regs(Live, Vst1),
extract_term(#t_bs_context{tail_unit=TailUnit}, bs_start_match,
[Src], Dst, Vst, Vst0);
validate_bs_start_match({f,Fail}, Live, Src, Dst, Vst) ->
assert_no_exception(Fail),
branch(Fail, Vst,
fun(FailVst) ->
update_type(fun subtract/2, #t_bs_matchable{}, Src, FailVst)
end,
fun(SuccVst) ->
validate_bs_start_match({atom,no_fail}, Live,
Src, Dst, SuccVst)
end).
%%
Validate the bs_match instruction .
%%
validate_bs_match([I|Is], Ctx, Unit0, Vst0) ->
case I of
{ensure_at_least,_Size,Unit} ->
Type = #t_bs_context{tail_unit=Unit},
Vst1 = update_bs_unit(Ctx, Unit, Vst0),
Vst = update_type(fun meet/2, Type, Ctx, Vst1),
validate_bs_match(Is, Ctx, Unit, Vst);
{ensure_exactly,Stride} ->
Vst = advance_bs_context(Ctx, Stride, Vst0),
validate_bs_match(Is, Ctx, Unit0, Vst);
{'=:=',nil,Bits,Value} when Bits =< 64, is_integer(Value) ->
validate_bs_match(Is, Ctx, Unit0, Vst0);
{Type0,Live,{literal,Flags},Size,Unit,Dst} when Type0 =:= binary;
Type0 =:= integer ->
validate_ctx_live(Ctx, Live),
verify_live(Live, Vst0),
Vst1 = prune_x_regs(Live, Vst0),
Type = case Type0 of
integer ->
true = is_integer(Size), %Assertion.
bs_integer_type({Size, Size}, Unit, Flags);
binary ->
SizeUnit = bsm_size_unit({integer,Size}, Unit),
#t_bitstring{size_unit=SizeUnit}
end,
Vst = extract_term(Type, bs_match, [Ctx], Dst, Vst1, Vst0),
validate_bs_match(Is, Ctx, Unit0, Vst);
{skip,_Stride} ->
validate_bs_match(Is, Ctx, Unit0, Vst0);
{get_tail,Live,_,Dst} ->
validate_ctx_live(Ctx, Live),
verify_live(Live, Vst0),
Vst1 = prune_x_regs(Live, Vst0),
#t_bs_context{tail_unit=Unit} = get_concrete_type(Ctx, Vst0),
Type = #t_bitstring{size_unit=Unit},
Vst = extract_term(Type, get_tail, [Ctx], Dst, Vst1, Vst0),
%% In rare circumstance, there can be multiple `get_tail` sub commands.
validate_bs_match(Is, Ctx, Unit, Vst)
end;
validate_bs_match([], _Ctx, _Unit, Vst) ->
Vst.
validate_ctx_live({x,X}=Ctx, Live) when X >= Live ->
error({live_does_not_preserve_context,Live,Ctx});
validate_ctx_live(_, _) ->
ok.
validate_failed_bs_match([{ensure_at_least,_Size,Unit}|_], Ctx, Vst) ->
Type = #t_bs_context{tail_unit=Unit},
update_type(fun subtract/2, Type, Ctx, Vst);
validate_failed_bs_match([_|Is], Ctx, Vst) ->
validate_failed_bs_match(Is, Ctx, Vst);
validate_failed_bs_match([], _Ctx, Vst) ->
Vst.
bs_integer_type(Bounds, Unit, Flags) ->
case beam_bounds:bounds('*', Bounds, {Unit, Unit}) of
{_, MaxBits} when is_integer(MaxBits), MaxBits >= 1, MaxBits =< 64 ->
case member(signed, Flags) of
true ->
Max = (1 bsl (MaxBits - 1)) - 1,
Min = -(Max + 1),
beam_types:make_integer(Min, Max);
false ->
Max = (1 bsl MaxBits) - 1,
beam_types:make_integer(0, Max)
end;
{_, 0} ->
beam_types:make_integer(0);
_ ->
case member(signed, Flags) of
true -> #t_integer{};
false -> #t_integer{elements={0,'+inf'}}
end
end.
%%
%% Common code for validating bs_get* instructions.
%%
validate_bs_get(_Op, Fail, Ctx0, Live, _Stride, none, _Dst, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
validate_bs_get_1(
Fail, Ctx, Live, Vst,
fun(SuccVst) ->
kill_state(SuccVst)
end);
validate_bs_get(Op, Fail, Ctx0, Live, Stride, Type, Dst, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
validate_bs_get_1(
Fail, Ctx, Live, Vst,
fun(SuccVst0) ->
SuccVst1 = advance_bs_context(Ctx, Stride, SuccVst0),
SuccVst = prune_x_regs(Live, SuccVst1),
extract_term(Type, Op, [Ctx], Dst, SuccVst, SuccVst0)
end).
validate_bs_get_all(Op, Fail, Ctx0, Live, Stride, Type, Dst, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
validate_bs_get_1(
Fail, Ctx, Live, Vst,
fun(SuccVst0) ->
%% This acts as an implicit unit test on the current match
%% position, so we'll update the unit in case we rewind here
%% later on.
SuccVst1 = update_bs_unit(Ctx, Stride, SuccVst0),
SuccVst2 = advance_bs_context(Ctx, Stride, SuccVst1),
SuccVst = prune_x_regs(Live, SuccVst2),
extract_term(Type, Op, [Ctx], Dst, SuccVst, SuccVst0)
end).
validate_bs_get_1(Fail, Ctx, Live, Vst, SuccFun) ->
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
verify_live(Live, Vst),
verify_y_init(Vst),
branch(Fail, Vst, SuccFun).
%%
%% Common code for validating bs_skip* instructions.
%%
validate_bs_skip(Fail, Ctx, Stride, Vst) ->
validate_bs_skip(Fail, Ctx, Stride, no_live, Vst).
validate_bs_skip(Fail, Ctx, Stride, Live, Vst) ->
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
validate_bs_skip_1(Fail, Ctx, Stride, Live, Vst).
validate_bs_skip_1(Fail, Ctx, Stride, no_live, Vst) ->
branch(Fail, Vst,
fun(SuccVst) ->
advance_bs_context(Ctx, Stride, SuccVst)
end);
validate_bs_skip_1(Fail, Ctx, Stride, Live, Vst) ->
verify_y_init(Vst),
verify_live(Live, Vst),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = advance_bs_context(Ctx, Stride, SuccVst0),
prune_x_regs(Live, SuccVst)
end).
advance_bs_context(_Ctx, 0, Vst) ->
%% We _KNOW_ we're not moving anywhere. Retain our current position and
%% type.
Vst;
advance_bs_context(_Ctx, Stride, _Vst) when Stride < 0 ->
%% We _KNOW_ we'll fail at runtime.
throw({invalid_argument, {negative_stride, Stride}});
advance_bs_context(Ctx, Stride, Vst0) ->
Vst = update_type(fun join/2, #t_bs_context{tail_unit=Stride}, Ctx, Vst0),
%% The latest saved position (if any) is no longer current, make sure
%% it isn't updated on the next match operation.
invalidate_current_ms_position(Ctx, Vst).
%% Updates the unit of our latest saved position, if it's current.
update_bs_unit(Ctx, Unit, #vst{current=St}=Vst) ->
CtxRef = get_reg_vref(Ctx, Vst),
case St#st.ms_positions of
#{ CtxRef := PosRef } ->
PosType = #t_abstract{kind={ms_position, Unit}},
update_type(fun meet/2, PosType, PosRef, Vst);
#{} ->
Vst
end.
mark_current_ms_position(Ctx, Pos, #vst{current=St0}=Vst) ->
CtxRef = get_reg_vref(Ctx, Vst),
PosRef = get_reg_vref(Pos, Vst),
#st{ms_positions=MsPos0} = St0,
MsPos = MsPos0#{ CtxRef => PosRef },
St = St0#st{ ms_positions=MsPos },
Vst#vst{current=St}.
invalidate_current_ms_position(Ctx, #vst{current=St0}=Vst) ->
CtxRef = get_reg_vref(Ctx, Vst),
#st{ms_positions=MsPos0} = St0,
case MsPos0 of
#{ CtxRef := _ } ->
MsPos = maps:remove(CtxRef, MsPos0),
St = St0#st{ms_positions=MsPos},
Vst#vst{current=St};
#{} ->
Vst
end.
%%
%% Common code for is_$type instructions.
%%
type_test(Fail, Type, Reg0, Vst) ->
Reg = unpack_typed_arg(Reg0, Vst),
assert_term(Reg, Vst),
assert_no_exception(Fail),
branch(Fail, Vst,
fun(FailVst) ->
update_type(fun subtract/2, Type, Reg, FailVst)
end,
fun(SuccVst) ->
update_type(fun meet/2, Type, Reg, SuccVst)
end).
%%
Special state handling for setelement/3 and set_tuple_element/3 instructions .
%% A possibility for garbage collection must not occur between setelement/3 and
%% set_tuple_element/3.
%%
%% Note that #vst.current will be 'none' if the instruction is unreachable.
%%
validate_mutation(I, Vst) ->
vm_1(I, Vst).
vm_1({move,_,_}, Vst) ->
Vst;
vm_1({swap,_,_}, Vst) ->
Vst;
vm_1({call_ext,3,{extfunc,erlang,setelement,3}}, #vst{current=#st{}=St}=Vst) ->
Vst#vst{current=St#st{setelem=true}};
vm_1({set_tuple_element,_,_,_}, #vst{current=#st{setelem=false}}) ->
error(illegal_context_for_set_tuple_element);
vm_1({set_tuple_element,_,_,_}, #vst{current=#st{setelem=true}}=Vst) ->
Vst;
vm_1({get_tuple_element,_,_,_}, Vst) ->
Vst;
vm_1({line,_}, Vst) ->
Vst;
vm_1(_, #vst{current=#st{setelem=true}=St}=Vst) ->
Vst#vst{current=St#st{setelem=false}};
vm_1(_, Vst) -> Vst.
kill_state(Vst) ->
Vst#vst{current=none}.
verify_call_args(_, 0, #vst{}) ->
ok;
verify_call_args({f,Lbl}, Live, #vst{ft=Ft}=Vst) ->
case Ft of
#{ Lbl := FuncInfo } ->
#{ arity := Live,
parameter_info := ParamInfo } = FuncInfo,
verify_local_args(Live - 1, ParamInfo, #{}, Vst);
#{} ->
error(local_call_to_unknown_function)
end;
verify_call_args(_, Live, Vst) ->
verify_remote_args_1(Live - 1, Vst).
verify_remote_args_1(-1, _) ->
ok;
verify_remote_args_1(X, Vst) ->
assert_durable_term({x, X}, Vst),
verify_remote_args_1(X - 1, Vst).
verify_local_args(-1, _ParamInfo, _CtxIds, _Vst) ->
ok;
verify_local_args(X, ParamInfo, CtxRefs, Vst) ->
Reg = {x, X},
assert_not_fragile(Reg, Vst),
case get_movable_term_type(Reg, Vst) of
#t_bs_context{}=Type ->
VRef = get_reg_vref(Reg, Vst),
case CtxRefs of
#{ VRef := Other } ->
error({multiple_match_contexts, [Reg, Other]});
#{} ->
verify_arg_type(Reg, Type, ParamInfo, Vst),
verify_local_args(X - 1, ParamInfo,
CtxRefs#{ VRef => Reg }, Vst)
end;
Type ->
verify_arg_type(Reg, Type, ParamInfo, Vst),
verify_local_args(X - 1, ParamInfo, CtxRefs, Vst)
end.
verify_arg_type(Reg, GivenType, ParamInfo, Vst) ->
case {ParamInfo, GivenType} of
{#{ Reg := Info }, #t_bs_context{}} ->
%% Match contexts require explicit support, and may not be passed
%% to a function that accepts arbitrary terms.
case member(accepts_match_context, Info) of
true -> verify_arg_type_1(Reg, GivenType, Info, Vst);
false -> error(no_bs_start_match2)
end;
{_, #t_bs_context{}} ->
error(no_bs_start_match2);
{#{ Reg := Info }, _} ->
verify_arg_type_1(Reg, GivenType, Info, Vst);
{#{}, _} ->
ok
end.
verify_arg_type_1(Reg, GivenType, Info, Vst) ->
RequiredType = proplists:get_value(type, Info, any),
case meet(GivenType, RequiredType) of
Type when Type =/= none, Vst#vst.level =:= weak ->
Strictly speaking this should always match GivenType , but
%% beam_jump:share/1 sometimes joins blocks in a manner that makes
%% it very difficult to accurately reconstruct type information,
%% for example:
%%
%% bug({Tag, _, _} = Key) when Tag == a; Tag == b ->
foo(Key ) ;
%% bug({Tag, _} = Key) when Tag == a; Tag == b ->
foo(Key ) .
%%
%% foo(I) -> I.
%%
At the first call to foo/1 , we know that we have either ` { a , _ } `
or ` { b , _ } ` , and at the second call ` { a , _ , _ } ` or ` { b , _ , _ } ` .
%%
%% When both calls to foo/1 are joined into the same block, all we
know is that we have tuple with an arity of at least 2 , whose
first element is ` a ` or ` b ` .
%%
%% Fixing this properly is a big undertaking, so for now we've
decided on a compromise that splits validation into two steps .
%%
%% We run a 'strong' pass directly after code generation in which
%% arguments must be at least as narrow as expected, and a 'weak'
%% pass after all optimizations have been applied in which we
%% tolerate arguments that aren't in direct conflict.
ok;
GivenType ->
true = GivenType =/= none, %Assertion.
ok;
_ ->
error({bad_arg_type, Reg, GivenType, RequiredType})
end.
allocate(Tag, Stk, Heap, Live, #vst{current=#st{numy=none}=St}=Vst0) ->
verify_live(Live, Vst0),
Vst1 = Vst0#vst{current=St#st{numy=Stk}},
Vst2 = prune_x_regs(Live, Vst1),
Vst = init_stack(Tag, Stk - 1, Vst2),
heap_alloc(Heap, Vst);
allocate(_, _, _, _, #vst{current=#st{numy=Numy}}) ->
error({existing_stack_frame,{size,Numy}}).
deallocate(#vst{current=St}=Vst) ->
Vst#vst{current=St#st{ys=#{},numy=none}}.
init_stack(_Tag, -1, Vst) ->
Vst;
init_stack(Tag, Y, Vst) ->
init_stack(Tag, Y - 1, create_tag(Tag, allocate, [], {y,Y}, Vst)).
trim_stack(From, To, Top, #st{ys=Ys0}=St) when From =:= Top ->
Ys = maps:filter(fun({y,Y}, _) -> Y < To end, Ys0),
St#st{numy=To,ys=Ys};
trim_stack(From, To, Top, St0) ->
Src = {y, From},
Dst = {y, To},
#st{ys=Ys0} = St0,
Ys = case Ys0 of
#{ Src := Ref } -> Ys0#{ Dst => Ref };
#{} -> error({invalid_shift,Src,Dst})
end,
St = St0#st{ys=Ys},
trim_stack(From + 1, To + 1, Top, St).
test_heap(Heap, Live, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
Vst = prune_x_regs(Live, Vst0),
heap_alloc(Heap, Vst).
heap_alloc(Heap, #vst{current=St0}=Vst) ->
{HeapWords, Floats, Funs} = heap_alloc_1(Heap),
St = St0#st{h=HeapWords,hf=Floats,hl=Funs},
Vst#vst{current=St}.
heap_alloc_1({alloc, Alloc}) ->
heap_alloc_2(Alloc, 0, 0, 0);
heap_alloc_1(HeapWords) when is_integer(HeapWords) ->
{HeapWords, 0, 0}.
heap_alloc_2([{words, HeapWords} | T], 0, Floats, Funs) ->
heap_alloc_2(T, HeapWords, Floats, Funs);
heap_alloc_2([{floats, Floats} | T], HeapWords, 0, Funs) ->
heap_alloc_2(T, HeapWords, Floats, Funs);
heap_alloc_2([{funs, Funs} | T], HeapWords, Floats, 0) ->
heap_alloc_2(T, HeapWords, Floats, Funs);
heap_alloc_2([], HeapWords, Floats, Funs) ->
{HeapWords, Floats, Funs}.
schedule_out(Live, Vst0) when is_integer(Live) ->
Vst1 = prune_x_regs(Live, Vst0),
Vst2 = kill_heap_allocation(Vst1),
Vst = kill_fregs(Vst2),
update_receive_state(none, Vst).
prune_x_regs(Live, #vst{current=St0}=Vst) when is_integer(Live) ->
#st{fragile=Fragile0,xs=Xs0} = St0,
Fragile = sets:filter(fun({x,X}) ->
X < Live;
({y,_}) ->
true
end, Fragile0),
Xs = maps:filter(fun({x,X}, _) ->
X < Live
end, Xs0),
St = St0#st{fragile=Fragile,xs=Xs},
Vst#vst{current=St}.
%% All choices in a select_val list must be integers, floats, or atoms.
%% All must be of the same type.
assert_choices([{Tag,_},{f,_}|T]) ->
if
Tag =:= atom; Tag =:= float; Tag =:= integer ->
assert_choices_1(T, Tag);
true ->
error(bad_select_list)
end;
assert_choices([]) -> ok.
assert_choices_1([{Tag,_},{f,_}|T], Tag) ->
assert_choices_1(T, Tag);
assert_choices_1([_,{f,_}|_], _Tag) ->
error(bad_select_list);
assert_choices_1([], _Tag) -> ok.
assert_arities([Arity,{f,_}|T]) when is_integer(Arity) ->
assert_arities(T);
assert_arities([]) -> ok;
assert_arities(_) -> error(bad_tuple_arity_list).
is_float_arith_bif(fadd, [_, _]) -> true;
is_float_arith_bif(fdiv, [_, _]) -> true;
is_float_arith_bif(fmul, [_, _]) -> true;
is_float_arith_bif(fnegate, [_]) -> true;
is_float_arith_bif(fsub, [_, _]) -> true;
is_float_arith_bif(_, _) -> false.
validate_float_arith_bif(Ss, Dst, Vst) ->
_ = [assert_freg_set(S, Vst) || S <- Ss],
set_freg(Dst, Vst).
init_fregs() -> 0.
kill_fregs(#vst{current=St0}=Vst) ->
St = St0#st{f=init_fregs()},
Vst#vst{current=St}.
set_freg({fr,Fr}=Freg, #vst{current=#st{f=Fregs0}=St}=Vst) ->
check_limit(Freg),
Bit = 1 bsl Fr,
if
Fregs0 band Bit =:= 0 ->
Fregs = Fregs0 bor Bit,
Vst#vst{current=St#st{f=Fregs}};
true -> Vst
end;
set_freg(Fr, _) -> error({bad_target,Fr}).
assert_freg_set({fr,Fr}=Freg, #vst{current=#st{f=Fregs}})
when is_integer(Fr), 0 =< Fr ->
if
(Fregs bsr Fr) band 1 =:= 0 ->
error({uninitialized_reg,Freg});
true ->
ok
end;
assert_freg_set(Fr, _) -> error({bad_source,Fr}).
%%% Maps
%% A single item list may be either a list or a register.
%%
%% A list with more than item must contain unique literals.
%%
%% An empty list is not allowed.
assert_unique_map_keys([]) ->
%% There is no reason to use the get_map_elements and
has_map_fields instructions with empty lists .
error(empty_field_list);
assert_unique_map_keys([_]) ->
ok;
assert_unique_map_keys([_,_|_]=Ls) ->
Vs = [begin
assert_literal(L),
L
end || L <- Ls],
case length(Vs) =:= sets:size(sets:from_list(Vs, [{version, 2}])) of
true -> ok;
false -> error(keys_not_unique)
end.
bsm_stride({integer, Size}, Unit) ->
Size * Unit;
bsm_stride(_Size, Unit) ->
Unit.
bsm_size_unit({integer, Size}, Unit) ->
max(1, Size) * max(1, Unit);
bsm_size_unit(_Size, Unit) ->
max(1, Unit).
validate_select_val(_Fail, _Choices, _Src, #vst{current=none}=Vst) ->
We 've already branched on all of 's possible values , so we know we
%% can't reach the fail label or any of the remaining choices.
Vst;
validate_select_val(Fail, [Val,{f,L}|T], Src, Vst0) ->
Vst = branch(L, Vst0,
fun(BranchVst) ->
update_eq_types(Src, Val, BranchVst)
end,
fun(FailVst) ->
update_ne_types(Src, Val, FailVst)
end),
validate_select_val(Fail, T, Src, Vst);
validate_select_val(Fail, [], _Src, Vst) ->
branch(Fail, Vst,
fun(SuccVst) ->
%% The next instruction is never executed.
kill_state(SuccVst)
end).
validate_select_tuple_arity(_Fail, _Choices, _Src, #vst{current=none}=Vst) ->
We 've already branched on all of 's possible values , so we know we
%% can't reach the fail label or any of the remaining choices.
Vst;
validate_select_tuple_arity(Fail, [Arity,{f,L}|T], Tuple, Vst0) ->
Type = #t_tuple{exact=true,size=Arity},
Vst = branch(L, Vst0,
fun(BranchVst) ->
update_type(fun meet/2, Type, Tuple, BranchVst)
end,
fun(FailVst) ->
update_type(fun subtract/2, Type, Tuple, FailVst)
end),
validate_select_tuple_arity(Fail, T, Tuple, Vst);
validate_select_tuple_arity(Fail, [], _, #vst{}=Vst) ->
branch(Fail, Vst,
fun(SuccVst) ->
%% The next instruction is never executed.
kill_state(SuccVst)
end).
%%
%% Infers types from comparisons, looking at the expressions that produced the
%% compared values and updates their types if we've learned something new from
%% the comparison.
%%
infer_types(CompareOp, {Kind,_}=LHS, RHS, Vst) when Kind =:= x; Kind =:= y ->
infer_types(CompareOp, get_reg_vref(LHS, Vst), RHS, Vst);
infer_types(CompareOp, LHS, {Kind,_}=RHS, Vst) when Kind =:= x; Kind =:= y ->
infer_types(CompareOp, LHS, get_reg_vref(RHS, Vst), Vst);
infer_types(CompareOp, LHS, RHS, #vst{current=#st{vs=Vs}}=Vst0) ->
case Vs of
#{ LHS := LEntry, RHS := REntry } ->
Vst = infer_types_1(LEntry, RHS, CompareOp, Vst0),
infer_types_1(REntry, LHS, CompareOp, Vst);
#{ LHS := LEntry } ->
infer_types_1(LEntry, RHS, CompareOp, Vst0);
#{ RHS := REntry } ->
infer_types_1(REntry, LHS, CompareOp, Vst0);
#{} ->
Vst0
end.
infer_types_1(#value{op={bif,'and'},args=[LHS,RHS]}, Val, Op, Vst0) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
Vst = update_eq_types(LHS, {atom,true}, Vst0),
update_eq_types(RHS, {atom,true}, Vst);
_ ->
%% As either of the arguments could be 'false', we can't infer
%% anything useful from that result.
Vst0
end;
infer_types_1(#value{op={bif,'or'},args=[LHS,RHS]}, Val, Op, Vst0) ->
case Val of
{atom, Bool} when Op =:= eq_exact, not Bool; Op =:= ne_exact, Bool ->
Vst = update_eq_types(LHS, {atom,false}, Vst0),
update_eq_types(RHS, {atom,false}, Vst);
_ ->
%% As either of the arguments could be 'true', we can't infer
%% anything useful from that result.
Vst0
end;
infer_types_1(#value{op={bif,'not'},args=[Arg]}, Val, Op, Vst0) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_eq_types(Arg, {atom,false}, Vst0);
{atom, Bool} when Op =:= eq_exact, not Bool; Op =:= ne_exact, Bool ->
update_eq_types(Arg, {atom,true}, Vst0);
_ ->
Vst0
end;
infer_types_1(#value{op={bif,'=:='},args=[LHS,RHS]}, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_eq_types(LHS, RHS, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
update_ne_types(LHS, RHS, Vst);
_ ->
Vst
end;
infer_types_1(#value{op={bif,'=/='},args=[LHS,RHS]}, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_ne_types(LHS, RHS, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
update_eq_types(LHS, RHS, Vst);
_ ->
Vst
end;
infer_types_1(#value{op={bif,RelOp},args=[_,_]=Args}, Val, Op, Vst)
when RelOp =:= '<'; RelOp =:= '=<'; RelOp =:= '>='; RelOp =:= '>' ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
Types = [get_term_type(Arg, Vst) || Arg <- Args],
infer_relop_types(RelOp, Args, Types, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
Types = [get_term_type(Arg, Vst) || Arg <- Args],
infer_relop_types(invert_relop(RelOp), Args, Types, Vst);
_ ->
Vst
end;
infer_types_1(#value{op={bif,is_atom},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_atom{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_boolean},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(beam_types:make_boolean(), Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_binary},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_bitstring{size_unit=8}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_bitstring},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_bitstring{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_float},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_float{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_function},args=[Src,{integer,Arity}]},
Val, Op, Vst)
when Arity >= 0, Arity =< ?MAX_FUNC_ARGS ->
infer_type_test_bif(#t_fun{arity=Arity}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_function},args=[Src,_Arity]}, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_type(fun meet/2, #t_fun{}, Src, Vst);
_ ->
%% We cannot subtract the function type when the arity is unknown:
%% `Src` may still be a function if the arity is outside the
%% allowed range.
Vst
end;
infer_types_1(#value{op={bif,is_function},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_fun{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_integer},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_integer{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_list},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_list{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_map},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_map{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_number},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_number{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_pid},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(pid, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_port},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(port, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_reference},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(reference, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_tuple},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_tuple{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,tuple_size}, args=[Tuple]},
{integer,Arity}, Op, Vst) ->
Type = #t_tuple{exact=true,size=Arity},
case Op of
eq_exact -> update_type(fun meet/2, Type, Tuple, Vst);
ne_exact -> update_type(fun subtract/2, Type, Tuple, Vst)
end;
infer_types_1(#value{op={bif,element},args=[{integer,Index}, Tuple]},
Val, eq_exact, Vst)
when Index >= 1 ->
ValType = get_term_type(Val, Vst),
Es = beam_types:set_tuple_element(Index, ValType, #{}),
TupleType = #t_tuple{size=Index,elements=Es},
update_type(fun meet/2, TupleType, Tuple, Vst);
infer_types_1(#value{op={bif,element},args=[{integer,Index}, Tuple]},
Val, ne_exact, Vst)
when Index >= 1 ->
%% Subtraction is only safe with singletons, see update_ne_types/3 for
%% details.
ValType = get_term_type(Val, Vst),
case beam_types:is_singleton_type(ValType) of
true ->
case beam_types:set_tuple_element(Index, ValType, #{}) of
#{ Index := _ }=Es ->
TupleType = #t_tuple{size=Index,elements=Es},
update_type(fun subtract/2, TupleType, Tuple, Vst);
#{} ->
%% Index was above the element limit; subtraction is not
%% safe.
Vst
end;
false ->
Vst
end;
infer_types_1(_, _, _, Vst) ->
Vst.
infer_type_test_bif(Type, Src, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_type(fun meet/2, Type, Src, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
update_type(fun subtract/2, Type, Src, Vst);
_ ->
Vst
end.
invert_relop('<') -> '>=';
invert_relop('=<') -> '>';
invert_relop('>=') -> '<';
invert_relop('>') -> '=<'.
%%%
%%% Keeping track of types.
%%%
%% Assigns Src to Dst and marks them as aliasing each other.
assign({y,_}=Src, {y,_}=Dst, Vst) ->
%% The stack trimming optimization may generate a move from an initialized
%% but unassigned Y register to another Y register.
case get_raw_type(Src, Vst) of
initialized -> create_tag(initialized, init, [], Dst, Vst);
_ -> assign_1(Src, Dst, Vst)
end;
assign({Kind,_}=Src, Dst, Vst) when Kind =:= x; Kind =:= y ->
assign_1(Src, Dst, Vst);
assign(Literal, Dst, Vst) ->
Type = get_literal_type(Literal),
create_term(Type, move, [Literal], Dst, Vst).
%% Creates a special tag value that isn't a regular term, such as 'initialized'
%% or 'catchtag'
create_tag(Tag, _Op, _Ss, {y,_}=Dst, #vst{current=#st{ys=Ys0}=St0}=Vst) ->
case maps:get(Dst, Ys0, uninitialized) of
{catchtag,_}=Prev ->
error(Prev);
{trytag,_}=Prev ->
error(Prev);
_ ->
check_try_catch_tags(Tag, Dst, Vst),
Ys = Ys0#{ Dst => Tag },
St = St0#st{ys=Ys},
remove_fragility(Dst, Vst#vst{current=St})
end;
create_tag(_Tag, _Op, _Ss, Dst, _Vst) ->
error({invalid_tag_register, Dst}).
%% Wipes a special tag, leaving the register initialized but empty.
kill_tag({y,_}=Reg, #vst{current=#st{ys=Ys0}=St0}=Vst) ->
_ = get_tag_type(Reg, Vst), %Assertion.
Ys = Ys0#{ Reg => initialized },
Vst#vst{current=St0#st{ys=Ys}}.
%% Creates a completely new term with the given type.
create_term(Type, Op, Ss0, Dst, Vst0) ->
create_term(Type, Op, Ss0, Dst, Vst0, Vst0).
As create_term/4 , but uses the incoming for argument resolution in
%% case x-regs have been pruned and the sources can no longer be found.
create_term(Type, Op, Ss0, Dst, Vst0, OrigVst) ->
{Ref, Vst1} = new_value(Type, Op, resolve_args(Ss0, OrigVst), Vst0),
Vst = remove_fragility(Dst, Vst1),
set_reg_vref(Ref, Dst, Vst).
Extracts a term from Ss , propagating fragility .
extract_term(Type, Op, Ss0, Dst, Vst0) ->
extract_term(Type, Op, Ss0, Dst, Vst0, Vst0).
As extract_term/4 , but uses the incoming for argument resolution in
%% case x-regs have been pruned and the sources can no longer be found.
extract_term(Type, Op, Ss0, Dst, Vst0, OrigVst) ->
{Ref, Vst1} = new_value(Type, Op, resolve_args(Ss0, OrigVst), Vst0),
Vst = propagate_fragility(Dst, Ss0, Vst1),
set_reg_vref(Ref, Dst, Vst).
%% Translates instruction arguments into the argument() type, decoupling them
%% from their registers, allowing us to infer their types after they've been
%% clobbered or moved.
resolve_args([{Kind,_}=Src | Args], Vst) when Kind =:= x; Kind =:= y ->
[get_reg_vref(Src, Vst) | resolve_args(Args, Vst)];
resolve_args([Lit | Args], Vst) ->
assert_literal(Lit),
[Lit | resolve_args(Args, Vst)];
resolve_args([], _Vst) ->
[].
Overrides the type of . This is ugly but a necessity for certain
%% destructive operations.
override_type(Type, Reg, Vst) ->
update_type(fun(_, T) -> T end, Type, Reg, Vst).
%% This is used when linear code finds out more and more information about a
%% type, so that the type gets more specialized.
update_type(Merge, With, #value_ref{}=Ref, Vst0) ->
%% If the old type can't be merged with the new one, the type information
%% is inconsistent and we know that some instructions will never be
%% executed at run-time. For example:
%%
%% {test,is_list,Fail,[Reg]}.
%% {test,is_tuple,Fail,[Reg]}.
%% {test,test_arity,Fail,[Reg,5]}.
%%
%% Note that the test_arity instruction can never be reached, so we need to
%% kill the state to avoid raising an error when we encounter it.
%%
%% Simply returning `kill_state(Vst)` is unsafe however as we might be in
%% the middle of an instruction, and altering the rest of the validator
%% (eg. prune_x_regs/2) to no-op on dead states is prone to error.
%%
%% We therefore throw a 'type_conflict' error instead, which causes
%% validation to fail unless we're in a context where such errors can be
%% handled, such as in a branch handler.
Current = get_concrete_type(Ref, Vst0),
case Merge(Current, With) of
none ->
throw({type_conflict, Current, With});
Type ->
Vst = update_container_type(Type, Ref, Vst0),
set_type(Type, Ref, Vst)
end;
update_type(Merge, With, {Kind,_}=Reg, Vst) when Kind =:= x; Kind =:= y ->
update_type(Merge, With, get_reg_vref(Reg, Vst), Vst);
update_type(Merge, With, Literal, Vst) ->
%% Literals always retain their type, but we still need to bail on type
%% conflicts.
Type = get_literal_type(Literal),
case Merge(Type, With) of
none -> throw({type_conflict, Type, With});
_Type -> Vst
end.
%% Updates the container the given value was extracted from, if any.
update_container_type(Type, Ref, #vst{current=#st{vs=Vs}}=Vst) ->
case Vs of
#{ Ref := #value{op={bif,element},
args=[{integer,Index},Tuple]} } when Index >= 1 ->
case {Index,Type} of
{1,#t_atom{elements=[_,_|_]}} ->
The first element is one atom out of a set of
at least two atoms . We must take care to
%% construct an atom set.
update_type(fun meet_tuple_set/2, Type, Tuple, Vst);
{_,_} ->
Es = beam_types:set_tuple_element(Index, Type, #{}),
TupleType = #t_tuple{size=Index,elements=Es},
update_type(fun meet/2, TupleType, Tuple, Vst)
end;
#{} ->
Vst
end.
meet_tuple_set(Type, #t_atom{elements=Atoms}) ->
Try to create a tuple set out of the known atoms for the first element .
#t_tuple{size=Size,exact=Exact} = normalize(meet(Type, #t_tuple{})),
Tuples = [#t_tuple{size=Size,exact=Exact,
elements=#{1 => #t_atom{elements=[A]}}} ||
A <- Atoms],
TupleSet = foldl(fun join/2, hd(Tuples), tl(Tuples)),
meet(Type, TupleSet).
update_eq_types(LHS, RHS, Vst0) ->
LType = get_term_type(LHS, Vst0),
RType = get_term_type(RHS, Vst0),
Vst1 = update_type(fun meet/2, RType, LHS, Vst0),
Vst = update_type(fun meet/2, LType, RHS, Vst1),
infer_types(eq_exact, LHS, RHS, Vst).
update_ne_types(LHS, RHS, Vst0) ->
Vst1 = update_ne_types_1(LHS, RHS, Vst0),
Vst = update_ne_types_1(RHS, LHS, Vst1),
infer_types(ne_exact, LHS, RHS, Vst).
update_ne_types_1(LHS, RHS, Vst0) ->
%% While updating types on equality is fairly straightforward, inequality
is a bit trickier since all we know is that the * value * of LHS differs
from RHS , so we ca n't blindly subtract their types .
%%
Consider ` # number { } = /= # t_integer { } ` ; all we know is that LHS is n't equal
%% to some *specific integer* of unknown value, and if we were to subtract
%% #t_integer{} we would erroneously infer that the new type is float.
%%
Therefore , we only subtract when we know that RHS has a specific value .
RType = get_term_type(RHS, Vst0),
case beam_types:is_singleton_type(RType) of
true ->
Vst = update_type(fun subtract/2, RType, LHS, Vst0),
If LHS has a specific value after subtraction we can infer types
%% as if we've made an exact match, which is much stronger than
%% ne_exact.
LType = get_term_type(LHS, Vst),
case beam_types:get_singleton_value(LType) of
{ok, Value} ->
infer_types(eq_exact, LHS, value_to_literal(Value), Vst);
error ->
Vst
end;
false ->
Vst0
end.
%% Helper functions for the above.
assign_1(Src, Dst, Vst0) ->
assert_movable(Src, Vst0),
Vst = propagate_fragility(Dst, [Src], Vst0),
set_reg_vref(get_reg_vref(Src, Vst), Dst, Vst).
set_reg_vref(Ref, {x,_}=Dst, Vst) ->
check_limit(Dst),
#vst{current=#st{xs=Xs0}=St0} = Vst,
St = St0#st{xs=Xs0#{ Dst => Ref }},
Vst#vst{current=St};
set_reg_vref(Ref, {y,_}=Dst, #vst{current=#st{ys=Ys0}=St0} = Vst) ->
check_limit(Dst),
case Ys0 of
#{ Dst := {catchtag,_}=Tag } ->
error(Tag);
#{ Dst := {trytag,_}=Tag } ->
error(Tag);
#{ Dst := _ } ->
St = St0#st{ys=Ys0#{ Dst => Ref }},
Vst#vst{current=St};
#{} ->
%% Storing into a non-existent Y register means that we haven't set
%% up a (sufficiently large) stack.
error({invalid_store, Dst})
end;
set_reg_vref(_Ref, Dst, _Vst) ->
error({invalid_register, Dst}).
get_reg_vref({x,_}=Src, #vst{current=#st{xs=Xs}}) ->
check_limit(Src),
case Xs of
#{ Src := #value_ref{}=Ref } ->
Ref;
#{} ->
error({uninitialized_reg, Src})
end;
get_reg_vref({y,_}=Src, #vst{current=#st{ys=Ys}}) ->
check_limit(Src),
case Ys of
#{ Src := #value_ref{}=Ref } ->
Ref;
#{ Src := initialized } ->
error({unassigned, Src});
#{ Src := Tag } when Tag =/= uninitialized ->
error(Tag);
#{} ->
error({uninitialized_reg, Src})
end;
get_reg_vref(Src, _Vst) ->
error({invalid_register, Src}).
set_type(Type, #value_ref{}=Ref, #vst{current=#st{vs=Vs0}=St}=Vst) ->
#{ Ref := #value{}=Entry } = Vs0,
Vs = Vs0#{ Ref => Entry#value{type=Type} },
Vst#vst{current=St#st{vs=Vs}}.
new_value(none, _, _, _) ->
error(creating_none_value);
new_value(Type, Op, Ss, #vst{current=#st{vs=Vs0}=St,ref_ctr=Counter}=Vst) ->
Ref = #value_ref{id=Counter},
Vs = Vs0#{ Ref => #value{op=Op,args=Ss,type=Type} },
{Ref, Vst#vst{current=St#st{vs=Vs},ref_ctr=Counter+1}}.
kill_catch_tag(Reg, #vst{current=#st{ct=[Tag|Tags]}=St}=Vst0) ->
Vst = Vst0#vst{current=St#st{ct=Tags}},
Tag = get_tag_type(Reg, Vst), %Assertion.
kill_tag(Reg, Vst).
check_try_catch_tags(Type, {y,N}=Reg, Vst) ->
%% Every catch or try/catch must use a lower Y register number than any
%% enclosing catch or try/catch. That will ensure that when the stack is
%% scanned when an exception occurs, the innermost try/catch tag is found
%% first.
case is_try_catch_tag(Type) of
true ->
case collect_try_catch_tags(N - 1, Vst, []) of
[_|_]=Bad -> error({bad_try_catch_nesting, Reg, Bad});
[] -> ok
end;
false ->
ok
end.
assert_no_exception(?EXCEPTION_LABEL) ->
error(throws_exception);
assert_no_exception(_) ->
ok.
assert_term(Src, Vst) ->
_ = get_term_type(Src, Vst),
ok.
assert_movable(Src, Vst) ->
_ = get_movable_term_type(Src, Vst),
ok.
assert_literal(Src) ->
case is_literal(Src) of
true -> ok;
false -> error({literal_required,Src})
end.
assert_not_literal(Src) ->
case is_literal(Src) of
true -> error({literal_not_allowed,Src});
false -> ok
end.
is_literal(nil) -> true;
is_literal({atom,A}) when is_atom(A) -> true;
is_literal({float,F}) when is_float(F) -> true;
is_literal({integer,I}) when is_integer(I) -> true;
is_literal({literal,_L}) -> true;
is_literal(_) -> false.
value_to_literal([]) -> nil;
value_to_literal(A) when is_atom(A) -> {atom,A};
value_to_literal(F) when is_float(F) -> {float,F};
value_to_literal(I) when is_integer(I) -> {integer,I};
value_to_literal(Other) -> {literal,Other}.
%% These are just wrappers around their equivalents in beam_types, which
%% handle the validator-specific #t_abstract{} type.
%%
%% The funny-looking abstract types produced here are intended to provoke
%% errors on actual use; they do no harm just lying around.
normalize(#t_abstract{}=A) -> error({abstract_type, A});
normalize(T) -> beam_types:normalize(T).
join(Same, Same) ->
Same;
join(#t_abstract{kind={ms_position, UnitA}},
#t_abstract{kind={ms_position, UnitB}}) ->
#t_abstract{kind={ms_position, gcd(UnitA, UnitB)}};
join(#t_abstract{}=A, B) ->
#t_abstract{kind={join, A, B}};
join(A, #t_abstract{}=B) ->
#t_abstract{kind={join, A, B}};
join(A, B) ->
beam_types:join(A, B).
meet(Same, Same) ->
Same;
meet(#t_abstract{kind={ms_position, UnitA}},
#t_abstract{kind={ms_position, UnitB}}) ->
Unit = UnitA * UnitB div gcd(UnitA, UnitB),
#t_abstract{kind={ms_position, Unit}};
meet(#t_abstract{}=A, B) ->
#t_abstract{kind={meet, A, B}};
meet(A, #t_abstract{}=B) ->
#t_abstract{kind={meet, A, B}};
meet(A, B) ->
beam_types:meet(A, B).
subtract(#t_abstract{}=A, B) ->
#t_abstract{kind={subtract, A, B}};
subtract(A, #t_abstract{}=B) ->
#t_abstract{kind={subtract, A, B}};
subtract(A, B) ->
beam_types:subtract(A, B).
assert_type(RequiredType, Term, Vst) ->
GivenType = get_movable_term_type(Term, Vst),
case meet(RequiredType, GivenType) of
GivenType ->
ok;
_RequiredType ->
error({bad_type,{needed,RequiredType},{actual,GivenType}})
end.
validate_src(Ss, Vst) when is_list(Ss) ->
_ = [assert_term(S, Vst) || S <- Ss],
ok.
unpack_typed_arg(#tr{r=Reg,t=Type}, Vst) ->
%% The validator is not yet clever enough to do proper range analysis like
%% the main type pass, so our types will be a bit cruder here, but they
%% should at the very least not be in direct conflict.
true = none =/= beam_types:meet(get_movable_term_type(Reg, Vst), Type),
Reg;
unpack_typed_arg(Arg, _Vst) ->
Arg.
get_term_type(Src , ) - > Type
Gets the type of the source , resolving deferred types into
%% a concrete type.
get_concrete_type(Src, #vst{current=#st{vs=Vs}}=Vst) ->
concrete_type(get_raw_type(Src, Vst), Vs).
get_term_type(Src , ) - > Type
Get the type of the source . The returned type Type will be
a standard Erlang type ( no catch / try tags or match contexts ) .
get_term_type(Src, Vst) ->
case get_movable_term_type(Src, Vst) of
#t_bs_context{} -> error({match_context,Src});
#t_abstract{} -> error({abstract_term,Src});
Type -> Type
end.
%% get_movable_term_type(Src, ValidatorState) -> Type
Get the type of the source . The returned type Type will be
a standard Erlang type ( no catch / try tags ) . Match contexts are OK .
get_movable_term_type(Src, Vst) ->
case get_concrete_type(Src, Vst) of
#t_abstract{kind=unfinished_tuple=Kind} -> error({Kind,Src});
initialized -> error({unassigned,Src});
uninitialized -> error({uninitialized_reg,Src});
{catchtag,_} -> error({catchtag,Src});
{trytag,_} -> error({trytag,Src});
Type -> Type
end.
%% get_tag_type(Src, ValidatorState) -> Type
%% Return the tag type of a Y register, erroring out if it contains a term.
get_tag_type({y,_}=Src, Vst) ->
case get_raw_type(Src, Vst) of
{catchtag, _}=Tag -> Tag;
{trytag, _}=Tag -> Tag;
uninitialized=Tag -> Tag;
initialized=Tag -> Tag;
Other -> error({invalid_tag,Src,Other})
end;
get_tag_type(Src, _) ->
error({invalid_tag_register,Src}).
%% get_raw_type(Src, ValidatorState) -> Type
%% Return the type of a register without doing any validity checks or
%% conversions.
get_raw_type({x,X}=Src, #vst{current=#st{xs=Xs}}=Vst) when is_integer(X) ->
check_limit(Src),
case Xs of
#{ Src := #value_ref{}=Ref } -> get_raw_type(Ref, Vst);
#{} -> uninitialized
end;
get_raw_type({y,Y}=Src, #vst{current=#st{ys=Ys}}=Vst) when is_integer(Y) ->
check_limit(Src),
case Ys of
#{ Src := #value_ref{}=Ref } -> get_raw_type(Ref, Vst);
#{ Src := Tag } -> Tag;
#{} -> uninitialized
end;
get_raw_type(#value_ref{}=Ref, #vst{current=#st{vs=Vs}}) ->
case Vs of
#{ Ref := #value{type=Type} } -> Type;
#{} -> none
end;
get_raw_type(Src, #vst{current=#st{}}) ->
get_literal_type(Src).
get_literal_type(nil) ->
beam_types:make_type_from_value([]);
get_literal_type({atom,A}) when is_atom(A) ->
beam_types:make_type_from_value(A);
get_literal_type({float,F}) when is_float(F) ->
beam_types:make_type_from_value(F);
get_literal_type({integer,I}) when is_integer(I) ->
beam_types:make_type_from_value(I);
get_literal_type({literal,L}) ->
beam_types:make_type_from_value(L);
get_literal_type(T) ->
error({not_literal,T}).
%%%
%%% Branch tracking
%%%
Forks the execution flow , with the provided funs returning the new state of
%% their respective branch; the "fail" fun returns the state where the branch
%% is taken, and the "success" fun returns the state where it's not.
%%
%% If either path is known not to be taken at runtime (eg. due to a type
%% conflict or argument errors), it will simply be discarded.
-spec branch(Lbl :: label(),
Original :: #vst{},
FailFun :: BranchFun,
SuccFun :: BranchFun) -> #vst{} when
BranchFun :: fun((#vst{}) -> #vst{}).
branch(Lbl, Vst0, FailFun, SuccFun) ->
validate_branch(Lbl, Vst0),
#vst{current=St0} = Vst0,
try FailFun(Vst0) of
Vst1 ->
Vst2 = fork_state(Lbl, Vst1),
Vst = Vst2#vst{current=St0},
try SuccFun(Vst) of
V -> V
catch
%% The instruction is guaranteed to fail; kill the state.
{type_conflict, _, _} ->
kill_state(Vst);
{invalid_argument, _} ->
kill_state(Vst)
end
catch
%% This instruction is guaranteed not to fail, so we run the success
%% branch *without* catching further errors to avoid hiding bugs in the
validator itself ; one of the branches must succeed .
{type_conflict, _, _} ->
SuccFun(Vst0);
{invalid_argument, _} ->
SuccFun(Vst0)
end.
validate_branch(Lbl, #vst{current=#st{ct=Tags}}) ->
validate_branch_1(Lbl, Tags).
validate_branch_1(Lbl, [{trytag, FailLbls} | Tags]) ->
%% 'try_case' assumes that an exception has been thrown, so a direct branch
%% will crash the emulator.
%%
%% (Jumping to a 'catch_end' is fine however as it will simply nop in the
%% absence of an exception.)
case ordsets:is_element(Lbl, FailLbls) of
true -> error({illegal_branch, try_handler, Lbl});
false -> validate_branch_1(Lbl, Tags)
end;
validate_branch_1(Lbl, [_ | Tags]) ->
validate_branch_1(Lbl, Tags);
validate_branch_1(_Lbl, _Tags) ->
ok.
%% A shorthand version of branch/4 for when the state is only altered on
%% success.
branch(Fail, Vst, SuccFun) ->
branch(Fail, Vst, fun(V) -> V end, SuccFun).
%% Shorthand of branch/4 for when the state is neither altered on failure nor
%% success.
branch(Fail, Vst) ->
branch(Fail, Vst, fun(V) -> V end).
%% Directly branches off the state. This is an "internal" operation that should
%% be used sparingly.
fork_state(?EXCEPTION_LABEL, Vst0) ->
#vst{current=#st{ct=CatchTags,numy=NumY}} = Vst0,
%% The stack will be scanned looking for a catch tag, so all Y registers
%% must be initialized.
verify_y_init(Vst0),
case CatchTags of
[{_, [Fail]} | _] when is_integer(Fail) ->
true = Fail =/= ?EXCEPTION_LABEL, %Assertion.
true = NumY =/= none, %Assertion.
%% Clear the receive marker and fork to our exception handler.
Vst = update_receive_state(none, Vst0),
fork_state(Fail, Vst);
[] ->
%% No catch handler; the exception leaves the function.
Vst0;
_ ->
error(ambiguous_catch_try_state)
end;
fork_state(L, #vst{current=St0,branched=Branched0,ref_ctr=Counter0}=Vst) ->
{St, Counter} = merge_states(L, St0, Branched0, Counter0),
Branched = Branched0#{ L => St },
Vst#vst{branched=Branched,ref_ctr=Counter}.
merge_states/3 is used when there 's more than one way to arrive at a
%% certain point, requiring the states to be merged down to the least
%% common subset for the subsequent code.
merge_states(L, St, Branched, Counter) when L =/= 0 ->
case Branched of
#{ L := OtherSt } -> merge_states_1(St, OtherSt, Counter);
#{} -> {St, Counter}
end.
merge_states_1(St, none, Counter) ->
{St, Counter};
merge_states_1(none, St, Counter) ->
{St, Counter};
merge_states_1(StA, StB, Counter0) ->
#st{xs=XsA,ys=YsA,vs=VsA,fragile=FragA,numy=NumYA,
h=HA,ct=CtA,recv_state=RecvStA,
ms_positions=MsPosA} = StA,
#st{xs=XsB,ys=YsB,vs=VsB,fragile=FragB,numy=NumYB,
h=HB,ct=CtB,recv_state=RecvStB,
ms_positions=MsPosB} = StB,
%% When merging registers we drop all registers that aren't defined in both
states , and resolve conflicts by creating new values ( similar to
%% nodes in SSA).
%%
%% While doing this we build a "merge map" detailing which values need to
%% be kept and which new values need to be created to resolve conflicts.
%% This map is then used to create a new value database where the types of
%% all values have been joined.
{Xs, Merge0, Counter1} = merge_regs(XsA, XsB, #{}, Counter0),
{Ys, Merge, Counter} = merge_regs(YsA, YsB, Merge0, Counter1),
Vs = merge_values(Merge, VsA, VsB),
RecvSt = merge_receive_state(RecvStA, RecvStB),
MsPos = merge_ms_positions(MsPosA, MsPosB, Vs),
Fragile = merge_fragility(FragA, FragB),
NumY = merge_stk(YsA, YsB, NumYA, NumYB),
Ct = merge_ct(CtA, CtB),
St = #st{xs=Xs,ys=Ys,vs=Vs,fragile=Fragile,numy=NumY,
h=min(HA, HB),ct=Ct,recv_state=RecvSt,
ms_positions=MsPos},
{St, Counter}.
Merges the contents of two register maps , returning the updated " merge map "
%% and the new registers.
merge_regs(RsA, RsB, Merge, Counter) ->
Keys = if
map_size(RsA) =< map_size(RsB) -> maps:keys(RsA);
map_size(RsA) > map_size(RsB) -> maps:keys(RsB)
end,
merge_regs_1(Keys, RsA, RsB, #{}, Merge, Counter).
merge_regs_1([Reg | Keys], RsA, RsB, Regs, Merge0, Counter0) ->
case {RsA, RsB} of
{#{ Reg := #value_ref{}=RefA }, #{ Reg := #value_ref{}=RefB }} ->
{Ref, Merge, Counter} = merge_vrefs(RefA, RefB, Merge0, Counter0),
merge_regs_1(Keys, RsA, RsB, Regs#{ Reg => Ref }, Merge, Counter);
{#{ Reg := TagA }, #{ Reg := TagB }} ->
%% Tags describe the state of the register rather than the value it
contains , so if a register contains a tag in one state we have
%% to merge it as a tag regardless of whether the other state says
%% it's a value.
{y, _} = Reg, %Assertion.
merge_regs_1(Keys, RsA, RsB, Regs#{ Reg => merge_tags(TagA,TagB) },
Merge0, Counter0);
{#{}, #{}} ->
merge_regs_1(Keys, RsA, RsB, Regs, Merge0, Counter0)
end;
merge_regs_1([], _, _, Regs, Merge, Counter) ->
{Regs, Merge, Counter}.
merge_tags(Same, Same) ->
Same;
merge_tags(uninitialized, _) ->
uninitialized;
merge_tags(_, uninitialized) ->
uninitialized;
merge_tags({trytag, LblsA}, {trytag, LblsB}) ->
{trytag, ordsets:union(LblsA, LblsB)};
merge_tags({catchtag, LblsA}, {catchtag, LblsB}) ->
{catchtag, ordsets:union(LblsA, LblsB)};
merge_tags(_A, _B) ->
%% All other combinations leave the register initialized. Errors arising
%% from this will be caught later on.
initialized.
merge_vrefs(Ref, Ref, Merge, Counter) ->
We have two ( potentially ) different versions of the same value , so we
%% should join their types into the same value.
{Ref, Merge#{ Ref => Ref }, Counter};
merge_vrefs(RefA, RefB, Merge, Counter) ->
We have two different values , so we need to create a new value from
%% their joined type if we haven't already done so.
Key = {RefA, RefB},
case Merge of
#{ Key := Ref } ->
{Ref, Merge, Counter};
#{} ->
Ref = #value_ref{id=Counter},
{Ref, Merge#{ Key => Ref }, Counter + 1}
end.
merge_values(Merge, VsA, VsB) ->
maps:fold(fun(Spec, New, Acc) ->
mv_1(Spec, New, VsA, VsB, Acc)
end, #{}, Merge).
mv_1(Same, Same, VsA, VsB, Acc0) ->
%% We're merging different versions of the same value, so it's safe to
%% reuse old entries if the type's unchanged.
Entry = case {VsA, VsB} of
{#{ Same := Entry0 }, #{ Same := Entry0 } } ->
Entry0;
{#{ Same := #value{type=TypeA}=Entry0 },
#{ Same := #value{type=TypeB} } } ->
ConcreteA = concrete_type(TypeA, VsA),
ConcreteB = concrete_type(TypeB, VsB),
Entry0#value{type=join(ConcreteA, ConcreteB)}
end,
Acc = Acc0#{ Same => Entry },
%% Type inference may depend on values that are no longer reachable from a
%% register, so all arguments must be merged into the new state.
mv_args(Entry#value.args, VsA, VsB, Acc);
mv_1({RefA, RefB}, New, VsA, VsB, Acc) ->
#value{type=TypeA} = map_get(RefA, VsA),
#value{type=TypeB} = map_get(RefB, VsB),
ConcreteA = concrete_type(TypeA, VsA),
ConcreteB = concrete_type(TypeB, VsB),
Acc#{ New => #value{op=join,args=[],type=join(ConcreteA, ConcreteB)} }.
concrete_type(T, Vs) when is_function(T) -> T(Vs);
concrete_type(T, _Vs) -> T.
mv_args([#value_ref{}=Arg | Args], VsA, VsB, Acc0) ->
case Acc0 of
#{ Arg := _ } ->
mv_args(Args, VsA, VsB, Acc0);
#{} ->
Acc = mv_1(Arg, Arg, VsA, VsB, Acc0),
mv_args(Args, VsA, VsB, Acc)
end;
mv_args([_ | Args], VsA, VsB, Acc) ->
mv_args(Args, VsA, VsB, Acc);
mv_args([], _VsA, _VsB, Acc) ->
Acc.
merge_fragility(FragileA, FragileB) ->
sets:union(FragileA, FragileB).
merge_ms_positions(MsPosA, MsPosB, Vs) ->
Keys = if
map_size(MsPosA) =< map_size(MsPosB) -> maps:keys(MsPosA);
map_size(MsPosA) > map_size(MsPosB) -> maps:keys(MsPosB)
end,
merge_ms_positions_1(Keys, MsPosA, MsPosB, Vs, #{}).
merge_ms_positions_1([Key | Keys], MsPosA, MsPosB, Vs, Acc) ->
case {MsPosA, MsPosB} of
{#{ Key := Pos }, #{ Key := Pos }} when is_map_key(Pos, Vs) ->
merge_ms_positions_1(Keys, MsPosA, MsPosB, Vs, Acc#{ Key => Pos });
{#{}, #{}} ->
merge_ms_positions_1(Keys, MsPosA, MsPosB, Vs, Acc)
end;
merge_ms_positions_1([], _MsPosA, _MsPosB, _Vs, Acc) ->
Acc.
merge_receive_state(Same, Same) -> Same;
merge_receive_state(_, _) -> undecided.
merge_stk(_, _, S, S) ->
S;
merge_stk(YsA, YsB, StkA, StkB) ->
merge_stk_undecided(YsA, YsB, StkA, StkB).
merge_stk_undecided(YsA, YsB, {undecided, StkA}, {undecided, StkB}) ->
We 're merging two branches with different stack sizes . This is only okay
%% if we're about to throw an exception, in which case all Y registers must
%% be initialized on both paths.
ok = merge_stk_verify_init(StkA - 1, YsA),
ok = merge_stk_verify_init(StkB - 1, YsB),
{undecided, min(StkA, StkB)};
merge_stk_undecided(YsA, YsB, StkA, StkB) when is_integer(StkA) ->
merge_stk_undecided(YsA, YsB, {undecided, StkA}, StkB);
merge_stk_undecided(YsA, YsB, StkA, StkB) when is_integer(StkB) ->
merge_stk_undecided(YsA, YsB, StkA, {undecided, StkB});
merge_stk_undecided(YsA, YsB, none, StkB) ->
merge_stk_undecided(YsA, YsB, {undecided, 0}, StkB);
merge_stk_undecided(YsA, YsB, StkA, none) ->
merge_stk_undecided(YsA, YsB, StkA, {undecided, 0}).
merge_stk_verify_init(-1, _Ys) ->
ok;
merge_stk_verify_init(Y, Ys) ->
Reg = {y, Y},
case Ys of
#{ Reg := TagOrVRef } when TagOrVRef =/= uninitialized ->
merge_stk_verify_init(Y - 1, Ys);
#{} ->
error({unsafe_stack, Reg, Ys})
end.
merge_ct(S, S) -> S;
merge_ct(Ct0, Ct1) -> merge_ct_1(Ct0, Ct1).
merge_ct_1([], []) ->
[];
merge_ct_1([{trytag, LblsA} | CtA], [{trytag, LblsB} | CtB]) ->
[{trytag, ordsets:union(LblsA, LblsB)} | merge_ct_1(CtA, CtB)];
merge_ct_1([{catchtag, LblsA} | CtA], [{catchtag, LblsB} | CtB]) ->
[{catchtag, ordsets:union(LblsA, LblsB)} | merge_ct_1(CtA, CtB)];
merge_ct_1(_, _) ->
undecided.
verify_y_init(#vst{current=#st{numy=NumY,ys=Ys}}=Vst) when is_integer(NumY) ->
HighestY = maps:fold(fun({y,Y}, _, Acc) -> max(Y, Acc) end, -1, Ys),
true = NumY > HighestY, %Assertion.
verify_y_init_1(NumY - 1, Vst),
ok;
verify_y_init(#vst{current=#st{numy={undecided,MinSlots},ys=Ys}}=Vst) ->
HighestY = maps:fold(fun({y,Y}, _, Acc) -> max(Y, Acc) end, -1, Ys),
true = MinSlots > HighestY, %Assertion.
verify_y_init_1(HighestY, Vst);
verify_y_init(#vst{}) ->
ok.
verify_y_init_1(-1, _Vst) ->
ok;
verify_y_init_1(Y, Vst) ->
Reg = {y, Y},
assert_not_fragile(Reg, Vst),
case get_raw_type(Reg, Vst) of
uninitialized -> error({uninitialized_reg,Reg});
_ -> verify_y_init_1(Y - 1, Vst)
end.
verify_live(0, _Vst) ->
ok;
verify_live(Live, Vst) when is_integer(Live), 0 < Live, Live =< 1023 ->
verify_live_1(Live - 1, Vst);
verify_live(Live, _Vst) ->
error({bad_number_of_live_regs,Live}).
verify_live_1(-1, _) ->
ok;
verify_live_1(X, Vst) when is_integer(X) ->
Reg = {x, X},
case get_raw_type(Reg, Vst) of
uninitialized -> error({Reg, not_live});
_ -> verify_live_1(X - 1, Vst)
end.
verify_no_ct(#vst{current=#st{numy=none}}) ->
ok;
verify_no_ct(#vst{current=#st{numy={undecided,_}}}) ->
error(unknown_size_of_stackframe);
verify_no_ct(#vst{current=St}=Vst) ->
case collect_try_catch_tags(St#st.numy - 1, Vst, []) of
[_|_]=Bad -> error({unfinished_catch_try,Bad});
[] -> ok
end.
Collects all try / catch tags , walking down from the Nth stack position .
collect_try_catch_tags(-1, _Vst, Acc) ->
Acc;
collect_try_catch_tags(Y, Vst, Acc0) ->
Tag = get_raw_type({y, Y}, Vst),
Acc = case is_try_catch_tag(Tag) of
true -> [{{y, Y}, Tag} | Acc0];
false -> Acc0
end,
collect_try_catch_tags(Y - 1, Vst, Acc).
is_try_catch_tag({catchtag,_}) -> true;
is_try_catch_tag({trytag,_}) -> true;
is_try_catch_tag(_) -> false.
eat_heap(N, #vst{current=#st{h=Heap0}=St}=Vst) ->
case Heap0-N of
Neg when Neg < 0 ->
error({heap_overflow,{left,Heap0},{wanted,N}});
Heap ->
Vst#vst{current=St#st{h=Heap}}
end.
eat_heap_fun(#vst{current=#st{hl=HeapFuns0}=St}=Vst) ->
case HeapFuns0-1 of
Neg when Neg < 0 ->
error({heap_overflow,{left,{HeapFuns0,funs}},{wanted,{1,funs}}});
HeapFuns ->
Vst#vst{current=St#st{hl=HeapFuns}}
end.
eat_heap_float(#vst{current=#st{hf=HeapFloats0}=St}=Vst) ->
case HeapFloats0-1 of
Neg when Neg < 0 ->
error({heap_overflow,{left,{HeapFloats0,floats}},{wanted,{1,floats}}});
HeapFloats ->
Vst#vst{current=St#st{hf=HeapFloats}}
end.
%%%
%%% RECEIVE
%%%
%% When the compiler knows that a message it's matching in a receive can't
%% exist before a certain point (e.g. it matches a newly created ref), it will
use " receive markers " to tell the corresponding where to start
%% looking.
%%
Since receive markers affect the next instruction it 's very
%% important that we properly exit the receive loop the mark is intended for,
%% either through timing out or matching a message. Should we return from the
%% function or enter a different receive loop, we risk skipping messages that
%% should have been matched.
update_receive_state(New0, #vst{current=St0}=Vst) ->
#st{recv_state=Current} = St0,
New = case {Current, New0} of
{none, marked_position} ->
marked_position;
{marked_position, entered_loop} ->
entered_loop;
{none, entered_loop} ->
entered_loop;
{_, none} ->
none;
{_, _} ->
error({invalid_receive_state_change, Current, New0})
end,
St = St0#st{recv_state=New},
Vst#vst{current=St}.
%% The loop_rec/2 instruction may return a reference to a term that is not
%% part of the root set. That term or any part of it must not be included in a
%% garbage collection. Therefore, the term (or any part of it) must not be
%% passed to another function, placed in another term, or live in a Y register
over an instruction that may GC .
%%
%% Fragility is marked on a per-register (rather than per-value) basis.
%% Marks Reg as fragile.
mark_fragile(Reg, Vst) ->
#vst{current=#st{fragile=Fragile0}=St0} = Vst,
Fragile = sets:add_element(Reg, Fragile0),
St = St0#st{fragile=Fragile},
Vst#vst{current=St}.
propagate_fragility(Reg, Args, #vst{current=St0}=Vst) ->
#st{fragile=Fragile0} = St0,
Sources = sets:from_list(Args, [{version, 2}]),
Fragile = case sets:is_disjoint(Sources, Fragile0) of
true -> sets:del_element(Reg, Fragile0);
false -> sets:add_element(Reg, Fragile0)
end,
St = St0#st{fragile=Fragile},
Vst#vst{current=St}.
%% Marks Reg as durable, must be used when assigning a newly created value to
%% a register.
remove_fragility(Reg, Vst) ->
#vst{current=#st{fragile=Fragile0}=St0} = Vst,
case sets:is_element(Reg, Fragile0) of
true ->
Fragile = sets:del_element(Reg, Fragile0),
St = St0#st{fragile=Fragile},
Vst#vst{current=St};
false ->
Vst
end.
Marks all registers as durable .
remove_fragility(#vst{current=St0}=Vst) ->
St = St0#st{fragile=sets:new([{version, 2}])},
Vst#vst{current=St}.
assert_durable_term(Src, Vst) ->
assert_term(Src, Vst),
assert_not_fragile(Src, Vst).
assert_not_fragile({Kind,_}=Src, Vst) when Kind =:= x; Kind =:= y ->
check_limit(Src),
#vst{current=#st{fragile=Fragile}} = Vst,
case sets:is_element(Src, Fragile) of
true -> error({fragile_message_reference, Src});
false -> ok
end;
assert_not_fragile(Lit, #vst{}) ->
assert_literal(Lit),
ok.
%%%
%%% Return/argument types of calls and BIFs
%%%
bif_types(Op, Ss, Vst) ->
Args = [get_term_type(Arg, Vst) || Arg <- Ss],
case {Op,Ss} of
{element,[_,{literal,Tuple}]} when tuple_size(Tuple) > 0 ->
case beam_call_types:types(erlang, Op, Args) of
{any,ArgTypes,Safe} ->
RetType = join_tuple_elements(Tuple),
{RetType,ArgTypes,Safe};
Other ->
Other
end;
{_,_} ->
beam_call_types:types(erlang, Op, Args)
end.
join_tuple_elements(Tuple) ->
join_tuple_elements(tuple_size(Tuple), Tuple, none).
join_tuple_elements(0, _Tuple, Type) ->
Type;
join_tuple_elements(I, Tuple, Type0) ->
Type1 = beam_types:make_type_from_value(element(I, Tuple)),
Type = beam_types:join(Type0, Type1),
join_tuple_elements(I - 1, Tuple, Type).
call_types({extfunc,M,F,A}, A, Vst) ->
Args = get_call_args(A, Vst),
beam_call_types:types(M, F, Args);
call_types(bs_init_writable, A, Vst) ->
T = beam_types:make_type_from_value(<<>>),
{T, get_call_args(A, Vst), false};
call_types(_, A, Vst) ->
{any, get_call_args(A, Vst), false}.
will_bif_succeed(raise, [_,_], _Vst) ->
Compiler - generated raise , the user - facing variant that can return
' badarg ' is : raise/3 .
no;
will_bif_succeed(Op, Ss, Vst) ->
case is_float_arith_bif(Op, Ss) of
true ->
'maybe';
false ->
Args = [get_term_type(Arg, Vst) || Arg <- Ss],
beam_call_types:will_succeed(erlang, Op, Args)
end.
will_call_succeed({extfunc,M,F,A}, _Live, Vst) ->
beam_call_types:will_succeed(M, F, get_call_args(A, Vst));
will_call_succeed(bs_init_writable, _Live, _Vst) ->
yes;
will_call_succeed(raw_raise, _Live, _Vst) ->
no;
will_call_succeed({f,Lbl}, _Live, #vst{ft=Ft}) ->
case Ft of
#{Lbl := #{always_fails := true}} ->
no;
#{} ->
'maybe'
end;
will_call_succeed(apply, Live, Vst) ->
Mod = get_term_type({x,Live-2}, Vst),
Name = get_term_type({x,Live-1}, Vst),
case {Mod,Name} of
{#t_atom{},#t_atom{}} ->
'maybe';
{_,_} ->
no
end;
will_call_succeed(_Call, _Live, _Vst) ->
'maybe'.
get_call_args(Arity, Vst) ->
get_call_args_1(0, Arity, Vst).
get_call_args_1(Arity, Arity, _) ->
[];
get_call_args_1(N, Arity, Vst) when N < Arity ->
ArgType = get_movable_term_type({x,N}, Vst),
[ArgType | get_call_args_1(N + 1, Arity, Vst)].
check_limit({x,X}=Src) when is_integer(X) ->
if
Note : x(1023 ) is reserved for use by the BEAM loader .
0 =< X, X < 1023 -> ok;
1023 =< X -> error(limit);
X < 0 -> error({bad_register, Src})
end;
check_limit({y,Y}=Src) when is_integer(Y) ->
if
0 =< Y, Y < 1024 -> ok;
1024 =< Y -> error(limit);
Y < 0 -> error({bad_register, Src})
end;
check_limit({fr,Fr}=Src) when is_integer(Fr) ->
if
0 =< Fr, Fr < 1023 -> ok;
1023 =< Fr -> error(limit);
Fr < 0 -> error({bad_register, Src})
end.
min(A, B) when is_integer(A), is_integer(B), A < B -> A;
min(A, B) when is_integer(A), is_integer(B) -> B.
gcd(A, B) ->
case A rem B of
0 -> B;
X -> gcd(B, X)
end.
error(Error) -> throw(Error).
| null | https://raw.githubusercontent.com/erlang/otp/8bd51c239d39923846936e00b8e52f4265d5e7b3/lib/compiler/src/beam_validator.erl | erlang |
%CopyrightBegin%
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.
%CopyrightEnd%
When an instruction throws an exception it does so by branching (branch/4)
to this label, following the {f,0} convention used in BIFs.
Instructions that have fail labels but cannot throw exceptions should guard
themselves with assert_no_exception/1, and instructions that are statically
guaranteed not to fail should simply skip branching.
To be called by the compiler.
Local functions follow.
The validator follows.
The purpose of the validator is to find errors in the generated
code that may cause the emulator to crash or behave strangely.
We don't care about type errors in the user's code that will
cause a proper exception at run-time.
Things currently not checked. XXX
- Heap allocation for binaries.
validate(Module, Level, [Function], Ft) -> [] | [Error]
A list of functions with their code. The code is in the same
Controlled error.
Crash.
The types are the same as in 'beam_types.hrl', with the addition of:
* `#t_abstract{}` which describes tuples under construction, match context
positions, and so on.
* `(fun(values()) -> type())` that defers figuring out the type until it's
actually used. Mainly used to coax more type information out of
affect the type of another.
contain (if any).
initialized The register has been initialized with some valid term
so that it is safe to pass to the garbage collector.
NOT safe to use in any other way (will not crash the
emulator, but clearly points to a bug in the compiler).
uninitialized The register contains any old garbage and can not be
passed to the garbage collector.
{catchtag,[Lbl]} A special term used within a catch. Must only be used
by the catch instructions; NOT safe to use in other
instructions.
{trytag,[Lbl]} A special term used within a try block. Must only be
used by the catch instructions; NOT safe to use in other
instructions.
Emulation state
All known values.
A set of all registers containing "fragile" terms. That is, terms
that don't exist on our process heap and would be destroyed by a
Number of Y registers.
Note that this may be 0 if there's a frame without saved values,
such as on a body-recursive call.
Available heap size.
Available heap size for funs (aka lambdas).
Available heap size for floats.
List of hot catch/try tags
Current receive state:
* 'none' - Not in a receive loop.
* 'entered_loop' - We're in a receive loop.
* 'undecided'
Holds the current saved position for each `#t_bs_context{}`, in the
sense that the position is equal to that of their context. They are
invalidated whenever their context advances.
These are used to update the unit of saved positions after
operations that test the incoming unit, such as bs_test_unit and
bs_get_binary2 with {atom,all}.
Validator state
Current state
Validation level
States at labels
All defined labels
Information of other functions in the module
Counter for #value_ref{} creation
Something is seriously wrong. Ignore it for now.
It will be detected and diagnosed later.
', _} | Is], Acc) ->
We validate the header after the body as the latter may jump to the
former to raise 'function_clause' exceptions.
Assertion.
Ignore all unreachable code.
Misc annotations
This is a hack to make prim_eval:'receive'/2 work.
Normally it's illegal to pass fragile terms as a function argument as we
have no way of knowing what the callee will do with it, but we know that
disabled while matching messages.
Moves
We don't expect fragile registers to be swapped.
Therefore, we can conservatively make both registers
swapping the fragility of the registers.
Swap the value references.
Matching and test instructions.
The next instruction is never executed.
We cannot subtract the function type when the arity is
unknown: `Src` may still be a function if the arity is
outside the allowed range.
is_nil is an exact check against the 'nil' value, and should not be
treated as a simple type test.
Simple getters that can't fail.
Allocate, deallocate, et.al.
Term-building instructions
This instruction never fails, though it may be invalid in some contexts;
see validate_mutation/2
Manually update the tuple type; we can't rely on the ordinary update
helpers as we must support overwriting (rather than just widening or
narrowing) known elements, and we can't use extract_term either since
the source tuple may be aliased.
Calls
Fun call with known target. Verify that the target exists, agrees with
the type annotation for `Fun`, and that it has environment variables.
Direct fun calls without environment variables must be expressed as
local fun calls.
Assertion.
Assertion.
Assertion.
Assertion.
Assertion.
Message instructions
This term may not be part of the root set until
remove_message/0 is executed. If control transfers to the
loop_rec_end/1 instruction, no part of this term must be
stored in a Y register.
The message term is no longer fragile. It can be used
without restrictions.
Catch & try.
{x,0} contains the caught term, if any.
Kill the catch tag without affecting X registers.
Kill the catch tag and all other state (as if we've been
scheduled out with no live registers). Only previously allocated
Y registers are alive at this point.
Class:Error:Stacktrace
Map instructions.
Bit syntax matching
Assertion.
Bit syntax positioning
Floating-point instructions (excluding BIFs)
Exception-raising instructions
Binary construction
Explicit type information inserted after make_fun2 instructions to mark
the return type of the created fun.
Explicit type information inserted by optimization passes to indicate
optimizations.
Tail call.
The stackframe must have a known size and be initialized.
Does not return to the instruction following the call.
The call cannot fail; we don't need to handle exceptions
The call may fail; make sure we update exception state
as we know that it will not be used in this case.
A "plain" call.
The stackframe must be initialized.
The instruction will return to the instruction following the call.
Note that we don't try to infer anything from the
argument types, as that may cause types to become
concrete "too early."
See beam_types_SUITE:premature_concretization/1 for
details.
Assertion.
get_map_elements may leave its destinations in an inconsistent state when
the fail label is taken. Consider the following:
If 'a' exists but not 'b', {x,1} is overwritten when we jump to {f,7}.
We must be careful to preserve the uninitialized status for Y registers
that have been allocated but not yet defined.
The destinations must not overwrite each other.
This instruction cannot fail.
Assertion.
Common code for validating returns, whether naked or as part of a tail call.
Returning in the middle of a receive loop will ruin the next receive.
Common code for validating BIFs.
OrigVst is the state we entered the instruction with, which is needed for
gc_bifs as X registers are pruned prior to calling this function, which may
have clobbered the sources.
handled without updating exception state.
exception handler.
an exception. Validation will fail if it returns 'none' or has a type
conflict on one of its arguments.
Assertion.
Common code for validating bs_start_match* instructions.
Retain the current unit, if known.
Assertion.
In rare circumstance, there can be multiple `get_tail` sub commands.
Common code for validating bs_get* instructions.
This acts as an implicit unit test on the current match
position, so we'll update the unit in case we rewind here
later on.
Common code for validating bs_skip* instructions.
We _KNOW_ we're not moving anywhere. Retain our current position and
type.
We _KNOW_ we'll fail at runtime.
The latest saved position (if any) is no longer current, make sure
it isn't updated on the next match operation.
Updates the unit of our latest saved position, if it's current.
Common code for is_$type instructions.
A possibility for garbage collection must not occur between setelement/3 and
set_tuple_element/3.
Note that #vst.current will be 'none' if the instruction is unreachable.
Match contexts require explicit support, and may not be passed
to a function that accepts arbitrary terms.
beam_jump:share/1 sometimes joins blocks in a manner that makes
it very difficult to accurately reconstruct type information,
for example:
bug({Tag, _, _} = Key) when Tag == a; Tag == b ->
bug({Tag, _} = Key) when Tag == a; Tag == b ->
foo(I) -> I.
When both calls to foo/1 are joined into the same block, all we
Fixing this properly is a big undertaking, so for now we've
We run a 'strong' pass directly after code generation in which
arguments must be at least as narrow as expected, and a 'weak'
pass after all optimizations have been applied in which we
tolerate arguments that aren't in direct conflict.
Assertion.
All choices in a select_val list must be integers, floats, or atoms.
All must be of the same type.
Maps
A single item list may be either a list or a register.
A list with more than item must contain unique literals.
An empty list is not allowed.
There is no reason to use the get_map_elements and
can't reach the fail label or any of the remaining choices.
The next instruction is never executed.
can't reach the fail label or any of the remaining choices.
The next instruction is never executed.
Infers types from comparisons, looking at the expressions that produced the
compared values and updates their types if we've learned something new from
the comparison.
As either of the arguments could be 'false', we can't infer
anything useful from that result.
As either of the arguments could be 'true', we can't infer
anything useful from that result.
We cannot subtract the function type when the arity is unknown:
`Src` may still be a function if the arity is outside the
allowed range.
Subtraction is only safe with singletons, see update_ne_types/3 for
details.
Index was above the element limit; subtraction is not
safe.
Keeping track of types.
Assigns Src to Dst and marks them as aliasing each other.
The stack trimming optimization may generate a move from an initialized
but unassigned Y register to another Y register.
Creates a special tag value that isn't a regular term, such as 'initialized'
or 'catchtag'
Wipes a special tag, leaving the register initialized but empty.
Assertion.
Creates a completely new term with the given type.
case x-regs have been pruned and the sources can no longer be found.
case x-regs have been pruned and the sources can no longer be found.
Translates instruction arguments into the argument() type, decoupling them
from their registers, allowing us to infer their types after they've been
clobbered or moved.
destructive operations.
This is used when linear code finds out more and more information about a
type, so that the type gets more specialized.
If the old type can't be merged with the new one, the type information
is inconsistent and we know that some instructions will never be
executed at run-time. For example:
{test,is_list,Fail,[Reg]}.
{test,is_tuple,Fail,[Reg]}.
{test,test_arity,Fail,[Reg,5]}.
Note that the test_arity instruction can never be reached, so we need to
kill the state to avoid raising an error when we encounter it.
Simply returning `kill_state(Vst)` is unsafe however as we might be in
the middle of an instruction, and altering the rest of the validator
(eg. prune_x_regs/2) to no-op on dead states is prone to error.
We therefore throw a 'type_conflict' error instead, which causes
validation to fail unless we're in a context where such errors can be
handled, such as in a branch handler.
Literals always retain their type, but we still need to bail on type
conflicts.
Updates the container the given value was extracted from, if any.
construct an atom set.
While updating types on equality is fairly straightforward, inequality
to some *specific integer* of unknown value, and if we were to subtract
#t_integer{} we would erroneously infer that the new type is float.
as if we've made an exact match, which is much stronger than
ne_exact.
Helper functions for the above.
Storing into a non-existent Y register means that we haven't set
up a (sufficiently large) stack.
Assertion.
Every catch or try/catch must use a lower Y register number than any
enclosing catch or try/catch. That will ensure that when the stack is
scanned when an exception occurs, the innermost try/catch tag is found
first.
These are just wrappers around their equivalents in beam_types, which
handle the validator-specific #t_abstract{} type.
The funny-looking abstract types produced here are intended to provoke
errors on actual use; they do no harm just lying around.
The validator is not yet clever enough to do proper range analysis like
the main type pass, so our types will be a bit cruder here, but they
should at the very least not be in direct conflict.
a concrete type.
get_movable_term_type(Src, ValidatorState) -> Type
get_tag_type(Src, ValidatorState) -> Type
Return the tag type of a Y register, erroring out if it contains a term.
get_raw_type(Src, ValidatorState) -> Type
Return the type of a register without doing any validity checks or
conversions.
Branch tracking
their respective branch; the "fail" fun returns the state where the branch
is taken, and the "success" fun returns the state where it's not.
If either path is known not to be taken at runtime (eg. due to a type
conflict or argument errors), it will simply be discarded.
The instruction is guaranteed to fail; kill the state.
This instruction is guaranteed not to fail, so we run the success
branch *without* catching further errors to avoid hiding bugs in the
'try_case' assumes that an exception has been thrown, so a direct branch
will crash the emulator.
(Jumping to a 'catch_end' is fine however as it will simply nop in the
absence of an exception.)
A shorthand version of branch/4 for when the state is only altered on
success.
Shorthand of branch/4 for when the state is neither altered on failure nor
success.
Directly branches off the state. This is an "internal" operation that should
be used sparingly.
The stack will be scanned looking for a catch tag, so all Y registers
must be initialized.
Assertion.
Assertion.
Clear the receive marker and fork to our exception handler.
No catch handler; the exception leaves the function.
certain point, requiring the states to be merged down to the least
common subset for the subsequent code.
When merging registers we drop all registers that aren't defined in both
nodes in SSA).
While doing this we build a "merge map" detailing which values need to
be kept and which new values need to be created to resolve conflicts.
This map is then used to create a new value database where the types of
all values have been joined.
and the new registers.
Tags describe the state of the register rather than the value it
to merge it as a tag regardless of whether the other state says
it's a value.
Assertion.
All other combinations leave the register initialized. Errors arising
from this will be caught later on.
should join their types into the same value.
their joined type if we haven't already done so.
We're merging different versions of the same value, so it's safe to
reuse old entries if the type's unchanged.
Type inference may depend on values that are no longer reachable from a
register, so all arguments must be merged into the new state.
if we're about to throw an exception, in which case all Y registers must
be initialized on both paths.
Assertion.
Assertion.
RECEIVE
When the compiler knows that a message it's matching in a receive can't
exist before a certain point (e.g. it matches a newly created ref), it will
looking.
important that we properly exit the receive loop the mark is intended for,
either through timing out or matching a message. Should we return from the
function or enter a different receive loop, we risk skipping messages that
should have been matched.
The loop_rec/2 instruction may return a reference to a term that is not
part of the root set. That term or any part of it must not be included in a
garbage collection. Therefore, the term (or any part of it) must not be
passed to another function, placed in another term, or live in a Y register
Fragility is marked on a per-register (rather than per-value) basis.
Marks Reg as fragile.
Marks Reg as durable, must be used when assigning a newly created value to
a register.
Return/argument types of calls and BIFs
| Copyright Ericsson AB 2004 - 2023 . 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(beam_validator).
-include("beam_asm.hrl").
-define(UNICODE_MAX, (16#10FFFF)).
-define(EXCEPTION_LABEL, 0).
-compile({no_auto_import,[min/2]}).
Avoid warning for local function error/1 clashing with autoimported BIF .
-compile({no_auto_import,[error/1]}).
Interface for compiler .
-export([validate/2, format_error/1]).
-import(lists, [dropwhile/2,foldl/3,member/2,reverse/2,zip/2]).
-spec validate(Code, Level) -> Result when
Code :: beam_utils:module_code(),
Level :: strong | weak,
Result :: ok | {error, [{atom(), list()}]}.
validate({Mod,Exp,Attr,Fs,Lc}, Level) when is_atom(Mod),
is_list(Exp),
is_list(Attr),
is_integer(Lc) ->
Ft = build_function_table(Fs, #{}),
case validate_0(Fs, Mod, Level, Ft) of
[] ->
ok;
Es0 ->
Es = [{1,?MODULE,E} || E <- Es0],
{error,[{atom_to_list(Mod),Es}]}
end.
-spec format_error(term()) -> iolist().
format_error({{_M,F,A},{I,Off,limit}}) ->
io_lib:format(
"function ~p/~p+~p:~n"
" An implementation limit was reached.~n"
" Try reducing the complexity of this function.~n~n"
" Instruction: ~p~n", [F,A,Off,I]);
format_error({{_M,F,A},{undef_labels,Lbls}}) ->
io_lib:format(
"function ~p/~p:~n"
" Internal consistency check failed - please report this bug.~n"
" The following label(s) were referenced but not defined:~n", [F,A]) ++
" " ++ [[integer_to_list(L)," "] || L <- Lbls] ++ "\n";
format_error({{_M,F,A},{I,Off,Desc}}) ->
io_lib:format(
"function ~p/~p+~p:~n"
" Internal consistency check failed - please report this bug.~n"
" Instruction: ~p~n"
" Error: ~p:~n", [F,A,Off,I,Desc]);
format_error(Error) ->
io_lib:format("~p~n", [Error]).
format as used in the compiler and in .S files .
validate_0([], _Module, _Level, _Ft) ->
[];
validate_0([{function, Name, Arity, Entry, Code} | Fs], Module, Level, Ft) ->
MFA = {Module, Name, Arity},
try validate_1(Code, MFA, Entry, Level, Ft) of
_ ->
validate_0(Fs, Module, Level, Ft)
catch
throw:Error ->
[Error | validate_0(Fs, Module, Level, Ft)];
Class:Error:Stack ->
io:fwrite("Function: ~w/~w\n", [Name,Arity]),
erlang:raise(Class, Error, Stack)
end.
-record(t_abstract, {kind}).
` get_tuple_element ` where a test on one element ( e.g. record tag ) may
-type validator_type() :: #t_abstract{} | fun((values()) -> type()) | type().
-record(value_ref, {id :: index()}).
-record(value, {op :: term(), args :: [argument()], type :: validator_type()}).
-type argument() :: #value_ref{} | beam_literal().
-type values() :: #{ #value_ref{} => #value{} }.
-type index() :: non_neg_integer().
Register tags describe the state of the register rather than the value they
-type tag() :: initialized |
uninitialized |
{catchtag, ordsets:ordset(label())} |
{trytag, ordsets:ordset(label())}.
-type x_regs() :: #{ {x, index()} => #value_ref{} }.
-type y_regs() :: #{ {y, index()} => tag() | #value_ref{} }.
-record(st,
vs=#{} :: values(),
Register states .
xs=#{} :: x_regs(),
ys=#{} :: y_regs(),
f=init_fregs(),
GC .
fragile=sets:new([{version, 2}]) :: sets:set(),
numy=none :: none | {undecided,index()} | index(),
h=0,
hl=0,
hf=0,
ct=[],
Previous instruction was setelement/3 .
setelem=false,
put/1 instructions left .
puts_left=none,
* ' marked_position ' - We 've used a marker prior to .
recv_state=none :: none | undecided | marked_position | entered_loop,
ms_positions=#{} :: #{ Ctx :: #value_ref{} => Pos :: #value_ref{} }
}).
-type label() :: integer().
-type state() :: #st{} | 'none'.
-record(vst,
current=none :: state(),
level :: strong | weak,
branched=#{} :: #{ label() => state() },
labels=sets:new([{version, 2}]) :: sets:set(),
ft=#{} :: #{ label() => map() },
ref_ctr=0 :: index()
}).
build_function_table([{function,Name,Arity,Entry,Code0}|Fs], Acc) ->
Code = dropwhile(fun({label,L}) when L =:= Entry ->
false;
(_) ->
true
end, Code0),
case Code of
[{label,Entry} | Is] ->
Info = #{ name => Name,
arity => Arity,
parameter_info => find_parameter_info(Is, #{}),
always_fails => always_fails(Is) },
build_function_table(Fs, Acc#{ Entry => Info });
_ ->
build_function_table(Fs, Acc)
end;
build_function_table([], Acc) ->
Acc.
' , { var_info , , Info } } | Is ] , Acc ) - >
find_parameter_info(Is, Acc#{ Reg => Info });
find_parameter_info(Is, Acc);
find_parameter_info(_, Acc) ->
Acc.
always_fails([{jump,_}|_]) -> true;
always_fails(_) -> false.
validate_1(Is, MFA0, Entry, Level, Ft) ->
{Offset, MFA, Header, Body} = extract_header(Is, MFA0, Entry, 1, []),
Vst0 = init_vst(MFA, Level, Ft),
Vst1 = validate_instrs(Body, MFA, Offset, Vst0),
Vst = validate_instrs(Header, MFA, 1, Vst1),
validate_branches(MFA, Vst).
extract_header([{func_info, {atom,Mod}, {atom,Name}, Arity}=I | Is],
MFA0, Entry, Offset, Acc) ->
MFA = {Mod, Name, Arity},
case Is of
[{label, Entry} | _] ->
Header = reverse(Acc, [I]),
{Offset + 1, MFA, Header, Is};
_ ->
error({MFA, no_entry_label})
end;
extract_header([{label,_}=I | Is], MFA, Entry, Offset, Acc) ->
extract_header(Is, MFA, Entry, Offset + 1, [I | Acc]);
extract_header([{line,_}=I | Is], MFA, Entry, Offset, Acc) ->
extract_header(Is, MFA, Entry, Offset + 1, [I | Acc]);
extract_header(_Is, MFA, _Entry, _Offset, _Acc) ->
error({MFA, invalid_function_header}).
init_vst({_, _, Arity}, Level, Ft) ->
Vst = #vst{branched=#{},
current=#st{},
ft=Ft,
labels=sets:new([{version, 2}]),
level=Level},
init_function_args(Arity - 1, Vst).
init_function_args(-1, Vst) ->
Vst;
init_function_args(X, Vst) ->
init_function_args(X - 1, create_term(any, argument, [], {x,X}, Vst)).
kill_heap_allocation(#vst{current=St0}=Vst) ->
St = St0#st{h=0,hl=0,hf=0},
Vst#vst{current=St}.
validate_branches(MFA, Vst) ->
#vst{ branched=Targets0, labels=Labels0 } = Vst,
Targets = maps:keys(Targets0),
Labels = sets:to_list(Labels0),
case Targets -- Labels of
[_|_]=Undef ->
Error = {undef_labels, Undef},
error({MFA, Error});
[] ->
Vst
end.
validate_instrs([I|Is], MFA, Offset, Vst0) ->
validate_instrs(Is, MFA, Offset+1,
try
Vst = validate_mutation(I, Vst0),
vi(I, Vst)
catch Error ->
error({MFA, {I, Offset, Error}})
end);
validate_instrs([], _MFA, _Offset, Vst) ->
Vst.
vi({label,Lbl}, #vst{current=St0,
ref_ctr=Counter0,
branched=Branched0,
labels=Labels0}=Vst) ->
{St, Counter} = merge_states(Lbl, St0, Branched0, Counter0),
Branched = Branched0#{ Lbl => St },
Labels = sets:add_element(Lbl, Labels0),
Vst#vst{current=St,
ref_ctr=Counter,
branched=Branched,
labels=Labels};
vi(_I, #vst{current=none}=Vst) ->
Vst;
' , { var_info , , Info } } , ) - >
validate_var_info(Info, Reg, Vst);
' , { remove_fragility , } } , ) - >
prim_eval:'receive'/2 wo n't leak the term , nor cause a GC since it 's
remove_fragility(Reg, Vst);
' , _ } , ) - >
Vst;
vi({line,_}, Vst) ->
Vst;
vi(nif_start, Vst) ->
Vst;
vi({move,Src,Dst}, Vst) ->
assign(Src, Dst, Vst);
vi({swap,RegA,RegB}, Vst0) ->
assert_movable(RegA, Vst0),
assert_movable(RegB, Vst0),
fragile if one of the register is fragile instead of
Sources = [RegA,RegB],
Vst1 = propagate_fragility(RegA, Sources, Vst0),
Vst2 = propagate_fragility(RegB, Sources, Vst1),
VrefA = get_reg_vref(RegA, Vst2),
VrefB = get_reg_vref(RegB, Vst2),
Vst = set_reg_vref(VrefB, RegA, Vst2),
set_reg_vref(VrefA, RegB, Vst);
vi({fmove,Src,{fr,_}=Dst}, Vst) ->
assert_type(#t_float{}, Src, Vst),
set_freg(Dst, Vst);
vi({fmove,{fr,_}=Src,Dst}, Vst0) ->
assert_freg_set(Src, Vst0),
Vst = eat_heap_float(Vst0),
create_term(#t_float{}, fmove, [], Dst, Vst);
vi({kill,Reg}, Vst) ->
create_tag(initialized, kill, [], Reg, Vst);
vi({init,Reg}, Vst) ->
create_tag(initialized, init, [], Reg, Vst);
vi({init_yregs,{list,Yregs}}, Vst0) ->
case ordsets:from_list(Yregs) of
[] -> error(empty_list);
Yregs -> ok;
_ -> error(not_ordset)
end,
foldl(fun(Y, Vst) ->
create_tag(initialized, init, [], Y, Vst)
end, Vst0, Yregs);
vi({jump,{f,Lbl}}, Vst) ->
assert_no_exception(Lbl),
branch(Lbl, Vst, fun kill_state/1);
vi({select_val,Src0,{f,Fail},{list,Choices}}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
assert_choices(Choices),
validate_select_val(Fail, Choices, Src, Vst);
vi({select_tuple_arity,Tuple0,{f,Fail},{list,Choices}}, Vst) ->
Tuple = unpack_typed_arg(Tuple0, Vst),
assert_type(#t_tuple{}, Tuple, Vst),
assert_arities(Choices),
validate_select_tuple_arity(Fail, Choices, Tuple, Vst);
vi({test,has_map_fields,{f,Lbl},Src,{list,List}}, Vst) ->
verify_has_map_fields(Lbl, Src, List, Vst);
vi({test,is_atom,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_atom{}, Src, Vst);
vi({test,is_binary,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_bitstring{size_unit=8}, Src, Vst);
vi({test,is_bitstr,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_bitstring{}, Src, Vst);
vi({test,is_boolean,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, beam_types:make_boolean(), Src, Vst);
vi({test,is_float,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_float{}, Src, Vst);
vi({test,is_function,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_fun{}, Src, Vst);
vi({test,is_function2,{f,Lbl},[Src,{integer,Arity}]}, Vst)
when Arity >= 0, Arity =< ?MAX_FUNC_ARGS ->
type_test(Lbl, #t_fun{arity=Arity}, Src, Vst);
vi({test,is_function2,{f,Lbl},[Src0,_Arity]}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
FailVst
end,
fun(SuccVst) ->
update_type(fun meet/2, #t_fun{}, Src, SuccVst)
end);
vi({test,is_tuple,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_tuple{}, Src, Vst);
vi({test,is_integer,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_integer{}, Src, Vst);
vi({test,is_nonempty_list,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_cons{}, Src, Vst);
vi({test,is_number,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_number{}, Src, Vst);
vi({test,is_list,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_list{}, Src, Vst);
vi({test,is_map,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, #t_map{}, Src, Vst);
vi({test,is_nil,{f,Lbl},[Src0]}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
update_ne_types(Src, nil, FailVst)
end,
fun(SuccVst) ->
update_eq_types(Src, nil, SuccVst)
end);
vi({test,is_pid,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, pid, Src, Vst);
vi({test,is_port,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, port, Src, Vst);
vi({test,is_reference,{f,Lbl},[Src]}, Vst) ->
type_test(Lbl, reference, Src, Vst);
vi({test,test_arity,{f,Lbl},[Tuple,Sz]}, Vst) when is_integer(Sz) ->
assert_type(#t_tuple{}, Tuple, Vst),
Type = #t_tuple{exact=true,size=Sz},
type_test(Lbl, Type, Tuple, Vst);
vi({test,is_tagged_tuple,{f,Lbl},[Src0,Sz,Atom]}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
Es = #{ 1 => get_literal_type(Atom) },
Type = #t_tuple{exact=true,size=Sz,elements=Es},
type_test(Lbl, Type, Src, Vst);
vi({test,is_eq_exact,{f,Lbl},[Src0,Val0]}, Vst) ->
assert_no_exception(Lbl),
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
Val = unpack_typed_arg(Val0, Vst),
assert_term(Val, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
update_ne_types(Src, Val, FailVst)
end,
fun(SuccVst) ->
update_eq_types(Src, Val, SuccVst)
end);
vi({test,is_ne_exact,{f,Lbl},[Src0,Val0]}, Vst) ->
assert_no_exception(Lbl),
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
Val = unpack_typed_arg(Val0, Vst),
assert_term(Val, Vst),
branch(Lbl, Vst,
fun(FailVst) ->
update_eq_types(Src, Val, FailVst)
end,
fun(SuccVst) ->
update_ne_types(Src, Val, SuccVst)
end);
vi({get_list,Src,D1,D2}, Vst0) ->
assert_not_literal(Src),
assert_type(#t_cons{}, Src, Vst0),
SrcType = get_term_type(Src, Vst0),
{HeadType, _, _} = beam_call_types:types(erlang, hd, [SrcType]),
{TailType, _, _} = beam_call_types:types(erlang, tl, [SrcType]),
Vst = extract_term(HeadType, get_hd, [Src], D1, Vst0),
extract_term(TailType, get_tl, [Src], D2, Vst, Vst0);
vi({get_hd,Src,Dst}, Vst) ->
assert_not_literal(Src),
assert_type(#t_cons{}, Src, Vst),
SrcType = get_term_type(Src, Vst),
{HeadType, _, _} = beam_call_types:types(erlang, hd, [SrcType]),
extract_term(HeadType, get_hd, [Src], Dst, Vst);
vi({get_tl,Src,Dst}, Vst) ->
assert_not_literal(Src),
assert_type(#t_cons{}, Src, Vst),
SrcType = get_term_type(Src, Vst),
{TailType, _, _} = beam_call_types:types(erlang, tl, [SrcType]),
extract_term(TailType, get_tl, [Src], Dst, Vst);
vi({get_tuple_element,Src,N,Dst}, Vst) ->
Index = N+1,
assert_not_literal(Src),
assert_type(#t_tuple{size=Index}, Src, Vst),
VRef = get_reg_vref(Src, Vst),
Type = fun(Vs) ->
#value{type=T} = map_get(VRef, Vs),
#t_tuple{elements=Es} = normalize(concrete_type(T, Vs)),
beam_types:get_tuple_element(Index, Es)
end,
extract_term(Type, {bif,element}, [{integer,Index}, Src], Dst, Vst);
vi({test_heap,Heap,Live}, Vst) ->
test_heap(Heap, Live, Vst);
vi({allocate,Stk,Live}, Vst) ->
allocate(uninitialized, Stk, 0, Live, Vst);
vi({allocate_heap,Stk,Heap,Live}, Vst) ->
allocate(uninitialized, Stk, Heap, Live, Vst);
vi({allocate_zero,Stk,Live}, Vst) ->
allocate(initialized, Stk, 0, Live, Vst);
vi({allocate_heap_zero,Stk,Heap,Live}, Vst) ->
allocate(initialized, Stk, Heap, Live, Vst);
vi({deallocate,StkSize}, #vst{current=#st{numy=StkSize}}=Vst) ->
verify_no_ct(Vst),
deallocate(Vst);
vi({deallocate,_}, #vst{current=#st{numy=NumY}}) ->
error({allocated,NumY});
vi({trim,N,Remaining}, #vst{current=St0}=Vst) ->
#st{numy=NumY} = St0,
if
N =< NumY, N+Remaining =:= NumY ->
Vst#vst{current=trim_stack(N, 0, NumY, St0)};
N > NumY; N+Remaining =/= NumY ->
error({trim,N,Remaining,allocated,NumY})
end;
vi({put_list,A,B,Dst}, Vst0) ->
Vst = eat_heap(2, Vst0),
Head = get_term_type(A, Vst),
Tail = get_term_type(B, Vst),
create_term(beam_types:make_cons(Head, Tail), put_list, [A, B], Dst, Vst);
vi({put_tuple2,Dst,{list,Elements}}, Vst0) ->
_ = [assert_term(El, Vst0) || El <- Elements],
Size = length(Elements),
Vst = eat_heap(Size+1, Vst0),
{Es,_} = foldl(fun(Val, {Es0, Index}) ->
Type = get_term_type(Val, Vst0),
Es = beam_types:set_tuple_element(Index, Type, Es0),
{Es, Index + 1}
end, {#{}, 1}, Elements),
Type = #t_tuple{exact=true,size=Size,elements=Es},
create_term(Type, put_tuple2, [], Dst, Vst);
vi({set_tuple_element,Src,Tuple,N}, Vst) ->
I = N + 1,
assert_term(Src, Vst),
assert_type(#t_tuple{size=I}, Tuple, Vst),
TupleType0 = get_term_type(Tuple, Vst),
ArgType = get_term_type(Src, Vst),
TupleType = beam_types:update_tuple(TupleType0, [{I, ArgType}]),
override_type(TupleType, Tuple, Vst);
vi({update_record,_Hint,Size,Src,Dst,{list,Ss}}, Vst) ->
verify_update_record(Size, Src, Dst, Ss, Vst);
vi({apply,Live}, Vst) ->
validate_body_call(apply, Live+2, Vst);
vi({apply_last,Live,N}, Vst) ->
validate_tail_call(N, apply, Live+2, Vst);
vi({call,Live,Func}, Vst) ->
validate_body_call(Func, Live, Vst);
vi({call_ext,Live,Func}, Vst) ->
validate_body_call(Func, Live, Vst);
vi({call_only,Live,Func}, Vst) ->
validate_tail_call(none, Func, Live, Vst);
vi({call_ext_only,Live,Func}, Vst) ->
validate_tail_call(none, Func, Live, Vst);
vi({call_last,Live,Func,N}, Vst) ->
validate_tail_call(N, Func, Live, Vst);
vi({call_ext_last,Live,Func,N}, Vst) ->
validate_tail_call(N, Func, Live, Vst);
vi({call_fun2,{f,Lbl},Live,Fun0}, #vst{ft=Ft}=Vst) ->
#{ name := Name, arity := TotalArity } = map_get(Lbl, Ft),
assert_term(Fun, Vst),
validate_body_call('fun', Live, Vst);
vi({call_fun2,Tag,Live,Fun0}, Vst) ->
Fun = unpack_typed_arg(Fun0, Vst),
assert_term(Fun, Vst),
case Tag of
{atom,safe} -> ok;
{atom,unsafe} -> ok;
_ -> error({invalid_tag,Tag})
end,
branch(?EXCEPTION_LABEL, Vst,
fun(SuccVst0) ->
SuccVst = update_type(fun meet/2, #t_fun{arity=Live},
Fun, SuccVst0),
validate_body_call('fun', Live, SuccVst)
end);
vi({call_fun,Live}, Vst) ->
Fun = {x,Live},
assert_term(Fun, Vst),
branch(?EXCEPTION_LABEL, Vst,
fun(SuccVst0) ->
SuccVst = update_type(fun meet/2, #t_fun{arity=Live},
Fun, SuccVst0),
validate_body_call('fun', Live+1, SuccVst)
end);
vi({make_fun2,{f,Lbl},_,_,NumFree}, #vst{ft=Ft}=Vst0) ->
#{ name := Name, arity := TotalArity } = map_get(Lbl, Ft),
Arity = TotalArity - NumFree,
Vst = prune_x_regs(NumFree, Vst0),
verify_call_args(make_fun, NumFree, Vst),
verify_y_init(Vst),
Type = #t_fun{target={Name,TotalArity},arity=Arity},
create_term(Type, make_fun, [], {x,0}, Vst);
vi({make_fun3,{f,Lbl},_,_,Dst,{list,Env}}, #vst{ft=Ft}=Vst0) ->
_ = [assert_term(E, Vst0) || E <- Env],
NumFree = length(Env),
#{ name := Name, arity := TotalArity } = map_get(Lbl, Ft),
Arity = TotalArity - NumFree,
Vst = eat_heap_fun(Vst0),
Type = #t_fun{target={Name,TotalArity},arity=Arity},
create_term(Type, make_fun, [], Dst, Vst);
vi(return, Vst) ->
assert_durable_term({x,0}, Vst),
verify_return(Vst);
BIF calls
vi({bif,Op,{f,Fail},Ss0,Dst0}, Vst0) ->
Ss = [unpack_typed_arg(Arg, Vst0) || Arg <- Ss0],
Dst = unpack_typed_arg(Dst0, Vst0),
case is_float_arith_bif(Op, Ss) of
true ->
validate_float_arith_bif(Ss, Dst, Vst0);
false ->
validate_src(Ss, Vst0),
validate_bif(bif, Op, Fail, Ss, Dst, Vst0, Vst0)
end;
vi({gc_bif,Op,{f,Fail},Live,Ss0,Dst0}, Vst0) ->
Ss = [unpack_typed_arg(Arg, Vst0) || Arg <- Ss0],
Dst = unpack_typed_arg(Dst0, Vst0),
validate_src(Ss, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
Heap allocations and X registers are killed regardless of whether we
fail or not , as we may fail after GC .
Vst1 = kill_heap_allocation(Vst0),
Vst = prune_x_regs(Live, Vst1),
validate_bif(gc_bif, Op, Fail, Ss, Dst, Vst0, Vst);
vi(send, Vst) ->
validate_body_call(send, 2, Vst);
vi({loop_rec,{f,Fail},Dst}, Vst0) ->
assert_no_exception(Fail),
Vst = update_receive_state(entered_loop, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
{Ref, SuccVst} = new_value(any, loop_rec, [], SuccVst0),
mark_fragile(Dst, set_reg_vref(Ref, Dst, SuccVst))
end);
vi({loop_rec_end,Lbl}, Vst) ->
assert_no_exception(Lbl),
verify_y_init(Vst),
kill_state(Vst);
vi({recv_marker_reserve=Op, Dst}, Vst) ->
create_term(#t_abstract{kind=receive_marker}, Op, [], Dst, Vst);
vi({recv_marker_bind, Marker, Ref}, Vst) ->
assert_type(#t_abstract{kind=receive_marker}, Marker, Vst),
assert_durable_term(Ref, Vst),
assert_not_literal(Ref),
Vst;
vi({recv_marker_clear, Ref}, Vst) ->
assert_durable_term(Ref, Vst),
assert_not_literal(Ref),
Vst;
vi({recv_marker_use, Ref}, Vst) ->
assert_durable_term(Ref, Vst),
assert_not_literal(Ref),
update_receive_state(marked_position, Vst);
vi(remove_message, Vst0) ->
Vst = update_receive_state(none, Vst0),
remove_fragility(Vst);
vi(timeout, Vst0) ->
Vst = update_receive_state(none, Vst0),
prune_x_regs(0, Vst);
vi({wait,{f,Lbl}}, Vst) ->
assert_no_exception(Lbl),
verify_y_init(Vst),
branch(Lbl, Vst, fun kill_state/1);
vi({wait_timeout,{f,Lbl},Src}, Vst0) ->
assert_no_exception(Lbl),
assert_term(Src, Vst0),
verify_y_init(Vst0),
Vst = branch(Lbl, schedule_out(0, Vst0)),
branch(?EXCEPTION_LABEL, Vst);
vi({'catch',Dst,{f,Fail}}, Vst) when Fail =/= none ->
init_try_catch_branch(catchtag, Dst, Fail, Vst);
vi({'try',Dst,{f,Fail}}, Vst) when Fail =/= none ->
init_try_catch_branch(trytag, Dst, Fail, Vst);
vi({catch_end,Reg}, #vst{current=#st{ct=[Tag|_]}}=Vst0) ->
case get_tag_type(Reg, Vst0) of
{catchtag,_Fail}=Tag ->
Vst = kill_catch_tag(Reg, Vst0),
create_term(any, catch_end, [], {x,0}, Vst);
Type ->
error({wrong_tag_type,Type})
end;
vi({try_end,Reg}, #vst{current=#st{ct=[Tag|_]}}=Vst) ->
case get_tag_type(Reg, Vst) of
{trytag,_Fail}=Tag ->
kill_catch_tag(Reg, Vst);
Type ->
error({wrong_tag_type,Type})
end;
vi({try_case,Reg}, #vst{current=#st{ct=[Tag|_]}}=Vst0) ->
case get_tag_type(Reg, Vst0) of
{trytag,_Fail}=Tag ->
Vst1 = kill_catch_tag(Reg, Vst0),
Vst2 = schedule_out(0, Vst1),
ClassType = #t_atom{elements=[error,exit,throw]},
Vst3 = create_term(ClassType, try_case, [], {x,0}, Vst2),
Vst = create_term(any, try_case, [], {x,1}, Vst3),
create_term(any, try_case, [], {x,2}, Vst);
Type ->
error({wrong_tag_type,Type})
end;
vi(build_stacktrace, Vst0) ->
verify_y_init(Vst0),
verify_live(1, Vst0),
Vst = prune_x_regs(1, Vst0),
Reg = {x,0},
assert_durable_term(Reg, Vst),
create_term(#t_list{}, build_stacktrace, [], Reg, Vst);
vi({get_map_elements,{f,Fail},Src0,{list,List}}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
verify_get_map(Fail, Src, List, Vst);
vi({put_map_assoc=Op,{f,Fail},Src,Dst,Live,{list,List}}, Vst) ->
verify_put_map(Op, Fail, Src, Dst, Live, List, Vst);
vi({put_map_exact=Op,{f,Fail},Src,Dst,Live,{list,List}}, Vst) ->
verify_put_map(Op, Fail, Src, Dst, Live, List, Vst);
vi({bs_match,{f,Fail},Ctx0,{commands,List}}, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
verify_y_init(Vst),
branch(Fail, Vst,
fun(FailVst) ->
validate_failed_bs_match(List, Ctx, FailVst)
end,
fun(SuccVst) ->
validate_bs_match(List, Ctx, 1, SuccVst)
end);
vi({bs_get_tail,Ctx,Dst,Live}, Vst0) ->
assert_type(#t_bs_context{}, Ctx, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
#t_bs_context{tail_unit=Unit} = get_concrete_type(Ctx, Vst0),
Vst = prune_x_regs(Live, Vst0),
extract_term(#t_bitstring{size_unit=Unit}, bs_get_tail, [Ctx], Dst,
Vst, Vst0);
vi({bs_start_match4,Fail,Live,Src,Dst}, Vst) ->
validate_bs_start_match(Fail, Live, Src, Dst, Vst);
vi({test,bs_start_match3,{f,_}=Fail,Live,[Src],Dst}, Vst) ->
validate_bs_start_match(Fail, Live, Src, Dst, Vst);
vi({test,bs_match_string,{f,Fail},[Ctx,Stride,{string,String}]}, Vst) ->
validate_bs_skip(Fail, Ctx, Stride, Vst);
vi({test,bs_skip_bits2,{f,Fail},[Ctx,Size0,Unit,_Flags]}, Vst) ->
Size = unpack_typed_arg(Size0, Vst),
assert_term(Size, Vst),
Stride = case get_concrete_type(Size, Vst) of
#t_integer{elements={Same,Same}} -> Same * Unit;
_ -> Unit
end,
validate_bs_skip(Fail, Ctx, Stride, Vst);
vi({test,bs_test_tail2,{f,Fail},[Ctx,_Size]}, Vst) ->
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
branch(Fail, Vst);
vi({test,bs_test_unit,{f,Fail},[Ctx,Unit]}, Vst) ->
assert_type(#t_bs_context{}, Ctx, Vst),
Type = #t_bs_context{tail_unit=Unit},
branch(Fail, Vst,
fun(FailVst) ->
update_type(fun subtract/2, Type, Ctx, FailVst)
end,
fun(SuccVst0) ->
SuccVst = update_bs_unit(Ctx, Unit, SuccVst0),
update_type(fun meet/2, Type, Ctx, SuccVst)
end);
vi({test,bs_skip_utf8,{f,Fail},[Ctx,Live,_]}, Vst) ->
validate_bs_skip(Fail, Ctx, 8, Live, Vst);
vi({test,bs_skip_utf16,{f,Fail},[Ctx,Live,_]}, Vst) ->
validate_bs_skip(Fail, Ctx, 16, Live, Vst);
vi({test,bs_skip_utf32,{f,Fail},[Ctx,Live,_]}, Vst) ->
validate_bs_skip(Fail, Ctx, 32, Live, Vst);
vi({test,bs_get_binary2=Op,{f,Fail},Live,[Ctx,{atom,all},Unit,_],Dst}, Vst) ->
Type = #t_bitstring{size_unit=Unit},
validate_bs_get_all(Op, Fail, Ctx, Live, Unit, Type, Dst, Vst);
vi({test,bs_get_binary2=Op,{f,Fail},Live,[Ctx,Size,Unit,_],Dst}, Vst) ->
Type = #t_bitstring{size_unit=bsm_size_unit(Size, Unit)},
Stride = bsm_stride(Size, Unit),
validate_bs_get(Op, Fail, Ctx, Live, Stride, Type, Dst, Vst);
vi({test,bs_get_integer2=Op,{f,Fail},Live,
[Ctx,{integer,Size},Unit,{field_flags,Flags}],Dst},Vst) ->
Type = bs_integer_type({Size, Size}, Unit, Flags),
Stride = Unit * Size,
validate_bs_get(Op, Fail, Ctx, Live, Stride, Type, Dst, Vst);
vi({test,bs_get_integer2=Op,{f,Fail},Live,[Ctx,Sz0,Unit,{field_flags,Flags}],Dst},Vst) ->
Sz = unpack_typed_arg(Sz0, Vst),
Type = case meet(get_term_type(Sz, Vst), #t_integer{}) of
#t_integer{elements=Bounds} ->
bs_integer_type(Bounds, Unit, Flags);
none ->
none
end,
validate_bs_get(Op, Fail, Ctx, Live, Unit, Type, Dst, Vst);
vi({test,bs_get_float2=Op,{f,Fail},Live,[Ctx,Size,Unit,_],Dst},Vst) ->
Stride = bsm_stride(Size, Unit),
validate_bs_get(Op, Fail, Ctx, Live, Stride, #t_float{}, Dst, Vst);
vi({test,bs_get_utf8=Op,{f,Fail},Live,[Ctx,_],Dst}, Vst) ->
Type = beam_types:make_integer(0, ?UNICODE_MAX),
validate_bs_get(Op, Fail, Ctx, Live, 8, Type, Dst, Vst);
vi({test,bs_get_utf16=Op,{f,Fail},Live,[Ctx,_],Dst}, Vst) ->
Type = beam_types:make_integer(0, ?UNICODE_MAX),
validate_bs_get(Op, Fail, Ctx, Live, 16, Type, Dst, Vst);
vi({test,bs_get_utf32=Op,{f,Fail},Live,[Ctx,_],Dst}, Vst) ->
Type = beam_types:make_integer(0, ?UNICODE_MAX),
validate_bs_get(Op, Fail, Ctx, Live, 32, Type, Dst, Vst);
vi({test,is_lt,{f,Fail},Args0}, Vst) ->
Args = [unpack_typed_arg(Arg, Vst) || Arg <- Args0],
validate_src(Args, Vst),
Types = [get_term_type(Arg, Vst) || Arg <- Args],
branch(Fail, Vst,
fun(FailVst) ->
infer_relop_types('>=', Args, Types, FailVst)
end,
fun(SuccVst) ->
infer_relop_types('<', Args, Types, SuccVst)
end);
vi({test,is_ge,{f,Fail},Args0}, Vst) ->
Args = [unpack_typed_arg(Arg, Vst) || Arg <- Args0],
validate_src(Args, Vst),
Types = [get_term_type(Arg, Vst) || Arg <- Args],
branch(Fail, Vst,
fun(FailVst) ->
infer_relop_types('<', Args, Types, FailVst)
end,
fun(SuccVst) ->
infer_relop_types('>=', Args, Types, SuccVst)
end);
vi({test,_Op,{f,Lbl},Ss}, Vst) ->
validate_src([unpack_typed_arg(Arg, Vst) || Arg <- Ss], Vst),
branch(Lbl, Vst);
vi({bs_get_position, Ctx, Dst, Live}, Vst0) ->
assert_type(#t_bs_context{}, Ctx, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
#t_bs_context{tail_unit=Unit} = get_concrete_type(Ctx, Vst0),
Vst1 = prune_x_regs(Live, Vst0),
Vst = create_term(#t_abstract{kind={ms_position, Unit}},
bs_get_position, [Ctx], Dst, Vst1, Vst0),
mark_current_ms_position(Ctx, Dst, Vst);
vi({bs_set_position, Ctx, Pos}, Vst0) ->
assert_type(#t_bs_context{}, Ctx, Vst0),
assert_type(#t_abstract{kind={ms_position,1}}, Pos, Vst0),
#t_abstract{kind={ms_position,Unit}} = get_concrete_type(Pos, Vst0),
Vst = override_type(#t_bs_context{tail_unit=Unit}, Ctx, Vst0),
mark_current_ms_position(Ctx, Pos, Vst);
vi({fconv,Src0,{fr,_}=Dst}, Vst) ->
Src = unpack_typed_arg(Src0, Vst),
assert_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst,
fun(SuccVst0) ->
SuccVst = update_type(fun meet/2, #t_number{}, Src, SuccVst0),
set_freg(Dst, SuccVst)
end);
vi({func_info, {atom, _Mod}, {atom, _Name}, Arity}, Vst) ->
#vst{current=#st{numy=NumY}} = Vst,
if
NumY =:= none ->
verify_live(Arity, Vst),
verify_call_args(func_info, Arity, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
NumY =/= none ->
error({allocated, NumY})
end;
vi({badmatch,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi({case_end,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi(if_end, Vst) ->
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi({try_case_end,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi({badrecord,Src}, Vst) ->
assert_durable_term(Src, Vst),
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1);
vi(raw_raise=I, Vst0) ->
validate_body_call(I, 3, Vst0);
vi(bs_init_writable=I, Vst) ->
validate_body_call(I, 1, Vst);
vi({bs_create_bin,{f,Fail},Heap,Live,Unit,Dst,{list,List0}}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
List = [unpack_typed_arg(Arg, Vst0) || Arg <- List0],
verify_create_bin_list(List, Vst0),
Vst = prune_x_regs(Live, Vst0),
branch(Fail, Vst,
fun(FailVst0) ->
heap_alloc(0, FailVst0)
end,
fun(SuccVst0) ->
SuccVst1 = update_create_bin_list(List, SuccVst0),
SuccVst = heap_alloc(Heap, SuccVst1),
create_term(#t_bitstring{size_unit=Unit}, bs_create_bin, [], Dst,
SuccVst)
end);
vi({bs_init2,{f,Fail},Sz,Heap,Live,_,Dst}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
if
is_integer(Sz) -> ok;
true -> assert_term(Sz, Vst0)
end,
Vst = heap_alloc(Heap, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
create_term(#t_bitstring{size_unit=8}, bs_init2, [], Dst,
SuccVst, SuccVst0)
end);
vi({bs_init_bits,{f,Fail},Sz,Heap,Live,_,Dst}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
if
is_integer(Sz) -> ok;
true -> assert_term(Sz, Vst0)
end,
Vst = heap_alloc(Heap, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
create_term(#t_bitstring{}, bs_init_bits, [], Dst, SuccVst)
end);
vi({bs_add,{f,Fail},[A,B,_],Dst}, Vst) ->
assert_term(A, Vst),
assert_term(B, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_integer{}, bs_add, [A, B], Dst, SuccVst)
end);
vi({bs_utf8_size,{f,Fail},A,Dst}, Vst) ->
assert_term(A, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_integer{}, bs_utf8_size, [A], Dst, SuccVst)
end);
vi({bs_utf16_size,{f,Fail},A,Dst}, Vst) ->
assert_term(A, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_integer{}, bs_utf16_size, [A], Dst, SuccVst)
end);
vi({bs_append,{f,Fail},Bits,Heap,Live,Unit,Bin,_Flags,Dst}, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
assert_term(Bits, Vst0),
assert_term(Bin, Vst0),
Vst = heap_alloc(Heap, Vst0),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
create_term(#t_bitstring{size_unit=Unit}, bs_append,
[Bin], Dst, SuccVst, SuccVst0)
end);
vi({bs_private_append,{f,Fail},Bits,Unit,Bin,_Flags,Dst}, Vst) ->
assert_term(Bits, Vst),
assert_term(Bin, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
create_term(#t_bitstring{size_unit=Unit}, bs_private_append,
[Bin], Dst, SuccVst)
end);
vi({bs_put_string,Sz,_}, Vst) when is_integer(Sz) ->
Vst;
vi({bs_put_binary,{f,Fail},Sz,_,_,Src}, Vst) ->
assert_term(Sz, Vst),
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_bitstring{}, Src, SuccVst)
end);
vi({bs_put_float,{f,Fail},Sz,_,_,Src}, Vst) ->
assert_term(Sz, Vst),
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_float{}, Src, SuccVst)
end);
vi({bs_put_integer,{f,Fail},Sz,_,_,Src}, Vst) ->
assert_term(Sz, Vst),
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi({bs_put_utf8,{f,Fail},_,Src}, Vst) ->
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi({bs_put_utf16,{f,Fail},_,Src}, Vst) ->
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi({bs_put_utf32,{f,Fail},_,Src}, Vst) ->
assert_term(Src, Vst),
branch(Fail, Vst,
fun(SuccVst) ->
update_type(fun meet/2, #t_integer{}, Src, SuccVst)
end);
vi(_, _) ->
error(unknown_instruction).
infer_relop_types(Op, Args, Types, Vst) ->
case infer_relop_types(Op, Types) of
[] ->
Vst;
Infer ->
Zipped = zip(Args, Infer),
foldl(fun({V,T}, Acc) ->
update_type(fun meet/2, T, V, Acc)
end, Vst, Zipped)
end.
infer_relop_types(Op, [#t_integer{elements=R1},
#t_integer{elements=R2}]) ->
case beam_bounds:infer_relop_types(Op, R1, R2) of
{NewR1,NewR2} ->
NewType1 = #t_integer{elements=NewR1},
NewType2 = #t_integer{elements=NewR2},
[NewType1,NewType2];
none ->
[none, none];
any ->
[]
end;
infer_relop_types(Op0, [Type1,Type2]) ->
Op = case Op0 of
'<' -> '=<';
'>' -> '>=';
_ -> Op0
end,
case {infer_get_range(Type1),infer_get_range(Type2)} of
{none,_}=R ->
[infer_relop_any(Op, R, Type1),Type2];
{_,none}=R ->
[Type1,infer_relop_any(Op, R, Type2)];
{R1,R2} ->
case beam_bounds:infer_relop_types(Op, R1, R2) of
{NewR1,NewR2} ->
NewType1 = meet(#t_number{elements=NewR1}, Type1),
NewType2 = meet(#t_number{elements=NewR2}, Type2),
[NewType1,NewType2];
none ->
[none, none];
any ->
[]
end
end;
infer_relop_types(_, _) ->
[].
infer_relop_any('=<', {none,any}, Type) ->
N = #t_number{},
meet(N, Type);
infer_relop_any('=<', {none,{_,Max}}, Type) ->
N = infer_make_number({'-inf',Max}),
meet(N, Type);
infer_relop_any('>=', {any,none}, Type) ->
N = #t_number{},
meet(N, Type);
infer_relop_any('>=', {{_,Max},none}, Type) ->
N = infer_make_number({'-inf',Max}),
meet(N, Type);
infer_relop_any('>=', {none,{Min,_}}, Type) when is_integer(Min) ->
N = #t_number{elements={'-inf',Min}},
meet(subtract(any, N), Type);
infer_relop_any('=<', {{Min,_},none}, Type) when is_integer(Min) ->
N = #t_number{elements={'-inf',Min}},
meet(subtract(any, N), Type);
infer_relop_any(_, _, Type) ->
Type.
infer_make_number({'-inf','+inf'}) ->
#t_number{};
infer_make_number({_,_}=R) ->
#t_number{elements=R}.
infer_get_range(#t_integer{elements=R}) -> R;
infer_get_range(#t_number{elements=R}) -> R;
infer_get_range(_) -> none.
validate_var_info([{fun_type, Type} | Info], Reg, Vst0) ->
Vst = update_type(fun meet/2, #t_fun{type=Type}, Reg, Vst0),
validate_var_info(Info, Reg, Vst);
validate_var_info([{type, none} | _Info], _Reg, Vst) ->
Unreachable code , typically after a call that never returns .
kill_state(Vst);
validate_var_info([{type, Type} | Info], Reg, Vst0) ->
that has a certain type , so that we can accept cross - function type
Vst = update_type(fun meet/2, Type, Reg, Vst0),
validate_var_info(Info, Reg, Vst);
validate_var_info([_ | Info], Reg, Vst) ->
validate_var_info(Info, Reg, Vst);
validate_var_info([], _Reg, Vst) ->
Vst.
validate_tail_call(Deallocate, Func, Live, #vst{current=#st{numy=NumY}}=Vst0) ->
verify_y_init(Vst0),
verify_live(Live, Vst0),
verify_call_args(Func, Live, Vst0),
case will_call_succeed(Func, Live, Vst0) of
yes when Deallocate =:= NumY ->
Vst = deallocate(Vst0),
verify_return(Vst);
'maybe' when Deallocate =:= NumY ->
Vst = deallocate(Vst0),
branch(?EXCEPTION_LABEL, Vst, fun verify_return/1);
no ->
The compiler is allowed to emit garbage values for " "
branch(?EXCEPTION_LABEL, Vst0, fun kill_state/1);
_ when Deallocate =/= NumY ->
error({allocated, NumY})
end.
validate_body_call(Func, Live,
#vst{current=#st{numy=NumY}}=Vst) when is_integer(NumY)->
verify_y_init(Vst),
verify_live(Live, Vst),
verify_call_args(Func, Live, Vst),
SuccFun = fun(SuccVst0) ->
{RetType, _, _} = call_types(Func, Live, SuccVst0),
SuccVst = schedule_out(0, SuccVst0),
create_term(RetType, call, [], {x,0}, SuccVst)
end,
case will_call_succeed(Func, Live, Vst) of
yes ->
SuccFun(Vst);
'maybe' ->
branch(?EXCEPTION_LABEL, Vst, SuccFun);
no ->
branch(?EXCEPTION_LABEL, Vst, fun kill_state/1)
end;
validate_body_call(_, _, #vst{current=#st{numy=NumY}}) ->
error({allocated, NumY}).
init_try_catch_branch(Kind, Dst, Fail, Vst0) ->
assert_no_exception(Fail),
Tag = {Kind, [Fail]},
Vst = create_tag(Tag, 'try_catch', [], Dst, Vst0),
#vst{current=St0} = Vst,
#st{ct=Tags}=St0,
St = St0#st{ct=[Tag|Tags]},
Vst#vst{current=St}.
verify_has_map_fields(Lbl, Src, List, Vst) ->
assert_type(#t_map{}, Src, Vst),
assert_unique_map_keys(List),
verify_map_fields(List, Src, Lbl, Vst).
verify_map_fields([Key | Keys], Map, Lbl, Vst) ->
assert_term(Key, Vst),
case bif_types(map_get, [Key, Map], Vst) of
{none, _, _} -> kill_state(Vst);
{_, _, _} -> verify_map_fields(Keys, Map, Lbl, Vst)
end;
verify_map_fields([], _Map, Lbl, Vst) ->
branch(Lbl, Vst).
verify_get_map(Fail, Src, List, Vst0) ->
assert_no_exception(Fail),
OTP 22 .
assert_type(#t_map{}, Src, Vst0),
branch(Fail, Vst0,
fun(FailVst) ->
clobber_map_vals(List, Src, FailVst)
end,
fun(SuccVst) ->
Keys = extract_map_keys(List, SuccVst),
assert_unique_map_keys(Keys),
extract_map_vals(List, Src, SuccVst)
end).
{ , a},{x,1},{atom , b},{x,2 } ] } } .
clobber_map_vals([Key0, Dst | T], Map, Vst0) ->
Key = unpack_typed_arg(Key0, Vst0),
case is_reg_initialized(Dst, Vst0) of
true ->
Vst = extract_term(any, {bif,map_get}, [Key, Map], Dst, Vst0),
clobber_map_vals(T, Map, Vst);
false ->
clobber_map_vals(T, Map, Vst0)
end;
clobber_map_vals([], _Map, Vst) ->
Vst.
is_reg_initialized({x,_}=Reg, #vst{current=#st{xs=Xs}}) ->
is_map_key(Reg, Xs);
is_reg_initialized({y,_}=Reg, #vst{current=#st{ys=Ys}}) ->
case Ys of
#{Reg:=Val} ->
Val =/= uninitialized;
#{} ->
false
end;
is_reg_initialized(V, #vst{}) -> error({not_a_register, V}).
extract_map_keys([Key,_Val | T], Vst) ->
[unpack_typed_arg(Key, Vst) | extract_map_keys(T, Vst)];
extract_map_keys([], _Vst) ->
[].
extract_map_vals(List, Src, SuccVst) ->
Seen = sets:new([{version, 2}]),
extract_map_vals(List, Src, Seen, SuccVst, SuccVst).
extract_map_vals([Key0, Dst | Vs], Map, Seen0, Vst0, Vsti0) ->
case sets:is_element(Dst, Seen0) of
true ->
error(conflicting_destinations);
false ->
Key = unpack_typed_arg(Key0, Vsti0),
assert_term(Key, Vst0),
case bif_types(map_get, [Key, Map], Vst0) of
{none, _, _} ->
kill_state(Vsti0);
{DstType, _, _} ->
Vsti = extract_term(DstType, {bif,map_get},
[Key, Map], Dst, Vsti0),
Seen = sets:add_element(Dst, Seen0),
extract_map_vals(Vs, Map, Seen, Vst0, Vsti)
end
end;
extract_map_vals([], _Map, _Seen, _Vst0, Vst) ->
Vst.
verify_put_map(Op, Fail, Src, Dst, Live, List, Vst0) ->
assert_type(#t_map{}, Src, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
_ = [assert_term(Term, Vst0) || Term <- List],
Vst = heap_alloc(0, Vst0),
SuccFun = fun(SuccVst0) ->
SuccVst = prune_x_regs(Live, SuccVst0),
Keys = extract_map_keys(List, SuccVst),
assert_unique_map_keys(Keys),
Type = put_map_type(Src, List, Vst),
create_term(Type, Op, [Src], Dst, SuccVst, SuccVst0)
end,
case Op of
put_map_exact ->
branch(Fail, Vst, SuccFun);
put_map_assoc ->
SuccFun(Vst)
end.
put_map_type(Map0, List, Vst) ->
Map = get_term_type(Map0, Vst),
pmt_1(List, Vst, Map).
pmt_1([Key0, Value0 | List], Vst, Acc0) ->
Key = get_term_type(Key0, Vst),
Value = get_term_type(Value0, Vst),
{Acc, _, _} = beam_call_types:types(maps, put, [Key, Value, Acc0]),
pmt_1(List, Vst, Acc);
pmt_1([], _Vst, Acc) ->
Acc.
verify_update_record(Size, Src, Dst, List, Vst0) ->
assert_type(#t_tuple{exact=true,size=Size}, Src, Vst0),
verify_y_init(Vst0),
Vst = eat_heap(Size + 1, Vst0),
case update_tuple_type(List, Src, Vst) of
none -> error(invalid_index);
Type -> create_term(Type, update_record, [], Dst, Vst)
end.
update_tuple_type([_|_]=Updates0, Src, Vst) ->
Filter = #t_tuple{size=update_tuple_highest_index(Updates0, -1)},
case meet(get_term_type(Src, Vst), Filter) of
none ->
none;
TupleType ->
Updates = update_tuple_type_1(Updates0, Vst),
beam_types:update_tuple(TupleType, Updates)
end.
update_tuple_type_1([Index, Value | Updates], Vst) ->
[{Index, get_term_type(Value, Vst)} | update_tuple_type_1(Updates, Vst)];
update_tuple_type_1([], _Vst) ->
[].
update_tuple_highest_index([Index, _Val | List], Acc) when is_integer(Index) ->
update_tuple_highest_index(List, max(Index, Acc));
update_tuple_highest_index([], Acc) when Acc >= 1 ->
Acc.
verify_create_bin_list([{atom,string},_Seg,Unit,Flags,Val,Size|Args], Vst) ->
assert_bs_unit({atom,string}, Unit),
assert_term(Flags, Vst),
case Val of
{string,Bs} when is_binary(Bs) -> ok;
_ -> error({not_string,Val})
end,
assert_term(Flags, Vst),
assert_term(Size, Vst),
verify_create_bin_list(Args, Vst);
verify_create_bin_list([Type,_Seg,Unit,Flags,Val,Size|Args], Vst) ->
assert_term(Type, Vst),
assert_bs_unit(Type, Unit),
assert_term(Flags, Vst),
assert_term(Val, Vst),
assert_term(Size, Vst),
verify_create_bin_list(Args, Vst);
verify_create_bin_list([], _Vst) -> ok.
update_create_bin_list([{atom,string},_Seg,_Unit,_Flags,_Val,_Size|T], Vst) ->
update_create_bin_list(T, Vst);
update_create_bin_list([{atom,Op},_Seg,_Unit,_Flags,Val,_Size|T], Vst0) ->
Type = update_create_bin_type(Op),
Vst = update_type(fun meet/2, Type, Val, Vst0),
update_create_bin_list(T, Vst);
update_create_bin_list([], Vst) -> Vst.
update_create_bin_type(append) -> #t_bitstring{};
update_create_bin_type(private_append) -> #t_bitstring{};
update_create_bin_type(binary) -> #t_bitstring{};
update_create_bin_type(float) -> #t_float{};
update_create_bin_type(integer) -> #t_integer{};
update_create_bin_type(utf8) -> #t_integer{};
update_create_bin_type(utf16) -> #t_integer{};
update_create_bin_type(utf32) -> #t_integer{}.
assert_bs_unit({atom,Type}, 0) ->
case Type of
utf8 -> ok;
utf16 -> ok;
utf32 -> ok;
_ -> error({zero_unit_invalid_for_type,Type})
end;
assert_bs_unit({atom,_Type}, Unit) when is_integer(Unit), 0 < Unit, Unit =< 256 ->
ok;
assert_bs_unit(_, Unit) ->
error({invalid,Unit}).
verify_return(#vst{current=#st{numy=NumY}}) when NumY =/= none ->
error({stack_frame,NumY});
verify_return(#vst{current=#st{recv_state=State}}) when State =/= none ->
error({return_in_receive,State});
verify_return(Vst) ->
verify_no_ct(Vst),
kill_state(Vst).
validate_bif(Kind, Op, Fail, Ss, Dst, OrigVst, Vst) ->
case will_bif_succeed(Op, Ss, Vst) of
yes ->
This BIF can not fail ( neither throw nor branch ) , make sure it 's
validate_bif_1(Kind, Op, cannot_fail, Ss, Dst, OrigVst, Vst);
no ->
This BIF always fails ; jump directly to the fail block or
branch(Fail, Vst, fun kill_state/1);
'maybe' ->
validate_bif_1(Kind, Op, Fail, Ss, Dst, OrigVst, Vst)
end.
validate_bif_1(Kind, Op, cannot_fail, Ss, Dst, OrigVst, Vst0) ->
This BIF explicitly can not fail ; it will not jump to a guard nor throw
{Type, ArgTypes, _CanSubtract} = bif_types(Op, Ss, Vst0),
ZippedArgs = zip(Ss, ArgTypes),
Vst = foldl(fun({A, T}, V) ->
update_type(fun meet/2, T, A, V)
end, Vst0, ZippedArgs),
extract_term(Type, {Kind, Op}, Ss, Dst, Vst, OrigVst);
validate_bif_1(Kind, Op, Fail, Ss, Dst, OrigVst, Vst) ->
{Type, ArgTypes, CanSubtract} = bif_types(Op, Ss, Vst),
ZippedArgs = zip(Ss, ArgTypes),
FailFun = case CanSubtract of
true ->
fun(FailVst0) ->
foldl(fun({A, T}, V) ->
update_type(fun subtract/2, T, A, V)
end, FailVst0, ZippedArgs)
end;
false ->
fun(S) -> S end
end,
SuccFun = fun(SuccVst0) ->
SuccVst = foldl(fun({A, T}, V) ->
update_type(fun meet/2, T, A, V)
end, SuccVst0, ZippedArgs),
extract_term(Type, {Kind, Op}, Ss, Dst, SuccVst, OrigVst)
end,
branch(Fail, Vst, FailFun, SuccFun).
validate_bs_start_match({atom,resume}, Live, Src, Dst, Vst0) ->
assert_type(#t_bs_context{}, Src, Vst0),
verify_live(Live, Vst0),
verify_y_init(Vst0),
Vst = assign(Src, Dst, Vst0),
prune_x_regs(Live, Vst);
validate_bs_start_match({atom,no_fail}, Live, Src, Dst, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
Vst1 = update_type(fun meet/2, #t_bs_matchable{}, Src, Vst0),
SrcType = get_movable_term_type(Src, Vst1),
TailUnit = beam_types:get_bs_matchable_unit(SrcType),
Vst = prune_x_regs(Live, Vst1),
extract_term(#t_bs_context{tail_unit=TailUnit}, bs_start_match,
[Src], Dst, Vst, Vst0);
validate_bs_start_match({f,Fail}, Live, Src, Dst, Vst) ->
assert_no_exception(Fail),
branch(Fail, Vst,
fun(FailVst) ->
update_type(fun subtract/2, #t_bs_matchable{}, Src, FailVst)
end,
fun(SuccVst) ->
validate_bs_start_match({atom,no_fail}, Live,
Src, Dst, SuccVst)
end).
Validate the bs_match instruction .
validate_bs_match([I|Is], Ctx, Unit0, Vst0) ->
case I of
{ensure_at_least,_Size,Unit} ->
Type = #t_bs_context{tail_unit=Unit},
Vst1 = update_bs_unit(Ctx, Unit, Vst0),
Vst = update_type(fun meet/2, Type, Ctx, Vst1),
validate_bs_match(Is, Ctx, Unit, Vst);
{ensure_exactly,Stride} ->
Vst = advance_bs_context(Ctx, Stride, Vst0),
validate_bs_match(Is, Ctx, Unit0, Vst);
{'=:=',nil,Bits,Value} when Bits =< 64, is_integer(Value) ->
validate_bs_match(Is, Ctx, Unit0, Vst0);
{Type0,Live,{literal,Flags},Size,Unit,Dst} when Type0 =:= binary;
Type0 =:= integer ->
validate_ctx_live(Ctx, Live),
verify_live(Live, Vst0),
Vst1 = prune_x_regs(Live, Vst0),
Type = case Type0 of
integer ->
bs_integer_type({Size, Size}, Unit, Flags);
binary ->
SizeUnit = bsm_size_unit({integer,Size}, Unit),
#t_bitstring{size_unit=SizeUnit}
end,
Vst = extract_term(Type, bs_match, [Ctx], Dst, Vst1, Vst0),
validate_bs_match(Is, Ctx, Unit0, Vst);
{skip,_Stride} ->
validate_bs_match(Is, Ctx, Unit0, Vst0);
{get_tail,Live,_,Dst} ->
validate_ctx_live(Ctx, Live),
verify_live(Live, Vst0),
Vst1 = prune_x_regs(Live, Vst0),
#t_bs_context{tail_unit=Unit} = get_concrete_type(Ctx, Vst0),
Type = #t_bitstring{size_unit=Unit},
Vst = extract_term(Type, get_tail, [Ctx], Dst, Vst1, Vst0),
validate_bs_match(Is, Ctx, Unit, Vst)
end;
validate_bs_match([], _Ctx, _Unit, Vst) ->
Vst.
validate_ctx_live({x,X}=Ctx, Live) when X >= Live ->
error({live_does_not_preserve_context,Live,Ctx});
validate_ctx_live(_, _) ->
ok.
validate_failed_bs_match([{ensure_at_least,_Size,Unit}|_], Ctx, Vst) ->
Type = #t_bs_context{tail_unit=Unit},
update_type(fun subtract/2, Type, Ctx, Vst);
validate_failed_bs_match([_|Is], Ctx, Vst) ->
validate_failed_bs_match(Is, Ctx, Vst);
validate_failed_bs_match([], _Ctx, Vst) ->
Vst.
bs_integer_type(Bounds, Unit, Flags) ->
case beam_bounds:bounds('*', Bounds, {Unit, Unit}) of
{_, MaxBits} when is_integer(MaxBits), MaxBits >= 1, MaxBits =< 64 ->
case member(signed, Flags) of
true ->
Max = (1 bsl (MaxBits - 1)) - 1,
Min = -(Max + 1),
beam_types:make_integer(Min, Max);
false ->
Max = (1 bsl MaxBits) - 1,
beam_types:make_integer(0, Max)
end;
{_, 0} ->
beam_types:make_integer(0);
_ ->
case member(signed, Flags) of
true -> #t_integer{};
false -> #t_integer{elements={0,'+inf'}}
end
end.
validate_bs_get(_Op, Fail, Ctx0, Live, _Stride, none, _Dst, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
validate_bs_get_1(
Fail, Ctx, Live, Vst,
fun(SuccVst) ->
kill_state(SuccVst)
end);
validate_bs_get(Op, Fail, Ctx0, Live, Stride, Type, Dst, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
validate_bs_get_1(
Fail, Ctx, Live, Vst,
fun(SuccVst0) ->
SuccVst1 = advance_bs_context(Ctx, Stride, SuccVst0),
SuccVst = prune_x_regs(Live, SuccVst1),
extract_term(Type, Op, [Ctx], Dst, SuccVst, SuccVst0)
end).
validate_bs_get_all(Op, Fail, Ctx0, Live, Stride, Type, Dst, Vst) ->
Ctx = unpack_typed_arg(Ctx0, Vst),
validate_bs_get_1(
Fail, Ctx, Live, Vst,
fun(SuccVst0) ->
SuccVst1 = update_bs_unit(Ctx, Stride, SuccVst0),
SuccVst2 = advance_bs_context(Ctx, Stride, SuccVst1),
SuccVst = prune_x_regs(Live, SuccVst2),
extract_term(Type, Op, [Ctx], Dst, SuccVst, SuccVst0)
end).
validate_bs_get_1(Fail, Ctx, Live, Vst, SuccFun) ->
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
verify_live(Live, Vst),
verify_y_init(Vst),
branch(Fail, Vst, SuccFun).
validate_bs_skip(Fail, Ctx, Stride, Vst) ->
validate_bs_skip(Fail, Ctx, Stride, no_live, Vst).
validate_bs_skip(Fail, Ctx, Stride, Live, Vst) ->
assert_no_exception(Fail),
assert_type(#t_bs_context{}, Ctx, Vst),
validate_bs_skip_1(Fail, Ctx, Stride, Live, Vst).
validate_bs_skip_1(Fail, Ctx, Stride, no_live, Vst) ->
branch(Fail, Vst,
fun(SuccVst) ->
advance_bs_context(Ctx, Stride, SuccVst)
end);
validate_bs_skip_1(Fail, Ctx, Stride, Live, Vst) ->
verify_y_init(Vst),
verify_live(Live, Vst),
branch(Fail, Vst,
fun(SuccVst0) ->
SuccVst = advance_bs_context(Ctx, Stride, SuccVst0),
prune_x_regs(Live, SuccVst)
end).
advance_bs_context(_Ctx, 0, Vst) ->
Vst;
advance_bs_context(_Ctx, Stride, _Vst) when Stride < 0 ->
throw({invalid_argument, {negative_stride, Stride}});
advance_bs_context(Ctx, Stride, Vst0) ->
Vst = update_type(fun join/2, #t_bs_context{tail_unit=Stride}, Ctx, Vst0),
invalidate_current_ms_position(Ctx, Vst).
update_bs_unit(Ctx, Unit, #vst{current=St}=Vst) ->
CtxRef = get_reg_vref(Ctx, Vst),
case St#st.ms_positions of
#{ CtxRef := PosRef } ->
PosType = #t_abstract{kind={ms_position, Unit}},
update_type(fun meet/2, PosType, PosRef, Vst);
#{} ->
Vst
end.
mark_current_ms_position(Ctx, Pos, #vst{current=St0}=Vst) ->
CtxRef = get_reg_vref(Ctx, Vst),
PosRef = get_reg_vref(Pos, Vst),
#st{ms_positions=MsPos0} = St0,
MsPos = MsPos0#{ CtxRef => PosRef },
St = St0#st{ ms_positions=MsPos },
Vst#vst{current=St}.
invalidate_current_ms_position(Ctx, #vst{current=St0}=Vst) ->
CtxRef = get_reg_vref(Ctx, Vst),
#st{ms_positions=MsPos0} = St0,
case MsPos0 of
#{ CtxRef := _ } ->
MsPos = maps:remove(CtxRef, MsPos0),
St = St0#st{ms_positions=MsPos},
Vst#vst{current=St};
#{} ->
Vst
end.
type_test(Fail, Type, Reg0, Vst) ->
Reg = unpack_typed_arg(Reg0, Vst),
assert_term(Reg, Vst),
assert_no_exception(Fail),
branch(Fail, Vst,
fun(FailVst) ->
update_type(fun subtract/2, Type, Reg, FailVst)
end,
fun(SuccVst) ->
update_type(fun meet/2, Type, Reg, SuccVst)
end).
Special state handling for setelement/3 and set_tuple_element/3 instructions .
validate_mutation(I, Vst) ->
vm_1(I, Vst).
vm_1({move,_,_}, Vst) ->
Vst;
vm_1({swap,_,_}, Vst) ->
Vst;
vm_1({call_ext,3,{extfunc,erlang,setelement,3}}, #vst{current=#st{}=St}=Vst) ->
Vst#vst{current=St#st{setelem=true}};
vm_1({set_tuple_element,_,_,_}, #vst{current=#st{setelem=false}}) ->
error(illegal_context_for_set_tuple_element);
vm_1({set_tuple_element,_,_,_}, #vst{current=#st{setelem=true}}=Vst) ->
Vst;
vm_1({get_tuple_element,_,_,_}, Vst) ->
Vst;
vm_1({line,_}, Vst) ->
Vst;
vm_1(_, #vst{current=#st{setelem=true}=St}=Vst) ->
Vst#vst{current=St#st{setelem=false}};
vm_1(_, Vst) -> Vst.
kill_state(Vst) ->
Vst#vst{current=none}.
verify_call_args(_, 0, #vst{}) ->
ok;
verify_call_args({f,Lbl}, Live, #vst{ft=Ft}=Vst) ->
case Ft of
#{ Lbl := FuncInfo } ->
#{ arity := Live,
parameter_info := ParamInfo } = FuncInfo,
verify_local_args(Live - 1, ParamInfo, #{}, Vst);
#{} ->
error(local_call_to_unknown_function)
end;
verify_call_args(_, Live, Vst) ->
verify_remote_args_1(Live - 1, Vst).
verify_remote_args_1(-1, _) ->
ok;
verify_remote_args_1(X, Vst) ->
assert_durable_term({x, X}, Vst),
verify_remote_args_1(X - 1, Vst).
verify_local_args(-1, _ParamInfo, _CtxIds, _Vst) ->
ok;
verify_local_args(X, ParamInfo, CtxRefs, Vst) ->
Reg = {x, X},
assert_not_fragile(Reg, Vst),
case get_movable_term_type(Reg, Vst) of
#t_bs_context{}=Type ->
VRef = get_reg_vref(Reg, Vst),
case CtxRefs of
#{ VRef := Other } ->
error({multiple_match_contexts, [Reg, Other]});
#{} ->
verify_arg_type(Reg, Type, ParamInfo, Vst),
verify_local_args(X - 1, ParamInfo,
CtxRefs#{ VRef => Reg }, Vst)
end;
Type ->
verify_arg_type(Reg, Type, ParamInfo, Vst),
verify_local_args(X - 1, ParamInfo, CtxRefs, Vst)
end.
verify_arg_type(Reg, GivenType, ParamInfo, Vst) ->
case {ParamInfo, GivenType} of
{#{ Reg := Info }, #t_bs_context{}} ->
case member(accepts_match_context, Info) of
true -> verify_arg_type_1(Reg, GivenType, Info, Vst);
false -> error(no_bs_start_match2)
end;
{_, #t_bs_context{}} ->
error(no_bs_start_match2);
{#{ Reg := Info }, _} ->
verify_arg_type_1(Reg, GivenType, Info, Vst);
{#{}, _} ->
ok
end.
verify_arg_type_1(Reg, GivenType, Info, Vst) ->
RequiredType = proplists:get_value(type, Info, any),
case meet(GivenType, RequiredType) of
Type when Type =/= none, Vst#vst.level =:= weak ->
Strictly speaking this should always match GivenType , but
foo(Key ) ;
foo(Key ) .
At the first call to foo/1 , we know that we have either ` { a , _ } `
or ` { b , _ } ` , and at the second call ` { a , _ , _ } ` or ` { b , _ , _ } ` .
know is that we have tuple with an arity of at least 2 , whose
first element is ` a ` or ` b ` .
decided on a compromise that splits validation into two steps .
ok;
GivenType ->
ok;
_ ->
error({bad_arg_type, Reg, GivenType, RequiredType})
end.
allocate(Tag, Stk, Heap, Live, #vst{current=#st{numy=none}=St}=Vst0) ->
verify_live(Live, Vst0),
Vst1 = Vst0#vst{current=St#st{numy=Stk}},
Vst2 = prune_x_regs(Live, Vst1),
Vst = init_stack(Tag, Stk - 1, Vst2),
heap_alloc(Heap, Vst);
allocate(_, _, _, _, #vst{current=#st{numy=Numy}}) ->
error({existing_stack_frame,{size,Numy}}).
deallocate(#vst{current=St}=Vst) ->
Vst#vst{current=St#st{ys=#{},numy=none}}.
init_stack(_Tag, -1, Vst) ->
Vst;
init_stack(Tag, Y, Vst) ->
init_stack(Tag, Y - 1, create_tag(Tag, allocate, [], {y,Y}, Vst)).
trim_stack(From, To, Top, #st{ys=Ys0}=St) when From =:= Top ->
Ys = maps:filter(fun({y,Y}, _) -> Y < To end, Ys0),
St#st{numy=To,ys=Ys};
trim_stack(From, To, Top, St0) ->
Src = {y, From},
Dst = {y, To},
#st{ys=Ys0} = St0,
Ys = case Ys0 of
#{ Src := Ref } -> Ys0#{ Dst => Ref };
#{} -> error({invalid_shift,Src,Dst})
end,
St = St0#st{ys=Ys},
trim_stack(From + 1, To + 1, Top, St).
test_heap(Heap, Live, Vst0) ->
verify_live(Live, Vst0),
verify_y_init(Vst0),
Vst = prune_x_regs(Live, Vst0),
heap_alloc(Heap, Vst).
heap_alloc(Heap, #vst{current=St0}=Vst) ->
{HeapWords, Floats, Funs} = heap_alloc_1(Heap),
St = St0#st{h=HeapWords,hf=Floats,hl=Funs},
Vst#vst{current=St}.
heap_alloc_1({alloc, Alloc}) ->
heap_alloc_2(Alloc, 0, 0, 0);
heap_alloc_1(HeapWords) when is_integer(HeapWords) ->
{HeapWords, 0, 0}.
heap_alloc_2([{words, HeapWords} | T], 0, Floats, Funs) ->
heap_alloc_2(T, HeapWords, Floats, Funs);
heap_alloc_2([{floats, Floats} | T], HeapWords, 0, Funs) ->
heap_alloc_2(T, HeapWords, Floats, Funs);
heap_alloc_2([{funs, Funs} | T], HeapWords, Floats, 0) ->
heap_alloc_2(T, HeapWords, Floats, Funs);
heap_alloc_2([], HeapWords, Floats, Funs) ->
{HeapWords, Floats, Funs}.
schedule_out(Live, Vst0) when is_integer(Live) ->
Vst1 = prune_x_regs(Live, Vst0),
Vst2 = kill_heap_allocation(Vst1),
Vst = kill_fregs(Vst2),
update_receive_state(none, Vst).
prune_x_regs(Live, #vst{current=St0}=Vst) when is_integer(Live) ->
#st{fragile=Fragile0,xs=Xs0} = St0,
Fragile = sets:filter(fun({x,X}) ->
X < Live;
({y,_}) ->
true
end, Fragile0),
Xs = maps:filter(fun({x,X}, _) ->
X < Live
end, Xs0),
St = St0#st{fragile=Fragile,xs=Xs},
Vst#vst{current=St}.
assert_choices([{Tag,_},{f,_}|T]) ->
if
Tag =:= atom; Tag =:= float; Tag =:= integer ->
assert_choices_1(T, Tag);
true ->
error(bad_select_list)
end;
assert_choices([]) -> ok.
assert_choices_1([{Tag,_},{f,_}|T], Tag) ->
assert_choices_1(T, Tag);
assert_choices_1([_,{f,_}|_], _Tag) ->
error(bad_select_list);
assert_choices_1([], _Tag) -> ok.
assert_arities([Arity,{f,_}|T]) when is_integer(Arity) ->
assert_arities(T);
assert_arities([]) -> ok;
assert_arities(_) -> error(bad_tuple_arity_list).
is_float_arith_bif(fadd, [_, _]) -> true;
is_float_arith_bif(fdiv, [_, _]) -> true;
is_float_arith_bif(fmul, [_, _]) -> true;
is_float_arith_bif(fnegate, [_]) -> true;
is_float_arith_bif(fsub, [_, _]) -> true;
is_float_arith_bif(_, _) -> false.
validate_float_arith_bif(Ss, Dst, Vst) ->
_ = [assert_freg_set(S, Vst) || S <- Ss],
set_freg(Dst, Vst).
init_fregs() -> 0.
kill_fregs(#vst{current=St0}=Vst) ->
St = St0#st{f=init_fregs()},
Vst#vst{current=St}.
set_freg({fr,Fr}=Freg, #vst{current=#st{f=Fregs0}=St}=Vst) ->
check_limit(Freg),
Bit = 1 bsl Fr,
if
Fregs0 band Bit =:= 0 ->
Fregs = Fregs0 bor Bit,
Vst#vst{current=St#st{f=Fregs}};
true -> Vst
end;
set_freg(Fr, _) -> error({bad_target,Fr}).
assert_freg_set({fr,Fr}=Freg, #vst{current=#st{f=Fregs}})
when is_integer(Fr), 0 =< Fr ->
if
(Fregs bsr Fr) band 1 =:= 0 ->
error({uninitialized_reg,Freg});
true ->
ok
end;
assert_freg_set(Fr, _) -> error({bad_source,Fr}).
assert_unique_map_keys([]) ->
has_map_fields instructions with empty lists .
error(empty_field_list);
assert_unique_map_keys([_]) ->
ok;
assert_unique_map_keys([_,_|_]=Ls) ->
Vs = [begin
assert_literal(L),
L
end || L <- Ls],
case length(Vs) =:= sets:size(sets:from_list(Vs, [{version, 2}])) of
true -> ok;
false -> error(keys_not_unique)
end.
bsm_stride({integer, Size}, Unit) ->
Size * Unit;
bsm_stride(_Size, Unit) ->
Unit.
bsm_size_unit({integer, Size}, Unit) ->
max(1, Size) * max(1, Unit);
bsm_size_unit(_Size, Unit) ->
max(1, Unit).
validate_select_val(_Fail, _Choices, _Src, #vst{current=none}=Vst) ->
We 've already branched on all of 's possible values , so we know we
Vst;
validate_select_val(Fail, [Val,{f,L}|T], Src, Vst0) ->
Vst = branch(L, Vst0,
fun(BranchVst) ->
update_eq_types(Src, Val, BranchVst)
end,
fun(FailVst) ->
update_ne_types(Src, Val, FailVst)
end),
validate_select_val(Fail, T, Src, Vst);
validate_select_val(Fail, [], _Src, Vst) ->
branch(Fail, Vst,
fun(SuccVst) ->
kill_state(SuccVst)
end).
validate_select_tuple_arity(_Fail, _Choices, _Src, #vst{current=none}=Vst) ->
We 've already branched on all of 's possible values , so we know we
Vst;
validate_select_tuple_arity(Fail, [Arity,{f,L}|T], Tuple, Vst0) ->
Type = #t_tuple{exact=true,size=Arity},
Vst = branch(L, Vst0,
fun(BranchVst) ->
update_type(fun meet/2, Type, Tuple, BranchVst)
end,
fun(FailVst) ->
update_type(fun subtract/2, Type, Tuple, FailVst)
end),
validate_select_tuple_arity(Fail, T, Tuple, Vst);
validate_select_tuple_arity(Fail, [], _, #vst{}=Vst) ->
branch(Fail, Vst,
fun(SuccVst) ->
kill_state(SuccVst)
end).
infer_types(CompareOp, {Kind,_}=LHS, RHS, Vst) when Kind =:= x; Kind =:= y ->
infer_types(CompareOp, get_reg_vref(LHS, Vst), RHS, Vst);
infer_types(CompareOp, LHS, {Kind,_}=RHS, Vst) when Kind =:= x; Kind =:= y ->
infer_types(CompareOp, LHS, get_reg_vref(RHS, Vst), Vst);
infer_types(CompareOp, LHS, RHS, #vst{current=#st{vs=Vs}}=Vst0) ->
case Vs of
#{ LHS := LEntry, RHS := REntry } ->
Vst = infer_types_1(LEntry, RHS, CompareOp, Vst0),
infer_types_1(REntry, LHS, CompareOp, Vst);
#{ LHS := LEntry } ->
infer_types_1(LEntry, RHS, CompareOp, Vst0);
#{ RHS := REntry } ->
infer_types_1(REntry, LHS, CompareOp, Vst0);
#{} ->
Vst0
end.
infer_types_1(#value{op={bif,'and'},args=[LHS,RHS]}, Val, Op, Vst0) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
Vst = update_eq_types(LHS, {atom,true}, Vst0),
update_eq_types(RHS, {atom,true}, Vst);
_ ->
Vst0
end;
infer_types_1(#value{op={bif,'or'},args=[LHS,RHS]}, Val, Op, Vst0) ->
case Val of
{atom, Bool} when Op =:= eq_exact, not Bool; Op =:= ne_exact, Bool ->
Vst = update_eq_types(LHS, {atom,false}, Vst0),
update_eq_types(RHS, {atom,false}, Vst);
_ ->
Vst0
end;
infer_types_1(#value{op={bif,'not'},args=[Arg]}, Val, Op, Vst0) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_eq_types(Arg, {atom,false}, Vst0);
{atom, Bool} when Op =:= eq_exact, not Bool; Op =:= ne_exact, Bool ->
update_eq_types(Arg, {atom,true}, Vst0);
_ ->
Vst0
end;
infer_types_1(#value{op={bif,'=:='},args=[LHS,RHS]}, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_eq_types(LHS, RHS, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
update_ne_types(LHS, RHS, Vst);
_ ->
Vst
end;
infer_types_1(#value{op={bif,'=/='},args=[LHS,RHS]}, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_ne_types(LHS, RHS, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
update_eq_types(LHS, RHS, Vst);
_ ->
Vst
end;
infer_types_1(#value{op={bif,RelOp},args=[_,_]=Args}, Val, Op, Vst)
when RelOp =:= '<'; RelOp =:= '=<'; RelOp =:= '>='; RelOp =:= '>' ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
Types = [get_term_type(Arg, Vst) || Arg <- Args],
infer_relop_types(RelOp, Args, Types, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
Types = [get_term_type(Arg, Vst) || Arg <- Args],
infer_relop_types(invert_relop(RelOp), Args, Types, Vst);
_ ->
Vst
end;
infer_types_1(#value{op={bif,is_atom},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_atom{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_boolean},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(beam_types:make_boolean(), Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_binary},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_bitstring{size_unit=8}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_bitstring},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_bitstring{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_float},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_float{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_function},args=[Src,{integer,Arity}]},
Val, Op, Vst)
when Arity >= 0, Arity =< ?MAX_FUNC_ARGS ->
infer_type_test_bif(#t_fun{arity=Arity}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_function},args=[Src,_Arity]}, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_type(fun meet/2, #t_fun{}, Src, Vst);
_ ->
Vst
end;
infer_types_1(#value{op={bif,is_function},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_fun{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_integer},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_integer{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_list},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_list{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_map},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_map{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_number},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_number{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_pid},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(pid, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_port},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(port, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_reference},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(reference, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,is_tuple},args=[Src]}, Val, Op, Vst) ->
infer_type_test_bif(#t_tuple{}, Src, Val, Op, Vst);
infer_types_1(#value{op={bif,tuple_size}, args=[Tuple]},
{integer,Arity}, Op, Vst) ->
Type = #t_tuple{exact=true,size=Arity},
case Op of
eq_exact -> update_type(fun meet/2, Type, Tuple, Vst);
ne_exact -> update_type(fun subtract/2, Type, Tuple, Vst)
end;
infer_types_1(#value{op={bif,element},args=[{integer,Index}, Tuple]},
Val, eq_exact, Vst)
when Index >= 1 ->
ValType = get_term_type(Val, Vst),
Es = beam_types:set_tuple_element(Index, ValType, #{}),
TupleType = #t_tuple{size=Index,elements=Es},
update_type(fun meet/2, TupleType, Tuple, Vst);
infer_types_1(#value{op={bif,element},args=[{integer,Index}, Tuple]},
Val, ne_exact, Vst)
when Index >= 1 ->
ValType = get_term_type(Val, Vst),
case beam_types:is_singleton_type(ValType) of
true ->
case beam_types:set_tuple_element(Index, ValType, #{}) of
#{ Index := _ }=Es ->
TupleType = #t_tuple{size=Index,elements=Es},
update_type(fun subtract/2, TupleType, Tuple, Vst);
#{} ->
Vst
end;
false ->
Vst
end;
infer_types_1(_, _, _, Vst) ->
Vst.
infer_type_test_bif(Type, Src, Val, Op, Vst) ->
case Val of
{atom, Bool} when Op =:= eq_exact, Bool; Op =:= ne_exact, not Bool ->
update_type(fun meet/2, Type, Src, Vst);
{atom, Bool} when Op =:= ne_exact, Bool; Op =:= eq_exact, not Bool ->
update_type(fun subtract/2, Type, Src, Vst);
_ ->
Vst
end.
invert_relop('<') -> '>=';
invert_relop('=<') -> '>';
invert_relop('>=') -> '<';
invert_relop('>') -> '=<'.
assign({y,_}=Src, {y,_}=Dst, Vst) ->
case get_raw_type(Src, Vst) of
initialized -> create_tag(initialized, init, [], Dst, Vst);
_ -> assign_1(Src, Dst, Vst)
end;
assign({Kind,_}=Src, Dst, Vst) when Kind =:= x; Kind =:= y ->
assign_1(Src, Dst, Vst);
assign(Literal, Dst, Vst) ->
Type = get_literal_type(Literal),
create_term(Type, move, [Literal], Dst, Vst).
create_tag(Tag, _Op, _Ss, {y,_}=Dst, #vst{current=#st{ys=Ys0}=St0}=Vst) ->
case maps:get(Dst, Ys0, uninitialized) of
{catchtag,_}=Prev ->
error(Prev);
{trytag,_}=Prev ->
error(Prev);
_ ->
check_try_catch_tags(Tag, Dst, Vst),
Ys = Ys0#{ Dst => Tag },
St = St0#st{ys=Ys},
remove_fragility(Dst, Vst#vst{current=St})
end;
create_tag(_Tag, _Op, _Ss, Dst, _Vst) ->
error({invalid_tag_register, Dst}).
kill_tag({y,_}=Reg, #vst{current=#st{ys=Ys0}=St0}=Vst) ->
Ys = Ys0#{ Reg => initialized },
Vst#vst{current=St0#st{ys=Ys}}.
create_term(Type, Op, Ss0, Dst, Vst0) ->
create_term(Type, Op, Ss0, Dst, Vst0, Vst0).
As create_term/4 , but uses the incoming for argument resolution in
create_term(Type, Op, Ss0, Dst, Vst0, OrigVst) ->
{Ref, Vst1} = new_value(Type, Op, resolve_args(Ss0, OrigVst), Vst0),
Vst = remove_fragility(Dst, Vst1),
set_reg_vref(Ref, Dst, Vst).
Extracts a term from Ss , propagating fragility .
extract_term(Type, Op, Ss0, Dst, Vst0) ->
extract_term(Type, Op, Ss0, Dst, Vst0, Vst0).
As extract_term/4 , but uses the incoming for argument resolution in
extract_term(Type, Op, Ss0, Dst, Vst0, OrigVst) ->
{Ref, Vst1} = new_value(Type, Op, resolve_args(Ss0, OrigVst), Vst0),
Vst = propagate_fragility(Dst, Ss0, Vst1),
set_reg_vref(Ref, Dst, Vst).
resolve_args([{Kind,_}=Src | Args], Vst) when Kind =:= x; Kind =:= y ->
[get_reg_vref(Src, Vst) | resolve_args(Args, Vst)];
resolve_args([Lit | Args], Vst) ->
assert_literal(Lit),
[Lit | resolve_args(Args, Vst)];
resolve_args([], _Vst) ->
[].
Overrides the type of . This is ugly but a necessity for certain
override_type(Type, Reg, Vst) ->
update_type(fun(_, T) -> T end, Type, Reg, Vst).
update_type(Merge, With, #value_ref{}=Ref, Vst0) ->
Current = get_concrete_type(Ref, Vst0),
case Merge(Current, With) of
none ->
throw({type_conflict, Current, With});
Type ->
Vst = update_container_type(Type, Ref, Vst0),
set_type(Type, Ref, Vst)
end;
update_type(Merge, With, {Kind,_}=Reg, Vst) when Kind =:= x; Kind =:= y ->
update_type(Merge, With, get_reg_vref(Reg, Vst), Vst);
update_type(Merge, With, Literal, Vst) ->
Type = get_literal_type(Literal),
case Merge(Type, With) of
none -> throw({type_conflict, Type, With});
_Type -> Vst
end.
update_container_type(Type, Ref, #vst{current=#st{vs=Vs}}=Vst) ->
case Vs of
#{ Ref := #value{op={bif,element},
args=[{integer,Index},Tuple]} } when Index >= 1 ->
case {Index,Type} of
{1,#t_atom{elements=[_,_|_]}} ->
The first element is one atom out of a set of
at least two atoms . We must take care to
update_type(fun meet_tuple_set/2, Type, Tuple, Vst);
{_,_} ->
Es = beam_types:set_tuple_element(Index, Type, #{}),
TupleType = #t_tuple{size=Index,elements=Es},
update_type(fun meet/2, TupleType, Tuple, Vst)
end;
#{} ->
Vst
end.
meet_tuple_set(Type, #t_atom{elements=Atoms}) ->
Try to create a tuple set out of the known atoms for the first element .
#t_tuple{size=Size,exact=Exact} = normalize(meet(Type, #t_tuple{})),
Tuples = [#t_tuple{size=Size,exact=Exact,
elements=#{1 => #t_atom{elements=[A]}}} ||
A <- Atoms],
TupleSet = foldl(fun join/2, hd(Tuples), tl(Tuples)),
meet(Type, TupleSet).
update_eq_types(LHS, RHS, Vst0) ->
LType = get_term_type(LHS, Vst0),
RType = get_term_type(RHS, Vst0),
Vst1 = update_type(fun meet/2, RType, LHS, Vst0),
Vst = update_type(fun meet/2, LType, RHS, Vst1),
infer_types(eq_exact, LHS, RHS, Vst).
update_ne_types(LHS, RHS, Vst0) ->
Vst1 = update_ne_types_1(LHS, RHS, Vst0),
Vst = update_ne_types_1(RHS, LHS, Vst1),
infer_types(ne_exact, LHS, RHS, Vst).
update_ne_types_1(LHS, RHS, Vst0) ->
is a bit trickier since all we know is that the * value * of LHS differs
from RHS , so we ca n't blindly subtract their types .
Consider ` # number { } = /= # t_integer { } ` ; all we know is that LHS is n't equal
Therefore , we only subtract when we know that RHS has a specific value .
RType = get_term_type(RHS, Vst0),
case beam_types:is_singleton_type(RType) of
true ->
Vst = update_type(fun subtract/2, RType, LHS, Vst0),
If LHS has a specific value after subtraction we can infer types
LType = get_term_type(LHS, Vst),
case beam_types:get_singleton_value(LType) of
{ok, Value} ->
infer_types(eq_exact, LHS, value_to_literal(Value), Vst);
error ->
Vst
end;
false ->
Vst0
end.
assign_1(Src, Dst, Vst0) ->
assert_movable(Src, Vst0),
Vst = propagate_fragility(Dst, [Src], Vst0),
set_reg_vref(get_reg_vref(Src, Vst), Dst, Vst).
set_reg_vref(Ref, {x,_}=Dst, Vst) ->
check_limit(Dst),
#vst{current=#st{xs=Xs0}=St0} = Vst,
St = St0#st{xs=Xs0#{ Dst => Ref }},
Vst#vst{current=St};
set_reg_vref(Ref, {y,_}=Dst, #vst{current=#st{ys=Ys0}=St0} = Vst) ->
check_limit(Dst),
case Ys0 of
#{ Dst := {catchtag,_}=Tag } ->
error(Tag);
#{ Dst := {trytag,_}=Tag } ->
error(Tag);
#{ Dst := _ } ->
St = St0#st{ys=Ys0#{ Dst => Ref }},
Vst#vst{current=St};
#{} ->
error({invalid_store, Dst})
end;
set_reg_vref(_Ref, Dst, _Vst) ->
error({invalid_register, Dst}).
get_reg_vref({x,_}=Src, #vst{current=#st{xs=Xs}}) ->
check_limit(Src),
case Xs of
#{ Src := #value_ref{}=Ref } ->
Ref;
#{} ->
error({uninitialized_reg, Src})
end;
get_reg_vref({y,_}=Src, #vst{current=#st{ys=Ys}}) ->
check_limit(Src),
case Ys of
#{ Src := #value_ref{}=Ref } ->
Ref;
#{ Src := initialized } ->
error({unassigned, Src});
#{ Src := Tag } when Tag =/= uninitialized ->
error(Tag);
#{} ->
error({uninitialized_reg, Src})
end;
get_reg_vref(Src, _Vst) ->
error({invalid_register, Src}).
set_type(Type, #value_ref{}=Ref, #vst{current=#st{vs=Vs0}=St}=Vst) ->
#{ Ref := #value{}=Entry } = Vs0,
Vs = Vs0#{ Ref => Entry#value{type=Type} },
Vst#vst{current=St#st{vs=Vs}}.
new_value(none, _, _, _) ->
error(creating_none_value);
new_value(Type, Op, Ss, #vst{current=#st{vs=Vs0}=St,ref_ctr=Counter}=Vst) ->
Ref = #value_ref{id=Counter},
Vs = Vs0#{ Ref => #value{op=Op,args=Ss,type=Type} },
{Ref, Vst#vst{current=St#st{vs=Vs},ref_ctr=Counter+1}}.
kill_catch_tag(Reg, #vst{current=#st{ct=[Tag|Tags]}=St}=Vst0) ->
Vst = Vst0#vst{current=St#st{ct=Tags}},
kill_tag(Reg, Vst).
check_try_catch_tags(Type, {y,N}=Reg, Vst) ->
case is_try_catch_tag(Type) of
true ->
case collect_try_catch_tags(N - 1, Vst, []) of
[_|_]=Bad -> error({bad_try_catch_nesting, Reg, Bad});
[] -> ok
end;
false ->
ok
end.
assert_no_exception(?EXCEPTION_LABEL) ->
error(throws_exception);
assert_no_exception(_) ->
ok.
assert_term(Src, Vst) ->
_ = get_term_type(Src, Vst),
ok.
assert_movable(Src, Vst) ->
_ = get_movable_term_type(Src, Vst),
ok.
assert_literal(Src) ->
case is_literal(Src) of
true -> ok;
false -> error({literal_required,Src})
end.
assert_not_literal(Src) ->
case is_literal(Src) of
true -> error({literal_not_allowed,Src});
false -> ok
end.
is_literal(nil) -> true;
is_literal({atom,A}) when is_atom(A) -> true;
is_literal({float,F}) when is_float(F) -> true;
is_literal({integer,I}) when is_integer(I) -> true;
is_literal({literal,_L}) -> true;
is_literal(_) -> false.
value_to_literal([]) -> nil;
value_to_literal(A) when is_atom(A) -> {atom,A};
value_to_literal(F) when is_float(F) -> {float,F};
value_to_literal(I) when is_integer(I) -> {integer,I};
value_to_literal(Other) -> {literal,Other}.
normalize(#t_abstract{}=A) -> error({abstract_type, A});
normalize(T) -> beam_types:normalize(T).
join(Same, Same) ->
Same;
join(#t_abstract{kind={ms_position, UnitA}},
#t_abstract{kind={ms_position, UnitB}}) ->
#t_abstract{kind={ms_position, gcd(UnitA, UnitB)}};
join(#t_abstract{}=A, B) ->
#t_abstract{kind={join, A, B}};
join(A, #t_abstract{}=B) ->
#t_abstract{kind={join, A, B}};
join(A, B) ->
beam_types:join(A, B).
meet(Same, Same) ->
Same;
meet(#t_abstract{kind={ms_position, UnitA}},
#t_abstract{kind={ms_position, UnitB}}) ->
Unit = UnitA * UnitB div gcd(UnitA, UnitB),
#t_abstract{kind={ms_position, Unit}};
meet(#t_abstract{}=A, B) ->
#t_abstract{kind={meet, A, B}};
meet(A, #t_abstract{}=B) ->
#t_abstract{kind={meet, A, B}};
meet(A, B) ->
beam_types:meet(A, B).
subtract(#t_abstract{}=A, B) ->
#t_abstract{kind={subtract, A, B}};
subtract(A, #t_abstract{}=B) ->
#t_abstract{kind={subtract, A, B}};
subtract(A, B) ->
beam_types:subtract(A, B).
assert_type(RequiredType, Term, Vst) ->
GivenType = get_movable_term_type(Term, Vst),
case meet(RequiredType, GivenType) of
GivenType ->
ok;
_RequiredType ->
error({bad_type,{needed,RequiredType},{actual,GivenType}})
end.
validate_src(Ss, Vst) when is_list(Ss) ->
_ = [assert_term(S, Vst) || S <- Ss],
ok.
unpack_typed_arg(#tr{r=Reg,t=Type}, Vst) ->
true = none =/= beam_types:meet(get_movable_term_type(Reg, Vst), Type),
Reg;
unpack_typed_arg(Arg, _Vst) ->
Arg.
get_term_type(Src , ) - > Type
Gets the type of the source , resolving deferred types into
get_concrete_type(Src, #vst{current=#st{vs=Vs}}=Vst) ->
concrete_type(get_raw_type(Src, Vst), Vs).
get_term_type(Src , ) - > Type
Get the type of the source . The returned type Type will be
a standard Erlang type ( no catch / try tags or match contexts ) .
get_term_type(Src, Vst) ->
case get_movable_term_type(Src, Vst) of
#t_bs_context{} -> error({match_context,Src});
#t_abstract{} -> error({abstract_term,Src});
Type -> Type
end.
Get the type of the source . The returned type Type will be
a standard Erlang type ( no catch / try tags ) . Match contexts are OK .
get_movable_term_type(Src, Vst) ->
case get_concrete_type(Src, Vst) of
#t_abstract{kind=unfinished_tuple=Kind} -> error({Kind,Src});
initialized -> error({unassigned,Src});
uninitialized -> error({uninitialized_reg,Src});
{catchtag,_} -> error({catchtag,Src});
{trytag,_} -> error({trytag,Src});
Type -> Type
end.
get_tag_type({y,_}=Src, Vst) ->
case get_raw_type(Src, Vst) of
{catchtag, _}=Tag -> Tag;
{trytag, _}=Tag -> Tag;
uninitialized=Tag -> Tag;
initialized=Tag -> Tag;
Other -> error({invalid_tag,Src,Other})
end;
get_tag_type(Src, _) ->
error({invalid_tag_register,Src}).
get_raw_type({x,X}=Src, #vst{current=#st{xs=Xs}}=Vst) when is_integer(X) ->
check_limit(Src),
case Xs of
#{ Src := #value_ref{}=Ref } -> get_raw_type(Ref, Vst);
#{} -> uninitialized
end;
get_raw_type({y,Y}=Src, #vst{current=#st{ys=Ys}}=Vst) when is_integer(Y) ->
check_limit(Src),
case Ys of
#{ Src := #value_ref{}=Ref } -> get_raw_type(Ref, Vst);
#{ Src := Tag } -> Tag;
#{} -> uninitialized
end;
get_raw_type(#value_ref{}=Ref, #vst{current=#st{vs=Vs}}) ->
case Vs of
#{ Ref := #value{type=Type} } -> Type;
#{} -> none
end;
get_raw_type(Src, #vst{current=#st{}}) ->
get_literal_type(Src).
get_literal_type(nil) ->
beam_types:make_type_from_value([]);
get_literal_type({atom,A}) when is_atom(A) ->
beam_types:make_type_from_value(A);
get_literal_type({float,F}) when is_float(F) ->
beam_types:make_type_from_value(F);
get_literal_type({integer,I}) when is_integer(I) ->
beam_types:make_type_from_value(I);
get_literal_type({literal,L}) ->
beam_types:make_type_from_value(L);
get_literal_type(T) ->
error({not_literal,T}).
Forks the execution flow , with the provided funs returning the new state of
-spec branch(Lbl :: label(),
Original :: #vst{},
FailFun :: BranchFun,
SuccFun :: BranchFun) -> #vst{} when
BranchFun :: fun((#vst{}) -> #vst{}).
branch(Lbl, Vst0, FailFun, SuccFun) ->
validate_branch(Lbl, Vst0),
#vst{current=St0} = Vst0,
try FailFun(Vst0) of
Vst1 ->
Vst2 = fork_state(Lbl, Vst1),
Vst = Vst2#vst{current=St0},
try SuccFun(Vst) of
V -> V
catch
{type_conflict, _, _} ->
kill_state(Vst);
{invalid_argument, _} ->
kill_state(Vst)
end
catch
validator itself ; one of the branches must succeed .
{type_conflict, _, _} ->
SuccFun(Vst0);
{invalid_argument, _} ->
SuccFun(Vst0)
end.
validate_branch(Lbl, #vst{current=#st{ct=Tags}}) ->
validate_branch_1(Lbl, Tags).
validate_branch_1(Lbl, [{trytag, FailLbls} | Tags]) ->
case ordsets:is_element(Lbl, FailLbls) of
true -> error({illegal_branch, try_handler, Lbl});
false -> validate_branch_1(Lbl, Tags)
end;
validate_branch_1(Lbl, [_ | Tags]) ->
validate_branch_1(Lbl, Tags);
validate_branch_1(_Lbl, _Tags) ->
ok.
branch(Fail, Vst, SuccFun) ->
branch(Fail, Vst, fun(V) -> V end, SuccFun).
branch(Fail, Vst) ->
branch(Fail, Vst, fun(V) -> V end).
fork_state(?EXCEPTION_LABEL, Vst0) ->
#vst{current=#st{ct=CatchTags,numy=NumY}} = Vst0,
verify_y_init(Vst0),
case CatchTags of
[{_, [Fail]} | _] when is_integer(Fail) ->
Vst = update_receive_state(none, Vst0),
fork_state(Fail, Vst);
[] ->
Vst0;
_ ->
error(ambiguous_catch_try_state)
end;
fork_state(L, #vst{current=St0,branched=Branched0,ref_ctr=Counter0}=Vst) ->
{St, Counter} = merge_states(L, St0, Branched0, Counter0),
Branched = Branched0#{ L => St },
Vst#vst{branched=Branched,ref_ctr=Counter}.
merge_states/3 is used when there 's more than one way to arrive at a
merge_states(L, St, Branched, Counter) when L =/= 0 ->
case Branched of
#{ L := OtherSt } -> merge_states_1(St, OtherSt, Counter);
#{} -> {St, Counter}
end.
merge_states_1(St, none, Counter) ->
{St, Counter};
merge_states_1(none, St, Counter) ->
{St, Counter};
merge_states_1(StA, StB, Counter0) ->
#st{xs=XsA,ys=YsA,vs=VsA,fragile=FragA,numy=NumYA,
h=HA,ct=CtA,recv_state=RecvStA,
ms_positions=MsPosA} = StA,
#st{xs=XsB,ys=YsB,vs=VsB,fragile=FragB,numy=NumYB,
h=HB,ct=CtB,recv_state=RecvStB,
ms_positions=MsPosB} = StB,
states , and resolve conflicts by creating new values ( similar to
{Xs, Merge0, Counter1} = merge_regs(XsA, XsB, #{}, Counter0),
{Ys, Merge, Counter} = merge_regs(YsA, YsB, Merge0, Counter1),
Vs = merge_values(Merge, VsA, VsB),
RecvSt = merge_receive_state(RecvStA, RecvStB),
MsPos = merge_ms_positions(MsPosA, MsPosB, Vs),
Fragile = merge_fragility(FragA, FragB),
NumY = merge_stk(YsA, YsB, NumYA, NumYB),
Ct = merge_ct(CtA, CtB),
St = #st{xs=Xs,ys=Ys,vs=Vs,fragile=Fragile,numy=NumY,
h=min(HA, HB),ct=Ct,recv_state=RecvSt,
ms_positions=MsPos},
{St, Counter}.
Merges the contents of two register maps , returning the updated " merge map "
merge_regs(RsA, RsB, Merge, Counter) ->
Keys = if
map_size(RsA) =< map_size(RsB) -> maps:keys(RsA);
map_size(RsA) > map_size(RsB) -> maps:keys(RsB)
end,
merge_regs_1(Keys, RsA, RsB, #{}, Merge, Counter).
merge_regs_1([Reg | Keys], RsA, RsB, Regs, Merge0, Counter0) ->
case {RsA, RsB} of
{#{ Reg := #value_ref{}=RefA }, #{ Reg := #value_ref{}=RefB }} ->
{Ref, Merge, Counter} = merge_vrefs(RefA, RefB, Merge0, Counter0),
merge_regs_1(Keys, RsA, RsB, Regs#{ Reg => Ref }, Merge, Counter);
{#{ Reg := TagA }, #{ Reg := TagB }} ->
contains , so if a register contains a tag in one state we have
merge_regs_1(Keys, RsA, RsB, Regs#{ Reg => merge_tags(TagA,TagB) },
Merge0, Counter0);
{#{}, #{}} ->
merge_regs_1(Keys, RsA, RsB, Regs, Merge0, Counter0)
end;
merge_regs_1([], _, _, Regs, Merge, Counter) ->
{Regs, Merge, Counter}.
merge_tags(Same, Same) ->
Same;
merge_tags(uninitialized, _) ->
uninitialized;
merge_tags(_, uninitialized) ->
uninitialized;
merge_tags({trytag, LblsA}, {trytag, LblsB}) ->
{trytag, ordsets:union(LblsA, LblsB)};
merge_tags({catchtag, LblsA}, {catchtag, LblsB}) ->
{catchtag, ordsets:union(LblsA, LblsB)};
merge_tags(_A, _B) ->
initialized.
merge_vrefs(Ref, Ref, Merge, Counter) ->
We have two ( potentially ) different versions of the same value , so we
{Ref, Merge#{ Ref => Ref }, Counter};
merge_vrefs(RefA, RefB, Merge, Counter) ->
We have two different values , so we need to create a new value from
Key = {RefA, RefB},
case Merge of
#{ Key := Ref } ->
{Ref, Merge, Counter};
#{} ->
Ref = #value_ref{id=Counter},
{Ref, Merge#{ Key => Ref }, Counter + 1}
end.
merge_values(Merge, VsA, VsB) ->
maps:fold(fun(Spec, New, Acc) ->
mv_1(Spec, New, VsA, VsB, Acc)
end, #{}, Merge).
mv_1(Same, Same, VsA, VsB, Acc0) ->
Entry = case {VsA, VsB} of
{#{ Same := Entry0 }, #{ Same := Entry0 } } ->
Entry0;
{#{ Same := #value{type=TypeA}=Entry0 },
#{ Same := #value{type=TypeB} } } ->
ConcreteA = concrete_type(TypeA, VsA),
ConcreteB = concrete_type(TypeB, VsB),
Entry0#value{type=join(ConcreteA, ConcreteB)}
end,
Acc = Acc0#{ Same => Entry },
mv_args(Entry#value.args, VsA, VsB, Acc);
mv_1({RefA, RefB}, New, VsA, VsB, Acc) ->
#value{type=TypeA} = map_get(RefA, VsA),
#value{type=TypeB} = map_get(RefB, VsB),
ConcreteA = concrete_type(TypeA, VsA),
ConcreteB = concrete_type(TypeB, VsB),
Acc#{ New => #value{op=join,args=[],type=join(ConcreteA, ConcreteB)} }.
concrete_type(T, Vs) when is_function(T) -> T(Vs);
concrete_type(T, _Vs) -> T.
mv_args([#value_ref{}=Arg | Args], VsA, VsB, Acc0) ->
case Acc0 of
#{ Arg := _ } ->
mv_args(Args, VsA, VsB, Acc0);
#{} ->
Acc = mv_1(Arg, Arg, VsA, VsB, Acc0),
mv_args(Args, VsA, VsB, Acc)
end;
mv_args([_ | Args], VsA, VsB, Acc) ->
mv_args(Args, VsA, VsB, Acc);
mv_args([], _VsA, _VsB, Acc) ->
Acc.
merge_fragility(FragileA, FragileB) ->
sets:union(FragileA, FragileB).
merge_ms_positions(MsPosA, MsPosB, Vs) ->
Keys = if
map_size(MsPosA) =< map_size(MsPosB) -> maps:keys(MsPosA);
map_size(MsPosA) > map_size(MsPosB) -> maps:keys(MsPosB)
end,
merge_ms_positions_1(Keys, MsPosA, MsPosB, Vs, #{}).
merge_ms_positions_1([Key | Keys], MsPosA, MsPosB, Vs, Acc) ->
case {MsPosA, MsPosB} of
{#{ Key := Pos }, #{ Key := Pos }} when is_map_key(Pos, Vs) ->
merge_ms_positions_1(Keys, MsPosA, MsPosB, Vs, Acc#{ Key => Pos });
{#{}, #{}} ->
merge_ms_positions_1(Keys, MsPosA, MsPosB, Vs, Acc)
end;
merge_ms_positions_1([], _MsPosA, _MsPosB, _Vs, Acc) ->
Acc.
merge_receive_state(Same, Same) -> Same;
merge_receive_state(_, _) -> undecided.
merge_stk(_, _, S, S) ->
S;
merge_stk(YsA, YsB, StkA, StkB) ->
merge_stk_undecided(YsA, YsB, StkA, StkB).
merge_stk_undecided(YsA, YsB, {undecided, StkA}, {undecided, StkB}) ->
We 're merging two branches with different stack sizes . This is only okay
ok = merge_stk_verify_init(StkA - 1, YsA),
ok = merge_stk_verify_init(StkB - 1, YsB),
{undecided, min(StkA, StkB)};
merge_stk_undecided(YsA, YsB, StkA, StkB) when is_integer(StkA) ->
merge_stk_undecided(YsA, YsB, {undecided, StkA}, StkB);
merge_stk_undecided(YsA, YsB, StkA, StkB) when is_integer(StkB) ->
merge_stk_undecided(YsA, YsB, StkA, {undecided, StkB});
merge_stk_undecided(YsA, YsB, none, StkB) ->
merge_stk_undecided(YsA, YsB, {undecided, 0}, StkB);
merge_stk_undecided(YsA, YsB, StkA, none) ->
merge_stk_undecided(YsA, YsB, StkA, {undecided, 0}).
merge_stk_verify_init(-1, _Ys) ->
ok;
merge_stk_verify_init(Y, Ys) ->
Reg = {y, Y},
case Ys of
#{ Reg := TagOrVRef } when TagOrVRef =/= uninitialized ->
merge_stk_verify_init(Y - 1, Ys);
#{} ->
error({unsafe_stack, Reg, Ys})
end.
merge_ct(S, S) -> S;
merge_ct(Ct0, Ct1) -> merge_ct_1(Ct0, Ct1).
merge_ct_1([], []) ->
[];
merge_ct_1([{trytag, LblsA} | CtA], [{trytag, LblsB} | CtB]) ->
[{trytag, ordsets:union(LblsA, LblsB)} | merge_ct_1(CtA, CtB)];
merge_ct_1([{catchtag, LblsA} | CtA], [{catchtag, LblsB} | CtB]) ->
[{catchtag, ordsets:union(LblsA, LblsB)} | merge_ct_1(CtA, CtB)];
merge_ct_1(_, _) ->
undecided.
verify_y_init(#vst{current=#st{numy=NumY,ys=Ys}}=Vst) when is_integer(NumY) ->
HighestY = maps:fold(fun({y,Y}, _, Acc) -> max(Y, Acc) end, -1, Ys),
verify_y_init_1(NumY - 1, Vst),
ok;
verify_y_init(#vst{current=#st{numy={undecided,MinSlots},ys=Ys}}=Vst) ->
HighestY = maps:fold(fun({y,Y}, _, Acc) -> max(Y, Acc) end, -1, Ys),
verify_y_init_1(HighestY, Vst);
verify_y_init(#vst{}) ->
ok.
verify_y_init_1(-1, _Vst) ->
ok;
verify_y_init_1(Y, Vst) ->
Reg = {y, Y},
assert_not_fragile(Reg, Vst),
case get_raw_type(Reg, Vst) of
uninitialized -> error({uninitialized_reg,Reg});
_ -> verify_y_init_1(Y - 1, Vst)
end.
verify_live(0, _Vst) ->
ok;
verify_live(Live, Vst) when is_integer(Live), 0 < Live, Live =< 1023 ->
verify_live_1(Live - 1, Vst);
verify_live(Live, _Vst) ->
error({bad_number_of_live_regs,Live}).
verify_live_1(-1, _) ->
ok;
verify_live_1(X, Vst) when is_integer(X) ->
Reg = {x, X},
case get_raw_type(Reg, Vst) of
uninitialized -> error({Reg, not_live});
_ -> verify_live_1(X - 1, Vst)
end.
verify_no_ct(#vst{current=#st{numy=none}}) ->
ok;
verify_no_ct(#vst{current=#st{numy={undecided,_}}}) ->
error(unknown_size_of_stackframe);
verify_no_ct(#vst{current=St}=Vst) ->
case collect_try_catch_tags(St#st.numy - 1, Vst, []) of
[_|_]=Bad -> error({unfinished_catch_try,Bad});
[] -> ok
end.
Collects all try / catch tags , walking down from the Nth stack position .
collect_try_catch_tags(-1, _Vst, Acc) ->
Acc;
collect_try_catch_tags(Y, Vst, Acc0) ->
Tag = get_raw_type({y, Y}, Vst),
Acc = case is_try_catch_tag(Tag) of
true -> [{{y, Y}, Tag} | Acc0];
false -> Acc0
end,
collect_try_catch_tags(Y - 1, Vst, Acc).
is_try_catch_tag({catchtag,_}) -> true;
is_try_catch_tag({trytag,_}) -> true;
is_try_catch_tag(_) -> false.
eat_heap(N, #vst{current=#st{h=Heap0}=St}=Vst) ->
case Heap0-N of
Neg when Neg < 0 ->
error({heap_overflow,{left,Heap0},{wanted,N}});
Heap ->
Vst#vst{current=St#st{h=Heap}}
end.
eat_heap_fun(#vst{current=#st{hl=HeapFuns0}=St}=Vst) ->
case HeapFuns0-1 of
Neg when Neg < 0 ->
error({heap_overflow,{left,{HeapFuns0,funs}},{wanted,{1,funs}}});
HeapFuns ->
Vst#vst{current=St#st{hl=HeapFuns}}
end.
eat_heap_float(#vst{current=#st{hf=HeapFloats0}=St}=Vst) ->
case HeapFloats0-1 of
Neg when Neg < 0 ->
error({heap_overflow,{left,{HeapFloats0,floats}},{wanted,{1,floats}}});
HeapFloats ->
Vst#vst{current=St#st{hf=HeapFloats}}
end.
use " receive markers " to tell the corresponding where to start
Since receive markers affect the next instruction it 's very
update_receive_state(New0, #vst{current=St0}=Vst) ->
#st{recv_state=Current} = St0,
New = case {Current, New0} of
{none, marked_position} ->
marked_position;
{marked_position, entered_loop} ->
entered_loop;
{none, entered_loop} ->
entered_loop;
{_, none} ->
none;
{_, _} ->
error({invalid_receive_state_change, Current, New0})
end,
St = St0#st{recv_state=New},
Vst#vst{current=St}.
over an instruction that may GC .
mark_fragile(Reg, Vst) ->
#vst{current=#st{fragile=Fragile0}=St0} = Vst,
Fragile = sets:add_element(Reg, Fragile0),
St = St0#st{fragile=Fragile},
Vst#vst{current=St}.
propagate_fragility(Reg, Args, #vst{current=St0}=Vst) ->
#st{fragile=Fragile0} = St0,
Sources = sets:from_list(Args, [{version, 2}]),
Fragile = case sets:is_disjoint(Sources, Fragile0) of
true -> sets:del_element(Reg, Fragile0);
false -> sets:add_element(Reg, Fragile0)
end,
St = St0#st{fragile=Fragile},
Vst#vst{current=St}.
remove_fragility(Reg, Vst) ->
#vst{current=#st{fragile=Fragile0}=St0} = Vst,
case sets:is_element(Reg, Fragile0) of
true ->
Fragile = sets:del_element(Reg, Fragile0),
St = St0#st{fragile=Fragile},
Vst#vst{current=St};
false ->
Vst
end.
Marks all registers as durable .
remove_fragility(#vst{current=St0}=Vst) ->
St = St0#st{fragile=sets:new([{version, 2}])},
Vst#vst{current=St}.
assert_durable_term(Src, Vst) ->
assert_term(Src, Vst),
assert_not_fragile(Src, Vst).
assert_not_fragile({Kind,_}=Src, Vst) when Kind =:= x; Kind =:= y ->
check_limit(Src),
#vst{current=#st{fragile=Fragile}} = Vst,
case sets:is_element(Src, Fragile) of
true -> error({fragile_message_reference, Src});
false -> ok
end;
assert_not_fragile(Lit, #vst{}) ->
assert_literal(Lit),
ok.
bif_types(Op, Ss, Vst) ->
Args = [get_term_type(Arg, Vst) || Arg <- Ss],
case {Op,Ss} of
{element,[_,{literal,Tuple}]} when tuple_size(Tuple) > 0 ->
case beam_call_types:types(erlang, Op, Args) of
{any,ArgTypes,Safe} ->
RetType = join_tuple_elements(Tuple),
{RetType,ArgTypes,Safe};
Other ->
Other
end;
{_,_} ->
beam_call_types:types(erlang, Op, Args)
end.
join_tuple_elements(Tuple) ->
join_tuple_elements(tuple_size(Tuple), Tuple, none).
join_tuple_elements(0, _Tuple, Type) ->
Type;
join_tuple_elements(I, Tuple, Type0) ->
Type1 = beam_types:make_type_from_value(element(I, Tuple)),
Type = beam_types:join(Type0, Type1),
join_tuple_elements(I - 1, Tuple, Type).
call_types({extfunc,M,F,A}, A, Vst) ->
Args = get_call_args(A, Vst),
beam_call_types:types(M, F, Args);
call_types(bs_init_writable, A, Vst) ->
T = beam_types:make_type_from_value(<<>>),
{T, get_call_args(A, Vst), false};
call_types(_, A, Vst) ->
{any, get_call_args(A, Vst), false}.
will_bif_succeed(raise, [_,_], _Vst) ->
Compiler - generated raise , the user - facing variant that can return
' badarg ' is : raise/3 .
no;
will_bif_succeed(Op, Ss, Vst) ->
case is_float_arith_bif(Op, Ss) of
true ->
'maybe';
false ->
Args = [get_term_type(Arg, Vst) || Arg <- Ss],
beam_call_types:will_succeed(erlang, Op, Args)
end.
will_call_succeed({extfunc,M,F,A}, _Live, Vst) ->
beam_call_types:will_succeed(M, F, get_call_args(A, Vst));
will_call_succeed(bs_init_writable, _Live, _Vst) ->
yes;
will_call_succeed(raw_raise, _Live, _Vst) ->
no;
will_call_succeed({f,Lbl}, _Live, #vst{ft=Ft}) ->
case Ft of
#{Lbl := #{always_fails := true}} ->
no;
#{} ->
'maybe'
end;
will_call_succeed(apply, Live, Vst) ->
Mod = get_term_type({x,Live-2}, Vst),
Name = get_term_type({x,Live-1}, Vst),
case {Mod,Name} of
{#t_atom{},#t_atom{}} ->
'maybe';
{_,_} ->
no
end;
will_call_succeed(_Call, _Live, _Vst) ->
'maybe'.
get_call_args(Arity, Vst) ->
get_call_args_1(0, Arity, Vst).
get_call_args_1(Arity, Arity, _) ->
[];
get_call_args_1(N, Arity, Vst) when N < Arity ->
ArgType = get_movable_term_type({x,N}, Vst),
[ArgType | get_call_args_1(N + 1, Arity, Vst)].
check_limit({x,X}=Src) when is_integer(X) ->
if
Note : x(1023 ) is reserved for use by the BEAM loader .
0 =< X, X < 1023 -> ok;
1023 =< X -> error(limit);
X < 0 -> error({bad_register, Src})
end;
check_limit({y,Y}=Src) when is_integer(Y) ->
if
0 =< Y, Y < 1024 -> ok;
1024 =< Y -> error(limit);
Y < 0 -> error({bad_register, Src})
end;
check_limit({fr,Fr}=Src) when is_integer(Fr) ->
if
0 =< Fr, Fr < 1023 -> ok;
1023 =< Fr -> error(limit);
Fr < 0 -> error({bad_register, Src})
end.
min(A, B) when is_integer(A), is_integer(B), A < B -> A;
min(A, B) when is_integer(A), is_integer(B) -> B.
gcd(A, B) ->
case A rem B of
0 -> B;
X -> gcd(B, X)
end.
error(Error) -> throw(Error).
|
00776d55a8f1da9ad09be7dcc24dbccdaaa4ff9005de623a07c8cd89b8230f5c | jellelicht/guix | upstream.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2010 , 2011 , 2012 , 2013 , 2014 , 2015 , 2016 < >
Copyright © 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix upstream)
#:use-module (guix records)
#:use-module (guix utils)
#:use-module ((guix download)
#:select (download-to-store))
#:use-module ((guix build utils)
#:select (substitute))
#:use-module (guix gnupg)
#:use-module (guix packages)
#:use-module (guix ui)
#:use-module (guix base32)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-26)
#:use-module (ice-9 match)
#:use-module (ice-9 regex)
#:export (upstream-source
upstream-source?
upstream-source-package
upstream-source-version
upstream-source-urls
upstream-source-signature-urls
upstream-source-archive-types
coalesce-sources
upstream-updater
upstream-updater?
upstream-updater-name
upstream-updater-description
upstream-updater-predicate
upstream-updater-latest
download-tarball
package-update-path
package-update
update-package-source))
;;; Commentary:
;;;
;;; This module provides tools to represent and manipulate a upstream source
;;; code, and to auto-update package recipes.
;;;
;;; Code:
;; Representation of upstream's source. There can be several URLs--e.g.,
tar.gz , tar.gz , etc . There can be correspond signature URLs , one per
;; source URL.
(define-record-type* <upstream-source>
upstream-source make-upstream-source
upstream-source?
(package upstream-source-package) ;string
(version upstream-source-version) ;string
(urls upstream-source-urls) ;list of strings
(signature-urls upstream-source-signature-urls ;#f | list of strings
(default #f)))
(define (upstream-source-archive-types release)
"Return the available types of archives for RELEASE---a list of strings such
as \"gz\" or \"xz\"."
(map file-extension (upstream-source-urls release)))
(define (coalesce-sources sources)
"Coalesce the elements of SOURCES, a list of <upstream-source>, that
correspond to the same version."
(define (same-version? r1 r2)
(string=? (upstream-source-version r1) (upstream-source-version r2)))
(define (release>? r1 r2)
(version>? (upstream-source-version r1) (upstream-source-version r2)))
(fold (lambda (release result)
(match result
((head . tail)
(if (same-version? release head)
(cons (upstream-source
(inherit release)
(urls (append (upstream-source-urls release)
(upstream-source-urls head)))
(signature-urls
(let ((one (upstream-source-signature-urls release))
(two (upstream-source-signature-urls head)))
(and one two (append one two)))))
tail)
(cons release result)))
(()
(list release))))
'()
(sort sources release>?)))
;;;
;;; Auto-update.
;;;
(define-record-type* <upstream-updater>
upstream-updater make-upstream-updater
upstream-updater?
(name upstream-updater-name)
(description upstream-updater-description)
(pred upstream-updater-predicate)
(latest upstream-updater-latest))
(define (lookup-updater package updaters)
"Return an updater among UPDATERS that matches PACKAGE, or #f if none of
them matches."
(any (match-lambda
(($ <upstream-updater> _ _ pred latest)
(and (pred package) latest)))
updaters))
(define (package-update-path package updaters)
"Return an upstream source to update PACKAGE to, or #f if no update is
needed or known."
(match (lookup-updater package updaters)
((? procedure? latest-release)
(match (latest-release (package-name package))
((and source ($ <upstream-source> name version))
(and (version>? version (package-version package))
source))
(_ #f)))
(#f #f)))
(define* (download-tarball store url signature-url
#:key (key-download 'interactive))
check its OpenPGP signature at
SIGNATURE-URL, unless SIGNATURE-URL is false. On success, return the tarball
file name. KEY-DOWNLOAD specifies a download policy for missing OpenPGP keys;
allowed values: 'interactive' (default), 'always', and 'never'."
(let ((tarball (download-to-store store url)))
(if (not signature-url)
tarball
(let* ((sig (download-to-store store signature-url))
(ret (gnupg-verify* sig tarball #:key-download key-download)))
(if ret
tarball
(begin
(warning (_ "signature verification failed for `~a'~%")
url)
(warning (_ "(could be because the public key is not in your keyring)~%"))
#f))))))
(define (find2 pred lst1 lst2)
"Like 'find', but operate on items from both LST1 and LST2. Return two
values: the item from LST1 and the item from LST2 that match PRED."
(let loop ((lst1 lst1) (lst2 lst2))
(match lst1
((head1 . tail1)
(match lst2
((head2 . tail2)
(if (pred head1 head2)
(values head1 head2)
(loop tail1 tail2)))))
(()
(values #f #f)))))
(define* (package-update store package updaters
#:key (key-download 'interactive))
"Return the new version and the file name of the new version tarball for
PACKAGE, or #f and #f when PACKAGE is up-to-date. KEY-DOWNLOAD specifies a
download policy for missing OpenPGP keys; allowed values: 'always', 'never',
and 'interactive' (default)."
(match (package-update-path package updaters)
(($ <upstream-source> _ version urls signature-urls)
(let*-values (((name)
(package-name package))
((archive-type)
(match (and=> (package-source package) origin-uri)
((? string? uri)
(or (file-extension uri) "gz"))
(_
"gz")))
((url signature-url)
(find2 (lambda (url sig-url)
(string-suffix? archive-type url))
urls
(or signature-urls (circular-list #f)))))
(let ((tarball (download-tarball store url signature-url
#:key-download key-download)))
(values version tarball))))
(#f
(values #f #f))))
(define (update-package-source package version hash)
"Modify the source file that defines PACKAGE to refer to VERSION,
whose tarball has SHA256 HASH (a bytevector). Return the new version string
if an update was made, and #f otherwise."
(define (new-line line matches replacement)
;; Iterate over MATCHES and return the modified line based on LINE.
;; Replace each match with REPLACEMENT.
(let loop ((m* matches) ; matches
(o 0) ; offset in L
(r '())) ; result
(match m*
(()
(let ((r (cons (substring line o) r)))
(string-concatenate-reverse r)))
((m . rest)
(loop rest
(match:end m)
(cons* replacement
(substring line o (match:start m))
r))))))
(define (update-source file old-version version
old-hash hash)
Update source file FILE , replacing occurrences OLD - VERSION by VERSION
and occurrences of OLD - HASH by ( base32 representation thereof ) .
TODO : Currently this is a bit of a sledgehammer : if VERSION occurs in
;; different unrelated places, we may modify it more than needed, for
;; instance. We should try to make changes only within the sexp that
;; corresponds to the definition of PACKAGE.
(let ((old-hash (bytevector->nix-base32-string old-hash))
(hash (bytevector->nix-base32-string hash)))
(substitute file
`((,(regexp-quote old-version)
. ,(cut new-line <> <> version))
(,(regexp-quote old-hash)
. ,(cut new-line <> <> hash))))
version))
(let ((name (package-name package))
(loc (package-field-location package 'version)))
(if loc
(let ((old-version (package-version package))
(old-hash (origin-sha256 (package-source package)))
(file (and=> (location-file loc)
(cut search-path %load-path <>))))
(if file
(update-source file
old-version version
old-hash hash)
(begin
(warning (_ "~a: could not locate source file")
(location-file loc))
#f)))
(begin
(format (current-error-port)
(_ "~a: ~a: no `version' field in source; skipping~%")
(location->string (package-location package))
name)))))
;;; upstream.scm ends here
| null | https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/guix/upstream.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Commentary:
This module provides tools to represent and manipulate a upstream source
code, and to auto-update package recipes.
Code:
Representation of upstream's source. There can be several URLs--e.g.,
source URL.
string
string
list of strings
#f | list of strings
Auto-update.
allowed values: 'always', 'never',
Iterate over MATCHES and return the modified line based on LINE.
Replace each match with REPLACEMENT.
matches
offset in L
result
different unrelated places, we may modify it more than needed, for
instance. We should try to make changes only within the sexp that
corresponds to the definition of PACKAGE.
upstream.scm ends here | Copyright © 2010 , 2011 , 2012 , 2013 , 2014 , 2015 , 2016 < >
Copyright © 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix upstream)
#:use-module (guix records)
#:use-module (guix utils)
#:use-module ((guix download)
#:select (download-to-store))
#:use-module ((guix build utils)
#:select (substitute))
#:use-module (guix gnupg)
#:use-module (guix packages)
#:use-module (guix ui)
#:use-module (guix base32)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-26)
#:use-module (ice-9 match)
#:use-module (ice-9 regex)
#:export (upstream-source
upstream-source?
upstream-source-package
upstream-source-version
upstream-source-urls
upstream-source-signature-urls
upstream-source-archive-types
coalesce-sources
upstream-updater
upstream-updater?
upstream-updater-name
upstream-updater-description
upstream-updater-predicate
upstream-updater-latest
download-tarball
package-update-path
package-update
update-package-source))
tar.gz , tar.gz , etc . There can be correspond signature URLs , one per
(define-record-type* <upstream-source>
upstream-source make-upstream-source
upstream-source?
(default #f)))
(define (upstream-source-archive-types release)
"Return the available types of archives for RELEASE---a list of strings such
as \"gz\" or \"xz\"."
(map file-extension (upstream-source-urls release)))
(define (coalesce-sources sources)
"Coalesce the elements of SOURCES, a list of <upstream-source>, that
correspond to the same version."
(define (same-version? r1 r2)
(string=? (upstream-source-version r1) (upstream-source-version r2)))
(define (release>? r1 r2)
(version>? (upstream-source-version r1) (upstream-source-version r2)))
(fold (lambda (release result)
(match result
((head . tail)
(if (same-version? release head)
(cons (upstream-source
(inherit release)
(urls (append (upstream-source-urls release)
(upstream-source-urls head)))
(signature-urls
(let ((one (upstream-source-signature-urls release))
(two (upstream-source-signature-urls head)))
(and one two (append one two)))))
tail)
(cons release result)))
(()
(list release))))
'()
(sort sources release>?)))
(define-record-type* <upstream-updater>
upstream-updater make-upstream-updater
upstream-updater?
(name upstream-updater-name)
(description upstream-updater-description)
(pred upstream-updater-predicate)
(latest upstream-updater-latest))
(define (lookup-updater package updaters)
"Return an updater among UPDATERS that matches PACKAGE, or #f if none of
them matches."
(any (match-lambda
(($ <upstream-updater> _ _ pred latest)
(and (pred package) latest)))
updaters))
(define (package-update-path package updaters)
"Return an upstream source to update PACKAGE to, or #f if no update is
needed or known."
(match (lookup-updater package updaters)
((? procedure? latest-release)
(match (latest-release (package-name package))
((and source ($ <upstream-source> name version))
(and (version>? version (package-version package))
source))
(_ #f)))
(#f #f)))
(define* (download-tarball store url signature-url
#:key (key-download 'interactive))
check its OpenPGP signature at
SIGNATURE-URL, unless SIGNATURE-URL is false. On success, return the tarball
allowed values: 'interactive' (default), 'always', and 'never'."
(let ((tarball (download-to-store store url)))
(if (not signature-url)
tarball
(let* ((sig (download-to-store store signature-url))
(ret (gnupg-verify* sig tarball #:key-download key-download)))
(if ret
tarball
(begin
(warning (_ "signature verification failed for `~a'~%")
url)
(warning (_ "(could be because the public key is not in your keyring)~%"))
#f))))))
(define (find2 pred lst1 lst2)
"Like 'find', but operate on items from both LST1 and LST2. Return two
values: the item from LST1 and the item from LST2 that match PRED."
(let loop ((lst1 lst1) (lst2 lst2))
(match lst1
((head1 . tail1)
(match lst2
((head2 . tail2)
(if (pred head1 head2)
(values head1 head2)
(loop tail1 tail2)))))
(()
(values #f #f)))))
(define* (package-update store package updaters
#:key (key-download 'interactive))
"Return the new version and the file name of the new version tarball for
PACKAGE, or #f and #f when PACKAGE is up-to-date. KEY-DOWNLOAD specifies a
and 'interactive' (default)."
(match (package-update-path package updaters)
(($ <upstream-source> _ version urls signature-urls)
(let*-values (((name)
(package-name package))
((archive-type)
(match (and=> (package-source package) origin-uri)
((? string? uri)
(or (file-extension uri) "gz"))
(_
"gz")))
((url signature-url)
(find2 (lambda (url sig-url)
(string-suffix? archive-type url))
urls
(or signature-urls (circular-list #f)))))
(let ((tarball (download-tarball store url signature-url
#:key-download key-download)))
(values version tarball))))
(#f
(values #f #f))))
(define (update-package-source package version hash)
"Modify the source file that defines PACKAGE to refer to VERSION,
whose tarball has SHA256 HASH (a bytevector). Return the new version string
if an update was made, and #f otherwise."
(define (new-line line matches replacement)
(match m*
(()
(let ((r (cons (substring line o) r)))
(string-concatenate-reverse r)))
((m . rest)
(loop rest
(match:end m)
(cons* replacement
(substring line o (match:start m))
r))))))
(define (update-source file old-version version
old-hash hash)
Update source file FILE , replacing occurrences OLD - VERSION by VERSION
and occurrences of OLD - HASH by ( base32 representation thereof ) .
TODO : Currently this is a bit of a sledgehammer : if VERSION occurs in
(let ((old-hash (bytevector->nix-base32-string old-hash))
(hash (bytevector->nix-base32-string hash)))
(substitute file
`((,(regexp-quote old-version)
. ,(cut new-line <> <> version))
(,(regexp-quote old-hash)
. ,(cut new-line <> <> hash))))
version))
(let ((name (package-name package))
(loc (package-field-location package 'version)))
(if loc
(let ((old-version (package-version package))
(old-hash (origin-sha256 (package-source package)))
(file (and=> (location-file loc)
(cut search-path %load-path <>))))
(if file
(update-source file
old-version version
old-hash hash)
(begin
(warning (_ "~a: could not locate source file")
(location-file loc))
#f)))
(begin
(format (current-error-port)
(_ "~a: ~a: no `version' field in source; skipping~%")
(location->string (package-location package))
name)))))
|
479fb708d7f2910b2dd3e94cece348dbf42a33707ec1ee53d23c53338e417d6b | AshleyYakeley/Truth | Ordered.hs | module Changes.Core.Types.List.Ordered where
import Changes.Core.Edit
import Changes.Core.Import
import Changes.Core.Lens
import Changes.Core.Read
import Changes.Core.Sequence
import Changes.Core.Types.List.Edit
import Changes.Core.Types.List.Read
import Changes.Core.Types.List.Update
import Changes.Core.Types.None
import Changes.Core.Types.One.FullResult
import Changes.Core.Types.One.Read
import Changes.Core.Types.One.Result
import Changes.Core.Types.ReadOnly
import Changes.Core.Types.Whole
-- | Like ListEdit, except without a way of adding new elements.
-- This is what both lists and unordered sets presented in some order have in common.
data OrderedListEdit edit where
OrderedListEditItem :: SequencePoint -> edit -> OrderedListEdit edit
OrderedListEditDelete :: SequencePoint -> OrderedListEdit edit
OrderedListEditClear :: OrderedListEdit edit
instance Floating (OrderedListEdit edit) SequencePoint where
floatingUpdate (OrderedListEditDelete p) i
| p < i = pred i
floatingUpdate _ i = i
instance Floating (OrderedListEdit edit) (OrderedListEdit edit) where
floatingUpdate edit (OrderedListEditItem i e) = OrderedListEditItem (floatingUpdate edit i) e
floatingUpdate edit (OrderedListEditDelete i) = OrderedListEditDelete (floatingUpdate edit i)
floatingUpdate _edit OrderedListEditClear = OrderedListEditClear
type instance EditReader (OrderedListEdit edit) = ListReader (EditReader edit)
instance (FullSubjectReader (EditReader edit), ApplicableEdit edit) => ApplicableEdit (OrderedListEdit edit) where
applyEdit (OrderedListEditItem p edit) mr (ListReadItem i rd)
| p == i = unComposeInner $ applyEdit edit (itemReadFunction i mr) rd -- already checks bounds
applyEdit (OrderedListEditItem _ _) mr rd = mr rd
applyEdit (OrderedListEditDelete p) mr ListReadLength = do
len <- mr ListReadLength
return $
if p >= 0 && p < len
then pred len
else len
applyEdit (OrderedListEditDelete p) mr (ListReadItem i rd)
| p >= 0 && p < i = mr $ ListReadItem (succ i) rd
applyEdit (OrderedListEditDelete _) mr (ListReadItem i rd) = mr $ ListReadItem i rd
applyEdit OrderedListEditClear _mr rd = subjectToReadable mempty rd
instance (SubjectReader (EditReader edit), SubjectMapEdit edit) => SubjectMapEdit (OrderedListEdit edit) where
mapSubjectEdits =
mapEditToMapEdits $ \listedit subj ->
case listedit of
OrderedListEditItem p edit -> let
(before, after) = seqSplitAt p subj
in case uncons after of
Just (olditem, rest) -> do
newitem <- mapSubjectEdits [edit] olditem
return $ before `mappend` opoint newitem `mappend` rest
Nothing -> return $ subj
OrderedListEditDelete p -> let
(before, after) = seqSplitAt p subj
in case uncons after of
Just (_, rest) -> return $ mappend before rest
Nothing -> return $ subj
OrderedListEditClear -> return mempty
data OrderedListUpdate update where
OrderedListUpdateItem :: SequencePoint -> SequencePoint -> [update] -> OrderedListUpdate update
OrderedListUpdateDelete :: SequencePoint -> OrderedListUpdate update
OrderedListUpdateInsert :: SequencePoint -> UpdateSubject update -> OrderedListUpdate update
OrderedListUpdateClear :: OrderedListUpdate update
type instance UpdateEdit (OrderedListUpdate update) = OrderedListEdit (UpdateEdit update)
instance FullSubjectReader (UpdateReader update) => FullUpdate (OrderedListUpdate update) where
replaceUpdate rd push = do
push OrderedListUpdateClear
len <- rd ListReadLength
for_ [0 .. pred len] $ \i -> do
msubj <- unComposeInner $ readableToSubject $ itemReadFunction i rd
case msubj of
Just subj -> push $ OrderedListUpdateInsert i $ subj
Nothing -> return ()
orderedListLengthLens :: forall update. ChangeLens (OrderedListUpdate update) (ROWUpdate SequencePoint)
orderedListLengthLens = let
clRead :: ReadFunction (ListReader (UpdateReader update)) (WholeReader SequencePoint)
clRead mr ReadWhole = mr ListReadLength
clUpdate ::
forall m. MonadIO m
=> OrderedListUpdate update
-> Readable m (ListReader (UpdateReader update))
-> m [ROWUpdate SequencePoint]
clUpdate OrderedListUpdateClear _ = return $ pure $ MkReadOnlyUpdate $ MkWholeUpdate 0
clUpdate (OrderedListUpdateItem _ _ _) _ = return []
clUpdate _ mr = do
i <- mr ListReadLength
return $ pure $ MkReadOnlyUpdate $ MkWholeUpdate i
in MkChangeLens {clPutEdits = clPutEditsNone, ..}
-- no "instance IsUpdate OrderedListUpdate", because we cannot calculate moves without knowing the order
-- | prevents creation of the element
orderedListItemLinearLens ::
forall update. (FullSubjectReader (UpdateReader update), ApplicableEdit (UpdateEdit update))
=> SequencePoint
-> LinearFloatingChangeLens (StateLensVar SequencePoint) (OrderedListUpdate update) (MaybeUpdate update)
orderedListItemLinearLens initpos = let
sclInit ::
forall m. MonadIO m
=> Readable m (ListReader (UpdateReader update))
-> m SequencePoint
sclInit _ = return initpos
sclRead ::
ReadFunctionT (StateT SequencePoint) (ListReader (UpdateReader update)) (OneReader Maybe (UpdateReader update))
sclRead mr (ReadOne rt) = do
i <- get
lift $ mr $ ListReadItem i rt
sclRead mr ReadHasOne = do
i <- get
if i < 0
then return Nothing
else do
len <- lift $ mr ListReadLength
return $
if i >= len
then Nothing
else Just ()
sclUpdate ::
forall m. MonadIO m
=> OrderedListUpdate update
-> Readable m (ListReader (UpdateReader update))
-> StateT SequencePoint m [MaybeUpdate update]
sclUpdate (OrderedListUpdateItem oldie newie lupdate) _ = do
i <- get
case compare oldie i of
EQ -> do
put newie
return $ fmap (\update -> MkFullResultOneUpdate $ SuccessResultOneUpdate update) lupdate
LT -> do
if newie >= i
then put $ pred i
else return ()
return []
GT -> do
if newie <= i
then put $ succ i
else return ()
return []
sclUpdate (OrderedListUpdateDelete ie) _ = do
i <- get
case compare ie i of
LT -> do
put $ pred i
return []
EQ -> return [MkFullResultOneUpdate $ NewResultOneUpdate Nothing]
GT -> return []
sclUpdate (OrderedListUpdateInsert ie _) _ = do
i <- get
if ie <= i
then put $ succ i
else return ()
return []
sclUpdate OrderedListUpdateClear _ = do
put 0
return [MkFullResultOneUpdate $ NewResultOneUpdate Nothing]
sPutEdit ::
forall m. MonadIO m
=> MaybeEdit (UpdateEdit update)
-> StateT SequencePoint m (Maybe [OrderedListEdit (UpdateEdit update)])
sPutEdit (SuccessFullResultOneEdit edit) = do
i <- get
return $ Just [OrderedListEditItem i edit]
sPutEdit (NewFullResultOneEdit Nothing) = do
i <- get
return $ Just [OrderedListEditDelete i]
sPutEdit (NewFullResultOneEdit (Just _)) = return Nothing
sclPutEdits ::
forall m. MonadIO m
=> [MaybeEdit (UpdateEdit update)]
-> Readable m NullReader
-> StateT SequencePoint m (Maybe [OrderedListEdit (UpdateEdit update)])
sclPutEdits = linearPutEditsFromPutEdit sPutEdit
in makeStateExpLens MkStateChangeLens {..}
-- | prevents creation of the element
orderedListItemLens ::
forall update. (FullSubjectReader (UpdateReader update), ApplicableEdit (UpdateEdit update))
=> SequencePoint
-> FloatingChangeLens (OrderedListUpdate update) (MaybeUpdate update)
orderedListItemLens initpos = expToFloatingChangeLens $ orderedListItemLinearLens initpos
listOrderedListChangeLens ::
forall update. (FullSubjectReader (UpdateReader update), ApplicableEdit (UpdateEdit update))
=> ChangeLens (ListUpdate update) (OrderedListUpdate update)
listOrderedListChangeLens = let
clRead :: ReadFunction (ListReader (UpdateReader update)) (ListReader (UpdateReader update))
clRead mr = mr
clUpdate ::
forall m. MonadIO m
=> ListUpdate update
-> Readable m (ListReader (UpdateReader update))
-> m [OrderedListUpdate update]
clUpdate (ListUpdateItem p update) _ = return $ pure $ OrderedListUpdateItem p p [update]
clUpdate (ListUpdateDelete p) _ = return $ pure $ OrderedListUpdateDelete p
clUpdate (ListUpdateInsert p subj) _ = return $ pure $ OrderedListUpdateInsert p subj
clUpdate ListUpdateClear _ = return $ pure OrderedListUpdateClear
clPutEdit ::
forall m. MonadIO m
=> OrderedListEdit (UpdateEdit update)
-> Readable m (ListReader (UpdateReader update))
-> m (Maybe [ListEdit (UpdateEdit update)])
clPutEdit (OrderedListEditItem p edit) _ = return $ Just $ pure $ ListEditItem p edit
clPutEdit (OrderedListEditDelete p) _ = return $ Just $ pure $ ListEditDelete p
clPutEdit OrderedListEditClear _ = return $ Just $ pure ListEditClear
clPutEdits ::
forall m. MonadIO m
=> [OrderedListEdit (UpdateEdit update)]
-> Readable m (ListReader (UpdateReader update))
-> m (Maybe [ListEdit (UpdateEdit update)])
clPutEdits = clPutEditsFromPutEdit clPutEdit
in MkChangeLens {..}
liftOrderedListChangeLens ::
forall updateA updateB.
( FullSubjectReader (UpdateReader updateA)
, ApplicableEdit (UpdateEdit updateA)
, FullSubjectReader (UpdateReader updateB)
)
=> ChangeLens updateA updateB
-> ChangeLens (OrderedListUpdate updateA) (OrderedListUpdate updateB)
liftOrderedListChangeLens (MkChangeLens g up pe) = let
clRead :: ReadFunction (ListReader (UpdateReader updateA)) (ListReader (UpdateReader updateB))
clRead rd ListReadLength = rd ListReadLength
clRead rd (ListReadItem i rb) = unComposeInner $ g (\ra -> MkComposeInner $ rd (ListReadItem i ra)) rb
clUpdate ::
forall m. MonadIO m
=> OrderedListUpdate updateA
-> Readable m (ListReader (UpdateReader updateA))
-> m [OrderedListUpdate updateB]
clUpdate (OrderedListUpdateItem i1 i2 lu) rd = do
u' <- for lu $ \u -> unComposeInner $ up u $ \ra -> MkComposeInner $ rd $ ListReadItem i1 ra
return $
case sequenceA u' of
Nothing -> []
Just ubb -> pure $ OrderedListUpdateItem i1 i2 $ mconcat ubb
clUpdate (OrderedListUpdateDelete i) _ = return $ pure $ OrderedListUpdateDelete $ i
clUpdate (OrderedListUpdateInsert i subjA) _ = do
subjB <- readableToSubject $ g $ subjectToReadable subjA
return $ pure $ OrderedListUpdateInsert i subjB
clUpdate OrderedListUpdateClear _ = return $ pure OrderedListUpdateClear
clPutEdit ::
forall m. MonadIO m
=> OrderedListEdit (UpdateEdit updateB)
-> Readable m (ListReader (UpdateReader updateA))
-> m (Maybe [OrderedListEdit (UpdateEdit updateA)])
clPutEdit (OrderedListEditItem i editB) rd =
unComposeInner $ do
meditAs <- pe [editB] $ \ra -> MkComposeInner $ rd (ListReadItem i ra)
editAs <- liftInner meditAs
return $ fmap (OrderedListEditItem $ i) editAs
clPutEdit (OrderedListEditDelete i) _ = return $ Just $ pure $ OrderedListEditDelete $ i
clPutEdit OrderedListEditClear _ = return $ Just $ pure OrderedListEditClear
clPutEdits ::
forall m. MonadIO m
=> [OrderedListEdit (UpdateEdit updateB)]
-> Readable m (ListReader (UpdateReader updateA))
-> m (Maybe [OrderedListEdit (UpdateEdit updateA)])
clPutEdits = clPutEditsFromPutEdit clPutEdit
in MkChangeLens {..}
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/2817d5e36bd1dc5de932d808026098b6c35e7185/Changes/changes-core/lib/Changes/Core/Types/List/Ordered.hs | haskell | | Like ListEdit, except without a way of adding new elements.
This is what both lists and unordered sets presented in some order have in common.
already checks bounds
no "instance IsUpdate OrderedListUpdate", because we cannot calculate moves without knowing the order
| prevents creation of the element
| prevents creation of the element | module Changes.Core.Types.List.Ordered where
import Changes.Core.Edit
import Changes.Core.Import
import Changes.Core.Lens
import Changes.Core.Read
import Changes.Core.Sequence
import Changes.Core.Types.List.Edit
import Changes.Core.Types.List.Read
import Changes.Core.Types.List.Update
import Changes.Core.Types.None
import Changes.Core.Types.One.FullResult
import Changes.Core.Types.One.Read
import Changes.Core.Types.One.Result
import Changes.Core.Types.ReadOnly
import Changes.Core.Types.Whole
data OrderedListEdit edit where
OrderedListEditItem :: SequencePoint -> edit -> OrderedListEdit edit
OrderedListEditDelete :: SequencePoint -> OrderedListEdit edit
OrderedListEditClear :: OrderedListEdit edit
instance Floating (OrderedListEdit edit) SequencePoint where
floatingUpdate (OrderedListEditDelete p) i
| p < i = pred i
floatingUpdate _ i = i
instance Floating (OrderedListEdit edit) (OrderedListEdit edit) where
floatingUpdate edit (OrderedListEditItem i e) = OrderedListEditItem (floatingUpdate edit i) e
floatingUpdate edit (OrderedListEditDelete i) = OrderedListEditDelete (floatingUpdate edit i)
floatingUpdate _edit OrderedListEditClear = OrderedListEditClear
type instance EditReader (OrderedListEdit edit) = ListReader (EditReader edit)
instance (FullSubjectReader (EditReader edit), ApplicableEdit edit) => ApplicableEdit (OrderedListEdit edit) where
applyEdit (OrderedListEditItem p edit) mr (ListReadItem i rd)
applyEdit (OrderedListEditItem _ _) mr rd = mr rd
applyEdit (OrderedListEditDelete p) mr ListReadLength = do
len <- mr ListReadLength
return $
if p >= 0 && p < len
then pred len
else len
applyEdit (OrderedListEditDelete p) mr (ListReadItem i rd)
| p >= 0 && p < i = mr $ ListReadItem (succ i) rd
applyEdit (OrderedListEditDelete _) mr (ListReadItem i rd) = mr $ ListReadItem i rd
applyEdit OrderedListEditClear _mr rd = subjectToReadable mempty rd
instance (SubjectReader (EditReader edit), SubjectMapEdit edit) => SubjectMapEdit (OrderedListEdit edit) where
mapSubjectEdits =
mapEditToMapEdits $ \listedit subj ->
case listedit of
OrderedListEditItem p edit -> let
(before, after) = seqSplitAt p subj
in case uncons after of
Just (olditem, rest) -> do
newitem <- mapSubjectEdits [edit] olditem
return $ before `mappend` opoint newitem `mappend` rest
Nothing -> return $ subj
OrderedListEditDelete p -> let
(before, after) = seqSplitAt p subj
in case uncons after of
Just (_, rest) -> return $ mappend before rest
Nothing -> return $ subj
OrderedListEditClear -> return mempty
data OrderedListUpdate update where
OrderedListUpdateItem :: SequencePoint -> SequencePoint -> [update] -> OrderedListUpdate update
OrderedListUpdateDelete :: SequencePoint -> OrderedListUpdate update
OrderedListUpdateInsert :: SequencePoint -> UpdateSubject update -> OrderedListUpdate update
OrderedListUpdateClear :: OrderedListUpdate update
type instance UpdateEdit (OrderedListUpdate update) = OrderedListEdit (UpdateEdit update)
instance FullSubjectReader (UpdateReader update) => FullUpdate (OrderedListUpdate update) where
replaceUpdate rd push = do
push OrderedListUpdateClear
len <- rd ListReadLength
for_ [0 .. pred len] $ \i -> do
msubj <- unComposeInner $ readableToSubject $ itemReadFunction i rd
case msubj of
Just subj -> push $ OrderedListUpdateInsert i $ subj
Nothing -> return ()
orderedListLengthLens :: forall update. ChangeLens (OrderedListUpdate update) (ROWUpdate SequencePoint)
orderedListLengthLens = let
clRead :: ReadFunction (ListReader (UpdateReader update)) (WholeReader SequencePoint)
clRead mr ReadWhole = mr ListReadLength
clUpdate ::
forall m. MonadIO m
=> OrderedListUpdate update
-> Readable m (ListReader (UpdateReader update))
-> m [ROWUpdate SequencePoint]
clUpdate OrderedListUpdateClear _ = return $ pure $ MkReadOnlyUpdate $ MkWholeUpdate 0
clUpdate (OrderedListUpdateItem _ _ _) _ = return []
clUpdate _ mr = do
i <- mr ListReadLength
return $ pure $ MkReadOnlyUpdate $ MkWholeUpdate i
in MkChangeLens {clPutEdits = clPutEditsNone, ..}
orderedListItemLinearLens ::
forall update. (FullSubjectReader (UpdateReader update), ApplicableEdit (UpdateEdit update))
=> SequencePoint
-> LinearFloatingChangeLens (StateLensVar SequencePoint) (OrderedListUpdate update) (MaybeUpdate update)
orderedListItemLinearLens initpos = let
sclInit ::
forall m. MonadIO m
=> Readable m (ListReader (UpdateReader update))
-> m SequencePoint
sclInit _ = return initpos
sclRead ::
ReadFunctionT (StateT SequencePoint) (ListReader (UpdateReader update)) (OneReader Maybe (UpdateReader update))
sclRead mr (ReadOne rt) = do
i <- get
lift $ mr $ ListReadItem i rt
sclRead mr ReadHasOne = do
i <- get
if i < 0
then return Nothing
else do
len <- lift $ mr ListReadLength
return $
if i >= len
then Nothing
else Just ()
sclUpdate ::
forall m. MonadIO m
=> OrderedListUpdate update
-> Readable m (ListReader (UpdateReader update))
-> StateT SequencePoint m [MaybeUpdate update]
sclUpdate (OrderedListUpdateItem oldie newie lupdate) _ = do
i <- get
case compare oldie i of
EQ -> do
put newie
return $ fmap (\update -> MkFullResultOneUpdate $ SuccessResultOneUpdate update) lupdate
LT -> do
if newie >= i
then put $ pred i
else return ()
return []
GT -> do
if newie <= i
then put $ succ i
else return ()
return []
sclUpdate (OrderedListUpdateDelete ie) _ = do
i <- get
case compare ie i of
LT -> do
put $ pred i
return []
EQ -> return [MkFullResultOneUpdate $ NewResultOneUpdate Nothing]
GT -> return []
sclUpdate (OrderedListUpdateInsert ie _) _ = do
i <- get
if ie <= i
then put $ succ i
else return ()
return []
sclUpdate OrderedListUpdateClear _ = do
put 0
return [MkFullResultOneUpdate $ NewResultOneUpdate Nothing]
sPutEdit ::
forall m. MonadIO m
=> MaybeEdit (UpdateEdit update)
-> StateT SequencePoint m (Maybe [OrderedListEdit (UpdateEdit update)])
sPutEdit (SuccessFullResultOneEdit edit) = do
i <- get
return $ Just [OrderedListEditItem i edit]
sPutEdit (NewFullResultOneEdit Nothing) = do
i <- get
return $ Just [OrderedListEditDelete i]
sPutEdit (NewFullResultOneEdit (Just _)) = return Nothing
sclPutEdits ::
forall m. MonadIO m
=> [MaybeEdit (UpdateEdit update)]
-> Readable m NullReader
-> StateT SequencePoint m (Maybe [OrderedListEdit (UpdateEdit update)])
sclPutEdits = linearPutEditsFromPutEdit sPutEdit
in makeStateExpLens MkStateChangeLens {..}
orderedListItemLens ::
forall update. (FullSubjectReader (UpdateReader update), ApplicableEdit (UpdateEdit update))
=> SequencePoint
-> FloatingChangeLens (OrderedListUpdate update) (MaybeUpdate update)
orderedListItemLens initpos = expToFloatingChangeLens $ orderedListItemLinearLens initpos
listOrderedListChangeLens ::
forall update. (FullSubjectReader (UpdateReader update), ApplicableEdit (UpdateEdit update))
=> ChangeLens (ListUpdate update) (OrderedListUpdate update)
listOrderedListChangeLens = let
clRead :: ReadFunction (ListReader (UpdateReader update)) (ListReader (UpdateReader update))
clRead mr = mr
clUpdate ::
forall m. MonadIO m
=> ListUpdate update
-> Readable m (ListReader (UpdateReader update))
-> m [OrderedListUpdate update]
clUpdate (ListUpdateItem p update) _ = return $ pure $ OrderedListUpdateItem p p [update]
clUpdate (ListUpdateDelete p) _ = return $ pure $ OrderedListUpdateDelete p
clUpdate (ListUpdateInsert p subj) _ = return $ pure $ OrderedListUpdateInsert p subj
clUpdate ListUpdateClear _ = return $ pure OrderedListUpdateClear
clPutEdit ::
forall m. MonadIO m
=> OrderedListEdit (UpdateEdit update)
-> Readable m (ListReader (UpdateReader update))
-> m (Maybe [ListEdit (UpdateEdit update)])
clPutEdit (OrderedListEditItem p edit) _ = return $ Just $ pure $ ListEditItem p edit
clPutEdit (OrderedListEditDelete p) _ = return $ Just $ pure $ ListEditDelete p
clPutEdit OrderedListEditClear _ = return $ Just $ pure ListEditClear
clPutEdits ::
forall m. MonadIO m
=> [OrderedListEdit (UpdateEdit update)]
-> Readable m (ListReader (UpdateReader update))
-> m (Maybe [ListEdit (UpdateEdit update)])
clPutEdits = clPutEditsFromPutEdit clPutEdit
in MkChangeLens {..}
liftOrderedListChangeLens ::
forall updateA updateB.
( FullSubjectReader (UpdateReader updateA)
, ApplicableEdit (UpdateEdit updateA)
, FullSubjectReader (UpdateReader updateB)
)
=> ChangeLens updateA updateB
-> ChangeLens (OrderedListUpdate updateA) (OrderedListUpdate updateB)
liftOrderedListChangeLens (MkChangeLens g up pe) = let
clRead :: ReadFunction (ListReader (UpdateReader updateA)) (ListReader (UpdateReader updateB))
clRead rd ListReadLength = rd ListReadLength
clRead rd (ListReadItem i rb) = unComposeInner $ g (\ra -> MkComposeInner $ rd (ListReadItem i ra)) rb
clUpdate ::
forall m. MonadIO m
=> OrderedListUpdate updateA
-> Readable m (ListReader (UpdateReader updateA))
-> m [OrderedListUpdate updateB]
clUpdate (OrderedListUpdateItem i1 i2 lu) rd = do
u' <- for lu $ \u -> unComposeInner $ up u $ \ra -> MkComposeInner $ rd $ ListReadItem i1 ra
return $
case sequenceA u' of
Nothing -> []
Just ubb -> pure $ OrderedListUpdateItem i1 i2 $ mconcat ubb
clUpdate (OrderedListUpdateDelete i) _ = return $ pure $ OrderedListUpdateDelete $ i
clUpdate (OrderedListUpdateInsert i subjA) _ = do
subjB <- readableToSubject $ g $ subjectToReadable subjA
return $ pure $ OrderedListUpdateInsert i subjB
clUpdate OrderedListUpdateClear _ = return $ pure OrderedListUpdateClear
clPutEdit ::
forall m. MonadIO m
=> OrderedListEdit (UpdateEdit updateB)
-> Readable m (ListReader (UpdateReader updateA))
-> m (Maybe [OrderedListEdit (UpdateEdit updateA)])
clPutEdit (OrderedListEditItem i editB) rd =
unComposeInner $ do
meditAs <- pe [editB] $ \ra -> MkComposeInner $ rd (ListReadItem i ra)
editAs <- liftInner meditAs
return $ fmap (OrderedListEditItem $ i) editAs
clPutEdit (OrderedListEditDelete i) _ = return $ Just $ pure $ OrderedListEditDelete $ i
clPutEdit OrderedListEditClear _ = return $ Just $ pure OrderedListEditClear
clPutEdits ::
forall m. MonadIO m
=> [OrderedListEdit (UpdateEdit updateB)]
-> Readable m (ListReader (UpdateReader updateA))
-> m (Maybe [OrderedListEdit (UpdateEdit updateA)])
clPutEdits = clPutEditsFromPutEdit clPutEdit
in MkChangeLens {..}
|
1da6f45bb2a309d019779a8783e86e5557579f9c6fe441874844756bddea6028 | lopec/LoPEC | chronicler_app.erl | %%%-------------------------------------------------------------------
@private
@author < >
( C ) 2009 , Clusterbusters
%%% @doc The logger client is responsible for all the logging in the system.
%%% @end
Created : 29 Sep 2009 by < >
%%%-------------------------------------------------------------------
-module(chronicler_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%%--------------------------------------------------------------------
%% @doc
%% This function is called whenever an application is started using
application : start/[1,2 ] , and should start the processes of the
%% application. If the application is structured according to the OTP
%% design principles as a supervision tree, this means starting the
%% top supervisor of the tree.
%%
@spec start(StartType , ) - > { ok , Pid } |
%% ignore |
%% {error, Reason}
%% StartType = normal | {takeover, Node} | {failover, Node}
= term ( )
%% @end
%%--------------------------------------------------------------------
start(_Type, _Args) ->
chronicler_sup:start_link().
%%--------------------------------------------------------------------
%% @doc
%% This function is called whenever an application has stopped. It
%% is intended to be the opposite of Module:start/2 and should do
%% any necessary cleaning up. The return value is ignored.
%%
%% @spec stop(State) -> void()
%% @end
%%--------------------------------------------------------------------
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/lopec/LoPEC/29a3989c48a60e5990615dea17bad9d24d770f7b/branches/stable-1/lib/chronicler/src/chronicler_app.erl | erlang | -------------------------------------------------------------------
@doc The logger client is responsible for all the logging in the system.
@end
-------------------------------------------------------------------
Application callbacks
--------------------------------------------------------------------
@doc
This function is called whenever an application is started using
application. If the application is structured according to the OTP
design principles as a supervision tree, this means starting the
top supervisor of the tree.
ignore |
{error, Reason}
StartType = normal | {takeover, Node} | {failover, Node}
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
This function is called whenever an application has stopped. It
is intended to be the opposite of Module:start/2 and should do
any necessary cleaning up. The return value is ignored.
@spec stop(State) -> void()
@end
-------------------------------------------------------------------- | @private
@author < >
( C ) 2009 , Clusterbusters
Created : 29 Sep 2009 by < >
-module(chronicler_app).
-behaviour(application).
-export([start/2, stop/1]).
application : start/[1,2 ] , and should start the processes of the
@spec start(StartType , ) - > { ok , Pid } |
= term ( )
start(_Type, _Args) ->
chronicler_sup:start_link().
stop(_State) ->
ok.
|
344d0a210c89c062921ad77f1f35e14aedafa0b21800f11992bb6c7e16dab9ee | luminus-framework/examples | nrepl.clj | (ns multi-client-ws-immutant.nrepl
(:require
[nrepl.server :as nrepl]
[clojure.tools.logging :as log]))
(defn start
"Start a network repl for debugging on specified port followed by
an optional parameters map. The :bind, :transport-fn, :handler,
:ack-port and :greeting-fn will be forwarded to
clojure.tools.nrepl.server/start-server as they are."
[{:keys [port bind transport-fn handler ack-port greeting-fn]}]
(try
(log/info "starting nREPL server on port" port)
(nrepl/start-server :port port
:bind bind
:transport-fn transport-fn
:handler handler
:ack-port ack-port
:greeting-fn greeting-fn)
(catch Throwable t
(log/error t "failed to start nREPL")
(throw t))))
(defn stop [server]
(nrepl/stop-server server)
(log/info "nREPL server stopped"))
| null | https://raw.githubusercontent.com/luminus-framework/examples/cbeee2fef8f457a6a6bac2cae0b640370ae2499b/multi-client-ws-immutant/src/clj/multi_client_ws_immutant/nrepl.clj | clojure | (ns multi-client-ws-immutant.nrepl
(:require
[nrepl.server :as nrepl]
[clojure.tools.logging :as log]))
(defn start
"Start a network repl for debugging on specified port followed by
an optional parameters map. The :bind, :transport-fn, :handler,
:ack-port and :greeting-fn will be forwarded to
clojure.tools.nrepl.server/start-server as they are."
[{:keys [port bind transport-fn handler ack-port greeting-fn]}]
(try
(log/info "starting nREPL server on port" port)
(nrepl/start-server :port port
:bind bind
:transport-fn transport-fn
:handler handler
:ack-port ack-port
:greeting-fn greeting-fn)
(catch Throwable t
(log/error t "failed to start nREPL")
(throw t))))
(defn stop [server]
(nrepl/stop-server server)
(log/info "nREPL server stopped"))
|
|
e69d34646aabbc8b86c552d3ce72f4a47a942ed383c7c91478bc2f8633f0ec50 | helvm/helma | FileExtra.hs | module HelVM.HelMA.Automata.WhiteSpace.FileExtra (
readWsFile,
readStnFile,
readExtFile,
buildAbsoluteWsFileName,
buildAbsoluteStnFileName,
buildAbsoluteWsIlFileName,
buildAbsoluteWsOutFileName,
buildAbsoluteWsLogFileName,
tokenTypeToExt,
showAscii,
options,
) where
import HelVM.HelMA.Automata.FileExtra
import HelVM.HelMA.Automaton.API.IOTypes
import HelVM.HelMA.Automaton.Types.TokenType
readWsFile :: FilePath -> IO Source
readWsFile = readSourceFile . buildAbsoluteWsFileName
readStnFile :: FilePath -> IO Source
readStnFile = readSourceFile . buildAbsoluteStnFileName
readExtFile :: FilePath -> FilePath -> IO Source
readExtFile ext = readSourceFile . buildAbsoluteExtFileName ext lang
buildAbsoluteWsFileName :: FilePath -> FilePath
buildAbsoluteWsFileName = buildAbsoluteExtFileName lang lang
buildAbsoluteStnFileName :: FilePath -> FilePath
buildAbsoluteStnFileName = buildAbsoluteExtFileName stn lang
buildAbsoluteWsIlFileName :: FilePath -> FilePath
buildAbsoluteWsIlFileName = buildAbsoluteIlFileName lang
buildAbsoluteWsOutFileName :: FilePath -> FilePath
buildAbsoluteWsOutFileName = buildAbsoluteOutFileName lang
buildAbsoluteWsLogFileName :: FilePath -> FilePath
buildAbsoluteWsLogFileName = buildAbsoluteLogFileName lang
tokenTypeToExt :: TokenType -> FilePath
tokenTypeToExt WhiteTokenType = lang
tokenTypeToExt VisibleTokenType = stn
stn :: FilePath
stn = "stn"
lang :: FilePath
lang = "ws"
| null | https://raw.githubusercontent.com/helvm/helma/36287506200d330cd6013a5517a8124380af5e97/hs/test/HelVM/HelMA/Automata/WhiteSpace/FileExtra.hs | haskell | module HelVM.HelMA.Automata.WhiteSpace.FileExtra (
readWsFile,
readStnFile,
readExtFile,
buildAbsoluteWsFileName,
buildAbsoluteStnFileName,
buildAbsoluteWsIlFileName,
buildAbsoluteWsOutFileName,
buildAbsoluteWsLogFileName,
tokenTypeToExt,
showAscii,
options,
) where
import HelVM.HelMA.Automata.FileExtra
import HelVM.HelMA.Automaton.API.IOTypes
import HelVM.HelMA.Automaton.Types.TokenType
readWsFile :: FilePath -> IO Source
readWsFile = readSourceFile . buildAbsoluteWsFileName
readStnFile :: FilePath -> IO Source
readStnFile = readSourceFile . buildAbsoluteStnFileName
readExtFile :: FilePath -> FilePath -> IO Source
readExtFile ext = readSourceFile . buildAbsoluteExtFileName ext lang
buildAbsoluteWsFileName :: FilePath -> FilePath
buildAbsoluteWsFileName = buildAbsoluteExtFileName lang lang
buildAbsoluteStnFileName :: FilePath -> FilePath
buildAbsoluteStnFileName = buildAbsoluteExtFileName stn lang
buildAbsoluteWsIlFileName :: FilePath -> FilePath
buildAbsoluteWsIlFileName = buildAbsoluteIlFileName lang
buildAbsoluteWsOutFileName :: FilePath -> FilePath
buildAbsoluteWsOutFileName = buildAbsoluteOutFileName lang
buildAbsoluteWsLogFileName :: FilePath -> FilePath
buildAbsoluteWsLogFileName = buildAbsoluteLogFileName lang
tokenTypeToExt :: TokenType -> FilePath
tokenTypeToExt WhiteTokenType = lang
tokenTypeToExt VisibleTokenType = stn
stn :: FilePath
stn = "stn"
lang :: FilePath
lang = "ws"
|
|
3f97a2839ebc3b6ea9ca59c00a204a356aae33c0e42b1a88979a6852e911c661 | mitsuchi/mud | Spec.hs | module Main where
import qualified Lib
import System.IO.Unsafe
import qualified Test.Framework as Test
import qualified Test.Framework.Providers.HUnit as Test
import Test.HUnit
main :: IO ()
main = do
Test.defaultMain $ Test.hUnitTestToTests $ TestList
[
"0" ~=? pe "0",
"42" ~=? pe "42",
"3" ~=? pe "1+2",
"7" ~=? pe "1+2*3",
"9" ~=? pe "(1+2)*3",
"2" ~=? pe "3-1",
"1" ~=? pe "a=1;a",
"3" ~=? pe "a=1;b=2;a+b",
"120" ~=? pe "fun fact : Int -> Int = {1->1; n->n*fact(n-1)}; fact 5",
"11" ~=? pe "fun inc : Int -> Int = n -> n + 1; 10.inc",
"3" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; add 1 2",
"3" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; 1.add 2",
"6" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; 1.add 2.add 3",
"hello" ~=? pe "'hello'",
"hello world" ~=? pe "'hello'+' world'",
"hellohellohello" ~=? pe "'hello'*3",
"3" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; fun add : String -> String -> String = x y -> x + y; 1+2",
"ab" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; fun add : String -> String -> String = x y -> x + y; 'a'+'b'",
"40" ~=? pe "fun double : Int -> Int = x -> x + x; fun twice : (Int->Int)->Int->Int = f x -> f (f x); twice (double:Int->Int) 10",
"a a a a" ~=? pe "fun double : Int -> Int = x -> x + x; fun double : String -> String = x ->x + ' ' + x; fun twice : (String->String)->String->String = f x -> f (f x); twice (double:String->String) 'a'",
"10" ~=? pe "fun id : a -> a = x -> x; id 10;",
"hoge" ~=? pe "fun id : a -> a = x -> x; id 'hoge';",
"40" ~=? pe "fun double : Int -> Int = x -> x + x; fun twice : (a->a)->a->a = f x -> f (f x); twice (double:Int->Int) 10",
"40" ~=? pe "fun double : Int -> Int = x -> x + x; fun twice : (Int->Int)->Int->Int = f x -> f (f x); twice double 10",
"10" ~=? pe "fun id : a -> a = x -> x; (id id) 10",
"aaaa" ~=? pe "fun double : a -> a = x -> x + x; fun twice : (a->a)->a->a = f x -> f (f x); twice double 'a'",
"40" ~=? pe "fun comp : (b->c) -> (a->b) -> a -> c = f g x -> f (g x); fun double : a->a = x -> x + x; comp double double 10",
"20" ~=? pe "(x->x+x:Int->Int) 10",
"aa" ~=? pe "(x->x+x:String->String) 'a'",
"40" ~=? pe "(x->x+x:a->a) 20",
"hogehoge" ~=? pe "(x->x+x:a->a) 'hoge'",
"40" ~=? pe "fun twice : (a->a)->a->a = f x -> f (f x); twice (x->x+x:a->a) 10",
"bbbb" ~=? pe "fun twice : (a->a)->a->a = f x -> f (f x); twice (x->x+x:a->a) 'b'",
"20" ~=? pe "fun apply : (a->a)->(a->a) = f -> (x -> f x : a->a); fun double:a->a = x->x+x; (apply double) 10",
"40" ~=? pe "fun twice : (a->a)->(a->a) = f -> (x -> f (f x) : a->a); fun double:a->a = x->x+x; (twice double) 10",
"1024" ~=? pe "fun ** : Int -> Int -> Int = { a 0 -> 1; a b -> (a ** (b-1)) * a }; 2 ** 10",
"3" ~=? pe "fun ** : (b->c) -> (a->b) -> (a->c) = f g -> (x -> x.g.f : a -> c); fun inc : Int -> Int = x -> x + 1; fun double : Int -> Int = x -> x * 2; (inc ** double) 1",
"5" ~=? pe "fun length : [a] -> Int = { [] -> 0; es -> 1 + length (tail es) }; length [4,5,6,7,8]",
"[2,4,6]" ~=? pe "fun map : [a] -> (a->a) -> [a] = { [] f -> []; es f -> [f (head es)] + (map (tail es) f)}; map [1,2,3] (x -> x + x : Int -> Int)",
"[4,3,2,1]" ~=? pe "fun reverse : [a] -> [a] = { [] -> []; es -> (reverse (tail es)) + [head es] }; reverse [1,2,3,4]",
"True" ~=? pe "True && True",
"False" ~=? pe "True && False",
"True" ~=? pe "True || True",
"True" ~=? pe "True || False",
"True" ~=? pe "True + True",
"False" ~=? pe "True * False",
"True" ~=? pe "1 < 2",
"False" ~=? pe "1 == 2",
"True" ~=? pe "1 == 1",
"True" ~=? pe "[1,2] == [1,2]",
"False" ~=? pe "1 > 2",
"False" ~=? pe "(1 > 2) && (3 == 3)",
"2" ~=? pe "if 1==1 then 2 else 3",
"3" ~=? pe "if 1>1 then 2 else 3",
"[1,2,3,4,5]" ~=? pe "fun select : [a] -> (a -> Bool) -> [a] = { [] f -> []; es f -> if (es.head.f) then ([es.head] + select (es.tail) f) else (select (es.tail) f) }; fun qsort : [a] -> [a] = { [] -> []; es -> es.tail.select (x -> x < es.head : a -> Bool).qsort + es.select (x -> x == es.head : a -> Bool) + es.tail.select (x -> x > es.head : a -> Bool).qsort }; qsort [3,5,1,4,2]",
"4.6" ~=? pe "1.2+3.4",
"6.8" ~=? pe "2*3.4",
"-3" ~=? pe "-3",
"-48" ~=? pe "-4*12",
"2.2" ~=? pe "fun add : Double -> Double -> Double = { x y -> x + y }; add 1.1 1.1",
"[4,3,2,1]" ~=? pe "fun reverse : [a] -> [a] = { [] -> []; [h,t] -> (reverse t) + [h] }; reverse [1,2,3,4]",
"3" ~=? pe "fun outer : a -> a = x -> { fun inner : a -> a -> a = x y -> x + y; inner 1 x }; outer 2",
"1" ~=? pe "type Complex = { r:Int, i:Int }; a = Complex 1 2; a.r",
"2" ~=? pe "type Complex = { r:Int, i:Int }; a = Complex 1 2; a.i",
"4" ~=? pe "type Complex = { r:Int, i:Int }; fun add : Complex -> Complex -> Complex = x y -> Complex (x.r+y.r) (x.i+y.i); a = Complex 1 2; b = Complex 3 4; (add a b).r",
"4" ~=? pe "type Complex = { r:Int, i:Int }; fun + : Complex -> Complex -> Complex = x y -> Complex (x.r+y.r) (x.i+y.i); a = Complex 1 2; b = Complex 3 4; (a + b).r",
"8" ~=? pe "type Complex = { r:Int, i:Int }; fun * : Complex -> Complex -> Complex = x y -> Complex (x.r*y.r) (x.i*y.i); a = Complex 1 2; b = Complex 3 4; (a * b).i",
"3" ~=? pe "type Complex = { r:Int, i:Int }; fun + : Complex -> Int -> Complex = x y -> Complex (x.r+y) (x.i); a = Complex 1 2; (a + 2).r",
"3" ~=? pe "type Complex = { r:Int, i:Int }; fun + : Int -> Complex -> Complex = y x -> Complex (x.r+y) (x.i); a = Complex 1 2; (2 + a).r",
"2" ~=? pe "type Complex = { r:Int, i:Int }; fun - : Complex -> Complex -> Complex = x y -> Complex (x.r-y.r) (x.i-y.i); a = Complex 1 2; b = Complex 3 4; (b - a).r",
"21" ~=? pe "fun * : (b->c) -> (a->b) -> (a->c) = f g -> (x -> x.g.f : a -> c); fun inc : Int -> Int = x -> x + 1; fun double : Int -> Int = x -> x * 2; (inc * double) 10",
"1:type mismatch. function '** : Int -> Int -> ?' not found" ~=? pe "1**2",
"10" ~=? pe "10.to_s",
"12.3" ~=? pe "(12.3).to_s",
"False" ~=? pe "False.to_s",
"[1,2,3]" ~=? pe "[1,2,3].to_s",
"1" ~=? pe "fun hoge : Int -> Int = x -> 1; fun hoge : a -> a = x -> x; hoge 2",
"2.0" ~=? pe "fun hoge : Int -> Int = x -> 1; fun hoge : a -> a = x -> x; hoge 2.0",
"True" ~=? pe "fun abs : Int -> Int = { a |a<0| -> -a; a -> a }; puts (abs (-3) == abs 3)",
"3" ~=? pe "(x -> x + 1) 2",
"20" ~=? pe "(x->x+x) 10",
"aa" ~=? pe "(x->x+x) 'a'",
"40" ~=? pe "(x->x+x) 20",
"40" ~=? pe "fun twice : (a->a)->a->a = f x -> f (f x); twice (x->x+x) 10",
"3" ~=? pe "fun ** : (b->c) -> (a->b) -> (a->c) = f g -> (x -> x.g.f); fun inc : Int -> Int = x -> x + 1; fun double : Int -> Int = x -> x * 2; (inc ** double) 1",
"3" ~=? pe "fun add = x y -> x + y; add 1 2",
"hoge" ~=? pe "fun add = x y -> x + y; add 'ho' 'ge'",
"6" ~=? pe "fun double = x -> x + x; double 3",
"120" ~=? pe "fun fact = {1->1; n->n*fact(n-1)}; fact 5",
"20" ~=? pe "fun double = x -> x + x; fun double : String -> String = x -> x + ' ' + x; double 10",
"hello hello" ~=? pe "fun double = x -> x + x; fun double : String -> String = x -> x + ' ' + x; double 'hello'",
"3" ~=? pe "(x -> x + 2) 1",
"3" ~=? pe "1.(x -> x + 2)",
"[4,3,2,1]" ~=? pe "fun reverse : [a] -> [a] = { [] -> []; [e;es] -> (reverse es) + [e] }; reverse [1,2,3,4]",
"1:variable 'id' already exists" ~=? pe "id = x -> x : Int -> Int; id = x -> x : Int -> Int",
"two" ~=? pe "fun inc : String -> String = { 'one' -> 'two' }; inc 'one'"
]
pe :: String -> String
pe program = unsafePerformIO (Lib.ev program)
| null | https://raw.githubusercontent.com/mitsuchi/mud/48c08a2847b6f3efcef598806682da7efca2449d/test/Spec.hs | haskell | module Main where
import qualified Lib
import System.IO.Unsafe
import qualified Test.Framework as Test
import qualified Test.Framework.Providers.HUnit as Test
import Test.HUnit
main :: IO ()
main = do
Test.defaultMain $ Test.hUnitTestToTests $ TestList
[
"0" ~=? pe "0",
"42" ~=? pe "42",
"3" ~=? pe "1+2",
"7" ~=? pe "1+2*3",
"9" ~=? pe "(1+2)*3",
"2" ~=? pe "3-1",
"1" ~=? pe "a=1;a",
"3" ~=? pe "a=1;b=2;a+b",
"120" ~=? pe "fun fact : Int -> Int = {1->1; n->n*fact(n-1)}; fact 5",
"11" ~=? pe "fun inc : Int -> Int = n -> n + 1; 10.inc",
"3" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; add 1 2",
"3" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; 1.add 2",
"6" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; 1.add 2.add 3",
"hello" ~=? pe "'hello'",
"hello world" ~=? pe "'hello'+' world'",
"hellohellohello" ~=? pe "'hello'*3",
"3" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; fun add : String -> String -> String = x y -> x + y; 1+2",
"ab" ~=? pe "fun add : Int -> Int -> Int = x y -> x + y; fun add : String -> String -> String = x y -> x + y; 'a'+'b'",
"40" ~=? pe "fun double : Int -> Int = x -> x + x; fun twice : (Int->Int)->Int->Int = f x -> f (f x); twice (double:Int->Int) 10",
"a a a a" ~=? pe "fun double : Int -> Int = x -> x + x; fun double : String -> String = x ->x + ' ' + x; fun twice : (String->String)->String->String = f x -> f (f x); twice (double:String->String) 'a'",
"10" ~=? pe "fun id : a -> a = x -> x; id 10;",
"hoge" ~=? pe "fun id : a -> a = x -> x; id 'hoge';",
"40" ~=? pe "fun double : Int -> Int = x -> x + x; fun twice : (a->a)->a->a = f x -> f (f x); twice (double:Int->Int) 10",
"40" ~=? pe "fun double : Int -> Int = x -> x + x; fun twice : (Int->Int)->Int->Int = f x -> f (f x); twice double 10",
"10" ~=? pe "fun id : a -> a = x -> x; (id id) 10",
"aaaa" ~=? pe "fun double : a -> a = x -> x + x; fun twice : (a->a)->a->a = f x -> f (f x); twice double 'a'",
"40" ~=? pe "fun comp : (b->c) -> (a->b) -> a -> c = f g x -> f (g x); fun double : a->a = x -> x + x; comp double double 10",
"20" ~=? pe "(x->x+x:Int->Int) 10",
"aa" ~=? pe "(x->x+x:String->String) 'a'",
"40" ~=? pe "(x->x+x:a->a) 20",
"hogehoge" ~=? pe "(x->x+x:a->a) 'hoge'",
"40" ~=? pe "fun twice : (a->a)->a->a = f x -> f (f x); twice (x->x+x:a->a) 10",
"bbbb" ~=? pe "fun twice : (a->a)->a->a = f x -> f (f x); twice (x->x+x:a->a) 'b'",
"20" ~=? pe "fun apply : (a->a)->(a->a) = f -> (x -> f x : a->a); fun double:a->a = x->x+x; (apply double) 10",
"40" ~=? pe "fun twice : (a->a)->(a->a) = f -> (x -> f (f x) : a->a); fun double:a->a = x->x+x; (twice double) 10",
"1024" ~=? pe "fun ** : Int -> Int -> Int = { a 0 -> 1; a b -> (a ** (b-1)) * a }; 2 ** 10",
"3" ~=? pe "fun ** : (b->c) -> (a->b) -> (a->c) = f g -> (x -> x.g.f : a -> c); fun inc : Int -> Int = x -> x + 1; fun double : Int -> Int = x -> x * 2; (inc ** double) 1",
"5" ~=? pe "fun length : [a] -> Int = { [] -> 0; es -> 1 + length (tail es) }; length [4,5,6,7,8]",
"[2,4,6]" ~=? pe "fun map : [a] -> (a->a) -> [a] = { [] f -> []; es f -> [f (head es)] + (map (tail es) f)}; map [1,2,3] (x -> x + x : Int -> Int)",
"[4,3,2,1]" ~=? pe "fun reverse : [a] -> [a] = { [] -> []; es -> (reverse (tail es)) + [head es] }; reverse [1,2,3,4]",
"True" ~=? pe "True && True",
"False" ~=? pe "True && False",
"True" ~=? pe "True || True",
"True" ~=? pe "True || False",
"True" ~=? pe "True + True",
"False" ~=? pe "True * False",
"True" ~=? pe "1 < 2",
"False" ~=? pe "1 == 2",
"True" ~=? pe "1 == 1",
"True" ~=? pe "[1,2] == [1,2]",
"False" ~=? pe "1 > 2",
"False" ~=? pe "(1 > 2) && (3 == 3)",
"2" ~=? pe "if 1==1 then 2 else 3",
"3" ~=? pe "if 1>1 then 2 else 3",
"[1,2,3,4,5]" ~=? pe "fun select : [a] -> (a -> Bool) -> [a] = { [] f -> []; es f -> if (es.head.f) then ([es.head] + select (es.tail) f) else (select (es.tail) f) }; fun qsort : [a] -> [a] = { [] -> []; es -> es.tail.select (x -> x < es.head : a -> Bool).qsort + es.select (x -> x == es.head : a -> Bool) + es.tail.select (x -> x > es.head : a -> Bool).qsort }; qsort [3,5,1,4,2]",
"4.6" ~=? pe "1.2+3.4",
"6.8" ~=? pe "2*3.4",
"-3" ~=? pe "-3",
"-48" ~=? pe "-4*12",
"2.2" ~=? pe "fun add : Double -> Double -> Double = { x y -> x + y }; add 1.1 1.1",
"[4,3,2,1]" ~=? pe "fun reverse : [a] -> [a] = { [] -> []; [h,t] -> (reverse t) + [h] }; reverse [1,2,3,4]",
"3" ~=? pe "fun outer : a -> a = x -> { fun inner : a -> a -> a = x y -> x + y; inner 1 x }; outer 2",
"1" ~=? pe "type Complex = { r:Int, i:Int }; a = Complex 1 2; a.r",
"2" ~=? pe "type Complex = { r:Int, i:Int }; a = Complex 1 2; a.i",
"4" ~=? pe "type Complex = { r:Int, i:Int }; fun add : Complex -> Complex -> Complex = x y -> Complex (x.r+y.r) (x.i+y.i); a = Complex 1 2; b = Complex 3 4; (add a b).r",
"4" ~=? pe "type Complex = { r:Int, i:Int }; fun + : Complex -> Complex -> Complex = x y -> Complex (x.r+y.r) (x.i+y.i); a = Complex 1 2; b = Complex 3 4; (a + b).r",
"8" ~=? pe "type Complex = { r:Int, i:Int }; fun * : Complex -> Complex -> Complex = x y -> Complex (x.r*y.r) (x.i*y.i); a = Complex 1 2; b = Complex 3 4; (a * b).i",
"3" ~=? pe "type Complex = { r:Int, i:Int }; fun + : Complex -> Int -> Complex = x y -> Complex (x.r+y) (x.i); a = Complex 1 2; (a + 2).r",
"3" ~=? pe "type Complex = { r:Int, i:Int }; fun + : Int -> Complex -> Complex = y x -> Complex (x.r+y) (x.i); a = Complex 1 2; (2 + a).r",
"2" ~=? pe "type Complex = { r:Int, i:Int }; fun - : Complex -> Complex -> Complex = x y -> Complex (x.r-y.r) (x.i-y.i); a = Complex 1 2; b = Complex 3 4; (b - a).r",
"21" ~=? pe "fun * : (b->c) -> (a->b) -> (a->c) = f g -> (x -> x.g.f : a -> c); fun inc : Int -> Int = x -> x + 1; fun double : Int -> Int = x -> x * 2; (inc * double) 10",
"1:type mismatch. function '** : Int -> Int -> ?' not found" ~=? pe "1**2",
"10" ~=? pe "10.to_s",
"12.3" ~=? pe "(12.3).to_s",
"False" ~=? pe "False.to_s",
"[1,2,3]" ~=? pe "[1,2,3].to_s",
"1" ~=? pe "fun hoge : Int -> Int = x -> 1; fun hoge : a -> a = x -> x; hoge 2",
"2.0" ~=? pe "fun hoge : Int -> Int = x -> 1; fun hoge : a -> a = x -> x; hoge 2.0",
"True" ~=? pe "fun abs : Int -> Int = { a |a<0| -> -a; a -> a }; puts (abs (-3) == abs 3)",
"3" ~=? pe "(x -> x + 1) 2",
"20" ~=? pe "(x->x+x) 10",
"aa" ~=? pe "(x->x+x) 'a'",
"40" ~=? pe "(x->x+x) 20",
"40" ~=? pe "fun twice : (a->a)->a->a = f x -> f (f x); twice (x->x+x) 10",
"3" ~=? pe "fun ** : (b->c) -> (a->b) -> (a->c) = f g -> (x -> x.g.f); fun inc : Int -> Int = x -> x + 1; fun double : Int -> Int = x -> x * 2; (inc ** double) 1",
"3" ~=? pe "fun add = x y -> x + y; add 1 2",
"hoge" ~=? pe "fun add = x y -> x + y; add 'ho' 'ge'",
"6" ~=? pe "fun double = x -> x + x; double 3",
"120" ~=? pe "fun fact = {1->1; n->n*fact(n-1)}; fact 5",
"20" ~=? pe "fun double = x -> x + x; fun double : String -> String = x -> x + ' ' + x; double 10",
"hello hello" ~=? pe "fun double = x -> x + x; fun double : String -> String = x -> x + ' ' + x; double 'hello'",
"3" ~=? pe "(x -> x + 2) 1",
"3" ~=? pe "1.(x -> x + 2)",
"[4,3,2,1]" ~=? pe "fun reverse : [a] -> [a] = { [] -> []; [e;es] -> (reverse es) + [e] }; reverse [1,2,3,4]",
"1:variable 'id' already exists" ~=? pe "id = x -> x : Int -> Int; id = x -> x : Int -> Int",
"two" ~=? pe "fun inc : String -> String = { 'one' -> 'two' }; inc 'one'"
]
pe :: String -> String
pe program = unsafePerformIO (Lib.ev program)
|
|
89ed142108c312e7ce7ca66461b22279265d73c20173447d8df0f4d3cb7dbf93 | nomeata/arbtt | TimeLog.hs | # LANGUAGE CPP #
# LANGUAGE PatternGuards #
module TimeLog where
import Data
import Control.Applicative
import System.IO
import Control.Concurrent
import Control.Monad
import Data.Time
import Data.Binary
import Data.Binary.StringRef
import Data.Binary.Get
import Data.Function
import Data.Char
import System.Directory
import Control.DeepSeq
#ifndef mingw32_HOST_OS
import System.Posix.Files
#endif
import System.IO.Unsafe (unsafeInterleaveIO)
import qualified Data.ByteString.Lazy as BS
import Data.Maybe
magic = BS.pack $ map (fromIntegral.ord) "arbtt-timelog-v1\n"
mkTimeLogEntry :: Integer -> a -> IO (TimeLogEntry a)
mkTimeLogEntry delay entry = do
date <- getCurrentTime
return $ TimeLogEntry date delay entry
-- | Runs the given action each delay milliseconds and appends the TimeLog to the
-- given file.
runLogger :: ListOfStringable a => FilePath -> Integer -> IO a -> IO ()
runLogger filename delay action = flip fix Nothing $ \loop prev -> do
entry <- action
tle <- mkTimeLogEntry delay entry
createTimeLog False filename
#ifndef mingw32_HOST_OS
setFileMode filename (ownerReadMode `unionFileModes` ownerWriteMode)
#endif
appendTimeLog filename prev tle
threadDelay (fromIntegral delay * 1000)
loop (Just entry)
createTimeLog :: Bool -> FilePath -> IO ()
createTimeLog force filename = do
ex <- doesFileExist filename
when (not ex || force) $ BS.writeFile filename magic
appendTimeLog :: ListOfStringable a => FilePath -> Maybe a -> TimeLogEntry a -> IO ()
appendTimeLog filename prev = BS.appendFile filename . ls_encode strs
where strs = maybe [] listOfStrings prev
writeTimeLog :: ListOfStringable a => FilePath -> TimeLog a -> IO ()
writeTimeLog filename tl = do
createTimeLog True filename
foldM_ go Nothing tl
where go prev v = do appendTimeLog filename prev v
return (Just (tlData v))
-- | This might be very bad style, and it hogs memory, but it might help in some situations...
-- Use of unsafeInterleaveIO should be replaced by conduit, pipe or something the like
recoverTimeLog :: ListOfStringable a => FilePath -> IO (TimeLog a)
recoverTimeLog filename = do
content <- BS.readFile filename
start content
where start content = case runGetOrFail (getLazyByteString (BS.length magic)) content of
Right (rest, off, startString)
| startString /= magic -> do
putStrLn $ "WARNING: Timelog starts with unknown marker " ++
show (map (chr.fromIntegral) (BS.unpack startString))
go Nothing rest off
| otherwise -> do
putStrLn $ "Found header, continuing... (" ++ show (BS.length rest) ++ " bytes to go)"
go Nothing rest off
Left _ -> do
putStrLn $ "WARNING: Timelog file shorter than a header marker"
return []
go prev input off = do
mb <- trySkip prev input off off
flip (maybe (return [])) mb $ \(v,rest,off') ->
if BS.null rest
then return [v]
else (v:) <$> (unsafeInterleaveIO $ go (Just (tlData v)) rest off')
trySkip prev input off orig_off
| Just i <- BS.findIndex validTimeLogEntryTag input = do
when (i > 0) $ do
putStrLn $ "At position " ++ show off ++ " skipping " ++ show i ++ " bytes to next valid TimeLogEntry tag"
tryGet prev (BS.drop i input) (off + i) orig_off
| otherwise = do
putStrLn "No valid TimeLogEntry tag bytes remaining"
return Nothing
tryGet prev input off orig_off = case runGetOrFail (ls_get strs) input of
Right (rest, off', v) -> do
when (off /= orig_off) $
putStrLn $ "Skipped from " ++ show orig_off ++ ", succesful read at position " ++ show off ++ ", lost " ++ show (off - orig_off) ++ " bytes."
return (Just (v, rest, off + off'))
Left (_, _, e) -> do
putStrLn $ "Failed to read value at position " ++ show off ++ ":"
putStrLn $ " " ++ e
if BS.length input <= 1
then do putStrLn $ "End of file reached"
return Nothing
else do trySkip prev (BS.tail input) (off+1) orig_off
where strs = maybe [] listOfStrings prev
readTimeLog :: (NFData a, ListOfStringable a) => FilePath -> IO (TimeLog a)
readTimeLog filename = do
content <- BS.readFile filename
return $ parseTimeLog content
parseTimeLog :: (NFData a, ListOfStringable a) => BS.ByteString -> TimeLog a
parseTimeLog input =
if startString == magic
then go Nothing rest off
else error $
"Timelog starts with unknown marker " ++
show (map (chr.fromIntegral) (BS.unpack startString))
where
(startString, rest, off) = case runGetOrFail (getLazyByteString (BS.length magic)) input of
Right (rest, off, x) -> (x, rest, off)
Left (_, off, e) -> error $ "Timelog parse error at " ++ show off ++ ": " ++ e
go prev input off
| BS.null input = []
| otherwise = case runGetOrFail (ls_get strs) input of
Right (rest, off', v) ->
v `deepseq` v : go (Just (tlData v)) rest (off + off')
Left (_, off', e) ->
error $ "Timelog parse error at " ++ show (off + off') ++ ": " ++ e
where strs = maybe [] listOfStrings prev
| null | https://raw.githubusercontent.com/nomeata/arbtt/85437e00de45db38c8778cb13d778ff20c0ecc54/src/TimeLog.hs | haskell | | Runs the given action each delay milliseconds and appends the TimeLog to the
given file.
| This might be very bad style, and it hogs memory, but it might help in some situations...
Use of unsafeInterleaveIO should be replaced by conduit, pipe or something the like | # LANGUAGE CPP #
# LANGUAGE PatternGuards #
module TimeLog where
import Data
import Control.Applicative
import System.IO
import Control.Concurrent
import Control.Monad
import Data.Time
import Data.Binary
import Data.Binary.StringRef
import Data.Binary.Get
import Data.Function
import Data.Char
import System.Directory
import Control.DeepSeq
#ifndef mingw32_HOST_OS
import System.Posix.Files
#endif
import System.IO.Unsafe (unsafeInterleaveIO)
import qualified Data.ByteString.Lazy as BS
import Data.Maybe
magic = BS.pack $ map (fromIntegral.ord) "arbtt-timelog-v1\n"
mkTimeLogEntry :: Integer -> a -> IO (TimeLogEntry a)
mkTimeLogEntry delay entry = do
date <- getCurrentTime
return $ TimeLogEntry date delay entry
runLogger :: ListOfStringable a => FilePath -> Integer -> IO a -> IO ()
runLogger filename delay action = flip fix Nothing $ \loop prev -> do
entry <- action
tle <- mkTimeLogEntry delay entry
createTimeLog False filename
#ifndef mingw32_HOST_OS
setFileMode filename (ownerReadMode `unionFileModes` ownerWriteMode)
#endif
appendTimeLog filename prev tle
threadDelay (fromIntegral delay * 1000)
loop (Just entry)
createTimeLog :: Bool -> FilePath -> IO ()
createTimeLog force filename = do
ex <- doesFileExist filename
when (not ex || force) $ BS.writeFile filename magic
appendTimeLog :: ListOfStringable a => FilePath -> Maybe a -> TimeLogEntry a -> IO ()
appendTimeLog filename prev = BS.appendFile filename . ls_encode strs
where strs = maybe [] listOfStrings prev
writeTimeLog :: ListOfStringable a => FilePath -> TimeLog a -> IO ()
writeTimeLog filename tl = do
createTimeLog True filename
foldM_ go Nothing tl
where go prev v = do appendTimeLog filename prev v
return (Just (tlData v))
recoverTimeLog :: ListOfStringable a => FilePath -> IO (TimeLog a)
recoverTimeLog filename = do
content <- BS.readFile filename
start content
where start content = case runGetOrFail (getLazyByteString (BS.length magic)) content of
Right (rest, off, startString)
| startString /= magic -> do
putStrLn $ "WARNING: Timelog starts with unknown marker " ++
show (map (chr.fromIntegral) (BS.unpack startString))
go Nothing rest off
| otherwise -> do
putStrLn $ "Found header, continuing... (" ++ show (BS.length rest) ++ " bytes to go)"
go Nothing rest off
Left _ -> do
putStrLn $ "WARNING: Timelog file shorter than a header marker"
return []
go prev input off = do
mb <- trySkip prev input off off
flip (maybe (return [])) mb $ \(v,rest,off') ->
if BS.null rest
then return [v]
else (v:) <$> (unsafeInterleaveIO $ go (Just (tlData v)) rest off')
trySkip prev input off orig_off
| Just i <- BS.findIndex validTimeLogEntryTag input = do
when (i > 0) $ do
putStrLn $ "At position " ++ show off ++ " skipping " ++ show i ++ " bytes to next valid TimeLogEntry tag"
tryGet prev (BS.drop i input) (off + i) orig_off
| otherwise = do
putStrLn "No valid TimeLogEntry tag bytes remaining"
return Nothing
tryGet prev input off orig_off = case runGetOrFail (ls_get strs) input of
Right (rest, off', v) -> do
when (off /= orig_off) $
putStrLn $ "Skipped from " ++ show orig_off ++ ", succesful read at position " ++ show off ++ ", lost " ++ show (off - orig_off) ++ " bytes."
return (Just (v, rest, off + off'))
Left (_, _, e) -> do
putStrLn $ "Failed to read value at position " ++ show off ++ ":"
putStrLn $ " " ++ e
if BS.length input <= 1
then do putStrLn $ "End of file reached"
return Nothing
else do trySkip prev (BS.tail input) (off+1) orig_off
where strs = maybe [] listOfStrings prev
readTimeLog :: (NFData a, ListOfStringable a) => FilePath -> IO (TimeLog a)
readTimeLog filename = do
content <- BS.readFile filename
return $ parseTimeLog content
parseTimeLog :: (NFData a, ListOfStringable a) => BS.ByteString -> TimeLog a
parseTimeLog input =
if startString == magic
then go Nothing rest off
else error $
"Timelog starts with unknown marker " ++
show (map (chr.fromIntegral) (BS.unpack startString))
where
(startString, rest, off) = case runGetOrFail (getLazyByteString (BS.length magic)) input of
Right (rest, off, x) -> (x, rest, off)
Left (_, off, e) -> error $ "Timelog parse error at " ++ show off ++ ": " ++ e
go prev input off
| BS.null input = []
| otherwise = case runGetOrFail (ls_get strs) input of
Right (rest, off', v) ->
v `deepseq` v : go (Just (tlData v)) rest (off + off')
Left (_, off', e) ->
error $ "Timelog parse error at " ++ show (off + off') ++ ": " ++ e
where strs = maybe [] listOfStrings prev
|
2583a2c00e88ffb3700148cf8f1728786a42157c428c338c4d14ec3ed19b11a0 | rwmjones/guestfs-tools | setlocale.ml | virt - builder
* Copyright ( C ) 2014 Red Hat Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License along
* with this program ; if not , write to the Free Software Foundation , Inc. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2014 Red Hat Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
type localecategory =
| LC_ALL
| LC_CTYPE
| LC_NUMERIC
| LC_TIME
| LC_COLLATE
| LC_MONETARY
| LC_MESSAGES
;;
external setlocale : localecategory -> string option -> string option =
"virt_builder_setlocale"
| null | https://raw.githubusercontent.com/rwmjones/guestfs-tools/57423d907270526ea664ff15601cce956353820e/builder/setlocale.ml | ocaml | virt - builder
* Copyright ( C ) 2014 Red Hat Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation ; either version 2 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License along
* with this program ; if not , write to the Free Software Foundation , Inc. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2014 Red Hat Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
type localecategory =
| LC_ALL
| LC_CTYPE
| LC_NUMERIC
| LC_TIME
| LC_COLLATE
| LC_MONETARY
| LC_MESSAGES
;;
external setlocale : localecategory -> string option -> string option =
"virt_builder_setlocale"
|
|
45f47d488992ea89441754b55c90e77fbd66d7d7269d3cbd730231baa03fcad3 | thelema/ocaml-community | hello.ml | (***********************************************************************)
(* *)
MLTk , Tcl / Tk interface of OCaml
(* *)
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
(* described in file LICENSE found in the OCaml source tree. *)
(* *)
(***********************************************************************)
$ Id$
LablTk4 Demonstration by JPF
First , open this modules for convenience
open Tk
(* initialization of Tk --- the result is a toplevel widget *)
let top = openTk ()
(* create a button on top *)
Button.create : use of create function defined in button.ml
(* But you shouldn't open Button module for other widget class modules use *)
let b = Button.create ~text: "Hello, LablTk!" top
(* Lack of toplevel expressions in lsl, you must use dummy let exp. *)
let _ = pack [coe b]
(* Last, you must call mainLoop *)
(* You can write just let _ = mainLoop () *)
(* But Printexc.print will help you *)
let _ = Printexc.print mainLoop ()
| null | https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/otherlibs/labltk/examples_labltk/hello.ml | ocaml | *********************************************************************
described in file LICENSE found in the OCaml source tree.
*********************************************************************
initialization of Tk --- the result is a toplevel widget
create a button on top
But you shouldn't open Button module for other widget class modules use
Lack of toplevel expressions in lsl, you must use dummy let exp.
Last, you must call mainLoop
You can write just let _ = mainLoop ()
But Printexc.print will help you | MLTk , Tcl / Tk interface of OCaml
, , and
projet Cristal , INRIA Rocquencourt
, Kyoto University RIMS
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
General Public License , with the special exception on linking
$ Id$
LablTk4 Demonstration by JPF
First , open this modules for convenience
open Tk
let top = openTk ()
Button.create : use of create function defined in button.ml
let b = Button.create ~text: "Hello, LablTk!" top
let _ = pack [coe b]
let _ = Printexc.print mainLoop ()
|
6f369cebb78fa34294453d135b8837ca546f74641d10f9da743d85230a073921 | ninjudd/cake | bar.clj | (ns bar
(:refer-clojure :exclude [inc]))
(defn foo []
(println "this is a bar, FOO!"))
(defn bar []
8)
(defn bar-inc [n]
(+ 2 n)) | null | https://raw.githubusercontent.com/ninjudd/cake/3a1627120b74e425ab21aa4d1b263be09e945cfd/examples/test/src/bar.clj | clojure | (ns bar
(:refer-clojure :exclude [inc]))
(defn foo []
(println "this is a bar, FOO!"))
(defn bar []
8)
(defn bar-inc [n]
(+ 2 n)) |
|
1904065d20c07927107e5d0264fc7c6cb9ed6d5ad3ffe598359a0f66e62000ac | jeromesimeon/Galax | alg_stream_project.ml | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : alg_stream_project.ml , v 1.2 2007/02/01 22:08:52 simeon Exp $
(* Module: Alg_stream_project
Description:
This module implements document projection on an XML stream.
*)
open Error
open Streaming_types
open Streaming_util
open Streaming_ops
open Ast_path_struct
open Alg_path_structutil
open Alg_project_context
(* Projects attributes *)
let project_attributes other_atts pfs' =
List.filter (one_step_attribute pfs') other_atts
let rec project_next_projection pfs project_context =
(* Get the next event *)
let xml_event = get_next_xml_event project_context in
(* And refill the buffer accordingly *)
match xml_event.se_desc with
| SAX_startDocument _ ->
raise (Query (Projection ("Should not have a start document event")))
| SAX_endDocument ->
pop_project_context project_context [xml_event]
| SAX_startElement (name, attributes, has_element_content, special, baseuri, relem, telem) ->
(* Identify which kind of action is required based on the path structure *)
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree ->
SUBTREE ACTION --
In the case the required action is to return the whole
subtree , flip to non - projection parsing using None in
the path structure stack . -
In the case the required action is to return the whole
subtree, flip to non-projection parsing using None in
the path structure stack. - Jerome *)
push_project_context_get_subtree project_context xml_event
| KeepMovingSkipNode pfs' ->
KEEP MOVING SKIP NODE ACTION --
In that case , we keep talking down the tree until we
can decide whether we should return the node or not . -
In that case, we keep talking down the tree until we
can decide whether we should return the node or not. - Jerome *)
(* Extract the namespace attributes and update the
namespace environment accordingly. *)
let projected_attributes = project_attributes attributes pfs' in
let new_xml_event = fmkse_event (SAX_startElement (name, projected_attributes, has_element_content, special, baseuri, relem, telem)) xml_event.se_loc in
if (projected_attributes = []) then
begin
push_project_context_keep_moving_skip_node
project_context
new_xml_event
pfs'
end
else
begin
push_project_context_keep_moving_preserve_node
project_context
new_xml_event
pfs'
end
| KeepMovingPreserveNode pfs' ->
KEEP MOVING PRESERVE NODE ACTION --
In that case , we return the current event and keep
talking down the tree . -
In that case, we return the current event and keep
talking down the tree. - Jerome *)
let projected_attributes = project_attributes attributes pfs' in
let new_xml_event = fmkse_event (SAX_startElement (name, projected_attributes, has_element_content, special, baseuri, relem, telem)) xml_event.se_loc in
begin
push_project_context_keep_moving_preserve_node
project_context
new_xml_event
pfs'
end
| PreserveNode ->
PRESERVE NODE ACTION --
In that case , discard the XML stream for the subtree ,
but keep the events for the current node . -
In that case, discard the XML stream for the subtree,
but keep the events for the current node. - Jerome *)
let refill_local_buffer = [
fmkse_event (SAX_startElement (name, attributes, has_element_content, special, baseuri, relem, telem)) xml_event.se_loc;
fmkse_event (SAX_endElement) xml_event.se_loc
]
in
push_project_context_preserve_node project_context refill_local_buffer
| SkipNode ->
SKIP NODE ACTION --
In that case , discard the XML stream . -
In that case, discard the XML stream. - Jerome *)
(* Extract the namespace attributes and update the
namespace environment accordingly. *)
push_project_context_skip_node project_context
end
| SAX_endElement ->
pop_project_context project_context [xml_event]
| SAX_processingInstruction (target,content) ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_comment c ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_characters _ ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_attribute a ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_atomicValue _ ->
(* A path expression never applies to an atomic value *)
project_next_projection pfs project_context
| SAX_hole ->
raise (Query (Projection "Should not apply projection operation on a stream with holes!"))
| SAX_startEncl
| SAX_endEncl ->
raise (Query (Projection "Should not apply projection operation on a stream with enclosed expressions!"))
let rec project_next_get_subtree project_context =
(* Get the next event *)
let xml_event = get_next_xml_event project_context in
match xml_event.se_desc with
| SAX_startDocument _
| SAX_startElement _ ->
push_project_context_get_subtree project_context xml_event
| SAX_endDocument
| SAX_endElement ->
pop_project_context project_context [xml_event]
| SAX_processingInstruction _
| SAX_comment _
| SAX_characters _
| SAX_attribute _
| SAX_atomicValue _ ->
refill_local_buffer project_context [xml_event]
| SAX_hole ->
raise (Query (Projection "Should not apply projection operation on a stream with holes!"))
| SAX_startEncl
| SAX_endEncl ->
raise (Query (Projection "Should not apply projection operation on a stream with enclosed expressions!"))
let rec project_next project_context =
(* Check wether stream is exhausted _before_ the context is queried
for projection paths.
- Michael *)
begin
if
project_stream_is_empty project_context
then
raise Stream.Failure
else
()
end;
let pfs = get_pfs project_context in
match pfs with
| None ->
project_next_get_subtree project_context
| Some pfs ->
(* Treat empty paths with subtree flag the same way as no paths at all.
Check tail recursion!
- Michael *)
let rec all_paths_empty_with_subtrees paths =
match paths with
| [] -> true
| (path, subtree) :: rest ->
let rest_empty = all_paths_empty_with_subtrees rest in
(path = []) && (subtree = Subtree) && rest_empty
in
if all_paths_empty_with_subtrees pfs
then
project_next_get_subtree project_context
else
(* previous version *)
project_next_projection pfs project_context
(* Stream wrapping function *)
let rec next_project_event_internal project_context =
match get_next_buffered_sax_event project_context with
| None ->
begin
project_next project_context;
next_project_event_internal project_context
end
| Some event ->
Some event
let next_project_event project_context n =
next_project_event_internal project_context
(* Top level stream operation *)
let project_xml_stream_from_document root_uri path_seq xml_stream =
let first_event = Cursor.cursor_next xml_stream in
begin
match first_event.se_desc with
| SAX_startDocument _ ->
()
| _ ->
raise (Query (Projection ("Was expecting a start document event")))
end;
let pfs = inside_document first_event path_seq (AnyURI._string_of_uri root_uri) in
let project_context =
build_project_context xml_stream pfs [first_event]
in
(Cursor.cursor_of_function (next_project_event project_context))
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/projection/alg_stream_project.ml | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Module: Alg_stream_project
Description:
This module implements document projection on an XML stream.
Projects attributes
Get the next event
And refill the buffer accordingly
Identify which kind of action is required based on the path structure
Extract the namespace attributes and update the
namespace environment accordingly.
Extract the namespace attributes and update the
namespace environment accordingly.
A path expression never applies to an atomic value
Get the next event
Check wether stream is exhausted _before_ the context is queried
for projection paths.
- Michael
Treat empty paths with subtree flag the same way as no paths at all.
Check tail recursion!
- Michael
previous version
Stream wrapping function
Top level stream operation | Copyright 2001 - 2007 .
$ I d : alg_stream_project.ml , v 1.2 2007/02/01 22:08:52 simeon Exp $
open Error
open Streaming_types
open Streaming_util
open Streaming_ops
open Ast_path_struct
open Alg_path_structutil
open Alg_project_context
let project_attributes other_atts pfs' =
List.filter (one_step_attribute pfs') other_atts
let rec project_next_projection pfs project_context =
let xml_event = get_next_xml_event project_context in
match xml_event.se_desc with
| SAX_startDocument _ ->
raise (Query (Projection ("Should not have a start document event")))
| SAX_endDocument ->
pop_project_context project_context [xml_event]
| SAX_startElement (name, attributes, has_element_content, special, baseuri, relem, telem) ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree ->
SUBTREE ACTION --
In the case the required action is to return the whole
subtree , flip to non - projection parsing using None in
the path structure stack . -
In the case the required action is to return the whole
subtree, flip to non-projection parsing using None in
the path structure stack. - Jerome *)
push_project_context_get_subtree project_context xml_event
| KeepMovingSkipNode pfs' ->
KEEP MOVING SKIP NODE ACTION --
In that case , we keep talking down the tree until we
can decide whether we should return the node or not . -
In that case, we keep talking down the tree until we
can decide whether we should return the node or not. - Jerome *)
let projected_attributes = project_attributes attributes pfs' in
let new_xml_event = fmkse_event (SAX_startElement (name, projected_attributes, has_element_content, special, baseuri, relem, telem)) xml_event.se_loc in
if (projected_attributes = []) then
begin
push_project_context_keep_moving_skip_node
project_context
new_xml_event
pfs'
end
else
begin
push_project_context_keep_moving_preserve_node
project_context
new_xml_event
pfs'
end
| KeepMovingPreserveNode pfs' ->
KEEP MOVING PRESERVE NODE ACTION --
In that case , we return the current event and keep
talking down the tree . -
In that case, we return the current event and keep
talking down the tree. - Jerome *)
let projected_attributes = project_attributes attributes pfs' in
let new_xml_event = fmkse_event (SAX_startElement (name, projected_attributes, has_element_content, special, baseuri, relem, telem)) xml_event.se_loc in
begin
push_project_context_keep_moving_preserve_node
project_context
new_xml_event
pfs'
end
| PreserveNode ->
PRESERVE NODE ACTION --
In that case , discard the XML stream for the subtree ,
but keep the events for the current node . -
In that case, discard the XML stream for the subtree,
but keep the events for the current node. - Jerome *)
let refill_local_buffer = [
fmkse_event (SAX_startElement (name, attributes, has_element_content, special, baseuri, relem, telem)) xml_event.se_loc;
fmkse_event (SAX_endElement) xml_event.se_loc
]
in
push_project_context_preserve_node project_context refill_local_buffer
| SkipNode ->
SKIP NODE ACTION --
In that case , discard the XML stream . -
In that case, discard the XML stream. - Jerome *)
push_project_context_skip_node project_context
end
| SAX_endElement ->
pop_project_context project_context [xml_event]
| SAX_processingInstruction (target,content) ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_comment c ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_characters _ ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_attribute a ->
let action = one_step xml_event pfs in
begin
match action with
| GetSubtree
| KeepMovingPreserveNode _
| PreserveNode ->
refill_local_buffer project_context [xml_event]
| KeepMovingSkipNode _
| SkipNode ->
project_next_projection pfs project_context
end
| SAX_atomicValue _ ->
project_next_projection pfs project_context
| SAX_hole ->
raise (Query (Projection "Should not apply projection operation on a stream with holes!"))
| SAX_startEncl
| SAX_endEncl ->
raise (Query (Projection "Should not apply projection operation on a stream with enclosed expressions!"))
let rec project_next_get_subtree project_context =
let xml_event = get_next_xml_event project_context in
match xml_event.se_desc with
| SAX_startDocument _
| SAX_startElement _ ->
push_project_context_get_subtree project_context xml_event
| SAX_endDocument
| SAX_endElement ->
pop_project_context project_context [xml_event]
| SAX_processingInstruction _
| SAX_comment _
| SAX_characters _
| SAX_attribute _
| SAX_atomicValue _ ->
refill_local_buffer project_context [xml_event]
| SAX_hole ->
raise (Query (Projection "Should not apply projection operation on a stream with holes!"))
| SAX_startEncl
| SAX_endEncl ->
raise (Query (Projection "Should not apply projection operation on a stream with enclosed expressions!"))
let rec project_next project_context =
begin
if
project_stream_is_empty project_context
then
raise Stream.Failure
else
()
end;
let pfs = get_pfs project_context in
match pfs with
| None ->
project_next_get_subtree project_context
| Some pfs ->
let rec all_paths_empty_with_subtrees paths =
match paths with
| [] -> true
| (path, subtree) :: rest ->
let rest_empty = all_paths_empty_with_subtrees rest in
(path = []) && (subtree = Subtree) && rest_empty
in
if all_paths_empty_with_subtrees pfs
then
project_next_get_subtree project_context
else
project_next_projection pfs project_context
let rec next_project_event_internal project_context =
match get_next_buffered_sax_event project_context with
| None ->
begin
project_next project_context;
next_project_event_internal project_context
end
| Some event ->
Some event
let next_project_event project_context n =
next_project_event_internal project_context
let project_xml_stream_from_document root_uri path_seq xml_stream =
let first_event = Cursor.cursor_next xml_stream in
begin
match first_event.se_desc with
| SAX_startDocument _ ->
()
| _ ->
raise (Query (Projection ("Was expecting a start document event")))
end;
let pfs = inside_document first_event path_seq (AnyURI._string_of_uri root_uri) in
let project_context =
build_project_context xml_stream pfs [first_event]
in
(Cursor.cursor_of_function (next_project_event project_context))
|
910005b4d46d7c3223440354debe442b1f7d84e451ee85b9f4a76b57577a8413 | swtwsk/vinci-lang | DList.hs | # LANGUAGE FlexibleContexts #
module Utils.DList (output) where
import Control.Monad.Writer (MonadWriter, tell)
import Data.DList (DList, singleton)
output :: (Monad m, MonadWriter (DList a) m) => a -> m ()
output = tell . singleton
| null | https://raw.githubusercontent.com/swtwsk/vinci-lang/9c7e01953e0b1cf135af7188e0c71fe6195bdfa1/src/Utils/DList.hs | haskell | # LANGUAGE FlexibleContexts #
module Utils.DList (output) where
import Control.Monad.Writer (MonadWriter, tell)
import Data.DList (DList, singleton)
output :: (Monad m, MonadWriter (DList a) m) => a -> m ()
output = tell . singleton
|
|
add32bddec6e897cb66e43e3d1dc80ed54a3e5231629fa005e9c380ed2860d6b | Naproche-SAD/Naproche-SAD | Main.hs |
Authors : ( 2001 - 2008 ) , ( 2017 - 2018 ) , ( 2018 )
Main application entry point : console or server mode .
Authors: Andrei Paskevich (2001 - 2008), Steffen Frerix (2017 - 2018), Makarius Wenzel (2018)
Main application entry point: console or server mode.
-}
# LANGUAGE TupleSections #
# LANGUAGE LambdaCase #
module Main where
import Data.Maybe
import Data.IORef
import Data.Time
import Control.Monad (when, unless)
import qualified System.Console.GetOpt as GetOpt
import qualified System.Environment as Environment
import qualified System.Exit as Exit
import qualified Control.Exception as Exception
import System.IO (IO)
import qualified System.IO as IO
import Isabelle.Library
import qualified Isabelle.File as File
import qualified Isabelle.Server as Server
import qualified Isabelle.Byte_Message as Byte_Message
import qualified Isabelle.Properties as Properties
import qualified Isabelle.XML as XML
import qualified Isabelle.YXML as YXML
import qualified Isabelle.UUID as UUID
import qualified Isabelle.Standard_Thread as Standard_Thread
import qualified Isabelle.Naproche as Naproche
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.ByteString.Char8 as Char8
import qualified Data.ByteString as ByteString
import Network.Socket (Socket)
import SAD.Core.Base
import qualified SAD.Core.Message as Message
import SAD.Core.SourcePos
import SAD.Core.Verify
import SAD.Data.Instr (Instr)
import qualified SAD.Data.Instr as Instr
import SAD.Data.Text.Block
import SAD.Export.Base
import SAD.Import.Reader
import SAD.Parser.Error
main :: IO ()
main = do
setup stdin / stdout
File.setup IO.stdin
File.setup IO.stdout
File.setup IO.stderr
IO.hSetBuffering IO.stdout IO.LineBuffering
IO.hSetBuffering IO.stderr IO.LineBuffering
-- command line and init file
args0 <- Environment.getArgs
(opts0, text0) <- readArgs args0
oldTextRef <- newIORef $ TextRoot []
if Instr.askBool Instr.Help False opts0 then
putStr (GetOpt.usageInfo usageHeader options)
else -- main body with explicit error handling, notably for PIDE
Exception.catch
(if Instr.askBool Instr.Server False opts0 then
Server.server (Server.publish_stdout "Naproche-SAD") (serverConnection oldTextRef args0)
else do Message.consoleThread; mainBody oldTextRef (opts0, text0))
(\err -> do
Message.exitThread
let msg = Exception.displayException (err :: Exception.SomeException)
IO.hPutStrLn IO.stderr msg
Exit.exitFailure)
mainBody :: IORef Text -> ([Instr], [Text]) -> IO ()
mainBody oldTextRef (opts0, text0) = do
startTime <- getCurrentTime
oldText <- readIORef oldTextRef
-- parse input text
text1 <- fmap TextRoot $ readText (Instr.askString Instr.Library "." opts0) text0
-- if -T / --onlytranslate is passed as an option, only print the translated text
if Instr.askBool Instr.OnlyTranslate False opts0 then
do
let timeDifference finishTime = showTimeDiff (diffUTCTime finishTime startTime)
TextRoot txts = text1
mapM_ (\case TextBlock bl -> print bl; _ -> return ()) txts
-- print statistics
finishTime <- getCurrentTime
Message.outputMain Message.TRACING noPos $ "total " ++ timeDifference finishTime
else
do
-- read provers.dat
provers <- readProverDatabase (Instr.askString Instr.Provers "provers.dat" opts0)
-- initialize reasoner state
reasonerState <- newIORef (RState [] False False)
proveStart <- getCurrentTime
case findParseError text1 of
Nothing -> do
let text = textToCheck oldText text1
newText <- verify (Instr.askString Instr.File "" opts0) provers reasonerState text
case newText of
Just txt -> writeIORef oldTextRef txt
_ -> return ()
Just err -> Message.errorParser (errorPos err) (show err)
finishTime <- getCurrentTime
finalReasonerState <- readIORef reasonerState
let counterList = counters finalReasonerState
accumulate = accumulateIntCounter counterList 0
-- print statistics
Message.outputMain Message.TRACING noPos $
"sections " ++ show (accumulate Sections)
++ " - goals " ++ show (accumulate Goals)
++ (let ignoredFails = accumulate FailedGoals
in if ignoredFails == 0
then ""
else " - failed " ++ show ignoredFails)
++ " - trivial " ++ show (accumulate TrivialGoals)
++ " - proved " ++ show (accumulate SuccessfulGoals)
++ " - equations " ++ show (accumulate Equations)
++ (let failedEquations = accumulate FailedEquations
in if failedEquations == 0
then ""
else " - failed " ++ show failedEquations)
let trivialChecks = accumulate TrivialChecks
Message.outputMain Message.TRACING noPos $
"symbols " ++ show (accumulate Symbols)
++ " - checks " ++ show
(accumulateIntCounter counterList trivialChecks HardChecks)
++ " - trivial " ++ show trivialChecks
++ " - proved " ++ show (accumulate SuccessfulChecks)
++ " - unfolds " ++ show (accumulate Unfolds)
let accumulateTime = accumulateTimeCounter counterList
proverTime = accumulateTime proveStart ProofTime
simplifyTime = accumulateTime proverTime SimplifyTime
Message.outputMain Message.TRACING noPos $
"parser " ++ showTimeDiff (diffUTCTime proveStart startTime)
++ " - reasoner " ++ showTimeDiff (diffUTCTime finishTime simplifyTime)
++ " - simplifier " ++ showTimeDiff (diffUTCTime simplifyTime proverTime)
++ " - prover " ++ showTimeDiff (diffUTCTime proverTime proveStart)
++ "/" ++ showTimeDiff (maximalTimeCounter counterList SuccessTime)
Message.outputMain Message.TRACING noPos $
"total "
++ showTimeDiff (diffUTCTime finishTime startTime)
serverConnection :: IORef Text -> [String] -> Socket -> IO ()
serverConnection oldTextRef args0 connection = do
thread_uuid <- Standard_Thread.my_uuid
mapM_ (Byte_Message.write_line_message connection . UUID.bytes) thread_uuid
res <- Byte_Message.read_line_message connection
case fmap (YXML.parse . UTF8.toString) res of
Just (XML.Elem ((command, _), body)) | command == Naproche.cancel_command ->
mapM_ Standard_Thread.stop_uuid (UUID.parse_string (XML.content_of body))
Just (XML.Elem ((command, props), body)) | command == Naproche.forthel_command ->
Exception.bracket_ (Message.initThread props (Byte_Message.write connection))
Message.exitThread
(do
let args1 = split_lines (the_default "" (Properties.get props Naproche.command_args))
(opts1, text0) <- readArgs (args0 ++ args1)
let text1 = text0 ++ [TextInstr Instr.noPos (Instr.String Instr.Text (XML.content_of body))]
Exception.catch (mainBody oldTextRef (opts1, text1))
(\err -> do
let msg = Exception.displayException (err :: Exception.SomeException)
Exception.catch
(if YXML.detect msg then
Byte_Message.write connection [UTF8.fromString msg]
else Message.outputMain Message.ERROR noPos msg)
(\err2 -> do
let e = err2 :: Exception.IOException
return ())))
_ -> return ()
-- Command line parsing
readArgs :: [String] -> IO ([Instr], [Text])
readArgs args = do
let (instrs, files, errs) = GetOpt.getOpt GetOpt.Permute options args
let fail msgs = errorWithoutStackTrace (cat_lines (map trim_line msgs))
unless (all wellformed instrs && null errs) $ fail errs
when (length files > 1) $ fail ["More than one file argument\n"]
let commandLine = case files of [file] -> instrs ++ [Instr.String Instr.File file]; _ -> instrs
initFile <- readInit (Instr.askString Instr.Init "init.opt" commandLine)
let initialOpts = initFile ++ map (Instr.noPos,) commandLine
let revInitialOpts = map snd $ reverse initialOpts
let initialText = map (uncurry TextInstr) initialOpts
return (revInitialOpts, initialText)
wellformed (Instr.Bool _ v) = v == v
wellformed (Instr.Int _ v) = v == v
wellformed _ = True
usageHeader =
"\nUsage: Naproche-SAD <options...> <file...>\n\n At most one file argument may be given; \"\" refers to stdin.\n\n Options are:\n"
options = [
GetOpt.Option "h" ["help"] (GetOpt.NoArg (Instr.Bool Instr.Help True)) "show command-line help",
GetOpt.Option "" ["init"] (GetOpt.ReqArg (Instr.String Instr.Init) "FILE")
"init file, empty to skip (def: init.opt)",
GetOpt.Option "T" ["onlytranslate"] (GetOpt.NoArg (Instr.Bool Instr.OnlyTranslate True))
"translate input text and exit",
GetOpt.Option "" ["translate"] (GetOpt.ReqArg (Instr.Bool Instr.Translation . bool) "{on|off}")
"print first-order translation of sentences",
GetOpt.Option "" ["server"] (GetOpt.NoArg (Instr.Bool Instr.Server True))
"run in server mode",
GetOpt.Option "" ["library"] (GetOpt.ReqArg (Instr.String Instr.Library) "DIR")
"place to look for library texts (def: .)",
GetOpt.Option "" ["provers"] (GetOpt.ReqArg (Instr.String Instr.Provers) "FILE")
"index of provers (def: provers.dat)",
GetOpt.Option "P" ["prover"] (GetOpt.ReqArg (Instr.String Instr.Prover) "NAME")
"use prover NAME (def: first listed)",
GetOpt.Option "t" ["timelimit"] (GetOpt.ReqArg (Instr.Int Instr.Timelimit . int) "N")
"N seconds per prover call (def: 3)",
GetOpt.Option "" ["depthlimit"] (GetOpt.ReqArg (Instr.Int Instr.Depthlimit . int) "N")
"N reasoner loops per goal (def: 7)",
GetOpt.Option "" ["checktime"] (GetOpt.ReqArg (Instr.Int Instr.Checktime . int) "N")
"timelimit for checker's tasks (def: 1)",
GetOpt.Option "" ["checkdepth"] (GetOpt.ReqArg (Instr.Int Instr.Checkdepth . int) "N")
"depthlimit for checker's tasks (def: 3)",
GetOpt.Option "n" [] (GetOpt.NoArg (Instr.Bool Instr.Prove False))
"cursory mode (equivalent to --prove off)",
GetOpt.Option "r" [] (GetOpt.NoArg (Instr.Bool Instr.Check False))
"raw mode (equivalent to --check off)",
GetOpt.Option "" ["prove"] (GetOpt.ReqArg (Instr.Bool Instr.Prove . bool) "{on|off}")
"prove goals in the text (def: on)",
GetOpt.Option "" ["check"] (GetOpt.ReqArg (Instr.Bool Instr.Check . bool) "{on|off}")
"check symbols for definedness (def: on)",
GetOpt.Option "" ["symsign"] (GetOpt.ReqArg (Instr.Bool Instr.Symsign . bool) "{on|off}")
"prevent ill-typed unification (def: on)",
GetOpt.Option "" ["info"] (GetOpt.ReqArg (Instr.Bool Instr.Info . bool) "{on|off}")
"collect \"evidence\" literals (def: on)",
GetOpt.Option "" ["thesis"] (GetOpt.ReqArg (Instr.Bool Instr.Thesis . bool) "{on|off}")
"maintain current thesis (def: on)",
GetOpt.Option "" ["filter"] (GetOpt.ReqArg (Instr.Bool Instr.Filter . bool) "{on|off}")
"filter prover tasks (def: on)",
GetOpt.Option "" ["skipfail"] (GetOpt.ReqArg (Instr.Bool Instr.Skipfail . bool) "{on|off}")
"ignore failed goals (def: off)",
GetOpt.Option "" ["flat"] (GetOpt.ReqArg (Instr.Bool Instr.Flat . bool) "{on|off}")
"do not read proofs (def: off)",
GetOpt.Option "q" [] (GetOpt.NoArg (Instr.Bool Instr.Verbose False))
"print no details",
GetOpt.Option "v" [] (GetOpt.NoArg (Instr.Bool Instr.Verbose True))
"print more details (-vv, -vvv, etc)",
GetOpt.Option "" ["printgoal"] (GetOpt.ReqArg (Instr.Bool Instr.Printgoal . bool) "{on|off}")
"print current goal (def: on)",
GetOpt.Option "" ["printreason"] (GetOpt.ReqArg (Instr.Bool Instr.Printreason . bool) "{on|off}")
"print reasoner's messages (def: off)",
GetOpt.Option "" ["printsection"] (GetOpt.ReqArg (Instr.Bool Instr.Printsection . bool) "{on|off}")
"print sentence translations (def: off)",
GetOpt.Option "" ["printcheck"] (GetOpt.ReqArg (Instr.Bool Instr.Printcheck . bool) "{on|off}")
"print checker's messages (def: off)",
GetOpt.Option "" ["printprover"] (GetOpt.ReqArg (Instr.Bool Instr.Printprover . bool) "{on|off}")
"print prover's messages (def: off)",
GetOpt.Option "" ["printunfold"] (GetOpt.ReqArg (Instr.Bool Instr.Printunfold . bool) "{on|off}")
"print definition unfoldings (def: off)",
GetOpt.Option "" ["printfulltask"] (GetOpt.ReqArg (Instr.Bool Instr.Printfulltask . bool) "{on|off}")
"print full prover tasks (def: off)",
GetOpt.Option "" ["printsimp"] (GetOpt.ReqArg (Instr.Bool Instr.Printsimp . bool) "{on|off}")
"print simplification process (def: off)",
GetOpt.Option "" ["printthesis"] (GetOpt.ReqArg (Instr.Bool Instr.Printthesis . bool) "{on|off}")
"print thesis development (def: off)",
GetOpt.Option "" ["ontored"] (GetOpt.ReqArg (Instr.Bool Instr.Ontored . bool) "{on|off}")
"enable ontological reduction (def: off)",
GetOpt.Option "" ["unfoldlow"] (GetOpt.ReqArg (Instr.Bool Instr.Unfoldlow . bool) "{on|off}")
"enable unfolding of definitions in the whole low level context (def: on)",
GetOpt.Option "" ["unfold"] (GetOpt.ReqArg (Instr.Bool Instr.Unfold . bool) "{on|off}")
"enable unfolding of definitions (def: on)",
GetOpt.Option "" ["unfoldsf"] (GetOpt.ReqArg (Instr.Bool Instr.Unfoldsf . bool) "{on|off}")
"enable unfolding of set conditions and function evaluations (def: on)",
GetOpt.Option "" ["unfoldlowsf"] (GetOpt.ReqArg (Instr.Bool Instr.Unfoldlowsf . bool) "{on|off}")
"enable unfolding of set and function conditions in general (def: off)",
GetOpt.Option "" ["checkontored"] (GetOpt.ReqArg (Instr.Bool Instr.Checkontored . bool) "{on|off}")
"enable ontological reduction for checking of symbols (def: off)"]
bool "yes" = True ; bool "on" = True
bool "no" = False; bool "off" = False
bool s = errorWithoutStackTrace $ "Invalid boolean argument: " ++ quote s
int s = case reads s of
((n, []) : _) | n >= 0 -> n
_ -> errorWithoutStackTrace $ "Invalid integer argument: " ++ quote s
| null | https://raw.githubusercontent.com/Naproche-SAD/Naproche-SAD/da131a6eaf65d4e02e82082a50a4febb6d42db3d/app/Main.hs | haskell | command line and init file
main body with explicit error handling, notably for PIDE
parse input text
if -T / --onlytranslate is passed as an option, only print the translated text
print statistics
read provers.dat
initialize reasoner state
print statistics
Command line parsing |
Authors : ( 2001 - 2008 ) , ( 2017 - 2018 ) , ( 2018 )
Main application entry point : console or server mode .
Authors: Andrei Paskevich (2001 - 2008), Steffen Frerix (2017 - 2018), Makarius Wenzel (2018)
Main application entry point: console or server mode.
-}
# LANGUAGE TupleSections #
# LANGUAGE LambdaCase #
module Main where
import Data.Maybe
import Data.IORef
import Data.Time
import Control.Monad (when, unless)
import qualified System.Console.GetOpt as GetOpt
import qualified System.Environment as Environment
import qualified System.Exit as Exit
import qualified Control.Exception as Exception
import System.IO (IO)
import qualified System.IO as IO
import Isabelle.Library
import qualified Isabelle.File as File
import qualified Isabelle.Server as Server
import qualified Isabelle.Byte_Message as Byte_Message
import qualified Isabelle.Properties as Properties
import qualified Isabelle.XML as XML
import qualified Isabelle.YXML as YXML
import qualified Isabelle.UUID as UUID
import qualified Isabelle.Standard_Thread as Standard_Thread
import qualified Isabelle.Naproche as Naproche
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.ByteString.Char8 as Char8
import qualified Data.ByteString as ByteString
import Network.Socket (Socket)
import SAD.Core.Base
import qualified SAD.Core.Message as Message
import SAD.Core.SourcePos
import SAD.Core.Verify
import SAD.Data.Instr (Instr)
import qualified SAD.Data.Instr as Instr
import SAD.Data.Text.Block
import SAD.Export.Base
import SAD.Import.Reader
import SAD.Parser.Error
main :: IO ()
main = do
setup stdin / stdout
File.setup IO.stdin
File.setup IO.stdout
File.setup IO.stderr
IO.hSetBuffering IO.stdout IO.LineBuffering
IO.hSetBuffering IO.stderr IO.LineBuffering
args0 <- Environment.getArgs
(opts0, text0) <- readArgs args0
oldTextRef <- newIORef $ TextRoot []
if Instr.askBool Instr.Help False opts0 then
putStr (GetOpt.usageInfo usageHeader options)
Exception.catch
(if Instr.askBool Instr.Server False opts0 then
Server.server (Server.publish_stdout "Naproche-SAD") (serverConnection oldTextRef args0)
else do Message.consoleThread; mainBody oldTextRef (opts0, text0))
(\err -> do
Message.exitThread
let msg = Exception.displayException (err :: Exception.SomeException)
IO.hPutStrLn IO.stderr msg
Exit.exitFailure)
mainBody :: IORef Text -> ([Instr], [Text]) -> IO ()
mainBody oldTextRef (opts0, text0) = do
startTime <- getCurrentTime
oldText <- readIORef oldTextRef
text1 <- fmap TextRoot $ readText (Instr.askString Instr.Library "." opts0) text0
if Instr.askBool Instr.OnlyTranslate False opts0 then
do
let timeDifference finishTime = showTimeDiff (diffUTCTime finishTime startTime)
TextRoot txts = text1
mapM_ (\case TextBlock bl -> print bl; _ -> return ()) txts
finishTime <- getCurrentTime
Message.outputMain Message.TRACING noPos $ "total " ++ timeDifference finishTime
else
do
provers <- readProverDatabase (Instr.askString Instr.Provers "provers.dat" opts0)
reasonerState <- newIORef (RState [] False False)
proveStart <- getCurrentTime
case findParseError text1 of
Nothing -> do
let text = textToCheck oldText text1
newText <- verify (Instr.askString Instr.File "" opts0) provers reasonerState text
case newText of
Just txt -> writeIORef oldTextRef txt
_ -> return ()
Just err -> Message.errorParser (errorPos err) (show err)
finishTime <- getCurrentTime
finalReasonerState <- readIORef reasonerState
let counterList = counters finalReasonerState
accumulate = accumulateIntCounter counterList 0
Message.outputMain Message.TRACING noPos $
"sections " ++ show (accumulate Sections)
++ " - goals " ++ show (accumulate Goals)
++ (let ignoredFails = accumulate FailedGoals
in if ignoredFails == 0
then ""
else " - failed " ++ show ignoredFails)
++ " - trivial " ++ show (accumulate TrivialGoals)
++ " - proved " ++ show (accumulate SuccessfulGoals)
++ " - equations " ++ show (accumulate Equations)
++ (let failedEquations = accumulate FailedEquations
in if failedEquations == 0
then ""
else " - failed " ++ show failedEquations)
let trivialChecks = accumulate TrivialChecks
Message.outputMain Message.TRACING noPos $
"symbols " ++ show (accumulate Symbols)
++ " - checks " ++ show
(accumulateIntCounter counterList trivialChecks HardChecks)
++ " - trivial " ++ show trivialChecks
++ " - proved " ++ show (accumulate SuccessfulChecks)
++ " - unfolds " ++ show (accumulate Unfolds)
let accumulateTime = accumulateTimeCounter counterList
proverTime = accumulateTime proveStart ProofTime
simplifyTime = accumulateTime proverTime SimplifyTime
Message.outputMain Message.TRACING noPos $
"parser " ++ showTimeDiff (diffUTCTime proveStart startTime)
++ " - reasoner " ++ showTimeDiff (diffUTCTime finishTime simplifyTime)
++ " - simplifier " ++ showTimeDiff (diffUTCTime simplifyTime proverTime)
++ " - prover " ++ showTimeDiff (diffUTCTime proverTime proveStart)
++ "/" ++ showTimeDiff (maximalTimeCounter counterList SuccessTime)
Message.outputMain Message.TRACING noPos $
"total "
++ showTimeDiff (diffUTCTime finishTime startTime)
serverConnection :: IORef Text -> [String] -> Socket -> IO ()
serverConnection oldTextRef args0 connection = do
thread_uuid <- Standard_Thread.my_uuid
mapM_ (Byte_Message.write_line_message connection . UUID.bytes) thread_uuid
res <- Byte_Message.read_line_message connection
case fmap (YXML.parse . UTF8.toString) res of
Just (XML.Elem ((command, _), body)) | command == Naproche.cancel_command ->
mapM_ Standard_Thread.stop_uuid (UUID.parse_string (XML.content_of body))
Just (XML.Elem ((command, props), body)) | command == Naproche.forthel_command ->
Exception.bracket_ (Message.initThread props (Byte_Message.write connection))
Message.exitThread
(do
let args1 = split_lines (the_default "" (Properties.get props Naproche.command_args))
(opts1, text0) <- readArgs (args0 ++ args1)
let text1 = text0 ++ [TextInstr Instr.noPos (Instr.String Instr.Text (XML.content_of body))]
Exception.catch (mainBody oldTextRef (opts1, text1))
(\err -> do
let msg = Exception.displayException (err :: Exception.SomeException)
Exception.catch
(if YXML.detect msg then
Byte_Message.write connection [UTF8.fromString msg]
else Message.outputMain Message.ERROR noPos msg)
(\err2 -> do
let e = err2 :: Exception.IOException
return ())))
_ -> return ()
readArgs :: [String] -> IO ([Instr], [Text])
readArgs args = do
let (instrs, files, errs) = GetOpt.getOpt GetOpt.Permute options args
let fail msgs = errorWithoutStackTrace (cat_lines (map trim_line msgs))
unless (all wellformed instrs && null errs) $ fail errs
when (length files > 1) $ fail ["More than one file argument\n"]
let commandLine = case files of [file] -> instrs ++ [Instr.String Instr.File file]; _ -> instrs
initFile <- readInit (Instr.askString Instr.Init "init.opt" commandLine)
let initialOpts = initFile ++ map (Instr.noPos,) commandLine
let revInitialOpts = map snd $ reverse initialOpts
let initialText = map (uncurry TextInstr) initialOpts
return (revInitialOpts, initialText)
wellformed (Instr.Bool _ v) = v == v
wellformed (Instr.Int _ v) = v == v
wellformed _ = True
usageHeader =
"\nUsage: Naproche-SAD <options...> <file...>\n\n At most one file argument may be given; \"\" refers to stdin.\n\n Options are:\n"
options = [
GetOpt.Option "h" ["help"] (GetOpt.NoArg (Instr.Bool Instr.Help True)) "show command-line help",
GetOpt.Option "" ["init"] (GetOpt.ReqArg (Instr.String Instr.Init) "FILE")
"init file, empty to skip (def: init.opt)",
GetOpt.Option "T" ["onlytranslate"] (GetOpt.NoArg (Instr.Bool Instr.OnlyTranslate True))
"translate input text and exit",
GetOpt.Option "" ["translate"] (GetOpt.ReqArg (Instr.Bool Instr.Translation . bool) "{on|off}")
"print first-order translation of sentences",
GetOpt.Option "" ["server"] (GetOpt.NoArg (Instr.Bool Instr.Server True))
"run in server mode",
GetOpt.Option "" ["library"] (GetOpt.ReqArg (Instr.String Instr.Library) "DIR")
"place to look for library texts (def: .)",
GetOpt.Option "" ["provers"] (GetOpt.ReqArg (Instr.String Instr.Provers) "FILE")
"index of provers (def: provers.dat)",
GetOpt.Option "P" ["prover"] (GetOpt.ReqArg (Instr.String Instr.Prover) "NAME")
"use prover NAME (def: first listed)",
GetOpt.Option "t" ["timelimit"] (GetOpt.ReqArg (Instr.Int Instr.Timelimit . int) "N")
"N seconds per prover call (def: 3)",
GetOpt.Option "" ["depthlimit"] (GetOpt.ReqArg (Instr.Int Instr.Depthlimit . int) "N")
"N reasoner loops per goal (def: 7)",
GetOpt.Option "" ["checktime"] (GetOpt.ReqArg (Instr.Int Instr.Checktime . int) "N")
"timelimit for checker's tasks (def: 1)",
GetOpt.Option "" ["checkdepth"] (GetOpt.ReqArg (Instr.Int Instr.Checkdepth . int) "N")
"depthlimit for checker's tasks (def: 3)",
GetOpt.Option "n" [] (GetOpt.NoArg (Instr.Bool Instr.Prove False))
"cursory mode (equivalent to --prove off)",
GetOpt.Option "r" [] (GetOpt.NoArg (Instr.Bool Instr.Check False))
"raw mode (equivalent to --check off)",
GetOpt.Option "" ["prove"] (GetOpt.ReqArg (Instr.Bool Instr.Prove . bool) "{on|off}")
"prove goals in the text (def: on)",
GetOpt.Option "" ["check"] (GetOpt.ReqArg (Instr.Bool Instr.Check . bool) "{on|off}")
"check symbols for definedness (def: on)",
GetOpt.Option "" ["symsign"] (GetOpt.ReqArg (Instr.Bool Instr.Symsign . bool) "{on|off}")
"prevent ill-typed unification (def: on)",
GetOpt.Option "" ["info"] (GetOpt.ReqArg (Instr.Bool Instr.Info . bool) "{on|off}")
"collect \"evidence\" literals (def: on)",
GetOpt.Option "" ["thesis"] (GetOpt.ReqArg (Instr.Bool Instr.Thesis . bool) "{on|off}")
"maintain current thesis (def: on)",
GetOpt.Option "" ["filter"] (GetOpt.ReqArg (Instr.Bool Instr.Filter . bool) "{on|off}")
"filter prover tasks (def: on)",
GetOpt.Option "" ["skipfail"] (GetOpt.ReqArg (Instr.Bool Instr.Skipfail . bool) "{on|off}")
"ignore failed goals (def: off)",
GetOpt.Option "" ["flat"] (GetOpt.ReqArg (Instr.Bool Instr.Flat . bool) "{on|off}")
"do not read proofs (def: off)",
GetOpt.Option "q" [] (GetOpt.NoArg (Instr.Bool Instr.Verbose False))
"print no details",
GetOpt.Option "v" [] (GetOpt.NoArg (Instr.Bool Instr.Verbose True))
"print more details (-vv, -vvv, etc)",
GetOpt.Option "" ["printgoal"] (GetOpt.ReqArg (Instr.Bool Instr.Printgoal . bool) "{on|off}")
"print current goal (def: on)",
GetOpt.Option "" ["printreason"] (GetOpt.ReqArg (Instr.Bool Instr.Printreason . bool) "{on|off}")
"print reasoner's messages (def: off)",
GetOpt.Option "" ["printsection"] (GetOpt.ReqArg (Instr.Bool Instr.Printsection . bool) "{on|off}")
"print sentence translations (def: off)",
GetOpt.Option "" ["printcheck"] (GetOpt.ReqArg (Instr.Bool Instr.Printcheck . bool) "{on|off}")
"print checker's messages (def: off)",
GetOpt.Option "" ["printprover"] (GetOpt.ReqArg (Instr.Bool Instr.Printprover . bool) "{on|off}")
"print prover's messages (def: off)",
GetOpt.Option "" ["printunfold"] (GetOpt.ReqArg (Instr.Bool Instr.Printunfold . bool) "{on|off}")
"print definition unfoldings (def: off)",
GetOpt.Option "" ["printfulltask"] (GetOpt.ReqArg (Instr.Bool Instr.Printfulltask . bool) "{on|off}")
"print full prover tasks (def: off)",
GetOpt.Option "" ["printsimp"] (GetOpt.ReqArg (Instr.Bool Instr.Printsimp . bool) "{on|off}")
"print simplification process (def: off)",
GetOpt.Option "" ["printthesis"] (GetOpt.ReqArg (Instr.Bool Instr.Printthesis . bool) "{on|off}")
"print thesis development (def: off)",
GetOpt.Option "" ["ontored"] (GetOpt.ReqArg (Instr.Bool Instr.Ontored . bool) "{on|off}")
"enable ontological reduction (def: off)",
GetOpt.Option "" ["unfoldlow"] (GetOpt.ReqArg (Instr.Bool Instr.Unfoldlow . bool) "{on|off}")
"enable unfolding of definitions in the whole low level context (def: on)",
GetOpt.Option "" ["unfold"] (GetOpt.ReqArg (Instr.Bool Instr.Unfold . bool) "{on|off}")
"enable unfolding of definitions (def: on)",
GetOpt.Option "" ["unfoldsf"] (GetOpt.ReqArg (Instr.Bool Instr.Unfoldsf . bool) "{on|off}")
"enable unfolding of set conditions and function evaluations (def: on)",
GetOpt.Option "" ["unfoldlowsf"] (GetOpt.ReqArg (Instr.Bool Instr.Unfoldlowsf . bool) "{on|off}")
"enable unfolding of set and function conditions in general (def: off)",
GetOpt.Option "" ["checkontored"] (GetOpt.ReqArg (Instr.Bool Instr.Checkontored . bool) "{on|off}")
"enable ontological reduction for checking of symbols (def: off)"]
bool "yes" = True ; bool "on" = True
bool "no" = False; bool "off" = False
bool s = errorWithoutStackTrace $ "Invalid boolean argument: " ++ quote s
int s = case reads s of
((n, []) : _) | n >= 0 -> n
_ -> errorWithoutStackTrace $ "Invalid integer argument: " ++ quote s
|
f73fe3151b58577f6b1fc5508805cf0cf8a03046e37878b2c9d66316406986b9 | softlab-ntua/bencherl | dialyzer_gui_wx.erl | -*- erlang - indent - level : 2 -*-
%%------------------------------------------------------------------------
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2009 - 2012 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%%-----------------------------------------------------------------------
%%% File : dialyzer_gui_wx.erl
Authors : < >
%%% Description : The wx-based graphical user interface of dialyzer.
%%%
Created : 07 Oct 2009 by < >
%%%-----------------------------------------------------------------------
-module(dialyzer_gui_wx).
-export([start/1]).
-include("dialyzer.hrl").
-include("dialyzer_gui_wx.hrl").
%%------------------------------------------------------------------------
-define(DIALYZER_ERROR_TITLE, "Dialyzer Error").
-define(DIALYZER_MESSAGE_TITLE, "Dialyzer Message").
%%------------------------------------------------------------------------
-record(menu, {file :: wx:wx_object(),
warnings :: wx:wx_object(),
plt :: wx:wx_object(),
options :: wx:wx_object(),
help :: wx:wx_object()}).
-type menu() :: #menu{}.
-record(gui_state, {add :: wx:wx_object(),
add_dir :: wx:wx_object(),
add_rec :: wx:wx_object(),
chosen_box :: wx:wx_object(),
analysis_pid :: pid(),
del_file :: wx:wx_object(),
doc_plt :: dialyzer_plt:plt(),
clear_chosen :: wx:wx_object(),
clear_log :: wx:wx_object(),
explain_warn :: wx:wx_object(),
clear_warn :: wx:wx_object(),
init_plt :: dialyzer_plt:plt(),
dir_entry :: wx:wx_object(),
file_box :: wx:wx_object(),
files_to_analyze :: ordset(string()),
gui :: wx:wx_object(),
log :: wx:wx_object(),
menu :: menu(),
mode :: wx:wx_object(),
options :: #options{},
run :: wx:wx_object(),
stop :: wx:wx_object(),
frame :: wx:wx_object(),
warnings_box :: wx:wx_object(),
explanation_box :: wx:wx_object(),
wantedWarnings :: list(),
rawWarnings :: list(),
backend_pid :: pid(),
expl_pid :: pid()}).
%%------------------------------------------------------------------------
-spec start(#options{}) -> ?RET_NOTHING_SUSPICIOUS.
start(DialyzerOptions) ->
process_flag(trap_exit, true),
Wx = wx:new(),
State = wx:batch(fun() -> create_window(Wx, DialyzerOptions) end),
gui_loop(State).
create_window(Wx, #options{init_plts = InitPltFiles} = DialyzerOptions) ->
{ok, Host} = inet:gethostname(),
%%---------- initializing frame ---------
Frame = wxFrame:new(Wx, -1, "Dialyzer " ++ ?VSN ++ " @ " ++ Host),
wxFrame:connect(Frame, close_window),
FileMenu = createFileMenu(),
WarningsMenu = createWarningsMenu(),
PltMenu = createPltMenu(),
OptionsMenu = createOptionsMenu(),
HelpMenu = createHelpMenu(),
MenuBar = wxMenuBar:new(),
wxMenuBar:append(MenuBar, FileMenu, "File"),
wxMenuBar:append(MenuBar, WarningsMenu, "Warnings"),
wxMenuBar:append(MenuBar, PltMenu, "Plt"),
wxMenuBar:append(MenuBar, OptionsMenu, "Options"),
wxMenuBar:append(MenuBar, HelpMenu, "Help"),
wxFrame:setMenuBar(Frame, MenuBar),
ok = wxFrame:connect(Frame, command_menu_selected),
%%----------- Set Labels -------------
Lab1 = wxStaticText:new(Frame, ?LABEL1, "Directories or modules to analyze"),
OptionsLabel = wxStaticText:new(Frame, ?LABEL2, "Analysis Options"),
LogLabel = wxStaticText:new(Frame, ?LABEL3, "Log"),
FileLabel = wxStaticText:new(Frame, ?LABEL4, "File: "),
DirLabel = wxStaticText:new(Frame, ?LABEL5, "Dir: "),
WarningsLabel = wxStaticText:new(Frame, ?LABEL6, "Warnings"),
---------- Set TextBoxes -----------
ChosenBox = wxListBox:new(Frame, ?ChosenBox,
[{size, {250,200}},
{style, ?wxLB_EXTENDED bor ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
LogBox = wxTextCtrl:new(Frame, ?LogBox,
[{size, {530,200}},
{style, ?wxTE_MULTILINE
bor ?wxTE_READONLY bor ?wxHSCROLL}]),
DefaultPath = code:root_dir(),
FilePicker = wxFilePickerCtrl:new(Frame, ?FilePicker,
[{path, DefaultPath},
{message, "Choose File to Analyse"},
{style,?wxFLP_FILE_MUST_EXIST bor ?wxFLP_USE_TEXTCTRL}]),
wxPickerBase:setTextCtrlProportion(FilePicker,3),
wxPickerBase:setPickerCtrlProportion(FilePicker,2),
DirPicker = wxDirPickerCtrl:new(Frame, ?DirPicker,
[{path, DefaultPath},
{message, "Choose Directory to Analyze"},
{style,?wxDIRP_DIR_MUST_EXIST bor ?wxDIRP_USE_TEXTCTRL}]),
WarningsBox = wxListBox:new(Frame, ?WarningsBox,
[{size, {700,200}},
{style, ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
%%--------- Set Buttons --------------
DeleteButton = wxButton:new(Frame, ?Del_Button, [{label, "Delete"}]),
DeleteAllButton = wxButton:new(Frame, ?DelAll_Button, [{label, "Delete All"}]),
FileType = wxRadioBox:new(Frame, ?RADIOBOX, " File Type: " , {1,1}, {150,90},
[["BeamFiles"],["SourceFiles"]]),
ClearLogButton = wxButton:new(Frame, ?ClearLog_Button, [{label, "Clear Log"}]),
AddButton = wxButton:new(Frame, ?Add_Button, [{label, "Add"}]),
AddDirButton = wxButton:new(Frame, ?AddDir_Button, [{label, "Add Dir"}]),
AddRecButton = wxButton:new(Frame, ?AddRec_Button, [{label, "Add Recursively"}]),
ExplainWarnButton = wxButton:new(Frame, ?ExplWarn_Button, [{label, "Explain Warning"}]),
ClearWarningsButton = wxButton:new(Frame, ?ClearWarn_Button, [{label, "Clear Warnings"}]),
RunButton = wxButton:new(Frame, ?Run_Button, [{label, "Run"}]),
StopButton = wxButton:new(Frame, ?Stop_Button, [{label, "Stop"}]),
wxWindow:disable(StopButton),
--------- Connect Buttons -----------
wxButton:connect(DeleteButton, command_button_clicked),
wxButton:connect(DeleteAllButton, command_button_clicked),
wxButton:connect(ClearLogButton, command_button_clicked),
wxButton:connect(AddButton, command_button_clicked),
wxButton:connect(AddDirButton, command_button_clicked),
wxButton:connect(AddRecButton, command_button_clicked),
wxButton:connect(ExplainWarnButton, command_button_clicked),
wxButton:connect(ClearWarningsButton, command_button_clicked),
wxButton:connect(RunButton, command_button_clicked),
wxButton:connect(StopButton, command_button_clicked),
%%------------Set Layout ------------
All = wxBoxSizer:new(?wxVERTICAL),
Top = wxBoxSizer:new(?wxHORIZONTAL),
Left = wxBoxSizer:new(?wxVERTICAL),
Right = wxBoxSizer:new(?wxVERTICAL),
RightUp = wxBoxSizer:new(?wxHORIZONTAL),
Opts = [{flag,?wxEXPAND bor ?wxALL}, {proportion,1}, {border, 1}],
Opts3 = [{flag,?wxEXPAND bor ?wxALL}, {proportion,3}, {border, 1}],
Center = [{flag, ?wxALIGN_CENTER_HORIZONTAL}],
ChooseItem = wxBoxSizer:new(?wxVERTICAL),
FileTypeItem = wxBoxSizer:new(?wxVERTICAL),
LogItem = wxBoxSizer:new(?wxVERTICAL),
FileDirItem = wxBoxSizer:new(?wxVERTICAL),
FileItem = wxBoxSizer:new(?wxHORIZONTAL),
DirItem = wxBoxSizer:new(?wxHORIZONTAL),
AddDirButtons = wxBoxSizer:new(?wxHORIZONTAL),
WarningsItem = wxBoxSizer:new(?wxVERTICAL),
ChooseButtons = wxBoxSizer:new(?wxHORIZONTAL),
WarnButtons = wxBoxSizer:new(?wxHORIZONTAL),
RunButtons = wxBoxSizer:new(?wxHORIZONTAL),
Buttons = wxFlexGridSizer:new(3),
wxSizer:add(ChooseButtons, DeleteButton, ?BorderOpt),
wxSizer:add(ChooseButtons, DeleteAllButton, ?BorderOpt),
wxSizer:add(ChooseItem, Lab1, Center),
wxSizer:add(ChooseItem, ChosenBox, Opts),
wxSizer:add(ChooseItem, ChooseButtons, ?BorderOpt),
wxSizer:add(FileTypeItem, OptionsLabel),
wxSizer:add(FileTypeItem, FileType, [{border, 5}, {flag, ?wxALL}]),
wxSizer:add(LogItem, LogLabel, Center),
wxSizer:add(LogItem, LogBox, Opts3),
wxSizer:add(LogItem, ClearLogButton, ?BorderOpt),
wxSizer:add(FileItem, FileLabel),
wxSizer:add(FileItem, FilePicker),
wxSizer:add(DirItem, DirLabel),
wxSizer:add(DirItem, DirPicker),
wxSizer:add(AddDirButtons, AddDirButton, ?BorderOpt),
wxSizer:add(AddDirButtons, AddRecButton, ?BorderOpt),
wxSizer:add(FileDirItem, FileItem),
wxSizer:add(FileDirItem, AddButton, ?BorderOpt),
wxSizer:add(FileDirItem, DirItem, ?BorderOpt),
wxSizer:add(FileDirItem, AddDirButtons, ?BorderOpt),
wxSizer:add(WarnButtons, ExplainWarnButton, ?BorderOpt),
wxSizer:add(WarnButtons, ClearWarningsButton, ?BorderOpt),
wxSizer:add(RunButtons, RunButton, ?BorderOpt),
wxSizer:add(RunButtons, StopButton, ?BorderOpt),
wxSizer:add(Buttons, WarnButtons),
wxSizer:add(Buttons, wxStaticText:new(Frame, ?LABEL7, ""), [{flag, ?wxEXPAND}]),
wxSizer:add(Buttons, RunButtons),
wxFlexGridSizer:addGrowableCol(Buttons, 1),
wxSizer:add(WarningsItem, WarningsLabel, Center),
wxSizer:add(WarningsItem, WarningsBox, Opts3),
wxSizer:add(WarningsItem, Buttons, [{flag, ?wxEXPAND bor ?wxALL},?Border]),
wxSizer:add(Left, ChooseItem, Opts),
wxSizer:add(Left, FileDirItem, [{proportion, 1}, {border, 60}, {flag, ?wxTOP}]),
wxSizer:add(RightUp, FileTypeItem, ?BorderOpt),
wxSizer:add(RightUp, LogItem, Opts3),
wxSizer:add(Right, RightUp, Opts3),
wxSizer:add(Right, WarningsItem, Opts3),
wxSizer:add(Top, Left, Opts),
wxSizer:add(Top, Right, Opts3),
wxSizer:add(All, Top, Opts),
wxWindow:setSizer(Frame, All),
wxWindow:setSizeHints(Frame, {1150,600}),
wxWindow:show(Frame),
Warnings = [{?WARN_RETURN_NO_RETURN, ?menuID_WARN_NO_RETURN_FUN},
{?WARN_RETURN_ONLY_EXIT, ?menuID_WARN_ERROR_HANDLING_FUN},
{?WARN_NOT_CALLED, ?menuID_WARN_UNUSED_FUN},
{?WARN_NON_PROPER_LIST, ?menuID_WARN_LIST_CONSTR},
{?WARN_FUN_APP, ?menuID_WARN_BAD_FUN},
{?WARN_MATCHING, ?menuID_WARN_MATCH_FAILURES},
{?WARN_OPAQUE, ?menuID_WARN_OPAQUE},
{?WARN_FAILING_CALL, ?menuID_WARN_FAIL_FUN_CALLS},
{?WARN_CALLGRAPH, ?menuID_WARN_UNEXPORTED_FUN},
{?WARN_RACE_CONDITION, ?menuID_WARN_RACE_CONDITIONS},
%% For contracts.
{?WARN_CONTRACT_TYPES,?menuID_WARN_WRONG_CONTRACTS},
{?WARN_CONTRACT_SYNTAX, ?menuID_WARN_CONTRACT_SYNTAX}
],
Menu = #menu{file = FileMenu,
warnings = WarningsMenu,
plt = PltMenu,
options =OptionsMenu,
help = HelpMenu},
InitPlt =
case InitPltFiles of
[] -> dialyzer_plt:new();
_ ->
Plts = [dialyzer_plt:from_file(F) || F <- InitPltFiles],
dialyzer_plt:merge_plts_or_report_conflicts(InitPltFiles, Plts)
end,
#gui_state{add = AddButton,
add_dir = AddDirButton,
add_rec = AddRecButton,
chosen_box = ChosenBox,
clear_chosen = DeleteAllButton,
clear_log = ClearLogButton,
explain_warn = ExplainWarnButton,
clear_warn = ClearWarningsButton,
del_file = DeleteButton,
doc_plt = dialyzer_plt:new(),
dir_entry = DirPicker,
file_box = FilePicker,
files_to_analyze = ordsets:new(),
gui = Wx,
init_plt = InitPlt,
log = LogBox,
menu = Menu,
mode = FileType,
options = DialyzerOptions,
run = RunButton,
stop = StopButton,
frame = Frame,
warnings_box = WarningsBox,
wantedWarnings = Warnings,
rawWarnings = []}.
createFileMenu() ->
FileMenu = wxMenu:new(),
wxMenu:append(FileMenu, wxMenuItem:new([{id, ?menuID_FILE_SAVE_WARNINGS},
{text, "Save &Warnings"}])),
wxMenu:append(FileMenu, wxMenuItem:new([{id, ?menuID_FILE_SAVE_LOG},
{text, "Save &Log"}])),
wxMenu:append(FileMenu, wxMenuItem:new([{id, ?menuID_FILE_QUIT},
{text, "E&xit\tAlt-X"}])),
FileMenu.
createWarningsMenu() ->
WarningsMenu = wxMenu:new(),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_MATCH_FAILURES,
"Match failures"),
wxMenu:check(WarningsMenu, ?menuID_WARN_MATCH_FAILURES, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_FAIL_FUN_CALLS,
"Failing function calls"),
wxMenu:check(WarningsMenu, ?menuID_WARN_FAIL_FUN_CALLS, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_BAD_FUN,
"Bad fun applications"),
wxMenu:check(WarningsMenu, ?menuID_WARN_BAD_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_OPAQUE,
"Opaqueness violations"),
wxMenu:check(WarningsMenu, ?menuID_WARN_OPAQUE, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_LIST_CONSTR,
"Improper list constructions"),
wxMenu:check(WarningsMenu, ?menuID_WARN_LIST_CONSTR, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_UNUSED_FUN,
"Unused functions"),
wxMenu:check(WarningsMenu, ?menuID_WARN_UNUSED_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_ERROR_HANDLING_FUN,
"Error handling functions"),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_NO_RETURN_FUN,
"Functions of no return"),
wxMenu:check(WarningsMenu, ?menuID_WARN_NO_RETURN_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_UNEXPORTED_FUN,
"Call to unexported function"),
wxMenu:check(WarningsMenu, ?menuID_WARN_UNEXPORTED_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_RACE_CONDITIONS,
"Possible race conditions"),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_WRONG_CONTRACTS,
"Wrong contracts"),
wxMenu:check(WarningsMenu, ?menuID_WARN_WRONG_CONTRACTS, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_CONTRACT_SYNTAX,
"Wrong contract syntax"),
wxMenu:check(WarningsMenu, ?menuID_WARN_CONTRACT_SYNTAX, true),
WarningsMenu.
createPltMenu() ->
PltMenu = wxMenu:new(),
wxMenu:appendCheckItem(PltMenu,
?menuID_PLT_INIT_EMPTY,
"Init with empty PLT"),
wxMenu:append(PltMenu, wxMenuItem:new([{id, ?menuID_PLT_SHOW_CONTENTS},
{text, "Show contents"}])),
wxMenu:append(PltMenu, wxMenuItem:new([{id, ?menuID_PLT_SEARCH_CONTENTS},
{text, "Search contents"}])),
PltMenu.
createOptionsMenu() ->
OptsMenu = wxMenu:new(),
wxMenu:append(OptsMenu, wxMenuItem:new([{id, ?menuID_OPTIONS_MACRO},
{text, "Manage Macro Definitions"}])),
wxMenu:append(OptsMenu, wxMenuItem:new([{id, ?menuID_OPTIONS_INCLUDE_DIR},
{text, "Manage Include Directories"}])),
OptsMenu.
createHelpMenu() ->
HelpMenu = wxMenu:new(),
wxMenu:append(HelpMenu, wxMenuItem:new([{id, ?menuID_HELP_MANUAL},
{text, "Manual"}])),
wxMenu:append(HelpMenu, wxMenuItem:new([{id, ?menuID_HELP_WARNING_OPTIONS},
{text, "Warning Options"}])),
wxMenu:append(HelpMenu, wxMenuItem:new([{id, ?menuID_HELP_ABOUT},
{text, "About"}])),
HelpMenu.
%% ----------------------------------------------------------------
%%
Main GUI Loop
%%
-spec gui_loop(#gui_state{}) -> ?RET_NOTHING_SUSPICIOUS.
gui_loop(#gui_state{backend_pid = BackendPid, doc_plt = DocPlt,
log = Log, frame = Frame,
warnings_box = WarningsBox} = State) ->
receive
#wx{event = #wxClose{}} ->
%% io:format("~p Closing window ~n", [self()]),
ok = wxFrame:setStatusText(Frame, "Closing...",[]),
wxWindow:destroy(Frame),
?RET_NOTHING_SUSPICIOUS;
%% ----- Menu -----
#wx{id = ?menuID_FILE_SAVE_LOG, obj = Frame,
event = #wxCommand{type = command_menu_selected}} ->
save_file(State, log),
gui_loop(State);
#wx{id=?menuID_FILE_SAVE_WARNINGS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
save_file(State, warnings),
gui_loop(State);
#wx{id=?menuID_FILE_QUIT, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
case maybe_quit(State) of
true -> ?RET_NOTHING_SUSPICIOUS;
false -> gui_loop(State)
end;
#wx{id=?menuID_PLT_SHOW_CONTENTS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
show_doc_plt(State),
gui_loop(State);
#wx{id=?menuID_PLT_SEARCH_CONTENTS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
case dialyzer_plt:get_specs(DocPlt) of
"" -> error_sms(State, "No analysis has been made yet!\n");
_ -> search_doc_plt(State)
end,
gui_loop(State);
#wx{id=?menuID_OPTIONS_INCLUDE_DIR, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
NewOptions = include_dialog(State),
NewState = State#gui_state{options = NewOptions},
gui_loop(NewState);
#wx{id=?menuID_OPTIONS_MACRO, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
NewOptions = macro_dialog(State),
NewState = State#gui_state{options = NewOptions},
gui_loop(NewState);
#wx{id=?menuID_HELP_MANUAL, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
handle_help(State, "Dialyzer Manual", "manual.txt"),
gui_loop(State);
#wx{id=?menuID_HELP_WARNING_OPTIONS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
handle_help(State, "Dialyzer Warnings", "warnings.txt"),
gui_loop(State);
#wx{id=?menuID_HELP_ABOUT, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
Message = " This is DIALYZER version " ++ ?VSN ++ " \n"++
"DIALYZER is a DIscrepany AnaLYZer for ERlang programs.\n\n"++
" Copyright (C) Tobias Lindahl <>\n"++
" Kostis Sagonas <>\n\n",
output_sms(State, "About Dialyzer", Message, info),
gui_loop(State);
%% ------ Buttons ---------
#wx{id=?Add_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_add_files(State),
gui_loop(State1);
#wx{id=?AddDir_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_add_dir(State),
gui_loop(State1);
#wx{id=?AddRec_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_add_rec(State),
gui_loop(State1);
#wx{id=?Del_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_file_delete(State),
gui_loop(State1);
#wx{id=?DelAll_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_file_delete_all(State),
gui_loop(State1);
#wx{id=?ClearLog_Button,
event=#wxCommand{type=command_button_clicked}} ->
wxTextCtrl:clear(State#gui_state.log),
gui_loop(State);
#wx{id=?ExplWarn_Button,
event=#wxCommand{type=command_button_clicked}} ->
handle_explanation(State),
gui_loop(State);
#wx{id=?ClearWarn_Button,
event=#wxCommand{type=command_button_clicked}} ->
wxListBox:clear(WarningsBox),
NewState = State#gui_state{rawWarnings = []},
gui_loop(NewState);
#wx{id=?Run_Button,
event=#wxCommand{type=command_button_clicked}} ->
NewState = start_analysis(State),
gui_loop(NewState);
#wx{id=?Stop_Button,
event=#wxCommand{type=command_button_clicked}} ->
BackendPid ! {self(), stop},
config_gui_stop(State),
update_editor(Log, "\n***** Analysis stopped ****\n"),
gui_loop(State);
%% ----- Analysis -----
{BackendPid, ext_calls, ExtCalls} ->
Msg = io_lib:format("The following functions are called "
"but type information about them is not available.\n"
"The analysis might get more precise by including "
"the modules containing these functions:\n\n\t~p\n",
[ExtCalls]),
free_editor(State,"Analysis Done", Msg),
gui_loop(State);
{BackendPid, ext_types, ExtTypes} ->
Map = fun({M,F,A}) -> io_lib:format("~p:~p/~p",[M,F,A]) end,
ExtTypeString = string:join(lists:map(Map, ExtTypes), "\n"),
Msg = io_lib:format("The following remote types are being used "
"but information about them is not available.\n"
"The analysis might get more precise by including "
"the modules containing these types and making sure "
"that they are exported:\n~s\n", [ExtTypeString]),
free_editor(State, "Analysis done", Msg),
gui_loop(State);
{BackendPid, log, LogMsg} ->
update_editor(Log, LogMsg),
gui_loop(State);
{BackendPid, warnings, Warns} ->
SortedWarns = lists:keysort(2, Warns), %% Sort on file/line
NewState = add_warnings(State, SortedWarns),
gui_loop(NewState);
{BackendPid, cserver, CServer, Plt} ->
Self = self(),
Fun =
fun() ->
dialyzer_explanation:expl_loop(Self, CServer, Plt)
end,
ExplanationPid = spawn_link(Fun),
gui_loop(State#gui_state{expl_pid = ExplanationPid});
{BackendPid, done, _NewPlt, NewDocPlt} ->
message(State, "Analysis done"),
config_gui_stop(State),
gui_loop(State#gui_state{doc_plt = NewDocPlt});
{'EXIT', BackendPid, {error, Reason}} ->
free_editor(State, ?DIALYZER_ERROR_TITLE, Reason),
config_gui_stop(State),
gui_loop(State);
{'EXIT', BackendPid, Reason} when Reason =/= 'normal' ->
free_editor(State, ?DIALYZER_ERROR_TITLE, io_lib:format("~p", [Reason])),
config_gui_stop(State),
gui_loop(State)
end.
maybe_quit(#gui_state{frame = Frame} = State) ->
case dialog(State, "Do you really want to quit?", ?DIALYZER_MESSAGE_TITLE) of
true ->
wxWindow:destroy(Frame),
true;
false ->
false
end.
%% ------------ Yes/No Question ------------
dialog(#gui_state{frame = Frame}, Message, Title) ->
MessageWin = wxMessageDialog:new(Frame, Message, [{caption, Title},{style, ?wxYES_NO bor ?wxICON_QUESTION bor ?wxNO_DEFAULT}]),
case wxDialog:showModal(MessageWin) of
?wxID_YES ->
true;
?wxID_NO ->
false;
?wxID_CANCEL ->
false
end.
search_doc_plt(#gui_state{gui = Wx} = State) ->
Dialog = wxFrame:new(Wx, ?SearchPltDialog, "Search the PLT",[{size,{400,100}},{style, ?wxSTAY_ON_TOP}]),
Size = {size,{120,30}},
ModLabel = wxStaticText:new(Dialog, ?ModLabel, "Module"),
ModText = wxTextCtrl:new(Dialog, ?ModText,[Size]),
FunLabel = wxStaticText:new(Dialog, ?FunLabel, "Function"),
FunText = wxTextCtrl:new(Dialog, ?FunText,[Size]),
ArLabel = wxStaticText:new(Dialog, ?ArLabel, "Arity"),
ArText = wxTextCtrl:new(Dialog, ?ArText,[Size]),
SearchButton = wxButton:new(Dialog, ?SearchButton, [{label, "Search"}]),
wxButton:connect(SearchButton, command_button_clicked),
Cancel = wxButton:new(Dialog, ?Search_Cancel, [{label, "Cancel"}]),
wxButton:connect(Cancel, command_button_clicked),
Layout = wxBoxSizer:new(?wxVERTICAL),
Top = wxBoxSizer:new(?wxHORIZONTAL),
ModLayout = wxBoxSizer:new(?wxVERTICAL),
FunLayout = wxBoxSizer:new(?wxVERTICAL),
ArLayout = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(ModLayout, ModLabel, ?BorderOpt),
wxSizer:add(ModLayout,ModText, ?BorderOpt),
wxSizer:add(FunLayout, FunLabel, ?BorderOpt),
wxSizer:add(FunLayout,FunText, ?BorderOpt),
wxSizer:add(ArLayout, ArLabel, ?BorderOpt),
wxSizer:add(ArLayout,ArText, ?BorderOpt),
wxSizer:add(Buttons, SearchButton, ?BorderOpt),
wxSizer:add(Buttons,Cancel, ?BorderOpt),
wxSizer:add(Top, ModLayout),
wxSizer:add(Top, FunLayout),
wxSizer:add(Top, ArLayout),
wxSizer:add(Layout, Top,[{flag, ?wxALIGN_CENTER}]),
wxSizer:add(Layout, Buttons,[{flag, ?wxALIGN_CENTER bor ?wxBOTTOM}]),
wxFrame:connect(Dialog, close_window),
wxWindow:setSizer(Dialog, Layout),
wxFrame:show(Dialog),
search_plt_loop(State, Dialog, ModText, FunText, ArText, SearchButton, Cancel).
search_plt_loop(State= #gui_state{doc_plt = DocPlt, frame = Frame}, Win, ModText, FunText, ArText, Search, Cancel) ->
receive
#wx{id = ?Search_Cancel,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win);
#wx{id = ?SearchPltDialog, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win);
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
wxWindow:destroy(Frame);
#wx{id = ?SearchButton,
event = #wxCommand{type = command_button_clicked}} ->
M = format_search(wxTextCtrl:getValue(ModText)),
F = format_search(wxTextCtrl:getValue(FunText)),
A = format_search(wxTextCtrl:getValue(ArText)),
if
(M =:= '_') orelse (F =:= '_') orelse (A =:= '_') ->
error_sms(State, "Please give:\n Module (atom)\n Function (atom)\n Arity (integer)\n"),
search_plt_loop(State, Win, ModText, FunText, ArText, Search, Cancel);
true ->
case dialyzer_plt:get_specs(DocPlt, M, F, A) of
none ->
error_sms(State, "No such function"),
search_plt_loop(State, Win, ModText, FunText, ArText, Search, Cancel);
NonEmptyString ->
wxWindow:destroy(Win),
free_editor(State, "Content of PLT", NonEmptyString)
end
end
end.
format_search([]) ->
'_';
format_search(String) ->
try list_to_integer(String)
catch error:_ -> list_to_atom(String)
end.
show_doc_plt(#gui_state{doc_plt = DocPLT} = State) ->
case dialyzer_plt:get_specs(DocPLT) of
"" -> error_sms(State, "No analysis has been made yet!\n");
NonEmptyString -> free_editor(State, "Content of PLT", NonEmptyString)
end.
message(State, Message) ->
output_sms(State, ?DIALYZER_MESSAGE_TITLE, Message, info).
error_sms(State, Message) ->
output_sms(State, ?DIALYZER_ERROR_TITLE, Message, error).
output_sms(#gui_state{frame = Frame}, Title, Message, Type) ->
case Type of
error ->
MessageWin = wxMessageDialog:new(Frame,Message,[{caption, Title},{style, ?wxOK bor ?wxICON_ERROR}]);
info ->
MessageWin = wxMessageDialog:new(Frame,Message,[{caption, Title},{style, ?wxOK bor ?wxICON_INFORMATION}])
end,
wxWindow:setSizeHints(MessageWin, {350,100}),
wxDialog:showModal(MessageWin).
free_editor(#gui_state{gui = Wx, frame = Frame}, Title, Contents0) ->
Contents = lists:flatten(Contents0),
Tokens = string:tokens(Contents, "\n"),
NofLines = length(Tokens),
LongestLine = lists:max([length(X) || X <- Tokens]),
Height0 = NofLines * 25 + 80,
Height = if Height0 > 500 -> 500; true -> Height0 end,
Width0 = LongestLine * 7 + 60,
Width = if Width0 > 800 -> 800; true -> Width0 end,
Size = {size,{Width, Height}},
Win = wxFrame:new(Wx, ?Message, Title, [{size,{Width+4, Height+50}}]),
Editor = wxTextCtrl:new(Win, ?Message_Info,
[Size,
{style, ?wxTE_MULTILINE
bor ?wxTE_READONLY bor ?wxVSCROLL bor ?wxEXPAND}]),
wxTextCtrl:appendText(Editor, Contents),
wxFrame:connect(Win, close_window),
Ok = wxButton:new(Win, ?Message_Ok, [{label, "OK"}]),
wxButton:connect(Ok, command_button_clicked),
Layout = wxBoxSizer:new(?wxVERTICAL),
wxSizer:add(Layout, Editor, ?BorderOpt),
wxSizer:add(Layout, Ok, [{flag, ?wxALIGN_CENTER bor ?wxBOTTOM bor ?wxALL}, ?Border]),
wxWindow:setSizer(Win, Layout),
wxWindow:show(Win),
show_info_loop(Frame, Win).
show_info_loop(Frame, Win) ->
receive
#wx{id = ?Message_Ok, event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win);
#wx{id = ?Message, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win);
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Frame)
end.
handle_add_files(#gui_state{chosen_box = ChosenBox, file_box = FileBox,
files_to_analyze = FileList,
mode = Mode} = State) ->
case wxFilePickerCtrl:getPath(FileBox) of
"" ->
State;
File ->
NewFile = ordsets:new(),
NewFile1 = ordsets:add_element(File,NewFile),
Ext =
case wxRadioBox:getSelection(Mode) of
0 -> ".beam";
1-> ".erl"
end,
State#gui_state{files_to_analyze = add_files(filter_mods(NewFile1, Ext), FileList, ChosenBox, Ext)}
end.
handle_add_dir(#gui_state{chosen_box = ChosenBox, dir_entry = DirBox,
files_to_analyze = FileList,
mode = Mode} = State) ->
case wxDirPickerCtrl:getPath(DirBox) of
"" ->
State;
Dir ->
NewDir = ordsets:new(),
NewDir1 = ordsets:add_element(Dir,NewDir),
Ext = case wxRadioBox:getSelection(Mode) of
0 -> ".beam";
1-> ".erl"
end,
State#gui_state{files_to_analyze = add_files(filter_mods(NewDir1,Ext), FileList, ChosenBox, Ext)}
end.
handle_add_rec(#gui_state{chosen_box = ChosenBox, dir_entry = DirBox, files_to_analyze = FileList,
mode = Mode} = State) ->
case wxDirPickerCtrl:getPath(DirBox) of
"" ->
State;
Dir ->
NewDir = ordsets:new(),
NewDir1 = ordsets:add_element(Dir,NewDir),
TargetDirs = ordsets:union(NewDir1, all_subdirs(NewDir1)),
case wxRadioBox:getSelection(Mode) of
0 -> Ext = ".beam";
1-> Ext = ".erl"
end,
State#gui_state{files_to_analyze = add_files(filter_mods(TargetDirs,Ext), FileList, ChosenBox, Ext)}
end.
handle_file_delete(#gui_state{chosen_box = ChosenBox,
files_to_analyze = FileList} = State) ->
{_, List} = wxListBox:getSelections(ChosenBox),
Set = ordsets:from_list([wxControlWithItems:getString(ChosenBox, X) || X <- List]),
FileList1 = ordsets:subtract(FileList,Set),
lists:foreach(fun (X) -> wxListBox:delete(ChosenBox, X) end, List),
State#gui_state{files_to_analyze = FileList1}.
handle_file_delete_all(#gui_state{chosen_box = ChosenBox} = State) ->
wxListBox:clear(ChosenBox),
State#gui_state{files_to_analyze = ordsets:new()}.
add_files(File, FileList, ChosenBox, Ext) ->
Set = filter_mods(FileList, Ext),
Files = ordsets:union(File, Set),
Files1 = ordsets:to_list(Files),
wxListBox:set(ChosenBox, Files1),
Files.
filter_mods(Mods, Extension) ->
Fun = fun(X) ->
filename:extension(X) =:= Extension
orelse
(filelib:is_dir(X) andalso
contains_files(X, Extension))
end,
ordsets:filter(Fun, Mods).
contains_files(Dir, Extension) ->
{ok, Files} = file:list_dir(Dir),
lists:any(fun(X) -> filename:extension(X) =:= Extension end, Files).
all_subdirs(Dirs) ->
all_subdirs(Dirs, []).
all_subdirs([Dir|T], Acc) ->
{ok, Files} = file:list_dir(Dir),
SubDirs = lists:zf(fun(F) ->
SubDir = filename:join(Dir, F),
case filelib:is_dir(SubDir) of
true -> {true, SubDir};
false -> false
end
end, Files),
NewAcc = ordsets:union(ordsets:from_list(SubDirs), Acc),
all_subdirs(T ++ SubDirs, NewAcc);
all_subdirs([], Acc) ->
Acc.
start_analysis(State) ->
Analysis = build_analysis_record(State),
case get_anal_files(State, Analysis#analysis.start_from) of
error ->
Msg = "You must choose one or more files or dirs\n"
"before starting the analysis!",
error_sms(State, Msg),
config_gui_stop(State),
State;
{ok, Files} ->
Msg = "\n========== Starting Analysis ==========\n\n",
update_editor(State#gui_state.log, Msg),
NewAnalysis = Analysis#analysis{files = Files},
run_analysis(State, NewAnalysis)
end.
build_analysis_record(#gui_state{mode = Mode, menu = Menu, options = Options,
init_plt = InitPlt0}) ->
StartFrom =
case wxRadioBox:getSelection(Mode) of
0 -> byte_code;
1 -> src_code
end,
InitPlt =
case wxMenu:isChecked(Menu#menu.plt, ?menuID_PLT_INIT_EMPTY) of
true -> dialyzer_plt:new();
false -> InitPlt0
end,
#analysis{defines = Options#options.defines,
include_dirs = Options#options.include_dirs,
plt = InitPlt,
start_from = StartFrom}.
get_anal_files(#gui_state{files_to_analyze = Files}, StartFrom) ->
FilteredMods =
case StartFrom of
src_code -> filter_mods(Files, ".erl");
byte_code -> filter_mods(Files, ".beam")
end,
FilteredDirs = [X || X <- Files, filelib:is_dir(X)],
case ordsets:union(FilteredMods, FilteredDirs) of
[] -> error;
Set -> {ok, Set}
end.
run_analysis(State, Analysis) ->
config_gui_start(State),
Self = self(),
NewAnalysis = Analysis#analysis{doc_plt = dialyzer_plt:new()},
LegalWarnings = find_legal_warnings(State),
Fun =
fun() ->
dialyzer_analysis_callgraph:start(Self, LegalWarnings, NewAnalysis)
end,
BackendPid = spawn_link(Fun),
State#gui_state{backend_pid = BackendPid}.
find_legal_warnings(#gui_state{menu = #menu{warnings = MenuWarnings},
wantedWarnings = Warnings }) ->
ordsets:from_list([Tag || {Tag, MenuItem} <- Warnings,
wxMenu:isChecked(MenuWarnings, MenuItem)]).
update_editor(Editor, Msg) ->
wxTextCtrl:appendText(Editor,Msg).
config_gui_stop(State) ->
wxWindow:disable(State#gui_state.stop),
wxWindow:enable(State#gui_state.run),
wxWindow:enable(State#gui_state.del_file),
wxWindow:enable(State#gui_state.clear_chosen),
wxWindow:enable(State#gui_state.add),
wxWindow:enable(State#gui_state.add_dir),
wxWindow:enable(State#gui_state.add_rec),
wxWindow:enable(State#gui_state.clear_warn),
wxWindow:enable(State#gui_state.clear_log),
Menu = State#gui_state.menu,
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_WARNINGS,true),
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_LOG,true),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_MACRO,true),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_INCLUDE_DIR,true),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_INIT_EMPTY,true),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SHOW_CONTENTS,true),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SEARCH_CONTENTS,true),
wxRadioBox:enable(State#gui_state.mode).
config_gui_start(State) ->
wxWindow:enable(State#gui_state.stop),
wxWindow:disable(State#gui_state.run),
wxWindow:disable(State#gui_state.del_file),
wxWindow:disable(State#gui_state.clear_chosen),
wxWindow:disable(State#gui_state.add),
wxWindow:disable(State#gui_state.add_dir),
wxWindow:disable(State#gui_state.add_rec),
wxWindow:disable(State#gui_state.clear_warn),
wxWindow:disable(State#gui_state.clear_log),
Menu = State#gui_state.menu,
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_WARNINGS, false),
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_LOG, false),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_MACRO, false),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_INCLUDE_DIR, false),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_INIT_EMPTY, false),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SHOW_CONTENTS, false),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SEARCH_CONTENTS, false),
wxRadioBox:disable(State#gui_state.mode).
save_file(#gui_state{frame = Frame, warnings_box = WBox, log = Log} = State, Type) ->
case Type of
warnings ->
Message = "Save Warnings",
Box = WBox;
log -> Message = "Save Log",
Box = Log
end,
case wxTextCtrl:getValue(Box) of
"" -> error_sms(State,"There is nothing to save...\n");
_ ->
DefaultPath = code:root_dir(),
FileDialog = wxFileDialog:new(Frame,
[{defaultDir, DefaultPath},
{message, Message},
{style,?wxFD_SAVE bor ?wxFD_OVERWRITE_PROMPT}]),
case wxFileDialog:showModal(FileDialog) of
?wxID_OK -> Path = wxFileDialog:getPath(FileDialog),
case wxTextCtrl:saveFile(Box,[{file,Path}]) of
true -> ok;
false -> error_sms(State,"Could not write to file:\n" ++ Path)
end;
?wxID_CANCEL -> wxWindow:destroy(FileDialog);
_ -> error_sms(State,"Could not write to file:\n")
end
end.
include_dialog(#gui_state{gui = Wx, frame = Frame, options = Options}) ->
Size = {size,{300,480}},
Dialog = wxFrame:new(Wx, ?IncludeDir, "Include Directories",[Size]),
DirLabel = wxStaticText:new(Dialog, ?InclLabel, "Directory: "),
DefaultPath = code:root_dir(),
DirPicker = wxDirPickerCtrl:new(Dialog, ?InclPicker,
[{path, DefaultPath},
{message, "Choose Directory to Include"},
{style,?wxDIRP_DIR_MUST_EXIST bor ?wxDIRP_USE_TEXTCTRL}]),
Box = wxListBox:new(Dialog, ?InclBox,
[{size, {200,300}},
{style, ?wxLB_EXTENDED bor ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
AddButton = wxButton:new(Dialog, ?InclAdd, [{label, "Add"}]),
DeleteButton = wxButton:new(Dialog, ?InclDel, [{label, "Delete"}]),
DeleteAllButton = wxButton:new(Dialog, ?InclDelAll, [{label, "Delete All"}]),
Ok = wxButton:new(Dialog, ?InclOk, [{label, "OK"}]),
Cancel = wxButton:new(Dialog, ?InclCancel, [{label, "Cancel"}]),
wxButton:connect(AddButton, command_button_clicked),
wxButton:connect(DeleteButton, command_button_clicked),
wxButton:connect(DeleteAllButton, command_button_clicked),
wxButton:connect(Ok, command_button_clicked),
wxButton:connect(Cancel, command_button_clicked),
Dirs = [io_lib:format("~s", [X])
|| X <- Options#options.include_dirs],
wxListBox:set(Box, Dirs),
Layout = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
Buttons1 = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(Layout, DirLabel, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Layout, DirPicker, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Layout,AddButton, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Layout,Box, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Buttons, DeleteButton, ?BorderOpt),
wxSizer:add(Buttons, DeleteAllButton, ?BorderOpt),
wxSizer:add(Layout,Buttons, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Buttons1, Ok, ?BorderOpt),
wxSizer:add(Buttons1,Cancel, ?BorderOpt),
wxSizer:add(Layout,Buttons1,[{flag, ?wxALIGN_RIGHT bor ?wxBOTTOM}]),
wxFrame:connect(Dialog, close_window),
wxWindow:setSizer(Dialog, Layout),
wxFrame:show(Dialog),
include_loop(Options, Dialog, Box, DirPicker, Frame).
include_loop(Options, Win, Box, DirPicker, Frame) ->
receive
#wx{id = ?InclCancel,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?IncludeDir, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
Options;
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
wxWindow:destroy(Frame);
#wx{id = ?InclOk,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?InclAdd,
event = #wxCommand{type = command_button_clicked}} ->
Dirs = Options#options.include_dirs,
NewDirs =
case wxDirPickerCtrl:getPath(DirPicker) of
"" -> Dirs;
Add -> [Add|Dirs]
end,
NewOptions = Options#options{include_dirs = NewDirs},
wxListBox:set(Box, NewDirs),
include_loop(NewOptions, Win, Box, DirPicker, Frame);
#wx{id = ?InclDel,
event = #wxCommand{type = command_button_clicked}} ->
NewOptions =
case wxListBox:getSelections(Box) of
{0,_} -> Options;
{_,List} ->
DelList = [wxControlWithItems:getString(Box,X) || X <- List],
NewDirs = Options#options.include_dirs -- DelList,
lists:foreach(fun (X) -> wxListBox:delete(Box, X) end, List),
Options#options{include_dirs = NewDirs}
end,
include_loop(NewOptions, Win, Box, DirPicker, Frame);
#wx{id = ?InclDelAll,
event = #wxCommand{type = command_button_clicked}} ->
wxListBox:clear(Box),
NewOptions = Options#options{include_dirs = []},
include_loop(NewOptions, Win, Box, DirPicker, Frame)
end.
macro_dialog(#gui_state{gui = Wx, frame = Frame, options = Options}) ->
Size = {size,{300,480}},
Size1 = {size,{120,30}},
Dialog = wxFrame:new(Wx, ?MacroDir, "Macro Definitions",[Size]),
MacroLabel = wxStaticText:new(Dialog, ?MacroLabel, "Macro"),
TermLabel = wxStaticText:new(Dialog, ?TermLabel, "Term"),
MacroText = wxTextCtrl:new(Dialog, ?MacroText, [Size1]),
TermText = wxTextCtrl:new(Dialog, ?TermText, [Size1]),
Box = wxListBox:new(Dialog, ?MacroBox,
[{size, {250,300}},
{style, ?wxLB_EXTENDED bor ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
AddButton = wxButton:new(Dialog, ?MacroAdd, [{label, "Add"}]),
DeleteButton = wxButton:new(Dialog, ?MacroDel, [{label, "Delete"}]),
DeleteAllButton = wxButton:new(Dialog, ?MacroDelAll, [{label, "Delete All"}]),
Ok = wxButton:new(Dialog, ?MacroOk, [{label, "OK"}]),
Cancel = wxButton:new(Dialog, ?MacroCancel, [{label, "Cancel"}]),
wxButton:connect(AddButton, command_button_clicked),
wxButton:connect(DeleteButton, command_button_clicked),
wxButton:connect(DeleteAllButton, command_button_clicked),
wxButton:connect(Ok, command_button_clicked),
wxButton:connect(Cancel, command_button_clicked),
Macros = [io_lib:format("~p = ~p", [X, Y])
|| {X,Y} <- Options#options.defines],
wxListBox:set(Box, Macros),
Layout = wxBoxSizer:new(?wxVERTICAL),
Item = wxBoxSizer:new(?wxHORIZONTAL),
MacroItem = wxBoxSizer:new(?wxVERTICAL),
TermItem = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
Buttons1 = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(MacroItem, MacroLabel, ?BorderOpt),
wxSizer:add(MacroItem, MacroText, ?BorderOpt),
wxSizer:add(TermItem, TermLabel, ?BorderOpt),
wxSizer:add(TermItem, TermText, ?BorderOpt),
wxSizer:add(Item, MacroItem),
wxSizer:add(Item, TermItem),
wxSizer:add(Layout, Item, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Layout, AddButton, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Layout, Box, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Buttons, DeleteButton, ?BorderOpt),
wxSizer:add(Buttons, DeleteAllButton, ?BorderOpt),
wxSizer:add(Layout, Buttons, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Buttons1, Ok, ?BorderOpt),
wxSizer:add(Buttons1, Cancel, ?BorderOpt),
wxSizer:add(Layout, Buttons1, [{flag, ?wxALIGN_RIGHT bor ?wxBOTTOM}]),
wxFrame:connect(Dialog, close_window),
wxWindow:setSizer(Dialog, Layout),
wxFrame:show(Dialog),
macro_loop(Options, Dialog, Box, MacroText, TermText, Frame).
macro_loop(Options, Win, Box, MacroText, TermText, Frame) ->
receive
#wx{id = ?MacroCancel,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?MacroDir, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
Options;
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
wxWindow:destroy(Frame);
#wx{id = ?MacroOk,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?MacroAdd,
event = #wxCommand{type = command_button_clicked}} ->
Defines = Options#options.defines,
NewDefines =
case wxTextCtrl:getValue(MacroText) of
"" -> Defines;
Macro ->
case wxTextCtrl:getValue(TermText) of
"" ->
orddict:store(list_to_atom(Macro), true, Defines);
String ->
orddict:store(list_to_atom(Macro), String, Defines)
end
end,
NewOptions = Options#options{defines = NewDefines},
NewEntries = [io_lib:format("~p = ~p", [X, Y]) || {X, Y} <- NewDefines],
wxListBox:set(Box, NewEntries),
macro_loop(NewOptions, Win, Box, MacroText, TermText, Frame);
#wx{id = ?MacroDel,
event = #wxCommand{type = command_button_clicked}} ->
NewOptions =
case wxListBox:getSelections(Box) of
{0, _} -> Options;
{_, List} ->
Fun =
fun(X) ->
Val = wxControlWithItems:getString(Box,X),
[MacroName|_] = re:split(Val, " ", [{return, list}]),
list_to_atom(MacroName)
end,
Delete = [Fun(X) || X <- List],
lists:foreach(fun (X) -> wxListBox:delete(Box, X) end, List),
Defines = Options#options.defines,
NewDefines = lists:foldl(fun(X, Acc) ->
orddict:erase(X, Acc)
end,
Defines, Delete),
Options#options{defines = NewDefines}
end,
macro_loop(NewOptions, Win, Box, MacroText, TermText, Frame);
#wx{id = ?MacroDelAll,
event = #wxCommand{type = command_button_clicked}} ->
wxListBox:clear(Box),
NewOptions = Options#options{defines = []},
macro_loop(NewOptions, Win, Box, MacroText, TermText, Frame)
end.
handle_help(State, Title, Txt) ->
FileName = filename:join([code:lib_dir(dialyzer), "doc", Txt]),
case file:open(FileName, [read]) of
{error, Reason} ->
error_sms(State,
io_lib:format("Could not find doc/~s file!\n\n ~p",
[Txt, Reason]));
{ok, _Handle} ->
case file:read_file(FileName) of
{error, Reason} ->
error_sms(State,
io_lib:format("Could not read doc/~s file!\n\n ~p",
[Txt, Reason]));
{ok, Binary} ->
Contents = binary_to_list(Binary),
free_editor(State, Title, Contents)
end
end.
add_warnings(#gui_state{warnings_box = WarnBox,
rawWarnings = RawWarns} = State, Warnings) ->
NewRawWarns = RawWarns ++ Warnings,
WarnList = [dialyzer:format_warning(W) -- "\n" || W <- NewRawWarns],
wxListBox:set(WarnBox, WarnList),
State#gui_state{rawWarnings = NewRawWarns}.
handle_explanation(#gui_state{rawWarnings = RawWarns,
warnings_box = WarnBox,
expl_pid = ExplPid} = State) ->
case wxListBox:isEmpty(WarnBox) of
true ->
error_sms(State, "\nThere are no warnings.\nRun the dialyzer first.");
false ->
case wxListBox:getSelections(WarnBox)of
{0, []} ->
error_sms(State,"\nYou must choose a warning to be explained\n");
{_, [WarnNumber]} ->
Warn = lists:nth(WarnNumber+1,RawWarns),
Self = self(),
ExplPid ! {Self, warning, Warn},
explanation_loop(State)
end
end.
explanation_loop(#gui_state{expl_pid = ExplPid} = State) ->
receive
{ExplPid, explanation, Explanation} ->
show_explanation(State, Explanation);
_ -> io:format("Unknown message\n"),
explanation_loop(State)
end.
show_explanation(#gui_state{gui = Wx} = State, Explanation) ->
case Explanation of
none ->
output_sms(State, ?DIALYZER_MESSAGE_TITLE,
"There is not any explanation for this error!\n", info);
Expl ->
ExplString = format_explanation(Expl),
Size = {size,{700, 300}},
Win = wxFrame:new(Wx, ?ExplWin, "Dialyzer Explanation", [{size,{740, 350}}]),
Editor = wxTextCtrl:new(Win, ?ExplText,
[Size,
{style, ?wxTE_MULTILINE
bor ?wxTE_READONLY bor ?wxVSCROLL bor ?wxEXPAND}]),
wxTextCtrl:appendText(Editor, ExplString),
wxFrame:connect(Win, close_window),
ExplButton = wxButton:new(Win, ?ExplButton, [{label, "Further Explain"}]),
wxButton:connect(ExplButton, command_button_clicked),
Ok = wxButton:new(Win, ?ExplOk, [{label, "OK"}]),
wxButton:connect(Ok, command_button_clicked),
Layout = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(Buttons, ExplButton, ?BorderOpt),
wxSizer:add(Buttons, Ok, ?BorderOpt),
wxSizer:add(Layout, Editor,[{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Layout, Buttons,[{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxWindow:setSizer(Win, Layout),
wxWindow:show(Win),
show_explanation_loop(State#gui_state{explanation_box = Editor}, Win, Explanation)
end.
show_explanation_loop(#gui_state{frame = Frame, expl_pid = ExplPid} = State, Win, Explanation) ->
receive
{ExplPid, none, _} ->
output_sms(State, ?DIALYZER_MESSAGE_TITLE,
"There is not any other explanation for this error!\n", info),
show_explanation_loop(State, Win, Explanation);
{ExplPid, further, NewExplanation} ->
update_explanation(State, NewExplanation),
show_explanation_loop(State, Win, NewExplanation);
#wx{id = ?ExplButton, event = #wxCommand{type = command_button_clicked}} ->
ExplPid ! {self(), further, Explanation},
show_explanation_loop(State, Win, Explanation);
#wx{id = ?ExplOk, event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win);
#wx{id = ?ExplWin, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win);
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Frame)
end.
update_explanation(#gui_state{explanation_box = Box}, Explanation) ->
ExplString = format_explanation(Explanation),
wxTextCtrl:appendText(Box, "\n --------------------------- \n"),
wxTextCtrl:appendText(Box, ExplString).
format_explanation({function_return, {M, F, A}, NewList}) ->
io_lib:format("The function ~p: ~p/~p returns ~p\n",
[M, F, A, erl_types:t_to_string(NewList)]);
format_explanation(Explanation) ->
io_lib:format("~p\n", [Explanation]).
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/dialyzer/src/dialyzer_gui_wx.erl | erlang | ------------------------------------------------------------------------
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
-----------------------------------------------------------------------
File : dialyzer_gui_wx.erl
Description : The wx-based graphical user interface of dialyzer.
-----------------------------------------------------------------------
------------------------------------------------------------------------
------------------------------------------------------------------------
------------------------------------------------------------------------
---------- initializing frame ---------
----------- Set Labels -------------
--------- Set Buttons --------------
------------Set Layout ------------
For contracts.
----------------------------------------------------------------
io:format("~p Closing window ~n", [self()]),
----- Menu -----
------ Buttons ---------
----- Analysis -----
Sort on file/line
------------ Yes/No Question ------------ | -*- erlang - indent - level : 2 -*-
Copyright Ericsson AB 2009 - 2012 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
Authors : < >
Created : 07 Oct 2009 by < >
-module(dialyzer_gui_wx).
-export([start/1]).
-include("dialyzer.hrl").
-include("dialyzer_gui_wx.hrl").
-define(DIALYZER_ERROR_TITLE, "Dialyzer Error").
-define(DIALYZER_MESSAGE_TITLE, "Dialyzer Message").
-record(menu, {file :: wx:wx_object(),
warnings :: wx:wx_object(),
plt :: wx:wx_object(),
options :: wx:wx_object(),
help :: wx:wx_object()}).
-type menu() :: #menu{}.
-record(gui_state, {add :: wx:wx_object(),
add_dir :: wx:wx_object(),
add_rec :: wx:wx_object(),
chosen_box :: wx:wx_object(),
analysis_pid :: pid(),
del_file :: wx:wx_object(),
doc_plt :: dialyzer_plt:plt(),
clear_chosen :: wx:wx_object(),
clear_log :: wx:wx_object(),
explain_warn :: wx:wx_object(),
clear_warn :: wx:wx_object(),
init_plt :: dialyzer_plt:plt(),
dir_entry :: wx:wx_object(),
file_box :: wx:wx_object(),
files_to_analyze :: ordset(string()),
gui :: wx:wx_object(),
log :: wx:wx_object(),
menu :: menu(),
mode :: wx:wx_object(),
options :: #options{},
run :: wx:wx_object(),
stop :: wx:wx_object(),
frame :: wx:wx_object(),
warnings_box :: wx:wx_object(),
explanation_box :: wx:wx_object(),
wantedWarnings :: list(),
rawWarnings :: list(),
backend_pid :: pid(),
expl_pid :: pid()}).
-spec start(#options{}) -> ?RET_NOTHING_SUSPICIOUS.
start(DialyzerOptions) ->
process_flag(trap_exit, true),
Wx = wx:new(),
State = wx:batch(fun() -> create_window(Wx, DialyzerOptions) end),
gui_loop(State).
create_window(Wx, #options{init_plts = InitPltFiles} = DialyzerOptions) ->
{ok, Host} = inet:gethostname(),
Frame = wxFrame:new(Wx, -1, "Dialyzer " ++ ?VSN ++ " @ " ++ Host),
wxFrame:connect(Frame, close_window),
FileMenu = createFileMenu(),
WarningsMenu = createWarningsMenu(),
PltMenu = createPltMenu(),
OptionsMenu = createOptionsMenu(),
HelpMenu = createHelpMenu(),
MenuBar = wxMenuBar:new(),
wxMenuBar:append(MenuBar, FileMenu, "File"),
wxMenuBar:append(MenuBar, WarningsMenu, "Warnings"),
wxMenuBar:append(MenuBar, PltMenu, "Plt"),
wxMenuBar:append(MenuBar, OptionsMenu, "Options"),
wxMenuBar:append(MenuBar, HelpMenu, "Help"),
wxFrame:setMenuBar(Frame, MenuBar),
ok = wxFrame:connect(Frame, command_menu_selected),
Lab1 = wxStaticText:new(Frame, ?LABEL1, "Directories or modules to analyze"),
OptionsLabel = wxStaticText:new(Frame, ?LABEL2, "Analysis Options"),
LogLabel = wxStaticText:new(Frame, ?LABEL3, "Log"),
FileLabel = wxStaticText:new(Frame, ?LABEL4, "File: "),
DirLabel = wxStaticText:new(Frame, ?LABEL5, "Dir: "),
WarningsLabel = wxStaticText:new(Frame, ?LABEL6, "Warnings"),
---------- Set TextBoxes -----------
ChosenBox = wxListBox:new(Frame, ?ChosenBox,
[{size, {250,200}},
{style, ?wxLB_EXTENDED bor ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
LogBox = wxTextCtrl:new(Frame, ?LogBox,
[{size, {530,200}},
{style, ?wxTE_MULTILINE
bor ?wxTE_READONLY bor ?wxHSCROLL}]),
DefaultPath = code:root_dir(),
FilePicker = wxFilePickerCtrl:new(Frame, ?FilePicker,
[{path, DefaultPath},
{message, "Choose File to Analyse"},
{style,?wxFLP_FILE_MUST_EXIST bor ?wxFLP_USE_TEXTCTRL}]),
wxPickerBase:setTextCtrlProportion(FilePicker,3),
wxPickerBase:setPickerCtrlProportion(FilePicker,2),
DirPicker = wxDirPickerCtrl:new(Frame, ?DirPicker,
[{path, DefaultPath},
{message, "Choose Directory to Analyze"},
{style,?wxDIRP_DIR_MUST_EXIST bor ?wxDIRP_USE_TEXTCTRL}]),
WarningsBox = wxListBox:new(Frame, ?WarningsBox,
[{size, {700,200}},
{style, ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
DeleteButton = wxButton:new(Frame, ?Del_Button, [{label, "Delete"}]),
DeleteAllButton = wxButton:new(Frame, ?DelAll_Button, [{label, "Delete All"}]),
FileType = wxRadioBox:new(Frame, ?RADIOBOX, " File Type: " , {1,1}, {150,90},
[["BeamFiles"],["SourceFiles"]]),
ClearLogButton = wxButton:new(Frame, ?ClearLog_Button, [{label, "Clear Log"}]),
AddButton = wxButton:new(Frame, ?Add_Button, [{label, "Add"}]),
AddDirButton = wxButton:new(Frame, ?AddDir_Button, [{label, "Add Dir"}]),
AddRecButton = wxButton:new(Frame, ?AddRec_Button, [{label, "Add Recursively"}]),
ExplainWarnButton = wxButton:new(Frame, ?ExplWarn_Button, [{label, "Explain Warning"}]),
ClearWarningsButton = wxButton:new(Frame, ?ClearWarn_Button, [{label, "Clear Warnings"}]),
RunButton = wxButton:new(Frame, ?Run_Button, [{label, "Run"}]),
StopButton = wxButton:new(Frame, ?Stop_Button, [{label, "Stop"}]),
wxWindow:disable(StopButton),
--------- Connect Buttons -----------
wxButton:connect(DeleteButton, command_button_clicked),
wxButton:connect(DeleteAllButton, command_button_clicked),
wxButton:connect(ClearLogButton, command_button_clicked),
wxButton:connect(AddButton, command_button_clicked),
wxButton:connect(AddDirButton, command_button_clicked),
wxButton:connect(AddRecButton, command_button_clicked),
wxButton:connect(ExplainWarnButton, command_button_clicked),
wxButton:connect(ClearWarningsButton, command_button_clicked),
wxButton:connect(RunButton, command_button_clicked),
wxButton:connect(StopButton, command_button_clicked),
All = wxBoxSizer:new(?wxVERTICAL),
Top = wxBoxSizer:new(?wxHORIZONTAL),
Left = wxBoxSizer:new(?wxVERTICAL),
Right = wxBoxSizer:new(?wxVERTICAL),
RightUp = wxBoxSizer:new(?wxHORIZONTAL),
Opts = [{flag,?wxEXPAND bor ?wxALL}, {proportion,1}, {border, 1}],
Opts3 = [{flag,?wxEXPAND bor ?wxALL}, {proportion,3}, {border, 1}],
Center = [{flag, ?wxALIGN_CENTER_HORIZONTAL}],
ChooseItem = wxBoxSizer:new(?wxVERTICAL),
FileTypeItem = wxBoxSizer:new(?wxVERTICAL),
LogItem = wxBoxSizer:new(?wxVERTICAL),
FileDirItem = wxBoxSizer:new(?wxVERTICAL),
FileItem = wxBoxSizer:new(?wxHORIZONTAL),
DirItem = wxBoxSizer:new(?wxHORIZONTAL),
AddDirButtons = wxBoxSizer:new(?wxHORIZONTAL),
WarningsItem = wxBoxSizer:new(?wxVERTICAL),
ChooseButtons = wxBoxSizer:new(?wxHORIZONTAL),
WarnButtons = wxBoxSizer:new(?wxHORIZONTAL),
RunButtons = wxBoxSizer:new(?wxHORIZONTAL),
Buttons = wxFlexGridSizer:new(3),
wxSizer:add(ChooseButtons, DeleteButton, ?BorderOpt),
wxSizer:add(ChooseButtons, DeleteAllButton, ?BorderOpt),
wxSizer:add(ChooseItem, Lab1, Center),
wxSizer:add(ChooseItem, ChosenBox, Opts),
wxSizer:add(ChooseItem, ChooseButtons, ?BorderOpt),
wxSizer:add(FileTypeItem, OptionsLabel),
wxSizer:add(FileTypeItem, FileType, [{border, 5}, {flag, ?wxALL}]),
wxSizer:add(LogItem, LogLabel, Center),
wxSizer:add(LogItem, LogBox, Opts3),
wxSizer:add(LogItem, ClearLogButton, ?BorderOpt),
wxSizer:add(FileItem, FileLabel),
wxSizer:add(FileItem, FilePicker),
wxSizer:add(DirItem, DirLabel),
wxSizer:add(DirItem, DirPicker),
wxSizer:add(AddDirButtons, AddDirButton, ?BorderOpt),
wxSizer:add(AddDirButtons, AddRecButton, ?BorderOpt),
wxSizer:add(FileDirItem, FileItem),
wxSizer:add(FileDirItem, AddButton, ?BorderOpt),
wxSizer:add(FileDirItem, DirItem, ?BorderOpt),
wxSizer:add(FileDirItem, AddDirButtons, ?BorderOpt),
wxSizer:add(WarnButtons, ExplainWarnButton, ?BorderOpt),
wxSizer:add(WarnButtons, ClearWarningsButton, ?BorderOpt),
wxSizer:add(RunButtons, RunButton, ?BorderOpt),
wxSizer:add(RunButtons, StopButton, ?BorderOpt),
wxSizer:add(Buttons, WarnButtons),
wxSizer:add(Buttons, wxStaticText:new(Frame, ?LABEL7, ""), [{flag, ?wxEXPAND}]),
wxSizer:add(Buttons, RunButtons),
wxFlexGridSizer:addGrowableCol(Buttons, 1),
wxSizer:add(WarningsItem, WarningsLabel, Center),
wxSizer:add(WarningsItem, WarningsBox, Opts3),
wxSizer:add(WarningsItem, Buttons, [{flag, ?wxEXPAND bor ?wxALL},?Border]),
wxSizer:add(Left, ChooseItem, Opts),
wxSizer:add(Left, FileDirItem, [{proportion, 1}, {border, 60}, {flag, ?wxTOP}]),
wxSizer:add(RightUp, FileTypeItem, ?BorderOpt),
wxSizer:add(RightUp, LogItem, Opts3),
wxSizer:add(Right, RightUp, Opts3),
wxSizer:add(Right, WarningsItem, Opts3),
wxSizer:add(Top, Left, Opts),
wxSizer:add(Top, Right, Opts3),
wxSizer:add(All, Top, Opts),
wxWindow:setSizer(Frame, All),
wxWindow:setSizeHints(Frame, {1150,600}),
wxWindow:show(Frame),
Warnings = [{?WARN_RETURN_NO_RETURN, ?menuID_WARN_NO_RETURN_FUN},
{?WARN_RETURN_ONLY_EXIT, ?menuID_WARN_ERROR_HANDLING_FUN},
{?WARN_NOT_CALLED, ?menuID_WARN_UNUSED_FUN},
{?WARN_NON_PROPER_LIST, ?menuID_WARN_LIST_CONSTR},
{?WARN_FUN_APP, ?menuID_WARN_BAD_FUN},
{?WARN_MATCHING, ?menuID_WARN_MATCH_FAILURES},
{?WARN_OPAQUE, ?menuID_WARN_OPAQUE},
{?WARN_FAILING_CALL, ?menuID_WARN_FAIL_FUN_CALLS},
{?WARN_CALLGRAPH, ?menuID_WARN_UNEXPORTED_FUN},
{?WARN_RACE_CONDITION, ?menuID_WARN_RACE_CONDITIONS},
{?WARN_CONTRACT_TYPES,?menuID_WARN_WRONG_CONTRACTS},
{?WARN_CONTRACT_SYNTAX, ?menuID_WARN_CONTRACT_SYNTAX}
],
Menu = #menu{file = FileMenu,
warnings = WarningsMenu,
plt = PltMenu,
options =OptionsMenu,
help = HelpMenu},
InitPlt =
case InitPltFiles of
[] -> dialyzer_plt:new();
_ ->
Plts = [dialyzer_plt:from_file(F) || F <- InitPltFiles],
dialyzer_plt:merge_plts_or_report_conflicts(InitPltFiles, Plts)
end,
#gui_state{add = AddButton,
add_dir = AddDirButton,
add_rec = AddRecButton,
chosen_box = ChosenBox,
clear_chosen = DeleteAllButton,
clear_log = ClearLogButton,
explain_warn = ExplainWarnButton,
clear_warn = ClearWarningsButton,
del_file = DeleteButton,
doc_plt = dialyzer_plt:new(),
dir_entry = DirPicker,
file_box = FilePicker,
files_to_analyze = ordsets:new(),
gui = Wx,
init_plt = InitPlt,
log = LogBox,
menu = Menu,
mode = FileType,
options = DialyzerOptions,
run = RunButton,
stop = StopButton,
frame = Frame,
warnings_box = WarningsBox,
wantedWarnings = Warnings,
rawWarnings = []}.
createFileMenu() ->
FileMenu = wxMenu:new(),
wxMenu:append(FileMenu, wxMenuItem:new([{id, ?menuID_FILE_SAVE_WARNINGS},
{text, "Save &Warnings"}])),
wxMenu:append(FileMenu, wxMenuItem:new([{id, ?menuID_FILE_SAVE_LOG},
{text, "Save &Log"}])),
wxMenu:append(FileMenu, wxMenuItem:new([{id, ?menuID_FILE_QUIT},
{text, "E&xit\tAlt-X"}])),
FileMenu.
createWarningsMenu() ->
WarningsMenu = wxMenu:new(),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_MATCH_FAILURES,
"Match failures"),
wxMenu:check(WarningsMenu, ?menuID_WARN_MATCH_FAILURES, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_FAIL_FUN_CALLS,
"Failing function calls"),
wxMenu:check(WarningsMenu, ?menuID_WARN_FAIL_FUN_CALLS, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_BAD_FUN,
"Bad fun applications"),
wxMenu:check(WarningsMenu, ?menuID_WARN_BAD_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_OPAQUE,
"Opaqueness violations"),
wxMenu:check(WarningsMenu, ?menuID_WARN_OPAQUE, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_LIST_CONSTR,
"Improper list constructions"),
wxMenu:check(WarningsMenu, ?menuID_WARN_LIST_CONSTR, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_UNUSED_FUN,
"Unused functions"),
wxMenu:check(WarningsMenu, ?menuID_WARN_UNUSED_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_ERROR_HANDLING_FUN,
"Error handling functions"),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_NO_RETURN_FUN,
"Functions of no return"),
wxMenu:check(WarningsMenu, ?menuID_WARN_NO_RETURN_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_UNEXPORTED_FUN,
"Call to unexported function"),
wxMenu:check(WarningsMenu, ?menuID_WARN_UNEXPORTED_FUN, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_RACE_CONDITIONS,
"Possible race conditions"),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_WRONG_CONTRACTS,
"Wrong contracts"),
wxMenu:check(WarningsMenu, ?menuID_WARN_WRONG_CONTRACTS, true),
wxMenu:appendCheckItem(WarningsMenu,
?menuID_WARN_CONTRACT_SYNTAX,
"Wrong contract syntax"),
wxMenu:check(WarningsMenu, ?menuID_WARN_CONTRACT_SYNTAX, true),
WarningsMenu.
createPltMenu() ->
PltMenu = wxMenu:new(),
wxMenu:appendCheckItem(PltMenu,
?menuID_PLT_INIT_EMPTY,
"Init with empty PLT"),
wxMenu:append(PltMenu, wxMenuItem:new([{id, ?menuID_PLT_SHOW_CONTENTS},
{text, "Show contents"}])),
wxMenu:append(PltMenu, wxMenuItem:new([{id, ?menuID_PLT_SEARCH_CONTENTS},
{text, "Search contents"}])),
PltMenu.
createOptionsMenu() ->
OptsMenu = wxMenu:new(),
wxMenu:append(OptsMenu, wxMenuItem:new([{id, ?menuID_OPTIONS_MACRO},
{text, "Manage Macro Definitions"}])),
wxMenu:append(OptsMenu, wxMenuItem:new([{id, ?menuID_OPTIONS_INCLUDE_DIR},
{text, "Manage Include Directories"}])),
OptsMenu.
createHelpMenu() ->
HelpMenu = wxMenu:new(),
wxMenu:append(HelpMenu, wxMenuItem:new([{id, ?menuID_HELP_MANUAL},
{text, "Manual"}])),
wxMenu:append(HelpMenu, wxMenuItem:new([{id, ?menuID_HELP_WARNING_OPTIONS},
{text, "Warning Options"}])),
wxMenu:append(HelpMenu, wxMenuItem:new([{id, ?menuID_HELP_ABOUT},
{text, "About"}])),
HelpMenu.
Main GUI Loop
-spec gui_loop(#gui_state{}) -> ?RET_NOTHING_SUSPICIOUS.
gui_loop(#gui_state{backend_pid = BackendPid, doc_plt = DocPlt,
log = Log, frame = Frame,
warnings_box = WarningsBox} = State) ->
receive
#wx{event = #wxClose{}} ->
ok = wxFrame:setStatusText(Frame, "Closing...",[]),
wxWindow:destroy(Frame),
?RET_NOTHING_SUSPICIOUS;
#wx{id = ?menuID_FILE_SAVE_LOG, obj = Frame,
event = #wxCommand{type = command_menu_selected}} ->
save_file(State, log),
gui_loop(State);
#wx{id=?menuID_FILE_SAVE_WARNINGS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
save_file(State, warnings),
gui_loop(State);
#wx{id=?menuID_FILE_QUIT, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
case maybe_quit(State) of
true -> ?RET_NOTHING_SUSPICIOUS;
false -> gui_loop(State)
end;
#wx{id=?menuID_PLT_SHOW_CONTENTS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
show_doc_plt(State),
gui_loop(State);
#wx{id=?menuID_PLT_SEARCH_CONTENTS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
case dialyzer_plt:get_specs(DocPlt) of
"" -> error_sms(State, "No analysis has been made yet!\n");
_ -> search_doc_plt(State)
end,
gui_loop(State);
#wx{id=?menuID_OPTIONS_INCLUDE_DIR, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
NewOptions = include_dialog(State),
NewState = State#gui_state{options = NewOptions},
gui_loop(NewState);
#wx{id=?menuID_OPTIONS_MACRO, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
NewOptions = macro_dialog(State),
NewState = State#gui_state{options = NewOptions},
gui_loop(NewState);
#wx{id=?menuID_HELP_MANUAL, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
handle_help(State, "Dialyzer Manual", "manual.txt"),
gui_loop(State);
#wx{id=?menuID_HELP_WARNING_OPTIONS, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
handle_help(State, "Dialyzer Warnings", "warnings.txt"),
gui_loop(State);
#wx{id=?menuID_HELP_ABOUT, obj=Frame,
event=#wxCommand{type=command_menu_selected}} ->
Message = " This is DIALYZER version " ++ ?VSN ++ " \n"++
"DIALYZER is a DIscrepany AnaLYZer for ERlang programs.\n\n"++
" Copyright (C) Tobias Lindahl <>\n"++
" Kostis Sagonas <>\n\n",
output_sms(State, "About Dialyzer", Message, info),
gui_loop(State);
#wx{id=?Add_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_add_files(State),
gui_loop(State1);
#wx{id=?AddDir_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_add_dir(State),
gui_loop(State1);
#wx{id=?AddRec_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_add_rec(State),
gui_loop(State1);
#wx{id=?Del_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_file_delete(State),
gui_loop(State1);
#wx{id=?DelAll_Button,
event=#wxCommand{type=command_button_clicked}} ->
State1 = handle_file_delete_all(State),
gui_loop(State1);
#wx{id=?ClearLog_Button,
event=#wxCommand{type=command_button_clicked}} ->
wxTextCtrl:clear(State#gui_state.log),
gui_loop(State);
#wx{id=?ExplWarn_Button,
event=#wxCommand{type=command_button_clicked}} ->
handle_explanation(State),
gui_loop(State);
#wx{id=?ClearWarn_Button,
event=#wxCommand{type=command_button_clicked}} ->
wxListBox:clear(WarningsBox),
NewState = State#gui_state{rawWarnings = []},
gui_loop(NewState);
#wx{id=?Run_Button,
event=#wxCommand{type=command_button_clicked}} ->
NewState = start_analysis(State),
gui_loop(NewState);
#wx{id=?Stop_Button,
event=#wxCommand{type=command_button_clicked}} ->
BackendPid ! {self(), stop},
config_gui_stop(State),
update_editor(Log, "\n***** Analysis stopped ****\n"),
gui_loop(State);
{BackendPid, ext_calls, ExtCalls} ->
Msg = io_lib:format("The following functions are called "
"but type information about them is not available.\n"
"The analysis might get more precise by including "
"the modules containing these functions:\n\n\t~p\n",
[ExtCalls]),
free_editor(State,"Analysis Done", Msg),
gui_loop(State);
{BackendPid, ext_types, ExtTypes} ->
Map = fun({M,F,A}) -> io_lib:format("~p:~p/~p",[M,F,A]) end,
ExtTypeString = string:join(lists:map(Map, ExtTypes), "\n"),
Msg = io_lib:format("The following remote types are being used "
"but information about them is not available.\n"
"The analysis might get more precise by including "
"the modules containing these types and making sure "
"that they are exported:\n~s\n", [ExtTypeString]),
free_editor(State, "Analysis done", Msg),
gui_loop(State);
{BackendPid, log, LogMsg} ->
update_editor(Log, LogMsg),
gui_loop(State);
{BackendPid, warnings, Warns} ->
NewState = add_warnings(State, SortedWarns),
gui_loop(NewState);
{BackendPid, cserver, CServer, Plt} ->
Self = self(),
Fun =
fun() ->
dialyzer_explanation:expl_loop(Self, CServer, Plt)
end,
ExplanationPid = spawn_link(Fun),
gui_loop(State#gui_state{expl_pid = ExplanationPid});
{BackendPid, done, _NewPlt, NewDocPlt} ->
message(State, "Analysis done"),
config_gui_stop(State),
gui_loop(State#gui_state{doc_plt = NewDocPlt});
{'EXIT', BackendPid, {error, Reason}} ->
free_editor(State, ?DIALYZER_ERROR_TITLE, Reason),
config_gui_stop(State),
gui_loop(State);
{'EXIT', BackendPid, Reason} when Reason =/= 'normal' ->
free_editor(State, ?DIALYZER_ERROR_TITLE, io_lib:format("~p", [Reason])),
config_gui_stop(State),
gui_loop(State)
end.
maybe_quit(#gui_state{frame = Frame} = State) ->
case dialog(State, "Do you really want to quit?", ?DIALYZER_MESSAGE_TITLE) of
true ->
wxWindow:destroy(Frame),
true;
false ->
false
end.
dialog(#gui_state{frame = Frame}, Message, Title) ->
MessageWin = wxMessageDialog:new(Frame, Message, [{caption, Title},{style, ?wxYES_NO bor ?wxICON_QUESTION bor ?wxNO_DEFAULT}]),
case wxDialog:showModal(MessageWin) of
?wxID_YES ->
true;
?wxID_NO ->
false;
?wxID_CANCEL ->
false
end.
search_doc_plt(#gui_state{gui = Wx} = State) ->
Dialog = wxFrame:new(Wx, ?SearchPltDialog, "Search the PLT",[{size,{400,100}},{style, ?wxSTAY_ON_TOP}]),
Size = {size,{120,30}},
ModLabel = wxStaticText:new(Dialog, ?ModLabel, "Module"),
ModText = wxTextCtrl:new(Dialog, ?ModText,[Size]),
FunLabel = wxStaticText:new(Dialog, ?FunLabel, "Function"),
FunText = wxTextCtrl:new(Dialog, ?FunText,[Size]),
ArLabel = wxStaticText:new(Dialog, ?ArLabel, "Arity"),
ArText = wxTextCtrl:new(Dialog, ?ArText,[Size]),
SearchButton = wxButton:new(Dialog, ?SearchButton, [{label, "Search"}]),
wxButton:connect(SearchButton, command_button_clicked),
Cancel = wxButton:new(Dialog, ?Search_Cancel, [{label, "Cancel"}]),
wxButton:connect(Cancel, command_button_clicked),
Layout = wxBoxSizer:new(?wxVERTICAL),
Top = wxBoxSizer:new(?wxHORIZONTAL),
ModLayout = wxBoxSizer:new(?wxVERTICAL),
FunLayout = wxBoxSizer:new(?wxVERTICAL),
ArLayout = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(ModLayout, ModLabel, ?BorderOpt),
wxSizer:add(ModLayout,ModText, ?BorderOpt),
wxSizer:add(FunLayout, FunLabel, ?BorderOpt),
wxSizer:add(FunLayout,FunText, ?BorderOpt),
wxSizer:add(ArLayout, ArLabel, ?BorderOpt),
wxSizer:add(ArLayout,ArText, ?BorderOpt),
wxSizer:add(Buttons, SearchButton, ?BorderOpt),
wxSizer:add(Buttons,Cancel, ?BorderOpt),
wxSizer:add(Top, ModLayout),
wxSizer:add(Top, FunLayout),
wxSizer:add(Top, ArLayout),
wxSizer:add(Layout, Top,[{flag, ?wxALIGN_CENTER}]),
wxSizer:add(Layout, Buttons,[{flag, ?wxALIGN_CENTER bor ?wxBOTTOM}]),
wxFrame:connect(Dialog, close_window),
wxWindow:setSizer(Dialog, Layout),
wxFrame:show(Dialog),
search_plt_loop(State, Dialog, ModText, FunText, ArText, SearchButton, Cancel).
search_plt_loop(State= #gui_state{doc_plt = DocPlt, frame = Frame}, Win, ModText, FunText, ArText, Search, Cancel) ->
receive
#wx{id = ?Search_Cancel,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win);
#wx{id = ?SearchPltDialog, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win);
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
wxWindow:destroy(Frame);
#wx{id = ?SearchButton,
event = #wxCommand{type = command_button_clicked}} ->
M = format_search(wxTextCtrl:getValue(ModText)),
F = format_search(wxTextCtrl:getValue(FunText)),
A = format_search(wxTextCtrl:getValue(ArText)),
if
(M =:= '_') orelse (F =:= '_') orelse (A =:= '_') ->
error_sms(State, "Please give:\n Module (atom)\n Function (atom)\n Arity (integer)\n"),
search_plt_loop(State, Win, ModText, FunText, ArText, Search, Cancel);
true ->
case dialyzer_plt:get_specs(DocPlt, M, F, A) of
none ->
error_sms(State, "No such function"),
search_plt_loop(State, Win, ModText, FunText, ArText, Search, Cancel);
NonEmptyString ->
wxWindow:destroy(Win),
free_editor(State, "Content of PLT", NonEmptyString)
end
end
end.
format_search([]) ->
'_';
format_search(String) ->
try list_to_integer(String)
catch error:_ -> list_to_atom(String)
end.
show_doc_plt(#gui_state{doc_plt = DocPLT} = State) ->
case dialyzer_plt:get_specs(DocPLT) of
"" -> error_sms(State, "No analysis has been made yet!\n");
NonEmptyString -> free_editor(State, "Content of PLT", NonEmptyString)
end.
message(State, Message) ->
output_sms(State, ?DIALYZER_MESSAGE_TITLE, Message, info).
error_sms(State, Message) ->
output_sms(State, ?DIALYZER_ERROR_TITLE, Message, error).
output_sms(#gui_state{frame = Frame}, Title, Message, Type) ->
case Type of
error ->
MessageWin = wxMessageDialog:new(Frame,Message,[{caption, Title},{style, ?wxOK bor ?wxICON_ERROR}]);
info ->
MessageWin = wxMessageDialog:new(Frame,Message,[{caption, Title},{style, ?wxOK bor ?wxICON_INFORMATION}])
end,
wxWindow:setSizeHints(MessageWin, {350,100}),
wxDialog:showModal(MessageWin).
free_editor(#gui_state{gui = Wx, frame = Frame}, Title, Contents0) ->
Contents = lists:flatten(Contents0),
Tokens = string:tokens(Contents, "\n"),
NofLines = length(Tokens),
LongestLine = lists:max([length(X) || X <- Tokens]),
Height0 = NofLines * 25 + 80,
Height = if Height0 > 500 -> 500; true -> Height0 end,
Width0 = LongestLine * 7 + 60,
Width = if Width0 > 800 -> 800; true -> Width0 end,
Size = {size,{Width, Height}},
Win = wxFrame:new(Wx, ?Message, Title, [{size,{Width+4, Height+50}}]),
Editor = wxTextCtrl:new(Win, ?Message_Info,
[Size,
{style, ?wxTE_MULTILINE
bor ?wxTE_READONLY bor ?wxVSCROLL bor ?wxEXPAND}]),
wxTextCtrl:appendText(Editor, Contents),
wxFrame:connect(Win, close_window),
Ok = wxButton:new(Win, ?Message_Ok, [{label, "OK"}]),
wxButton:connect(Ok, command_button_clicked),
Layout = wxBoxSizer:new(?wxVERTICAL),
wxSizer:add(Layout, Editor, ?BorderOpt),
wxSizer:add(Layout, Ok, [{flag, ?wxALIGN_CENTER bor ?wxBOTTOM bor ?wxALL}, ?Border]),
wxWindow:setSizer(Win, Layout),
wxWindow:show(Win),
show_info_loop(Frame, Win).
show_info_loop(Frame, Win) ->
receive
#wx{id = ?Message_Ok, event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win);
#wx{id = ?Message, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win);
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Frame)
end.
handle_add_files(#gui_state{chosen_box = ChosenBox, file_box = FileBox,
files_to_analyze = FileList,
mode = Mode} = State) ->
case wxFilePickerCtrl:getPath(FileBox) of
"" ->
State;
File ->
NewFile = ordsets:new(),
NewFile1 = ordsets:add_element(File,NewFile),
Ext =
case wxRadioBox:getSelection(Mode) of
0 -> ".beam";
1-> ".erl"
end,
State#gui_state{files_to_analyze = add_files(filter_mods(NewFile1, Ext), FileList, ChosenBox, Ext)}
end.
handle_add_dir(#gui_state{chosen_box = ChosenBox, dir_entry = DirBox,
files_to_analyze = FileList,
mode = Mode} = State) ->
case wxDirPickerCtrl:getPath(DirBox) of
"" ->
State;
Dir ->
NewDir = ordsets:new(),
NewDir1 = ordsets:add_element(Dir,NewDir),
Ext = case wxRadioBox:getSelection(Mode) of
0 -> ".beam";
1-> ".erl"
end,
State#gui_state{files_to_analyze = add_files(filter_mods(NewDir1,Ext), FileList, ChosenBox, Ext)}
end.
handle_add_rec(#gui_state{chosen_box = ChosenBox, dir_entry = DirBox, files_to_analyze = FileList,
mode = Mode} = State) ->
case wxDirPickerCtrl:getPath(DirBox) of
"" ->
State;
Dir ->
NewDir = ordsets:new(),
NewDir1 = ordsets:add_element(Dir,NewDir),
TargetDirs = ordsets:union(NewDir1, all_subdirs(NewDir1)),
case wxRadioBox:getSelection(Mode) of
0 -> Ext = ".beam";
1-> Ext = ".erl"
end,
State#gui_state{files_to_analyze = add_files(filter_mods(TargetDirs,Ext), FileList, ChosenBox, Ext)}
end.
handle_file_delete(#gui_state{chosen_box = ChosenBox,
files_to_analyze = FileList} = State) ->
{_, List} = wxListBox:getSelections(ChosenBox),
Set = ordsets:from_list([wxControlWithItems:getString(ChosenBox, X) || X <- List]),
FileList1 = ordsets:subtract(FileList,Set),
lists:foreach(fun (X) -> wxListBox:delete(ChosenBox, X) end, List),
State#gui_state{files_to_analyze = FileList1}.
handle_file_delete_all(#gui_state{chosen_box = ChosenBox} = State) ->
wxListBox:clear(ChosenBox),
State#gui_state{files_to_analyze = ordsets:new()}.
add_files(File, FileList, ChosenBox, Ext) ->
Set = filter_mods(FileList, Ext),
Files = ordsets:union(File, Set),
Files1 = ordsets:to_list(Files),
wxListBox:set(ChosenBox, Files1),
Files.
filter_mods(Mods, Extension) ->
Fun = fun(X) ->
filename:extension(X) =:= Extension
orelse
(filelib:is_dir(X) andalso
contains_files(X, Extension))
end,
ordsets:filter(Fun, Mods).
contains_files(Dir, Extension) ->
{ok, Files} = file:list_dir(Dir),
lists:any(fun(X) -> filename:extension(X) =:= Extension end, Files).
all_subdirs(Dirs) ->
all_subdirs(Dirs, []).
all_subdirs([Dir|T], Acc) ->
{ok, Files} = file:list_dir(Dir),
SubDirs = lists:zf(fun(F) ->
SubDir = filename:join(Dir, F),
case filelib:is_dir(SubDir) of
true -> {true, SubDir};
false -> false
end
end, Files),
NewAcc = ordsets:union(ordsets:from_list(SubDirs), Acc),
all_subdirs(T ++ SubDirs, NewAcc);
all_subdirs([], Acc) ->
Acc.
start_analysis(State) ->
Analysis = build_analysis_record(State),
case get_anal_files(State, Analysis#analysis.start_from) of
error ->
Msg = "You must choose one or more files or dirs\n"
"before starting the analysis!",
error_sms(State, Msg),
config_gui_stop(State),
State;
{ok, Files} ->
Msg = "\n========== Starting Analysis ==========\n\n",
update_editor(State#gui_state.log, Msg),
NewAnalysis = Analysis#analysis{files = Files},
run_analysis(State, NewAnalysis)
end.
build_analysis_record(#gui_state{mode = Mode, menu = Menu, options = Options,
init_plt = InitPlt0}) ->
StartFrom =
case wxRadioBox:getSelection(Mode) of
0 -> byte_code;
1 -> src_code
end,
InitPlt =
case wxMenu:isChecked(Menu#menu.plt, ?menuID_PLT_INIT_EMPTY) of
true -> dialyzer_plt:new();
false -> InitPlt0
end,
#analysis{defines = Options#options.defines,
include_dirs = Options#options.include_dirs,
plt = InitPlt,
start_from = StartFrom}.
get_anal_files(#gui_state{files_to_analyze = Files}, StartFrom) ->
FilteredMods =
case StartFrom of
src_code -> filter_mods(Files, ".erl");
byte_code -> filter_mods(Files, ".beam")
end,
FilteredDirs = [X || X <- Files, filelib:is_dir(X)],
case ordsets:union(FilteredMods, FilteredDirs) of
[] -> error;
Set -> {ok, Set}
end.
run_analysis(State, Analysis) ->
config_gui_start(State),
Self = self(),
NewAnalysis = Analysis#analysis{doc_plt = dialyzer_plt:new()},
LegalWarnings = find_legal_warnings(State),
Fun =
fun() ->
dialyzer_analysis_callgraph:start(Self, LegalWarnings, NewAnalysis)
end,
BackendPid = spawn_link(Fun),
State#gui_state{backend_pid = BackendPid}.
find_legal_warnings(#gui_state{menu = #menu{warnings = MenuWarnings},
wantedWarnings = Warnings }) ->
ordsets:from_list([Tag || {Tag, MenuItem} <- Warnings,
wxMenu:isChecked(MenuWarnings, MenuItem)]).
update_editor(Editor, Msg) ->
wxTextCtrl:appendText(Editor,Msg).
config_gui_stop(State) ->
wxWindow:disable(State#gui_state.stop),
wxWindow:enable(State#gui_state.run),
wxWindow:enable(State#gui_state.del_file),
wxWindow:enable(State#gui_state.clear_chosen),
wxWindow:enable(State#gui_state.add),
wxWindow:enable(State#gui_state.add_dir),
wxWindow:enable(State#gui_state.add_rec),
wxWindow:enable(State#gui_state.clear_warn),
wxWindow:enable(State#gui_state.clear_log),
Menu = State#gui_state.menu,
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_WARNINGS,true),
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_LOG,true),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_MACRO,true),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_INCLUDE_DIR,true),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_INIT_EMPTY,true),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SHOW_CONTENTS,true),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SEARCH_CONTENTS,true),
wxRadioBox:enable(State#gui_state.mode).
config_gui_start(State) ->
wxWindow:enable(State#gui_state.stop),
wxWindow:disable(State#gui_state.run),
wxWindow:disable(State#gui_state.del_file),
wxWindow:disable(State#gui_state.clear_chosen),
wxWindow:disable(State#gui_state.add),
wxWindow:disable(State#gui_state.add_dir),
wxWindow:disable(State#gui_state.add_rec),
wxWindow:disable(State#gui_state.clear_warn),
wxWindow:disable(State#gui_state.clear_log),
Menu = State#gui_state.menu,
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_WARNINGS, false),
wxMenu:enable(Menu#menu.file,?menuID_FILE_SAVE_LOG, false),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_MACRO, false),
wxMenu:enable(Menu#menu.options,?menuID_OPTIONS_INCLUDE_DIR, false),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_INIT_EMPTY, false),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SHOW_CONTENTS, false),
wxMenu:enable(Menu#menu.plt,?menuID_PLT_SEARCH_CONTENTS, false),
wxRadioBox:disable(State#gui_state.mode).
save_file(#gui_state{frame = Frame, warnings_box = WBox, log = Log} = State, Type) ->
case Type of
warnings ->
Message = "Save Warnings",
Box = WBox;
log -> Message = "Save Log",
Box = Log
end,
case wxTextCtrl:getValue(Box) of
"" -> error_sms(State,"There is nothing to save...\n");
_ ->
DefaultPath = code:root_dir(),
FileDialog = wxFileDialog:new(Frame,
[{defaultDir, DefaultPath},
{message, Message},
{style,?wxFD_SAVE bor ?wxFD_OVERWRITE_PROMPT}]),
case wxFileDialog:showModal(FileDialog) of
?wxID_OK -> Path = wxFileDialog:getPath(FileDialog),
case wxTextCtrl:saveFile(Box,[{file,Path}]) of
true -> ok;
false -> error_sms(State,"Could not write to file:\n" ++ Path)
end;
?wxID_CANCEL -> wxWindow:destroy(FileDialog);
_ -> error_sms(State,"Could not write to file:\n")
end
end.
include_dialog(#gui_state{gui = Wx, frame = Frame, options = Options}) ->
Size = {size,{300,480}},
Dialog = wxFrame:new(Wx, ?IncludeDir, "Include Directories",[Size]),
DirLabel = wxStaticText:new(Dialog, ?InclLabel, "Directory: "),
DefaultPath = code:root_dir(),
DirPicker = wxDirPickerCtrl:new(Dialog, ?InclPicker,
[{path, DefaultPath},
{message, "Choose Directory to Include"},
{style,?wxDIRP_DIR_MUST_EXIST bor ?wxDIRP_USE_TEXTCTRL}]),
Box = wxListBox:new(Dialog, ?InclBox,
[{size, {200,300}},
{style, ?wxLB_EXTENDED bor ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
AddButton = wxButton:new(Dialog, ?InclAdd, [{label, "Add"}]),
DeleteButton = wxButton:new(Dialog, ?InclDel, [{label, "Delete"}]),
DeleteAllButton = wxButton:new(Dialog, ?InclDelAll, [{label, "Delete All"}]),
Ok = wxButton:new(Dialog, ?InclOk, [{label, "OK"}]),
Cancel = wxButton:new(Dialog, ?InclCancel, [{label, "Cancel"}]),
wxButton:connect(AddButton, command_button_clicked),
wxButton:connect(DeleteButton, command_button_clicked),
wxButton:connect(DeleteAllButton, command_button_clicked),
wxButton:connect(Ok, command_button_clicked),
wxButton:connect(Cancel, command_button_clicked),
Dirs = [io_lib:format("~s", [X])
|| X <- Options#options.include_dirs],
wxListBox:set(Box, Dirs),
Layout = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
Buttons1 = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(Layout, DirLabel, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Layout, DirPicker, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Layout,AddButton, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Layout,Box, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Buttons, DeleteButton, ?BorderOpt),
wxSizer:add(Buttons, DeleteAllButton, ?BorderOpt),
wxSizer:add(Layout,Buttons, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Buttons1, Ok, ?BorderOpt),
wxSizer:add(Buttons1,Cancel, ?BorderOpt),
wxSizer:add(Layout,Buttons1,[{flag, ?wxALIGN_RIGHT bor ?wxBOTTOM}]),
wxFrame:connect(Dialog, close_window),
wxWindow:setSizer(Dialog, Layout),
wxFrame:show(Dialog),
include_loop(Options, Dialog, Box, DirPicker, Frame).
include_loop(Options, Win, Box, DirPicker, Frame) ->
receive
#wx{id = ?InclCancel,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?IncludeDir, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
Options;
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
wxWindow:destroy(Frame);
#wx{id = ?InclOk,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?InclAdd,
event = #wxCommand{type = command_button_clicked}} ->
Dirs = Options#options.include_dirs,
NewDirs =
case wxDirPickerCtrl:getPath(DirPicker) of
"" -> Dirs;
Add -> [Add|Dirs]
end,
NewOptions = Options#options{include_dirs = NewDirs},
wxListBox:set(Box, NewDirs),
include_loop(NewOptions, Win, Box, DirPicker, Frame);
#wx{id = ?InclDel,
event = #wxCommand{type = command_button_clicked}} ->
NewOptions =
case wxListBox:getSelections(Box) of
{0,_} -> Options;
{_,List} ->
DelList = [wxControlWithItems:getString(Box,X) || X <- List],
NewDirs = Options#options.include_dirs -- DelList,
lists:foreach(fun (X) -> wxListBox:delete(Box, X) end, List),
Options#options{include_dirs = NewDirs}
end,
include_loop(NewOptions, Win, Box, DirPicker, Frame);
#wx{id = ?InclDelAll,
event = #wxCommand{type = command_button_clicked}} ->
wxListBox:clear(Box),
NewOptions = Options#options{include_dirs = []},
include_loop(NewOptions, Win, Box, DirPicker, Frame)
end.
macro_dialog(#gui_state{gui = Wx, frame = Frame, options = Options}) ->
Size = {size,{300,480}},
Size1 = {size,{120,30}},
Dialog = wxFrame:new(Wx, ?MacroDir, "Macro Definitions",[Size]),
MacroLabel = wxStaticText:new(Dialog, ?MacroLabel, "Macro"),
TermLabel = wxStaticText:new(Dialog, ?TermLabel, "Term"),
MacroText = wxTextCtrl:new(Dialog, ?MacroText, [Size1]),
TermText = wxTextCtrl:new(Dialog, ?TermText, [Size1]),
Box = wxListBox:new(Dialog, ?MacroBox,
[{size, {250,300}},
{style, ?wxLB_EXTENDED bor ?wxLB_HSCROLL
bor ?wxLB_NEEDED_SB}]),
AddButton = wxButton:new(Dialog, ?MacroAdd, [{label, "Add"}]),
DeleteButton = wxButton:new(Dialog, ?MacroDel, [{label, "Delete"}]),
DeleteAllButton = wxButton:new(Dialog, ?MacroDelAll, [{label, "Delete All"}]),
Ok = wxButton:new(Dialog, ?MacroOk, [{label, "OK"}]),
Cancel = wxButton:new(Dialog, ?MacroCancel, [{label, "Cancel"}]),
wxButton:connect(AddButton, command_button_clicked),
wxButton:connect(DeleteButton, command_button_clicked),
wxButton:connect(DeleteAllButton, command_button_clicked),
wxButton:connect(Ok, command_button_clicked),
wxButton:connect(Cancel, command_button_clicked),
Macros = [io_lib:format("~p = ~p", [X, Y])
|| {X,Y} <- Options#options.defines],
wxListBox:set(Box, Macros),
Layout = wxBoxSizer:new(?wxVERTICAL),
Item = wxBoxSizer:new(?wxHORIZONTAL),
MacroItem = wxBoxSizer:new(?wxVERTICAL),
TermItem = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
Buttons1 = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(MacroItem, MacroLabel, ?BorderOpt),
wxSizer:add(MacroItem, MacroText, ?BorderOpt),
wxSizer:add(TermItem, TermLabel, ?BorderOpt),
wxSizer:add(TermItem, TermText, ?BorderOpt),
wxSizer:add(Item, MacroItem),
wxSizer:add(Item, TermItem),
wxSizer:add(Layout, Item, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Layout, AddButton, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Layout, Box, [{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Buttons, DeleteButton, ?BorderOpt),
wxSizer:add(Buttons, DeleteAllButton, ?BorderOpt),
wxSizer:add(Layout, Buttons, [{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxSizer:add(Buttons1, Ok, ?BorderOpt),
wxSizer:add(Buttons1, Cancel, ?BorderOpt),
wxSizer:add(Layout, Buttons1, [{flag, ?wxALIGN_RIGHT bor ?wxBOTTOM}]),
wxFrame:connect(Dialog, close_window),
wxWindow:setSizer(Dialog, Layout),
wxFrame:show(Dialog),
macro_loop(Options, Dialog, Box, MacroText, TermText, Frame).
macro_loop(Options, Win, Box, MacroText, TermText, Frame) ->
receive
#wx{id = ?MacroCancel,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?MacroDir, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
Options;
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win),
wxWindow:destroy(Frame);
#wx{id = ?MacroOk,
event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win),
Options;
#wx{id = ?MacroAdd,
event = #wxCommand{type = command_button_clicked}} ->
Defines = Options#options.defines,
NewDefines =
case wxTextCtrl:getValue(MacroText) of
"" -> Defines;
Macro ->
case wxTextCtrl:getValue(TermText) of
"" ->
orddict:store(list_to_atom(Macro), true, Defines);
String ->
orddict:store(list_to_atom(Macro), String, Defines)
end
end,
NewOptions = Options#options{defines = NewDefines},
NewEntries = [io_lib:format("~p = ~p", [X, Y]) || {X, Y} <- NewDefines],
wxListBox:set(Box, NewEntries),
macro_loop(NewOptions, Win, Box, MacroText, TermText, Frame);
#wx{id = ?MacroDel,
event = #wxCommand{type = command_button_clicked}} ->
NewOptions =
case wxListBox:getSelections(Box) of
{0, _} -> Options;
{_, List} ->
Fun =
fun(X) ->
Val = wxControlWithItems:getString(Box,X),
[MacroName|_] = re:split(Val, " ", [{return, list}]),
list_to_atom(MacroName)
end,
Delete = [Fun(X) || X <- List],
lists:foreach(fun (X) -> wxListBox:delete(Box, X) end, List),
Defines = Options#options.defines,
NewDefines = lists:foldl(fun(X, Acc) ->
orddict:erase(X, Acc)
end,
Defines, Delete),
Options#options{defines = NewDefines}
end,
macro_loop(NewOptions, Win, Box, MacroText, TermText, Frame);
#wx{id = ?MacroDelAll,
event = #wxCommand{type = command_button_clicked}} ->
wxListBox:clear(Box),
NewOptions = Options#options{defines = []},
macro_loop(NewOptions, Win, Box, MacroText, TermText, Frame)
end.
handle_help(State, Title, Txt) ->
FileName = filename:join([code:lib_dir(dialyzer), "doc", Txt]),
case file:open(FileName, [read]) of
{error, Reason} ->
error_sms(State,
io_lib:format("Could not find doc/~s file!\n\n ~p",
[Txt, Reason]));
{ok, _Handle} ->
case file:read_file(FileName) of
{error, Reason} ->
error_sms(State,
io_lib:format("Could not read doc/~s file!\n\n ~p",
[Txt, Reason]));
{ok, Binary} ->
Contents = binary_to_list(Binary),
free_editor(State, Title, Contents)
end
end.
add_warnings(#gui_state{warnings_box = WarnBox,
rawWarnings = RawWarns} = State, Warnings) ->
NewRawWarns = RawWarns ++ Warnings,
WarnList = [dialyzer:format_warning(W) -- "\n" || W <- NewRawWarns],
wxListBox:set(WarnBox, WarnList),
State#gui_state{rawWarnings = NewRawWarns}.
handle_explanation(#gui_state{rawWarnings = RawWarns,
warnings_box = WarnBox,
expl_pid = ExplPid} = State) ->
case wxListBox:isEmpty(WarnBox) of
true ->
error_sms(State, "\nThere are no warnings.\nRun the dialyzer first.");
false ->
case wxListBox:getSelections(WarnBox)of
{0, []} ->
error_sms(State,"\nYou must choose a warning to be explained\n");
{_, [WarnNumber]} ->
Warn = lists:nth(WarnNumber+1,RawWarns),
Self = self(),
ExplPid ! {Self, warning, Warn},
explanation_loop(State)
end
end.
explanation_loop(#gui_state{expl_pid = ExplPid} = State) ->
receive
{ExplPid, explanation, Explanation} ->
show_explanation(State, Explanation);
_ -> io:format("Unknown message\n"),
explanation_loop(State)
end.
show_explanation(#gui_state{gui = Wx} = State, Explanation) ->
case Explanation of
none ->
output_sms(State, ?DIALYZER_MESSAGE_TITLE,
"There is not any explanation for this error!\n", info);
Expl ->
ExplString = format_explanation(Expl),
Size = {size,{700, 300}},
Win = wxFrame:new(Wx, ?ExplWin, "Dialyzer Explanation", [{size,{740, 350}}]),
Editor = wxTextCtrl:new(Win, ?ExplText,
[Size,
{style, ?wxTE_MULTILINE
bor ?wxTE_READONLY bor ?wxVSCROLL bor ?wxEXPAND}]),
wxTextCtrl:appendText(Editor, ExplString),
wxFrame:connect(Win, close_window),
ExplButton = wxButton:new(Win, ?ExplButton, [{label, "Further Explain"}]),
wxButton:connect(ExplButton, command_button_clicked),
Ok = wxButton:new(Win, ?ExplOk, [{label, "OK"}]),
wxButton:connect(Ok, command_button_clicked),
Layout = wxBoxSizer:new(?wxVERTICAL),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxSizer:add(Buttons, ExplButton, ?BorderOpt),
wxSizer:add(Buttons, Ok, ?BorderOpt),
wxSizer:add(Layout, Editor,[{flag, ?wxALIGN_CENTER_HORIZONTAL bor ?wxALL}, ?Border]),
wxSizer:add(Layout, Buttons,[{flag, ?wxALIGN_CENTER_HORIZONTAL}]),
wxWindow:setSizer(Win, Layout),
wxWindow:show(Win),
show_explanation_loop(State#gui_state{explanation_box = Editor}, Win, Explanation)
end.
show_explanation_loop(#gui_state{frame = Frame, expl_pid = ExplPid} = State, Win, Explanation) ->
receive
{ExplPid, none, _} ->
output_sms(State, ?DIALYZER_MESSAGE_TITLE,
"There is not any other explanation for this error!\n", info),
show_explanation_loop(State, Win, Explanation);
{ExplPid, further, NewExplanation} ->
update_explanation(State, NewExplanation),
show_explanation_loop(State, Win, NewExplanation);
#wx{id = ?ExplButton, event = #wxCommand{type = command_button_clicked}} ->
ExplPid ! {self(), further, Explanation},
show_explanation_loop(State, Win, Explanation);
#wx{id = ?ExplOk, event = #wxCommand{type = command_button_clicked}} ->
wxWindow:destroy(Win);
#wx{id = ?ExplWin, event = #wxClose{type = close_window}} ->
wxWindow:destroy(Win);
#wx{event = #wxClose{type = close_window}} ->
wxWindow:destroy(Frame)
end.
update_explanation(#gui_state{explanation_box = Box}, Explanation) ->
ExplString = format_explanation(Explanation),
wxTextCtrl:appendText(Box, "\n --------------------------- \n"),
wxTextCtrl:appendText(Box, ExplString).
format_explanation({function_return, {M, F, A}, NewList}) ->
io_lib:format("The function ~p: ~p/~p returns ~p\n",
[M, F, A, erl_types:t_to_string(NewList)]);
format_explanation(Explanation) ->
io_lib:format("~p\n", [Explanation]).
|
a53630043984504084c391b8b69e85336fb454e147188ee1f3f1385a4a1cd6bc | btq-ag/keelung | Field.hs | # LANGUAGE DataKinds #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE RankNTypes #-}
-- | Field types provided by the compiler
module Keelung.Field
( B64,
GF181,
BN128,
FieldType (..),
realizeAs,
normalize,
module Keelung.Data.N,
)
where
import Control.DeepSeq (NFData)
import Data.Field.Galois (Binary, Prime)
import Data.Serialize (Serialize (..))
import GHC.Generics (Generic)
import Keelung.Data.N
--------------------------------------------------------------------------------
| Binary field of 64 bits
type B64 = Binary 18446744073709551643
| Prime field of order 1552511030102430251236801561344621993261920897571225601
type GF181 = Prime 1552511030102430251236801561344621993261920897571225601
| Barreto - Naehrig curve of 128 bits
type BN128 = Prime 21888242871839275222246405745257275088548364400416034343698204186575808495617
instance Serialize B64 where
put = put . toInteger
get = fromInteger <$> get
instance Serialize GF181 where
put = put . toInteger
get = fromInteger <$> get
instance Serialize BN128 where
put = put . toInteger
get = fromInteger <$> get
--------------------------------------------------------------------------------
-- | Field types provided by the compiler
data FieldType
| Binary field of 64 bits
B64
| Prime field of order 181
GF181
| Barreto - Naehrig curve of 128 bits
BN128
deriving
( Generic,
Eq,
Show,
NFData
)
| Restore the field type from an ' Integer '
realizeAs :: Num n => FieldType -> Integer -> n
realizeAs B64 n = fromInteger n
realizeAs GF181 n = fromInteger n
realizeAs BN128 n = fromInteger n
-- | Utility function for normalizing an 'Integer' as some field element
-- the number will be negated if it is on the "upper half" of the field
normalize :: FieldType -> Integer -> Integer
normalize B64 n = toInteger (N (fromIntegral n :: B64))
normalize GF181 n = toInteger (N (fromIntegral n :: GF181))
normalize BN128 n = toInteger (N (fromIntegral n :: BN128)) | null | https://raw.githubusercontent.com/btq-ag/keelung/930c265d6fa0ccfbce6aad473b7396a250ddb0d1/src/Keelung/Field.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE RankNTypes #
| Field types provided by the compiler
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Field types provided by the compiler
| Utility function for normalizing an 'Integer' as some field element
the number will be negated if it is on the "upper half" of the field | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
module Keelung.Field
( B64,
GF181,
BN128,
FieldType (..),
realizeAs,
normalize,
module Keelung.Data.N,
)
where
import Control.DeepSeq (NFData)
import Data.Field.Galois (Binary, Prime)
import Data.Serialize (Serialize (..))
import GHC.Generics (Generic)
import Keelung.Data.N
| Binary field of 64 bits
type B64 = Binary 18446744073709551643
| Prime field of order 1552511030102430251236801561344621993261920897571225601
type GF181 = Prime 1552511030102430251236801561344621993261920897571225601
| Barreto - Naehrig curve of 128 bits
type BN128 = Prime 21888242871839275222246405745257275088548364400416034343698204186575808495617
instance Serialize B64 where
put = put . toInteger
get = fromInteger <$> get
instance Serialize GF181 where
put = put . toInteger
get = fromInteger <$> get
instance Serialize BN128 where
put = put . toInteger
get = fromInteger <$> get
data FieldType
| Binary field of 64 bits
B64
| Prime field of order 181
GF181
| Barreto - Naehrig curve of 128 bits
BN128
deriving
( Generic,
Eq,
Show,
NFData
)
| Restore the field type from an ' Integer '
realizeAs :: Num n => FieldType -> Integer -> n
realizeAs B64 n = fromInteger n
realizeAs GF181 n = fromInteger n
realizeAs BN128 n = fromInteger n
normalize :: FieldType -> Integer -> Integer
normalize B64 n = toInteger (N (fromIntegral n :: B64))
normalize GF181 n = toInteger (N (fromIntegral n :: GF181))
normalize BN128 n = toInteger (N (fromIntegral n :: BN128)) |
1eb27ad3de3e6c47056ad4706460b42c38115a2ab04a127b56da1f1152451557 | TrustInSoft/tis-kernel | binary_cache.mli | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(** Very low-level abstract functorial caches. Do not use them unless
you understand what happens in this module, and do not forget that
those caches are not aware of projects. *)
val cache_size: int
(** Size of the caches. Controlled by environment variable
[memory_footprint_var_name]. *)
module type Cacheable = sig
type t
val hash : t -> int
val sentinel : t
val equal : t -> t -> bool
end
module type Result = sig
type t
val sentinel : t
end
type elt1 = A | B of int
module Symmetric_Binary(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> H.t -> R.t) -> H.t -> H.t -> R.t
end
module Binary_Predicate(H0 : Cacheable)(H1 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> bool) -> H0.t -> H1.t -> bool
end
module Symmetric_Binary_Predicate(H0 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H0.t -> bool) -> H0.t -> H0.t -> bool
end
module Arity_One(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> R.t) -> H.t -> R.t
end
module Arity_Two(H0 : Cacheable)(H1 : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> R.t) -> H0.t -> H1.t -> R.t
end
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/libraries/utils/binary_cache.mli | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* Very low-level abstract functorial caches. Do not use them unless
you understand what happens in this module, and do not forget that
those caches are not aware of projects.
* Size of the caches. Controlled by environment variable
[memory_footprint_var_name].
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
val cache_size: int
module type Cacheable = sig
type t
val hash : t -> int
val sentinel : t
val equal : t -> t -> bool
end
module type Result = sig
type t
val sentinel : t
end
type elt1 = A | B of int
module Symmetric_Binary(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> H.t -> R.t) -> H.t -> H.t -> R.t
end
module Binary_Predicate(H0 : Cacheable)(H1 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> bool) -> H0.t -> H1.t -> bool
end
module Symmetric_Binary_Predicate(H0 : Cacheable): sig
val clear : unit -> unit
val merge : (H0.t -> H0.t -> bool) -> H0.t -> H0.t -> bool
end
module Arity_One(H : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H.t -> R.t) -> H.t -> R.t
end
module Arity_Two(H0 : Cacheable)(H1 : Cacheable)(R : Result): sig
val clear : unit -> unit
val merge : (H0.t -> H1.t -> R.t) -> H0.t -> H1.t -> R.t
end
|
b634b618b7a256c93874e5f5a71106ccb1904831b7d44ae8e28478b2b4d23952 | jcfaracco/lispvirt | lispvirt-tests-connection.lisp | ;;;-------------------------------------------------------------------------
Lispvirt - Common LISP bindings for Libvirt .
;;;
Copyright ( C ) 2015
;;;
lispvirt-tests-connection.lisp is part of Lispvirt .
;;;
Lispvirt is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;; (at your option) any later version.
;;;
Lispvirt 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 Lispvirt . If not , see < / > .
;;;-------------------------------------------------------------------------
(defpackage :lispvirt-tests-connection
(:use :cl :lispvirt :lispvirt-host :cffi :xlunit)
(:export :run-all-tests-connection))
(in-package :lispvirt-tests-connection)
(defclass lispvirt-tests-connection (test-case)
())
(def-test-method test-virconnect ((test lispvirt-tests-connection) :run nil)
(virConnectOpen "test"))
(defun run-all-tests-connection ()
(textui-test-run (get-suite lispvirt-tests-connection)))
;;(test test-virconnect
;; (virconnectopen "test"))
| null | https://raw.githubusercontent.com/jcfaracco/lispvirt/568495b00bb19b46a40f4669b8b21395e5f5fe74/tests/lispvirt-tests-connection.lisp | lisp | -------------------------------------------------------------------------
(at your option) any later version.
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.
-------------------------------------------------------------------------
(test test-virconnect
(virconnectopen "test")) | Lispvirt - Common LISP bindings for Libvirt .
Copyright ( C ) 2015
lispvirt-tests-connection.lisp is part of Lispvirt .
Lispvirt is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
Lispvirt is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with Lispvirt . If not , see < / > .
(defpackage :lispvirt-tests-connection
(:use :cl :lispvirt :lispvirt-host :cffi :xlunit)
(:export :run-all-tests-connection))
(in-package :lispvirt-tests-connection)
(defclass lispvirt-tests-connection (test-case)
())
(def-test-method test-virconnect ((test lispvirt-tests-connection) :run nil)
(virConnectOpen "test"))
(defun run-all-tests-connection ()
(textui-test-run (get-suite lispvirt-tests-connection)))
|
d141fb066bcfe3eb29a00562f99a8b19a95bcfd398829bd13781f31646c97fd6 | jcomellas/bstr | bstr.erl | %%%-------------------------------------------------------------------
@author < >
@author < >
2008 - 2011 , .
@doc String implemented over an Erlang binary .
%%% @end
This source file is subject to the New BSD License . You should have received
%%% a copy of the New BSD license with this software. If not, it can be
%%% retrieved from: -license.php
%%%-------------------------------------------------------------------
-module(bstr).
-author('Juan Jose Comellas <>').
-author('Mahesh Paolini-Subramanya <>').
-export([ bstr/1
, chomp/1
, concat/2
, duplicate/2
, equal/2
, from_atom/1
, from_float/1
, from_integer/1
, from_integer/2
, from_integer/3
, from_list/1
, from_number/1
, get_line/1
, hex_char_to_integer/1
, hexdecode/1
, hexencode/1
, index/2
, insert/3
, integer_to_hex_char/1
, integer_to_hex_char/2
, is_alnum/1
, is_alpha/1
, is_atom_as_binary/1
, is_atom_char/1
, is_blank/1
, is_digit/1
, is_lower/1
, is_numeric/1
, is_space/1
, is_upper/1
, is_xdigit/1
, join/1
, join/2
, join/3
, left/2
, len/1
, lower/1
, lpad/2
, lpad/3
, lstrip/1
, lstrip/2
, member/2
, nth/2
, pad/2
, pad/3
, prefix/2
, right/2
, rindex/2
, rpad/2
, rpad/3
, rstrip/1
, rstrip/2
, split/2
, strip/1
, strip/2
, substr/2
, substr/3
, suffix/2
, to_atom/1
, to_boolean/1
, to_existing_atom/1
, to_float/1
, to_integer/1
, to_integer/2
, to_list/1
, to_number/1
, upper/1
, urldecode/1
, urlencode/1
, xmldecode/1
, xmlencode/1
]).
%% @doc Return the length of a string.
-spec len(binary()) -> non_neg_integer().
len(Str) when is_binary(Str) ->
size(Str).
@doc Checks if two strings are equal .
-spec equal(binary(), binary()) -> boolean().
equal(Str, Str) ->
true;
equal(_, _) ->
false.
@doc two strings .
-spec concat(binary(), binary()) -> binary().
concat(Str1, Str2) when is_binary(Str1), is_binary(Str2) ->
<<Str1/binary, Str2/binary>>.
%% @doc Return the character in the nth position of the string.
-spec nth(binary(), pos_integer()) -> char().
nth(Str, Pos) when Pos > 0, Pos =< size(Str) ->
Offset = Pos - 1,
<<_Head:Offset/binary, Char, _Tail/binary>> = Str,
Char.
@doc Return the index of the first appearance of a character in a string .
-spec index(binary(), char()) -> integer().
index(Str, Char) when is_binary(Str), is_integer(Char) ->
index(Str, Char, 0).
index(<<Char, _Tail/binary>>, Char, N) ->
N;
index(<<_Char, Tail/binary>>, Char, N) ->
index(Tail, Char, N + 1);
index(<<>>, _Char, _N) ->
-1.
%% @doc Return the index of the last appearance of a character in a string.
-spec rindex(binary(), char()) -> integer().
rindex(Str, Char) when is_binary(Str), is_integer(Char) ->
rindex(Str, Char, size(Str) - 1).
rindex(Str, Char, Offset) ->
case Str of
<<_Head:Offset/binary, Char, _Tail/binary>> ->
Offset;
<<_Head:Offset/binary, _Char, _Tail/binary>> ->
rindex(Str, Char, Offset - 1);
_ ->
-1
end.
%% @doc Return whether the character is present in the string.
-spec member(binary(), char()) -> boolean().
member(<<Char, _Tail/binary>>, Char) ->
true;
member(<<_Char, Tail/binary>>, Char) ->
member(Tail, Char);
member(<<>>, _Char) ->
false.
%% @doc Indicates whether a string is a prefix of another one.
-spec prefix(binary(), binary()) -> boolean().
prefix(Str, Prefix) when is_binary(Str), is_binary(Prefix) ->
N = size(Prefix),
case Str of
<<Prefix:N/binary, _Tail/binary>> ->
true;
_ ->
false
end.
%% @doc Indicates whether a string is a suffix of another one.
-spec suffix(binary(), binary()) -> boolean().
suffix(Str, Suffix) when is_binary(Str), is_binary(Suffix) ->
N = size(Str) - size(Suffix),
case Str of
<<_Head:N/binary, Suffix/binary>> ->
true;
_ ->
false
end.
%% @doc Determines if a string is composed of alphabetic characters.
-spec is_alpha(binary()) -> boolean().
is_alpha(<<>>) ->
false;
is_alpha(Str) when is_binary(Str) ->
is_x(Str, fun char:is_alpha/1);
is_alpha(Char) when is_integer(Char) ->
char:is_alpha(Char).
%% @doc Determines if a string is composed of alphanumeric characters.
-spec is_alnum(binary()) -> boolean().
is_alnum(<<>>) ->
false;
is_alnum(Str) when is_binary(Str) ->
is_x(Str, fun char:is_alnum/1);
is_alnum(Char) when is_integer(Char) ->
char:is_alnum(Char).
%% @doc Determines if a string is composed of lower-case alphabetic characters.
-spec is_lower(binary()) -> boolean().
is_lower(<<>>) ->
false;
is_lower(Str) when is_binary(Str) ->
is_x(Str, fun char:is_lower/1);
is_lower(Char) when is_integer(Char) ->
char:is_lower(Char).
%% @doc Determines if a string is composed of upper-case alphabetic characters.
-spec is_upper(binary()) -> boolean().
is_upper(<<>>) ->
false;
is_upper(Str) when is_binary(Str) ->
is_x(Str, fun char:is_upper/1);
is_upper(Char) when is_integer(Char) ->
char:is_upper(Char).
%% @doc Determines if a string is composed of digits.
-spec is_digit(binary()) -> boolean().
is_digit(<<>>) ->
false;
is_digit(Str) when is_binary(Str) ->
is_x(Str, fun char:is_digit/1);
is_digit(Char) when is_integer(Char) ->
char:is_digit(Char).
%% @doc Determines if a string is composed of hexadecimal digits.
-spec is_xdigit(binary()) -> boolean().
is_xdigit(<<>>) ->
false;
is_xdigit(Str) when is_binary(Str) ->
is_x(Str, fun char:is_xdigit/1);
is_xdigit(Char) when is_integer(Char) ->
char:is_xdigit(Char).
%% @doc Determines if a string is composed of blank characters.
-spec is_blank(binary()) -> boolean().
is_blank(<<>>) ->
false;
is_blank(Char) when is_integer(Char) ->
char:is_blank(Char);
is_blank(Str) ->
is_x(Str, fun char:is_blank/1).
%% @doc Determines if a string is composed of spaces or tabs.
-spec is_space(binary()) -> boolean().
is_space(<<>>) ->
false;
is_space(Char) when is_integer(Char) ->
char:is_space(Char);
is_space(Str) ->
is_x(Str, fun char:is_space/1).
%% @doc Determines if a string is an unquoted atom.
-spec is_atom_as_binary(binary()) -> boolean().
is_atom_as_binary(<<>>) ->
false;
is_atom_as_binary(<<Char, Tail/binary>>) ->
char:is_lower(Char) andalso is_x(Tail, fun is_atom_char/1);
is_atom_as_binary(Char) when is_integer(Char) ->
is_atom_char(Char).
%% @doc Determine if a character is lower case, numeric, '_' or '@'.
-spec is_atom_char(char()) -> boolean().
is_atom_char(Char) ->
((Char >= $a) andalso (Char =< $z)) orelse
((Char >= $0) andalso (Char =< $9)) orelse
(Char =:= $_) orelse
(Char =:= $@).
%% @doc Determines if a string is a number.
-spec is_numeric(binary()) -> boolean().
is_numeric(Str) when is_binary(Str) ->
is_numeric_sign(Str);
is_numeric(Char) when is_integer(Char) ->
char:is_digit(Char).
is_numeric_sign(<<Char, Tail/binary>>)
when (Char >= $0 andalso Char =< $9) orelse (Char =:= $-) orelse (Char =:= $+) ->
is_numeric_digits(Tail);
is_numeric_sign(_Str) ->
false.
is_numeric_digits(<<Char, Tail/binary>>) when (Char >= $0 andalso Char =< $9) ->
is_numeric_digits(Tail);
is_numeric_digits(<<Char, Tail/binary>>) when Char =:= $. ->
is_numeric_decimals(Tail, first);
is_numeric_digits(<<_Char, _Tail/binary>>) ->
false;
is_numeric_digits(<<>>) ->
true.
is_numeric_decimals(<<Char, Tail/binary>>, _Stage) when (Char >= $0 andalso Char =< $9) ->
is_numeric_decimals(Tail, second);
is_numeric_decimals(<<>>, second) ->
true;
is_numeric_decimals(_Str, _Stage) ->
false.
%% @doc Helper function used to check whether all the characters in a string
%% meet a specific criteria that is passed as a function to it.
%% @end
-spec is_x(Str::binary(), Fun::fun((char()) -> boolean())) -> boolean().
is_x ( < < > > , _ Fun , _ Offset ) - >
%% false;
%% is_x(Str, Fun, Offset) ->
case of
< < _ Head : Offset / binary , , _ Tail / binary > > - >
case ) of
%% true ->
is_x(Str , Fun , Offset + 1 ) ;
%% false ->
%% false
%% end;
%% %% If we reach the end we have a string composed entirely of characters
%% %% that meet the criteria specified in the Fun().
%% _ ->
%% true
%% end.
This version is about 5 % faster than the one above . Re - test once
%% is released.
is_x(<<Char, Tail/binary>>, Fun) ->
case Fun(Char) of
true ->
is_x(Tail, Fun);
false ->
false
end;
is_x(<<>>, _Fun) ->
true.
%% @doc Insert a string into another one at the indicated position.
-spec insert(binary(), pos_integer(), binary()) -> binary().
insert(Str, Pos, Str1) when is_binary(Str), is_integer(Pos) ->
N = Pos - 1,
case Str of
<<Head:N/binary, Tail/binary>> ->
<<Head/binary, Str1/binary, Tail/binary>>;
_ ->
erlang:error(badarg)
end.
%% @doc Return 'Count' copies of a string.
-spec duplicate(char() | binary(), Count :: non_neg_integer()) -> binary().
duplicate(Char, Count) when is_integer(Char) ->
duplicate_char(Char, Count, <<>>);
duplicate(Str, Count) ->
duplicate_bin(Str, Count, <<>>).
duplicate_char(Char, Count, Acc) when Count > 0 ->
duplicate_char(Char, Count - 1, <<Acc/binary, Char>>);
duplicate_char(_Char, _Len, Acc) ->
Acc.
duplicate_bin(Str, Count, Acc) when Count > 0 ->
duplicate_bin(Str, Count - 1, <<Acc/binary, Str/binary>>);
duplicate_bin(_Str, _Len, Acc) ->
Acc.
%% @doc Return a substring starting at position 'Pos'.
-spec substr(binary(), integer()) -> binary().
substr(Str, 1) ->
Str;
substr(Str, Pos) ->
N = Pos - 1,
case Str of
<<_Head:N/binary, Substr/binary>> ->
Substr;
_ ->
<<>>
end.
%% @doc Return a substring starting at position 'Pos' with a length of 'Len' bytes.
-spec substr(binary(), Pos::integer(), Len::integer()) -> binary().
substr(Str, 1, Len) when is_binary(Str), Len =:= size(Str) ->
Str;
substr(Str, Pos, Len) when is_binary(Str) ->
N = Pos - 1,
case Str of
<<_Head:N/binary, Substr:Len/binary, _Tail/binary>> ->
Substr;
<<_Head:N/binary, Substr/binary>> ->
Substr;
_ ->
<<>>
end.
@doc Return a substring of ' ' bytes starting from the beginning of the
%% string. If the string does not have enough characters, the original
%% string is returned.
-spec left(binary(), integer()) -> binary().
left(Str, Len) when Len >= size(Str) ->
Str;
left(Str, Len) when Len >= 0 ->
<<Left:Len/binary, _Tail/binary>> = Str,
Left.
@doc Return a substring of ' ' bytes starting from the end of the string .
%% If the string does not have enough characters, the original string is
%% returned.
-spec right(binary(), integer()) -> binary().
right(Str, Len) when Len >= size(Str) ->
Str;
right(Str, Len) when Len >= 0 ->
Offset = size(Str) - Len,
<<_Head:Offset/binary, Right/binary>> = Str,
Right.
@doc Return a string of ' ' bytes padded with spaces to the left and to the right .
-spec pad(binary(), non_neg_integer()) -> binary().
pad(Str, Len) when Len >= 0 ->
pad(Str, Len, $\s).
@doc Return a string of ' ' bytes padded with ' ' to the left and to the right .
-spec pad(binary(), non_neg_integer(), char()) -> binary().
pad(Str, Len, Char) when Len >= 0, is_integer(Char) ->
PadLen = Len - size(Str),
if
PadLen > 0 ->
LeftPadLen = PadLen div 2,
RightPadLen = PadLen - LeftPadLen,
Padding = duplicate(Char, LeftPadLen),
if
RightPadLen > 0 ->
if
LeftPadLen =:= RightPadLen ->
<<Padding/binary, Str/binary, Padding/binary>>;
true ->
<<Padding/binary, Str/binary, Padding/binary, Char>>
end;
true ->
<<Padding/binary, Str/binary>>
end;
true ->
Str
end.
%% @doc Return a string of 'Len' bytes left-padded with spaces.
-spec lpad(binary(), non_neg_integer()) -> binary().
lpad(Str, Len) when Len >= 0 ->
lpad(Str, Len, $\s).
@doc Return a string of ' Len ' bytes left - padded with ' ' .
-spec lpad(binary(), non_neg_integer(), char()) -> binary().
lpad(Str, Len, Char) when Len >= 0, is_integer(Char) ->
PadLen = Len - size(Str),
if
PadLen > 0 ->
Padding = duplicate(Char, PadLen),
<<Padding/binary, Str/binary>>;
true ->
Str
end.
@doc Return a string of ' ' bytes right - padded with spaces .
-spec rpad(binary(), non_neg_integer()) -> binary().
rpad(Str, Len) when Len >= 0 ->
rpad(Str, Len, $\s).
@doc Return a string of ' ' bytes right - padded with ' ' .
-spec rpad(binary(), non_neg_integer(), char()) -> binary().
rpad(Str, Len, Char) when Len >= 0, is_integer(Char) ->
PadLen = Len - size(Str),
if
PadLen > 0 ->
Padding = duplicate(Char, PadLen),
<<Str/binary, Padding/binary>>;
true ->
Str
end.
%% @doc Remove all the spaces present both to the left and to the right of the string.
-spec strip(binary()) -> binary().
strip(Str) ->
strip(Str, <<"\s\t\n\r\f\v">>).
%% @doc Remove all the 'Chars' present both to the left and to the right of the string.
-spec strip(binary(), char() | binary()) -> binary().
strip(Str, Char) ->
rstrip(lstrip(Str, Char), Char).
%% @doc Remove all the spaces present to the left of the string.
-spec lstrip(binary()) -> binary().
lstrip(Str) ->
lstrip(Str, <<"\s\t\n\r\f\v">>).
%% @doc Remove all the 'Chars' present to the left of the string.
-spec lstrip(binary(), char() | binary()) -> binary().
lstrip(Str, Char) when is_integer(Char) ->
lstrip_char(Str, Char);
lstrip(Str, Chars) when is_binary(Chars) ->
lstrip_bin(Str, Chars).
%% @hidden
lstrip_char(<<Char, Tail/binary>>, Char) ->
lstrip_char(Tail, Char);
lstrip_char(Str, _Char) ->
Str.
%% @hidden
lstrip_bin(<<Char, Tail/binary>> = Str, Chars) ->
case member(Chars, Char) of
true ->
lstrip_bin(Tail, Chars);
_ ->
Str
end;
lstrip_bin(Str, _Chars) ->
Str.
%% @doc Remove all the spaces present to the right of the string.
-spec rstrip(binary()) -> binary().
rstrip(Str) ->
rstrip(Str, <<"\s\t\n\r\f\v">>).
%% @doc Remove all the 'Chars' present to the right of the string.
-spec rstrip(binary(), char() | binary()) -> binary().
rstrip(Str, Char) when is_integer(Char) ->
rstrip_char(Str, Char, size(Str) - 1);
rstrip(Str, Chars) ->
rstrip_bin(Str, Chars, size(Str) - 1).
%% @hidden
rstrip_char(Str, Char, Pos) ->
case Str of
<<Head:Pos/binary, Char>> ->
rstrip_char(Head, Char, Pos - 1);
_ ->
Str
end.
%% @hidden
rstrip_bin(Str, Chars, Pos) ->
case Str of
<<Head:Pos/binary, Char>> ->
case member(Chars, Char) of
true ->
rstrip_bin(Head, Chars, Pos - 1);
_ ->
Str
end;
_ ->
Str
end.
@doc Remove all the newlines ( \r and ) present at the end of the string .
-spec chomp(binary()) -> binary().
chomp(Str) ->
Pos = size(Str) - 1,
case Str of
<<Head:Pos/binary, Char>> when Char =:= $\r; Char =:= $\n ->
chomp(Head);
_ ->
Str
end.
%% @doc Divide a string into a list of tokens that were originally separated
%% by the character 'Sep'.
-spec split(binary(), Sep::char() | binary()) -> list(binary()).
split(<<>>, _Sep) ->
[];
split(Str, Sep) when is_integer(Sep) ->
lists:reverse(split_char_sep(Str, <<>>, Sep, []));
split(Str, Sep) ->
Tokens =
case Sep of
<<Char>> ->
split_char_sep(Str, <<>>, Char, []);
_ ->
split_str_sep(Str, <<>>, Sep, [])
end,
lists:reverse(Tokens).
%% @doc Helper function used to tokenize a string when the separator is a character.
-spec split_char_sep(binary(), binary(), char(), [binary()]) -> [binary()].
split_char_sep(<<Sep, Tail/binary>>, TokenAcc, Sep, Tokens) ->
split_char_sep(Tail, <<>>, Sep, [TokenAcc | Tokens]);
split_char_sep(<<Char, Tail/binary>>, TokenAcc, Sep, Tokens) ->
split_char_sep(Tail, <<TokenAcc/binary, Char>>, Sep, Tokens);
split_char_sep(<<>>, TokenAcc, _Sep, Tokens) ->
[TokenAcc | Tokens].
%% @doc Helper function used to tokenize a string when there are multiple separators.
-spec split_str_sep(binary(), binary(), binary(), [binary()]) -> [binary(),...].
split_str_sep(<<Char, Tail/binary>>, TokenAcc, Sep, Tokens) ->
case member(Sep, Char) of
true ->
split_str_sep(Tail, <<>>, Sep, [TokenAcc | Tokens]);
false ->
split_str_sep(Tail, <<TokenAcc/binary, Char>>, Sep, Tokens)
end;
split_str_sep(<<>>, TokenAcc, _Sep, Tokens) ->
[TokenAcc | Tokens].
@doc Join a a list of strings into one string .
-spec join([binary()]) -> binary().
%% join(List) when is_list(List) ->
%% join_list(List, <<>>).
join_list([Head|Tail ] , Acc ) - >
%% Value = bstr(Head),
%% join_list(Tail, <<Acc/binary, Value/binary>>);
%% join_list([], Acc) ->
Acc .
This version is about 5 % faster than the one above with Erlang R14B01 .
join(List) when is_list(List) ->
list_to_binary(join_list(List, [])).
join_list([Head | Tail], Acc) when is_atom(Head) ->
join_list(Tail, [atom_to_list(Head) | Acc]);
join_list([Head | Tail], Acc) when is_list(Head) ->
join_list(Tail, [join_list(Head, []) | Acc]);
join_list([Head | Tail], Acc) ->
join_list(Tail, [Head | Acc]);
join_list([], Acc) ->
lists:reverse(Acc).
@doc Join a a list of strings into one string , adding a separator between
%% each string.
-spec join([binary()], Sep::char() | binary()) -> binary().
join(List, Sep) when is_list(List) ->
list_to_binary(join_list_sep(List, Sep)).
-spec join_list_sep([any()], char() | binary()) -> [any()].
join_list_sep([Head | Tail], Sep) when is_atom(Head) ->
join_list_sep(Tail, Sep, [atom_to_list(Head)]);
join_list_sep([Head | Tail], Sep) when is_list(Head) ->
join_list_sep(Tail, Sep, [join_list(Head, [])]);
join_list_sep([Head | Tail], Sep) ->
join_list_sep(Tail, Sep, [Head]);
join_list_sep([], _Sep) ->
[].
join_list_sep([Head | Tail], Sep, Acc) when is_atom(Head) ->
join_list_sep(Tail, Sep, [atom_to_list(Head), Sep | Acc]);
join_list_sep([Head | Tail], Sep, Acc) when is_list(Head) ->
join_list_sep(Tail, Sep, [join_list(Head, []), Sep | Acc]);
join_list_sep([Head | Tail], Sep, Acc) ->
join_list_sep(Tail, Sep, [Head, Sep | Acc]);
join_list_sep([], _Sep, Acc) ->
lists:reverse(Acc).
@doc Join a a list of strings into one string , adding a separator between
%% each string and escaping both the separator and the escape char itself
%% with the escape char.
%%
%% e.g.:
` ` bstr : join([<<"1 " > > , < < " , " > > , < < " " > > , < < " 2,3 " > > ] , $ , , $ \ ) - > < < " 1,\,,\\1,2\,3 " > > . ''
%% @end
-spec join([binary()], Sep :: char() | binary(), Esc :: char()) -> binary().
join(Members, Sep, Esc) ->
EscStr =
case Esc of
$\\ ->
"\\\\";
$& ->
"\\&";
OtherEsc ->
[OtherEsc]
end,
SepStr =
case Sep of
$\\ ->
"\\\\";
$& ->
"\\&";
OtherSep ->
[OtherSep]
end,
" [ sep]|[esc ] "
Replace = EscStr ++ "&",
bstr:join(
lists:map(fun(Member) when is_atom(Member) ->
re:replace(atom_to_list(Member),
Find,
Replace,
[{return, binary}, global]);
(Member) ->
re:replace(Member,
Find,
Replace,
[{return, binary}, global])
end, Members),
Sep).
%% @doc Convert all the characters in a binary to lowercase.
-spec lower(binary() | char()) -> binary() | char().
lower(Char) when is_integer(Char) ->
case char:is_upper(Char) of
true ->
Char - $A + $a;
false ->
Char
end;
lower(Str) ->
lower(Str, <<>>).
lower(<<Char, Tail/binary>>, Acc) ->
case char:is_upper(Char) of
true ->
Lower = Char - $A + $a,
lower(Tail, <<Acc/binary, Lower>>);
false ->
lower(Tail, <<Acc/binary, Char>>)
end;
lower(<<>>, Acc) ->
Acc.
%% @doc Convert all the characters in a binary to uppercase.
-spec upper(binary() | char()) -> binary() | char().
upper(Char) when is_integer(Char) ->
case char:is_lower(Char) of
true ->
Char - $a + $A;
false ->
Char
end;
upper(Str) ->
upper(Str, <<>>).
upper(<<Char, Tail/binary>>, Acc) ->
case char:is_lower(Char) of
true ->
Upper = Char - $a + $A,
upper(Tail, <<Acc/binary, Upper>>);
false ->
upper(Tail, <<Acc/binary, Char>>)
end;
upper(<<>>, Acc) ->
Acc.
%% @doc Convert an "object" to a binary.
-spec bstr(binary() | atom() | list() | char()) -> binary().
bstr(Bin) when is_binary(Bin) ->
Bin;
bstr(Pid) when is_pid(Pid) ->
list_to_binary(pid_to_list(Pid));
bstr(Atom) when is_atom(Atom) ->
from_atom(Atom);
bstr(Integer) when is_integer(Integer), Integer > 0, Integer =< 255 ->
<<Integer>>;
bstr(Integer) when is_integer(Integer) ->
from_integer(Integer);
bstr(Float) when is_float(Float) ->
from_float(Float);
bstr(List) when is_list(List) ->
list_to_binary(List).
%% @doc Convert an atom to a bstr.
-spec from_atom(atom()) -> binary().
from_atom(Atom) ->
atom_to_binary(Atom, utf8).
@doc Convert a bstr containing a string to an Erlang atom .
-spec to_atom(binary()) -> atom().
to_atom(Str) ->
binary_to_atom(Str, utf8).
@doc Convert a bstr containing a string to an Erlang atom only if the atom
%% already existed (i.e. had been previously defined).
-spec to_existing_atom(binary()) -> atom().
to_existing_atom(Str) ->
binary_to_existing_atom(Str, utf8).
%% @doc Convert a list containing a string to a binary.
-spec from_list(list()) -> binary().
from_list(List) ->
list_to_binary(List).
@doc Convert a bstr containing a string to an Erlang list / string .
-spec to_list(binary()) -> [byte()].
to_list(Str) ->
binary_to_list(Str).
@doc Convert a bstr containing a string to an Erlang list / string .
-spec to_boolean(binary()) -> boolean().
to_boolean(<<"true">>) ->
true;
to_boolean(<<"false">>) ->
false.
@doc Convert an integer to a bstr in base 10 format .
-spec from_integer(integer()) -> binary().
from_integer(I) ->
integer_to_binary(I).
%% @doc Convert an integer to a bstr in base 'n' format.
-spec from_integer(integer ( ) , 1 .. 255 ) - > binary ( ) .
from_integer(I, 10) ->
erlang:integer_to_binary(I);
from_integer(I, Base)
when erlang:is_integer(I), erlang:is_integer(Base),
Base >= 2, Base =< 1+$Z-$A+10 ->
%% We can't use integer_to_binary/2 in versions <= R16B01 as the function
generates wrong output values in bases other than 10 for 0 and negative
%% integers.
if I < 0 ->
<<$-,(from_integer1(-I, Base, <<>>))/binary>>;
true ->
from_integer1(I, Base, <<>>)
end;
from_integer(I, Base) ->
erlang:error(badarg, [I, Base]).
%% integer_to_binary(I, Base).
%% integer_to_binary(I0, Base, R0) ->
from_integer1(I0, Base, R0) ->
D = I0 rem Base,
I1 = I0 div Base,
R1 = if
D >= 10 -> <<(D-10+$A),R0/binary>>;
true -> <<(D+$0),R0/binary>>
end,
if
I1 =:= 0 -> R1;
true -> from_integer1(I1,Base,R1)
end.
%% @doc Convert an integer to a bstr in base 'n' format in the specified case.
-spec from_integer(integer(), 2..36, upper | lower) -> binary().
from_integer(I, Base, Case) when is_integer(I), is_integer(Base), Base >= 2, Base =< $Z - $A + 11 ->
BaseLetter = case Case of
upper ->
$A;
lower ->
$a
end,
list_to_binary(
if
I < 0 ->
[$- | from_integer(-I, Base, BaseLetter, [])];
true ->
from_integer(I, Base, BaseLetter, [])
end
);
from_integer(I, Base, Case) ->
erlang:error(badarg, [I, Base, Case]).
%% Helper function to convert an integer to a base 'n' representation.
-spec from_integer(integer(), pos_integer(), 65 | 97, [integer()]) -> [integer(),...].
from_integer(I0, Base, BaseLetter, Acc) ->
I1 = I0 div Base,
Digit = I0 rem Base,
Acc1 = [
if
(Digit >= 10) ->
Digit - 10 + BaseLetter;
true ->
Digit + $0
end | Acc
],
if
I1 =:= 0 ->
Acc1;
true ->
from_integer(I1, Base, BaseLetter, Acc1)
end.
%% @doc Convert a bstr containing a string representing a decimal number
%% to an integer.
-spec to_integer(binary()) -> integer().
to_integer(Str) ->
binary_to_integer(Str).
%% @doc Convert a bstr containing a string representing a positive number
%% in the specified 'Base' to an integer. 'Base' must be an integer
between 2 and 32 .
Optimized version for base 10
-spec to_integer(binary(), 1..255) -> integer().
to_integer(Str, Base) ->
binary_to_integer(Str, Base).
%% @doc Convert a floating point number to a bstr.
-spec from_float(float()) -> binary().
from_float(Float) ->
float_to_binary(Float, [{decimals, 10}, compact]).
%% @doc Convert a bstr formatted as a floating point number to a float.
-spec to_float(binary()) -> float().
to_float(Str) ->
binary_to_float(Str).
%% @doc Convert an integer or floating point number into a bstr.
-spec from_number(integer() | float()) -> binary().
from_number(Number) when is_float(Number) ->
float_to_binary(Number, [{decimals, 10}, compact]);
from_number(Number) ->
integer_to_binary(Number).
%% @doc Convert a formatted binary into an integer or floating point number.
-spec to_number(binary()) -> integer() | float().
to_number(Str) ->
case member(Str, $.) of
true -> binary_to_float(Str);
false -> binary_to_integer(Str)
end.
@doc Get the first text line from a binary string . It returns a tuple with
the first text line as the first element and the rest of the string as
%% the last element.
-spec get_line(binary()) -> {binary(), binary()}.
get_line(Str) ->
get_line(Str, <<>>).
get_line(<<$\n, Tail/binary>>, Acc) ->
{Acc, Tail};
get_line(<<$\r, $\n, Tail/binary>>, Acc) ->
{Acc, Tail};
get_line(<<Char, Tail/binary>>, Acc) ->
get_line(Tail, <<Acc/binary, Char>>);
get_line(<<>>, Acc) ->
{Acc, <<>>}.
%% @doc Encode a bstr using the URL-encoding scheme.
-spec urlencode(binary()) -> binary().
urlencode(Str) ->
urlencode(Str, <<>>).
urlencode(<<Char, Tail/binary>>, Acc) ->
urlencode(Tail,
case is_urlencoded(Char) of
true ->
Hi = integer_to_hex_char((Char band 16#f0) bsr 4),
Lo = integer_to_hex_char((Char band 16#0f)),
, Hi , > > ;
false ->
<<Acc/binary, Char>>
end
);
urlencode(<<>>, Acc) ->
Acc.
%% @doc Determine whether a character has to be URL-encoded.
is_urlencoded(Char) ->
not (((Char >= $0) andalso (Char =< $9)) orelse
((Char >= $A) andalso (Char =< $Z)) orelse
((Char >= $a) andalso (Char =< $z)) orelse
(Char =:= $-) orelse (Char =:= $_) orelse
(Char =:= $.) orelse (Char =:= $~)).
%% @doc Convert an integer between 0 and 15 to an hexadecimal character.
-spec integer_to_hex_char(char()) -> char().
integer_to_hex_char(N) when N >= 0 ->
if
N =< 9 ->
$0 + N;
N =< 15 ->
$A - 10 + N;
true ->
erlang:error(badarg)
end.
%% @hidden
-spec integer_to_hex_char(char(), lower | upper) -> char().
integer_to_hex_char(N, lower) when N >= 0 ->
if
N =< 9 ->
$0 + N;
N =< 15 ->
$a - 10 + N;
true ->
erlang:error(badarg)
end;
integer_to_hex_char(N, upper) ->
integer_to_hex_char(N).
%% @doc Decode a bstr using the URL-encoding scheme.
-spec urldecode(binary()) -> binary().
urldecode(Str) ->
urldecode(Str, <<>>).
, Hi , , Tail / binary > > , Acc ) - >
Char = ((hex_char_to_integer(Hi) bsl 4) bor hex_char_to_integer(Lo)),
urldecode(Tail, <<Acc/binary, Char>>);
urldecode(<<$%, _Tail/binary>>, _Acc) ->
erlang:error(badarg);
urldecode(<<Char, Tail/binary>>, Acc) ->
urldecode(Tail, <<Acc/binary, Char>>);
urldecode(<<>>, Acc) ->
Acc.
%% @doc Convert an hexadecimal character to an integer. If the character is not an
%% hexadecimal character we return a 'badarg' exception.
-spec hex_char_to_integer(char()) -> char().
hex_char_to_integer(Char) ->
if
(Char >= $0) and (Char =< $9) ->
Char - $0;
(Char >= $A) and (Char =< $F) ->
Char - $A + 10;
(Char >= $a) and (Char =< $f) ->
Char - $a + 10;
true ->
erlang:error(badarg)
end.
@doc Encode a bstr using the XML - encoding scheme .
WARNING : This function assumes that the input is a valid UTF-8 string
%% and supports non-printable characters in the ASCII range
00h-1Fh . Bytes that are not part of a valid UTF-8 character
%% are not converted at all.
-spec xmlencode(binary()) -> binary().
xmlencode(Str) ->
xmlencode(Str, <<>>).
xmlencode(<<Char, Tail/binary>>, Acc) ->
xmlencode(Tail,
case is_xmlencoded(Char) of
true ->
Encoded = xmlencode_char(Char),
<<Acc/binary, $&, Encoded/binary, $;>>;
false ->
<<Acc/binary, Char>>
end
);
xmlencode(<<>>, Acc) ->
Acc.
%% @doc Determine whether a character has to be XML-encoded. See
%% <a href="-8#Description">Wikipedia</a>,
%% <a href="/">ASCII Table</a>
is_xmlencoded(Char) ->
(Char < 32) orelse (Char =:= 192) orelse (Char =:= 193) orelse (Char > 244)
orelse (Char =:= $&) orelse (Char =:= $<) orelse (Char =:= $>)
orelse (Char =:= $') orelse (Char =:= $").
Encode a single character using the XML encoding scheme to create a
%% character entity reference.
xmlencode_char($&) ->
<<"amp">>;
xmlencode_char($<) ->
<<"lt">>;
xmlencode_char($>) ->
<<"gt">>;
xmlencode_char($') ->
<<"apos">>;
xmlencode_char($") ->
<<"quot">>;
xmlencode_char(Char) when Char < 32 ->
Hi = integer_to_hex_char((Char band 16#f0) bsr 4),
Lo = integer_to_hex_char((Char band 16#0f)),
<<"#x", Hi, Lo>>;
xmlencode_char(Char) ->
Char.
@doc Decode a bstr using the XML - encoding scheme to resolve any character
%% entity reference present in the string.
-spec xmldecode(binary()) -> binary().
xmldecode(Str) ->
xmldecode(Str, <<>>).
xmldecode(<<"&", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $&>>);
xmldecode(<<"<", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $<>>);
xmldecode(<<">", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $>>>);
xmldecode(<<"'", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $'>>);
xmldecode(<<""", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $">>);
xmldecode(<<"&#x", Hi, Lo, $;, Tail/binary>>, Acc) ->
Char = (hex_char_to_integer(Hi) bsl 4) bor hex_char_to_integer(Lo),
xmldecode(Tail, <<Acc/binary, Char>>);
xmldecode(<<Char, Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, Char>>);
xmldecode(<<>>, Acc) ->
Acc.
%% @doc Encode a bstr converting each character to its hexadecimal
%% representation.
-spec hexencode(binary()) -> binary().
hexencode(Str) ->
hexencode(Str, <<>>).
hexencode(<<Hi:4, Lo:4, Tail/binary>>, Acc) ->
HiChar = integer_to_hex_char(Hi, lower),
LoChar = integer_to_hex_char(Lo, lower),
hexencode(Tail, <<Acc/binary, HiChar, LoChar>>);
hexencode(<<>>, Acc) ->
Acc.
%% @doc Decode a bstr with an hexadecimal representation of a string.
-spec hexdecode(binary()) -> binary().
hexdecode(Str) ->
hexdecode(Str, <<>>).
hexdecode(<<Hi, Lo, Tail/binary>>, Acc) ->
Char = ((hex_char_to_integer(Hi) bsl 4) bor hex_char_to_integer(Lo)),
hexdecode(Tail, <<Acc/binary, Char>>);
% If the number of characters wasn't even we raise an exception.
hexdecode(<<_Char>>, _Acc) ->
erlang:error(badarg);
hexdecode(<<>>, Acc) ->
Acc.
| null | https://raw.githubusercontent.com/jcomellas/bstr/609ba263df6b940b4d7f66ac2768f73ac9e17e0e/src/bstr.erl | erlang | -------------------------------------------------------------------
@end
a copy of the New BSD license with this software. If not, it can be
retrieved from: -license.php
-------------------------------------------------------------------
@doc Return the length of a string.
@doc Return the character in the nth position of the string.
@doc Return the index of the last appearance of a character in a string.
@doc Return whether the character is present in the string.
@doc Indicates whether a string is a prefix of another one.
@doc Indicates whether a string is a suffix of another one.
@doc Determines if a string is composed of alphabetic characters.
@doc Determines if a string is composed of alphanumeric characters.
@doc Determines if a string is composed of lower-case alphabetic characters.
@doc Determines if a string is composed of upper-case alphabetic characters.
@doc Determines if a string is composed of digits.
@doc Determines if a string is composed of hexadecimal digits.
@doc Determines if a string is composed of blank characters.
@doc Determines if a string is composed of spaces or tabs.
@doc Determines if a string is an unquoted atom.
@doc Determine if a character is lower case, numeric, '_' or '@'.
@doc Determines if a string is a number.
@doc Helper function used to check whether all the characters in a string
meet a specific criteria that is passed as a function to it.
@end
false;
is_x(Str, Fun, Offset) ->
true ->
false ->
false
end;
%% If we reach the end we have a string composed entirely of characters
%% that meet the criteria specified in the Fun().
_ ->
true
end.
faster than the one above . Re - test once
is released.
@doc Insert a string into another one at the indicated position.
@doc Return 'Count' copies of a string.
@doc Return a substring starting at position 'Pos'.
@doc Return a substring starting at position 'Pos' with a length of 'Len' bytes.
string. If the string does not have enough characters, the original
string is returned.
If the string does not have enough characters, the original string is
returned.
@doc Return a string of 'Len' bytes left-padded with spaces.
@doc Remove all the spaces present both to the left and to the right of the string.
@doc Remove all the 'Chars' present both to the left and to the right of the string.
@doc Remove all the spaces present to the left of the string.
@doc Remove all the 'Chars' present to the left of the string.
@hidden
@hidden
@doc Remove all the spaces present to the right of the string.
@doc Remove all the 'Chars' present to the right of the string.
@hidden
@hidden
@doc Divide a string into a list of tokens that were originally separated
by the character 'Sep'.
@doc Helper function used to tokenize a string when the separator is a character.
@doc Helper function used to tokenize a string when there are multiple separators.
join(List) when is_list(List) ->
join_list(List, <<>>).
Value = bstr(Head),
join_list(Tail, <<Acc/binary, Value/binary>>);
join_list([], Acc) ->
faster than the one above with Erlang R14B01 .
each string.
each string and escaping both the separator and the escape char itself
with the escape char.
e.g.:
@end
@doc Convert all the characters in a binary to lowercase.
@doc Convert all the characters in a binary to uppercase.
@doc Convert an "object" to a binary.
@doc Convert an atom to a bstr.
already existed (i.e. had been previously defined).
@doc Convert a list containing a string to a binary.
@doc Convert an integer to a bstr in base 'n' format.
We can't use integer_to_binary/2 in versions <= R16B01 as the function
integers.
integer_to_binary(I, Base).
integer_to_binary(I0, Base, R0) ->
@doc Convert an integer to a bstr in base 'n' format in the specified case.
Helper function to convert an integer to a base 'n' representation.
@doc Convert a bstr containing a string representing a decimal number
to an integer.
@doc Convert a bstr containing a string representing a positive number
in the specified 'Base' to an integer. 'Base' must be an integer
@doc Convert a floating point number to a bstr.
@doc Convert a bstr formatted as a floating point number to a float.
@doc Convert an integer or floating point number into a bstr.
@doc Convert a formatted binary into an integer or floating point number.
the last element.
@doc Encode a bstr using the URL-encoding scheme.
@doc Determine whether a character has to be URL-encoded.
@doc Convert an integer between 0 and 15 to an hexadecimal character.
@hidden
@doc Decode a bstr using the URL-encoding scheme.
, _Tail/binary>>, _Acc) ->
@doc Convert an hexadecimal character to an integer. If the character is not an
hexadecimal character we return a 'badarg' exception.
and supports non-printable characters in the ASCII range
are not converted at all.
@doc Determine whether a character has to be XML-encoded. See
<a href="-8#Description">Wikipedia</a>,
<a href="/">ASCII Table</a>
character entity reference.
entity reference present in the string.
@doc Encode a bstr converting each character to its hexadecimal
representation.
@doc Decode a bstr with an hexadecimal representation of a string.
If the number of characters wasn't even we raise an exception. | @author < >
@author < >
2008 - 2011 , .
@doc String implemented over an Erlang binary .
This source file is subject to the New BSD License . You should have received
-module(bstr).
-author('Juan Jose Comellas <>').
-author('Mahesh Paolini-Subramanya <>').
-export([ bstr/1
, chomp/1
, concat/2
, duplicate/2
, equal/2
, from_atom/1
, from_float/1
, from_integer/1
, from_integer/2
, from_integer/3
, from_list/1
, from_number/1
, get_line/1
, hex_char_to_integer/1
, hexdecode/1
, hexencode/1
, index/2
, insert/3
, integer_to_hex_char/1
, integer_to_hex_char/2
, is_alnum/1
, is_alpha/1
, is_atom_as_binary/1
, is_atom_char/1
, is_blank/1
, is_digit/1
, is_lower/1
, is_numeric/1
, is_space/1
, is_upper/1
, is_xdigit/1
, join/1
, join/2
, join/3
, left/2
, len/1
, lower/1
, lpad/2
, lpad/3
, lstrip/1
, lstrip/2
, member/2
, nth/2
, pad/2
, pad/3
, prefix/2
, right/2
, rindex/2
, rpad/2
, rpad/3
, rstrip/1
, rstrip/2
, split/2
, strip/1
, strip/2
, substr/2
, substr/3
, suffix/2
, to_atom/1
, to_boolean/1
, to_existing_atom/1
, to_float/1
, to_integer/1
, to_integer/2
, to_list/1
, to_number/1
, upper/1
, urldecode/1
, urlencode/1
, xmldecode/1
, xmlencode/1
]).
-spec len(binary()) -> non_neg_integer().
len(Str) when is_binary(Str) ->
size(Str).
@doc Checks if two strings are equal .
-spec equal(binary(), binary()) -> boolean().
equal(Str, Str) ->
true;
equal(_, _) ->
false.
@doc two strings .
-spec concat(binary(), binary()) -> binary().
concat(Str1, Str2) when is_binary(Str1), is_binary(Str2) ->
<<Str1/binary, Str2/binary>>.
-spec nth(binary(), pos_integer()) -> char().
nth(Str, Pos) when Pos > 0, Pos =< size(Str) ->
Offset = Pos - 1,
<<_Head:Offset/binary, Char, _Tail/binary>> = Str,
Char.
@doc Return the index of the first appearance of a character in a string .
-spec index(binary(), char()) -> integer().
index(Str, Char) when is_binary(Str), is_integer(Char) ->
index(Str, Char, 0).
index(<<Char, _Tail/binary>>, Char, N) ->
N;
index(<<_Char, Tail/binary>>, Char, N) ->
index(Tail, Char, N + 1);
index(<<>>, _Char, _N) ->
-1.
-spec rindex(binary(), char()) -> integer().
rindex(Str, Char) when is_binary(Str), is_integer(Char) ->
rindex(Str, Char, size(Str) - 1).
rindex(Str, Char, Offset) ->
case Str of
<<_Head:Offset/binary, Char, _Tail/binary>> ->
Offset;
<<_Head:Offset/binary, _Char, _Tail/binary>> ->
rindex(Str, Char, Offset - 1);
_ ->
-1
end.
-spec member(binary(), char()) -> boolean().
member(<<Char, _Tail/binary>>, Char) ->
true;
member(<<_Char, Tail/binary>>, Char) ->
member(Tail, Char);
member(<<>>, _Char) ->
false.
-spec prefix(binary(), binary()) -> boolean().
prefix(Str, Prefix) when is_binary(Str), is_binary(Prefix) ->
N = size(Prefix),
case Str of
<<Prefix:N/binary, _Tail/binary>> ->
true;
_ ->
false
end.
-spec suffix(binary(), binary()) -> boolean().
suffix(Str, Suffix) when is_binary(Str), is_binary(Suffix) ->
N = size(Str) - size(Suffix),
case Str of
<<_Head:N/binary, Suffix/binary>> ->
true;
_ ->
false
end.
-spec is_alpha(binary()) -> boolean().
is_alpha(<<>>) ->
false;
is_alpha(Str) when is_binary(Str) ->
is_x(Str, fun char:is_alpha/1);
is_alpha(Char) when is_integer(Char) ->
char:is_alpha(Char).
-spec is_alnum(binary()) -> boolean().
is_alnum(<<>>) ->
false;
is_alnum(Str) when is_binary(Str) ->
is_x(Str, fun char:is_alnum/1);
is_alnum(Char) when is_integer(Char) ->
char:is_alnum(Char).
-spec is_lower(binary()) -> boolean().
is_lower(<<>>) ->
false;
is_lower(Str) when is_binary(Str) ->
is_x(Str, fun char:is_lower/1);
is_lower(Char) when is_integer(Char) ->
char:is_lower(Char).
-spec is_upper(binary()) -> boolean().
is_upper(<<>>) ->
false;
is_upper(Str) when is_binary(Str) ->
is_x(Str, fun char:is_upper/1);
is_upper(Char) when is_integer(Char) ->
char:is_upper(Char).
-spec is_digit(binary()) -> boolean().
is_digit(<<>>) ->
false;
is_digit(Str) when is_binary(Str) ->
is_x(Str, fun char:is_digit/1);
is_digit(Char) when is_integer(Char) ->
char:is_digit(Char).
-spec is_xdigit(binary()) -> boolean().
is_xdigit(<<>>) ->
false;
is_xdigit(Str) when is_binary(Str) ->
is_x(Str, fun char:is_xdigit/1);
is_xdigit(Char) when is_integer(Char) ->
char:is_xdigit(Char).
-spec is_blank(binary()) -> boolean().
is_blank(<<>>) ->
false;
is_blank(Char) when is_integer(Char) ->
char:is_blank(Char);
is_blank(Str) ->
is_x(Str, fun char:is_blank/1).
-spec is_space(binary()) -> boolean().
is_space(<<>>) ->
false;
is_space(Char) when is_integer(Char) ->
char:is_space(Char);
is_space(Str) ->
is_x(Str, fun char:is_space/1).
-spec is_atom_as_binary(binary()) -> boolean().
is_atom_as_binary(<<>>) ->
false;
is_atom_as_binary(<<Char, Tail/binary>>) ->
char:is_lower(Char) andalso is_x(Tail, fun is_atom_char/1);
is_atom_as_binary(Char) when is_integer(Char) ->
is_atom_char(Char).
-spec is_atom_char(char()) -> boolean().
is_atom_char(Char) ->
((Char >= $a) andalso (Char =< $z)) orelse
((Char >= $0) andalso (Char =< $9)) orelse
(Char =:= $_) orelse
(Char =:= $@).
-spec is_numeric(binary()) -> boolean().
is_numeric(Str) when is_binary(Str) ->
is_numeric_sign(Str);
is_numeric(Char) when is_integer(Char) ->
char:is_digit(Char).
is_numeric_sign(<<Char, Tail/binary>>)
when (Char >= $0 andalso Char =< $9) orelse (Char =:= $-) orelse (Char =:= $+) ->
is_numeric_digits(Tail);
is_numeric_sign(_Str) ->
false.
is_numeric_digits(<<Char, Tail/binary>>) when (Char >= $0 andalso Char =< $9) ->
is_numeric_digits(Tail);
is_numeric_digits(<<Char, Tail/binary>>) when Char =:= $. ->
is_numeric_decimals(Tail, first);
is_numeric_digits(<<_Char, _Tail/binary>>) ->
false;
is_numeric_digits(<<>>) ->
true.
is_numeric_decimals(<<Char, Tail/binary>>, _Stage) when (Char >= $0 andalso Char =< $9) ->
is_numeric_decimals(Tail, second);
is_numeric_decimals(<<>>, second) ->
true;
is_numeric_decimals(_Str, _Stage) ->
false.
-spec is_x(Str::binary(), Fun::fun((char()) -> boolean())) -> boolean().
is_x ( < < > > , _ Fun , _ Offset ) - >
case of
< < _ Head : Offset / binary , , _ Tail / binary > > - >
case ) of
is_x(Str , Fun , Offset + 1 ) ;
is_x(<<Char, Tail/binary>>, Fun) ->
case Fun(Char) of
true ->
is_x(Tail, Fun);
false ->
false
end;
is_x(<<>>, _Fun) ->
true.
-spec insert(binary(), pos_integer(), binary()) -> binary().
insert(Str, Pos, Str1) when is_binary(Str), is_integer(Pos) ->
N = Pos - 1,
case Str of
<<Head:N/binary, Tail/binary>> ->
<<Head/binary, Str1/binary, Tail/binary>>;
_ ->
erlang:error(badarg)
end.
-spec duplicate(char() | binary(), Count :: non_neg_integer()) -> binary().
duplicate(Char, Count) when is_integer(Char) ->
duplicate_char(Char, Count, <<>>);
duplicate(Str, Count) ->
duplicate_bin(Str, Count, <<>>).
duplicate_char(Char, Count, Acc) when Count > 0 ->
duplicate_char(Char, Count - 1, <<Acc/binary, Char>>);
duplicate_char(_Char, _Len, Acc) ->
Acc.
duplicate_bin(Str, Count, Acc) when Count > 0 ->
duplicate_bin(Str, Count - 1, <<Acc/binary, Str/binary>>);
duplicate_bin(_Str, _Len, Acc) ->
Acc.
-spec substr(binary(), integer()) -> binary().
substr(Str, 1) ->
Str;
substr(Str, Pos) ->
N = Pos - 1,
case Str of
<<_Head:N/binary, Substr/binary>> ->
Substr;
_ ->
<<>>
end.
-spec substr(binary(), Pos::integer(), Len::integer()) -> binary().
substr(Str, 1, Len) when is_binary(Str), Len =:= size(Str) ->
Str;
substr(Str, Pos, Len) when is_binary(Str) ->
N = Pos - 1,
case Str of
<<_Head:N/binary, Substr:Len/binary, _Tail/binary>> ->
Substr;
<<_Head:N/binary, Substr/binary>> ->
Substr;
_ ->
<<>>
end.
@doc Return a substring of ' ' bytes starting from the beginning of the
-spec left(binary(), integer()) -> binary().
left(Str, Len) when Len >= size(Str) ->
Str;
left(Str, Len) when Len >= 0 ->
<<Left:Len/binary, _Tail/binary>> = Str,
Left.
@doc Return a substring of ' ' bytes starting from the end of the string .
-spec right(binary(), integer()) -> binary().
right(Str, Len) when Len >= size(Str) ->
Str;
right(Str, Len) when Len >= 0 ->
Offset = size(Str) - Len,
<<_Head:Offset/binary, Right/binary>> = Str,
Right.
@doc Return a string of ' ' bytes padded with spaces to the left and to the right .
-spec pad(binary(), non_neg_integer()) -> binary().
pad(Str, Len) when Len >= 0 ->
pad(Str, Len, $\s).
@doc Return a string of ' ' bytes padded with ' ' to the left and to the right .
-spec pad(binary(), non_neg_integer(), char()) -> binary().
pad(Str, Len, Char) when Len >= 0, is_integer(Char) ->
PadLen = Len - size(Str),
if
PadLen > 0 ->
LeftPadLen = PadLen div 2,
RightPadLen = PadLen - LeftPadLen,
Padding = duplicate(Char, LeftPadLen),
if
RightPadLen > 0 ->
if
LeftPadLen =:= RightPadLen ->
<<Padding/binary, Str/binary, Padding/binary>>;
true ->
<<Padding/binary, Str/binary, Padding/binary, Char>>
end;
true ->
<<Padding/binary, Str/binary>>
end;
true ->
Str
end.
-spec lpad(binary(), non_neg_integer()) -> binary().
lpad(Str, Len) when Len >= 0 ->
lpad(Str, Len, $\s).
@doc Return a string of ' Len ' bytes left - padded with ' ' .
-spec lpad(binary(), non_neg_integer(), char()) -> binary().
lpad(Str, Len, Char) when Len >= 0, is_integer(Char) ->
PadLen = Len - size(Str),
if
PadLen > 0 ->
Padding = duplicate(Char, PadLen),
<<Padding/binary, Str/binary>>;
true ->
Str
end.
@doc Return a string of ' ' bytes right - padded with spaces .
-spec rpad(binary(), non_neg_integer()) -> binary().
rpad(Str, Len) when Len >= 0 ->
rpad(Str, Len, $\s).
@doc Return a string of ' ' bytes right - padded with ' ' .
-spec rpad(binary(), non_neg_integer(), char()) -> binary().
rpad(Str, Len, Char) when Len >= 0, is_integer(Char) ->
PadLen = Len - size(Str),
if
PadLen > 0 ->
Padding = duplicate(Char, PadLen),
<<Str/binary, Padding/binary>>;
true ->
Str
end.
-spec strip(binary()) -> binary().
strip(Str) ->
strip(Str, <<"\s\t\n\r\f\v">>).
-spec strip(binary(), char() | binary()) -> binary().
strip(Str, Char) ->
rstrip(lstrip(Str, Char), Char).
-spec lstrip(binary()) -> binary().
lstrip(Str) ->
lstrip(Str, <<"\s\t\n\r\f\v">>).
-spec lstrip(binary(), char() | binary()) -> binary().
lstrip(Str, Char) when is_integer(Char) ->
lstrip_char(Str, Char);
lstrip(Str, Chars) when is_binary(Chars) ->
lstrip_bin(Str, Chars).
lstrip_char(<<Char, Tail/binary>>, Char) ->
lstrip_char(Tail, Char);
lstrip_char(Str, _Char) ->
Str.
lstrip_bin(<<Char, Tail/binary>> = Str, Chars) ->
case member(Chars, Char) of
true ->
lstrip_bin(Tail, Chars);
_ ->
Str
end;
lstrip_bin(Str, _Chars) ->
Str.
-spec rstrip(binary()) -> binary().
rstrip(Str) ->
rstrip(Str, <<"\s\t\n\r\f\v">>).
-spec rstrip(binary(), char() | binary()) -> binary().
rstrip(Str, Char) when is_integer(Char) ->
rstrip_char(Str, Char, size(Str) - 1);
rstrip(Str, Chars) ->
rstrip_bin(Str, Chars, size(Str) - 1).
rstrip_char(Str, Char, Pos) ->
case Str of
<<Head:Pos/binary, Char>> ->
rstrip_char(Head, Char, Pos - 1);
_ ->
Str
end.
rstrip_bin(Str, Chars, Pos) ->
case Str of
<<Head:Pos/binary, Char>> ->
case member(Chars, Char) of
true ->
rstrip_bin(Head, Chars, Pos - 1);
_ ->
Str
end;
_ ->
Str
end.
@doc Remove all the newlines ( \r and ) present at the end of the string .
-spec chomp(binary()) -> binary().
chomp(Str) ->
Pos = size(Str) - 1,
case Str of
<<Head:Pos/binary, Char>> when Char =:= $\r; Char =:= $\n ->
chomp(Head);
_ ->
Str
end.
-spec split(binary(), Sep::char() | binary()) -> list(binary()).
split(<<>>, _Sep) ->
[];
split(Str, Sep) when is_integer(Sep) ->
lists:reverse(split_char_sep(Str, <<>>, Sep, []));
split(Str, Sep) ->
Tokens =
case Sep of
<<Char>> ->
split_char_sep(Str, <<>>, Char, []);
_ ->
split_str_sep(Str, <<>>, Sep, [])
end,
lists:reverse(Tokens).
-spec split_char_sep(binary(), binary(), char(), [binary()]) -> [binary()].
split_char_sep(<<Sep, Tail/binary>>, TokenAcc, Sep, Tokens) ->
split_char_sep(Tail, <<>>, Sep, [TokenAcc | Tokens]);
split_char_sep(<<Char, Tail/binary>>, TokenAcc, Sep, Tokens) ->
split_char_sep(Tail, <<TokenAcc/binary, Char>>, Sep, Tokens);
split_char_sep(<<>>, TokenAcc, _Sep, Tokens) ->
[TokenAcc | Tokens].
-spec split_str_sep(binary(), binary(), binary(), [binary()]) -> [binary(),...].
split_str_sep(<<Char, Tail/binary>>, TokenAcc, Sep, Tokens) ->
case member(Sep, Char) of
true ->
split_str_sep(Tail, <<>>, Sep, [TokenAcc | Tokens]);
false ->
split_str_sep(Tail, <<TokenAcc/binary, Char>>, Sep, Tokens)
end;
split_str_sep(<<>>, TokenAcc, _Sep, Tokens) ->
[TokenAcc | Tokens].
@doc Join a a list of strings into one string .
-spec join([binary()]) -> binary().
join_list([Head|Tail ] , Acc ) - >
Acc .
join(List) when is_list(List) ->
list_to_binary(join_list(List, [])).
join_list([Head | Tail], Acc) when is_atom(Head) ->
join_list(Tail, [atom_to_list(Head) | Acc]);
join_list([Head | Tail], Acc) when is_list(Head) ->
join_list(Tail, [join_list(Head, []) | Acc]);
join_list([Head | Tail], Acc) ->
join_list(Tail, [Head | Acc]);
join_list([], Acc) ->
lists:reverse(Acc).
@doc Join a a list of strings into one string , adding a separator between
-spec join([binary()], Sep::char() | binary()) -> binary().
join(List, Sep) when is_list(List) ->
list_to_binary(join_list_sep(List, Sep)).
-spec join_list_sep([any()], char() | binary()) -> [any()].
join_list_sep([Head | Tail], Sep) when is_atom(Head) ->
join_list_sep(Tail, Sep, [atom_to_list(Head)]);
join_list_sep([Head | Tail], Sep) when is_list(Head) ->
join_list_sep(Tail, Sep, [join_list(Head, [])]);
join_list_sep([Head | Tail], Sep) ->
join_list_sep(Tail, Sep, [Head]);
join_list_sep([], _Sep) ->
[].
join_list_sep([Head | Tail], Sep, Acc) when is_atom(Head) ->
join_list_sep(Tail, Sep, [atom_to_list(Head), Sep | Acc]);
join_list_sep([Head | Tail], Sep, Acc) when is_list(Head) ->
join_list_sep(Tail, Sep, [join_list(Head, []), Sep | Acc]);
join_list_sep([Head | Tail], Sep, Acc) ->
join_list_sep(Tail, Sep, [Head, Sep | Acc]);
join_list_sep([], _Sep, Acc) ->
lists:reverse(Acc).
@doc Join a a list of strings into one string , adding a separator between
` ` bstr : join([<<"1 " > > , < < " , " > > , < < " " > > , < < " 2,3 " > > ] , $ , , $ \ ) - > < < " 1,\,,\\1,2\,3 " > > . ''
-spec join([binary()], Sep :: char() | binary(), Esc :: char()) -> binary().
join(Members, Sep, Esc) ->
EscStr =
case Esc of
$\\ ->
"\\\\";
$& ->
"\\&";
OtherEsc ->
[OtherEsc]
end,
SepStr =
case Sep of
$\\ ->
"\\\\";
$& ->
"\\&";
OtherSep ->
[OtherSep]
end,
" [ sep]|[esc ] "
Replace = EscStr ++ "&",
bstr:join(
lists:map(fun(Member) when is_atom(Member) ->
re:replace(atom_to_list(Member),
Find,
Replace,
[{return, binary}, global]);
(Member) ->
re:replace(Member,
Find,
Replace,
[{return, binary}, global])
end, Members),
Sep).
-spec lower(binary() | char()) -> binary() | char().
lower(Char) when is_integer(Char) ->
case char:is_upper(Char) of
true ->
Char - $A + $a;
false ->
Char
end;
lower(Str) ->
lower(Str, <<>>).
lower(<<Char, Tail/binary>>, Acc) ->
case char:is_upper(Char) of
true ->
Lower = Char - $A + $a,
lower(Tail, <<Acc/binary, Lower>>);
false ->
lower(Tail, <<Acc/binary, Char>>)
end;
lower(<<>>, Acc) ->
Acc.
-spec upper(binary() | char()) -> binary() | char().
upper(Char) when is_integer(Char) ->
case char:is_lower(Char) of
true ->
Char - $a + $A;
false ->
Char
end;
upper(Str) ->
upper(Str, <<>>).
upper(<<Char, Tail/binary>>, Acc) ->
case char:is_lower(Char) of
true ->
Upper = Char - $a + $A,
upper(Tail, <<Acc/binary, Upper>>);
false ->
upper(Tail, <<Acc/binary, Char>>)
end;
upper(<<>>, Acc) ->
Acc.
-spec bstr(binary() | atom() | list() | char()) -> binary().
bstr(Bin) when is_binary(Bin) ->
Bin;
bstr(Pid) when is_pid(Pid) ->
list_to_binary(pid_to_list(Pid));
bstr(Atom) when is_atom(Atom) ->
from_atom(Atom);
bstr(Integer) when is_integer(Integer), Integer > 0, Integer =< 255 ->
<<Integer>>;
bstr(Integer) when is_integer(Integer) ->
from_integer(Integer);
bstr(Float) when is_float(Float) ->
from_float(Float);
bstr(List) when is_list(List) ->
list_to_binary(List).
-spec from_atom(atom()) -> binary().
from_atom(Atom) ->
atom_to_binary(Atom, utf8).
@doc Convert a bstr containing a string to an Erlang atom .
-spec to_atom(binary()) -> atom().
to_atom(Str) ->
binary_to_atom(Str, utf8).
@doc Convert a bstr containing a string to an Erlang atom only if the atom
-spec to_existing_atom(binary()) -> atom().
to_existing_atom(Str) ->
binary_to_existing_atom(Str, utf8).
-spec from_list(list()) -> binary().
from_list(List) ->
list_to_binary(List).
@doc Convert a bstr containing a string to an Erlang list / string .
-spec to_list(binary()) -> [byte()].
to_list(Str) ->
binary_to_list(Str).
@doc Convert a bstr containing a string to an Erlang list / string .
-spec to_boolean(binary()) -> boolean().
to_boolean(<<"true">>) ->
true;
to_boolean(<<"false">>) ->
false.
@doc Convert an integer to a bstr in base 10 format .
-spec from_integer(integer()) -> binary().
from_integer(I) ->
integer_to_binary(I).
-spec from_integer(integer ( ) , 1 .. 255 ) - > binary ( ) .
from_integer(I, 10) ->
erlang:integer_to_binary(I);
from_integer(I, Base)
when erlang:is_integer(I), erlang:is_integer(Base),
Base >= 2, Base =< 1+$Z-$A+10 ->
generates wrong output values in bases other than 10 for 0 and negative
if I < 0 ->
<<$-,(from_integer1(-I, Base, <<>>))/binary>>;
true ->
from_integer1(I, Base, <<>>)
end;
from_integer(I, Base) ->
erlang:error(badarg, [I, Base]).
from_integer1(I0, Base, R0) ->
D = I0 rem Base,
I1 = I0 div Base,
R1 = if
D >= 10 -> <<(D-10+$A),R0/binary>>;
true -> <<(D+$0),R0/binary>>
end,
if
I1 =:= 0 -> R1;
true -> from_integer1(I1,Base,R1)
end.
-spec from_integer(integer(), 2..36, upper | lower) -> binary().
from_integer(I, Base, Case) when is_integer(I), is_integer(Base), Base >= 2, Base =< $Z - $A + 11 ->
BaseLetter = case Case of
upper ->
$A;
lower ->
$a
end,
list_to_binary(
if
I < 0 ->
[$- | from_integer(-I, Base, BaseLetter, [])];
true ->
from_integer(I, Base, BaseLetter, [])
end
);
from_integer(I, Base, Case) ->
erlang:error(badarg, [I, Base, Case]).
-spec from_integer(integer(), pos_integer(), 65 | 97, [integer()]) -> [integer(),...].
from_integer(I0, Base, BaseLetter, Acc) ->
I1 = I0 div Base,
Digit = I0 rem Base,
Acc1 = [
if
(Digit >= 10) ->
Digit - 10 + BaseLetter;
true ->
Digit + $0
end | Acc
],
if
I1 =:= 0 ->
Acc1;
true ->
from_integer(I1, Base, BaseLetter, Acc1)
end.
-spec to_integer(binary()) -> integer().
to_integer(Str) ->
binary_to_integer(Str).
between 2 and 32 .
Optimized version for base 10
-spec to_integer(binary(), 1..255) -> integer().
to_integer(Str, Base) ->
binary_to_integer(Str, Base).
-spec from_float(float()) -> binary().
from_float(Float) ->
float_to_binary(Float, [{decimals, 10}, compact]).
-spec to_float(binary()) -> float().
to_float(Str) ->
binary_to_float(Str).
-spec from_number(integer() | float()) -> binary().
from_number(Number) when is_float(Number) ->
float_to_binary(Number, [{decimals, 10}, compact]);
from_number(Number) ->
integer_to_binary(Number).
-spec to_number(binary()) -> integer() | float().
to_number(Str) ->
case member(Str, $.) of
true -> binary_to_float(Str);
false -> binary_to_integer(Str)
end.
@doc Get the first text line from a binary string . It returns a tuple with
the first text line as the first element and the rest of the string as
-spec get_line(binary()) -> {binary(), binary()}.
get_line(Str) ->
get_line(Str, <<>>).
get_line(<<$\n, Tail/binary>>, Acc) ->
{Acc, Tail};
get_line(<<$\r, $\n, Tail/binary>>, Acc) ->
{Acc, Tail};
get_line(<<Char, Tail/binary>>, Acc) ->
get_line(Tail, <<Acc/binary, Char>>);
get_line(<<>>, Acc) ->
{Acc, <<>>}.
-spec urlencode(binary()) -> binary().
urlencode(Str) ->
urlencode(Str, <<>>).
urlencode(<<Char, Tail/binary>>, Acc) ->
urlencode(Tail,
case is_urlencoded(Char) of
true ->
Hi = integer_to_hex_char((Char band 16#f0) bsr 4),
Lo = integer_to_hex_char((Char band 16#0f)),
, Hi , > > ;
false ->
<<Acc/binary, Char>>
end
);
urlencode(<<>>, Acc) ->
Acc.
is_urlencoded(Char) ->
not (((Char >= $0) andalso (Char =< $9)) orelse
((Char >= $A) andalso (Char =< $Z)) orelse
((Char >= $a) andalso (Char =< $z)) orelse
(Char =:= $-) orelse (Char =:= $_) orelse
(Char =:= $.) orelse (Char =:= $~)).
-spec integer_to_hex_char(char()) -> char().
integer_to_hex_char(N) when N >= 0 ->
if
N =< 9 ->
$0 + N;
N =< 15 ->
$A - 10 + N;
true ->
erlang:error(badarg)
end.
-spec integer_to_hex_char(char(), lower | upper) -> char().
integer_to_hex_char(N, lower) when N >= 0 ->
if
N =< 9 ->
$0 + N;
N =< 15 ->
$a - 10 + N;
true ->
erlang:error(badarg)
end;
integer_to_hex_char(N, upper) ->
integer_to_hex_char(N).
-spec urldecode(binary()) -> binary().
urldecode(Str) ->
urldecode(Str, <<>>).
, Hi , , Tail / binary > > , Acc ) - >
Char = ((hex_char_to_integer(Hi) bsl 4) bor hex_char_to_integer(Lo)),
urldecode(Tail, <<Acc/binary, Char>>);
erlang:error(badarg);
urldecode(<<Char, Tail/binary>>, Acc) ->
urldecode(Tail, <<Acc/binary, Char>>);
urldecode(<<>>, Acc) ->
Acc.
-spec hex_char_to_integer(char()) -> char().
hex_char_to_integer(Char) ->
if
(Char >= $0) and (Char =< $9) ->
Char - $0;
(Char >= $A) and (Char =< $F) ->
Char - $A + 10;
(Char >= $a) and (Char =< $f) ->
Char - $a + 10;
true ->
erlang:error(badarg)
end.
@doc Encode a bstr using the XML - encoding scheme .
WARNING : This function assumes that the input is a valid UTF-8 string
00h-1Fh . Bytes that are not part of a valid UTF-8 character
-spec xmlencode(binary()) -> binary().
xmlencode(Str) ->
xmlencode(Str, <<>>).
xmlencode(<<Char, Tail/binary>>, Acc) ->
xmlencode(Tail,
case is_xmlencoded(Char) of
true ->
Encoded = xmlencode_char(Char),
<<Acc/binary, $&, Encoded/binary, $;>>;
false ->
<<Acc/binary, Char>>
end
);
xmlencode(<<>>, Acc) ->
Acc.
is_xmlencoded(Char) ->
(Char < 32) orelse (Char =:= 192) orelse (Char =:= 193) orelse (Char > 244)
orelse (Char =:= $&) orelse (Char =:= $<) orelse (Char =:= $>)
orelse (Char =:= $') orelse (Char =:= $").
Encode a single character using the XML encoding scheme to create a
xmlencode_char($&) ->
<<"amp">>;
xmlencode_char($<) ->
<<"lt">>;
xmlencode_char($>) ->
<<"gt">>;
xmlencode_char($') ->
<<"apos">>;
xmlencode_char($") ->
<<"quot">>;
xmlencode_char(Char) when Char < 32 ->
Hi = integer_to_hex_char((Char band 16#f0) bsr 4),
Lo = integer_to_hex_char((Char band 16#0f)),
<<"#x", Hi, Lo>>;
xmlencode_char(Char) ->
Char.
@doc Decode a bstr using the XML - encoding scheme to resolve any character
-spec xmldecode(binary()) -> binary().
xmldecode(Str) ->
xmldecode(Str, <<>>).
xmldecode(<<"&", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $&>>);
xmldecode(<<"<", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $<>>);
xmldecode(<<">", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $>>>);
xmldecode(<<"'", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $'>>);
xmldecode(<<""", Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, $">>);
xmldecode(<<"&#x", Hi, Lo, $;, Tail/binary>>, Acc) ->
Char = (hex_char_to_integer(Hi) bsl 4) bor hex_char_to_integer(Lo),
xmldecode(Tail, <<Acc/binary, Char>>);
xmldecode(<<Char, Tail/binary>>, Acc) ->
xmldecode(Tail, <<Acc/binary, Char>>);
xmldecode(<<>>, Acc) ->
Acc.
-spec hexencode(binary()) -> binary().
hexencode(Str) ->
hexencode(Str, <<>>).
hexencode(<<Hi:4, Lo:4, Tail/binary>>, Acc) ->
HiChar = integer_to_hex_char(Hi, lower),
LoChar = integer_to_hex_char(Lo, lower),
hexencode(Tail, <<Acc/binary, HiChar, LoChar>>);
hexencode(<<>>, Acc) ->
Acc.
-spec hexdecode(binary()) -> binary().
hexdecode(Str) ->
hexdecode(Str, <<>>).
hexdecode(<<Hi, Lo, Tail/binary>>, Acc) ->
Char = ((hex_char_to_integer(Hi) bsl 4) bor hex_char_to_integer(Lo)),
hexdecode(Tail, <<Acc/binary, Char>>);
hexdecode(<<_Char>>, _Acc) ->
erlang:error(badarg);
hexdecode(<<>>, Acc) ->
Acc.
|
39822788439c2de68a4c7e1f3d875ee104b6a7adb3a2949dd42c456a5cf4f2c8 | bcc32/projecteuler-ocaml | test_digits.ml | open! Core
open! Import
let%test_unit "basic round tripping" =
let check_round_trip (n, digits) =
[%test_result: int] ~expect:n (Number_theory.Int.As_base10.of_list digits);
[%test_result: int list] ~expect:digits (Number_theory.Int.As_base10.to_list n)
in
let digits_through_string n =
n |> Int.to_string |> String.to_list |> List.map ~f:Char.get_digit_exn
in
let gen =
let open Quickcheck.Let_syntax in
let%map_open n = small_non_negative_int in
n, digits_through_string n
in
Q.test
gen
~examples:
[ 0, [ 0 ]; 1, [ 1 ]; 10, [ 1; 0 ]; 123, [ 1; 2; 3 ]; 54312, [ 5; 4; 3; 1; 2 ] ]
~f:check_round_trip
;;
module type Test_arg = sig
type t = int * int list [@@deriving sexp_of]
(** [quickcheck_generator] should generate pairs of [(int, digits)] where
[digits] corresponds to the digits of [int] in the order specified by
[M]. *)
val quickcheck_generator : t Quickcheck.Generator.t
end
module Test_container
(M : Number_theory.As_digits_one_direction with type integer := int)
(T : Test_arg) : Number_theory.As_digits_one_direction with type integer := int
This signature helps ensure that we test all of the Container interface .
open M
let base = base
let fold = fold
let%test_unit "fold" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
let init = [] in
let f acc d = d :: acc in
[%test_result: int list] ~expect:(List.fold digits ~init ~f) (fold int ~init ~f))
;;
let iter = iter
let%test_unit "iter" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
let list =
let result = ref [] in
List.iter digits ~f:(fun d -> result := d :: !result);
!result
in
let as_digits =
let result = ref [] in
iter int ~f:(fun d -> result := d :: !result);
!result
in
[%test_result: int list] ~expect:list as_digits)
;;
let length = length
let%test_unit "length" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
[%test_result: int] ~expect:(List.length digits) (length int))
;;
let to_list = to_list
let to_sequence = to_sequence
let to_array = to_array
let%test_unit "to_list/to_sequence/to_array" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
[%test_result: int list] ~expect:digits (to_list int);
[%test_result: int Sequence.t] ~expect:(Sequence.of_list digits) (to_sequence int);
[%test_result: int array] ~expect:(Array.of_list digits) (to_array int))
;;
let of_list = of_list
let of_sequence = of_sequence
let of_array = of_array
let%test_unit "of_list/of_sequence/of_array" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
[%test_result: int] ~expect:int (of_list digits);
[%test_result: int] ~expect:int (of_sequence (Sequence.of_list digits));
[%test_result: int] ~expect:int (of_array (Array.of_list digits)))
;;
let append = append
let%test_unit "append" =
Quickcheck.test
[%quickcheck.generator: T.t * T.t]
~sexp_of:[%sexp_of: T.t * T.t]
~f:(fun ((int1, digits1), (int2, digits2)) ->
[%test_result: int] ~expect:(of_list (digits1 @ digits2)) (append int1 int2))
;;
(* Don't bother testing functions that are produced by the functor. They are
probably correct. *)
let mem = mem
let is_empty = is_empty
let fold_result = fold_result
let fold_until = fold_until
let exists = exists
let for_all = for_all
let count = count
let sum = sum
let find = find
let find_map = find_map
let to_array = to_array
let min_elt = min_elt
let max_elt = max_elt
end
module Test_left_to_right = struct
type t = int * int list [@@deriving sexp_of]
let quickcheck_generator =
let open Quickcheck.Let_syntax in
let%map_open n = small_non_negative_int in
let digits = Int.to_string n |> String.to_list |> List.map ~f:Char.get_digit_exn in
n, digits
;;
end
module Test_right_to_left = struct
include Test_left_to_right
let quickcheck_generator =
let open Quickcheck.Let_syntax in
let%map n, digits = quickcheck_generator in
n, List.rev digits
;;
end
let%test_module "left-to-right" =
(module Test_container (Number_theory.Int.As_base10.Left_to_right) (Test_left_to_right))
;;
let%test_module "right-to-left" =
(module Test_container (Number_theory.Int.As_base10.Right_to_left) (Test_right_to_left))
;;
let%test_module "non-directional" =
(module struct
* Testing functions that are n't part of the As_digits_one_direction
signature .
signature. *)
let%test_unit "rev" =
Quickcheck.test
Quickcheck.Generator.small_non_negative_int
~sexp_of:[%sexp_of: int]
~examples:[ 0; 1; 10; 12; 123 ]
~f:(fun n ->
[%test_result: int]
~expect:(n |> Int.to_string |> String.rev |> Int.of_string)
(Number_theory.Int.As_base10.rev n))
;;
end)
;;
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/test/test_digits.ml | ocaml | * [quickcheck_generator] should generate pairs of [(int, digits)] where
[digits] corresponds to the digits of [int] in the order specified by
[M].
Don't bother testing functions that are produced by the functor. They are
probably correct. | open! Core
open! Import
let%test_unit "basic round tripping" =
let check_round_trip (n, digits) =
[%test_result: int] ~expect:n (Number_theory.Int.As_base10.of_list digits);
[%test_result: int list] ~expect:digits (Number_theory.Int.As_base10.to_list n)
in
let digits_through_string n =
n |> Int.to_string |> String.to_list |> List.map ~f:Char.get_digit_exn
in
let gen =
let open Quickcheck.Let_syntax in
let%map_open n = small_non_negative_int in
n, digits_through_string n
in
Q.test
gen
~examples:
[ 0, [ 0 ]; 1, [ 1 ]; 10, [ 1; 0 ]; 123, [ 1; 2; 3 ]; 54312, [ 5; 4; 3; 1; 2 ] ]
~f:check_round_trip
;;
module type Test_arg = sig
type t = int * int list [@@deriving sexp_of]
val quickcheck_generator : t Quickcheck.Generator.t
end
module Test_container
(M : Number_theory.As_digits_one_direction with type integer := int)
(T : Test_arg) : Number_theory.As_digits_one_direction with type integer := int
This signature helps ensure that we test all of the Container interface .
open M
let base = base
let fold = fold
let%test_unit "fold" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
let init = [] in
let f acc d = d :: acc in
[%test_result: int list] ~expect:(List.fold digits ~init ~f) (fold int ~init ~f))
;;
let iter = iter
let%test_unit "iter" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
let list =
let result = ref [] in
List.iter digits ~f:(fun d -> result := d :: !result);
!result
in
let as_digits =
let result = ref [] in
iter int ~f:(fun d -> result := d :: !result);
!result
in
[%test_result: int list] ~expect:list as_digits)
;;
let length = length
let%test_unit "length" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
[%test_result: int] ~expect:(List.length digits) (length int))
;;
let to_list = to_list
let to_sequence = to_sequence
let to_array = to_array
let%test_unit "to_list/to_sequence/to_array" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
[%test_result: int list] ~expect:digits (to_list int);
[%test_result: int Sequence.t] ~expect:(Sequence.of_list digits) (to_sequence int);
[%test_result: int array] ~expect:(Array.of_list digits) (to_array int))
;;
let of_list = of_list
let of_sequence = of_sequence
let of_array = of_array
let%test_unit "of_list/of_sequence/of_array" =
Quickcheck.test
[%quickcheck.generator: T.t]
~sexp_of:[%sexp_of: T.t]
~f:(fun (int, digits) ->
[%test_result: int] ~expect:int (of_list digits);
[%test_result: int] ~expect:int (of_sequence (Sequence.of_list digits));
[%test_result: int] ~expect:int (of_array (Array.of_list digits)))
;;
let append = append
let%test_unit "append" =
Quickcheck.test
[%quickcheck.generator: T.t * T.t]
~sexp_of:[%sexp_of: T.t * T.t]
~f:(fun ((int1, digits1), (int2, digits2)) ->
[%test_result: int] ~expect:(of_list (digits1 @ digits2)) (append int1 int2))
;;
let mem = mem
let is_empty = is_empty
let fold_result = fold_result
let fold_until = fold_until
let exists = exists
let for_all = for_all
let count = count
let sum = sum
let find = find
let find_map = find_map
let to_array = to_array
let min_elt = min_elt
let max_elt = max_elt
end
module Test_left_to_right = struct
type t = int * int list [@@deriving sexp_of]
let quickcheck_generator =
let open Quickcheck.Let_syntax in
let%map_open n = small_non_negative_int in
let digits = Int.to_string n |> String.to_list |> List.map ~f:Char.get_digit_exn in
n, digits
;;
end
module Test_right_to_left = struct
include Test_left_to_right
let quickcheck_generator =
let open Quickcheck.Let_syntax in
let%map n, digits = quickcheck_generator in
n, List.rev digits
;;
end
let%test_module "left-to-right" =
(module Test_container (Number_theory.Int.As_base10.Left_to_right) (Test_left_to_right))
;;
let%test_module "right-to-left" =
(module Test_container (Number_theory.Int.As_base10.Right_to_left) (Test_right_to_left))
;;
let%test_module "non-directional" =
(module struct
* Testing functions that are n't part of the As_digits_one_direction
signature .
signature. *)
let%test_unit "rev" =
Quickcheck.test
Quickcheck.Generator.small_non_negative_int
~sexp_of:[%sexp_of: int]
~examples:[ 0; 1; 10; 12; 123 ]
~f:(fun n ->
[%test_result: int]
~expect:(n |> Int.to_string |> String.rev |> Int.of_string)
(Number_theory.Int.As_base10.rev n))
;;
end)
;;
|
38b6bb51299c8869a4474490ad9504af92aae15d40ae3260dc5343adf7816e19 | DrTom/clj-pg-types | arrays_test.clj | (ns pg-types.arrays-test
(:require
[pg-types.connection :refer :all]
[pg-types.all]
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[java-time]))
(def db-spec (env-db-spec))
(deftest arrays
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test
(iarray integer[], tarray text[])")
(testing "result of inserting "
(let [result (->> {:iarray [1 2 3]
:tarray ["Foo" "Bar" "Baz"]}
(jdbc/insert! tx :test ) first)]
(testing "vector of integers is equal to input"
(is (= (:iarray result) [1 2 3])))
(testing "vector of strings is equal to input"
(is (= (:tarray result) ["Foo" "Bar" "Baz"])))))))
(deftest lazy-seqs
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test (iarray integer[])")
(testing "result of inserting "
(let [result (->> {:iarray (map identity [1 2 3])}
(jdbc/insert! tx :test) first)]
(testing "equal to input"
(is (= (:iarray result) [1 2 3])))))))
(deftest array-of-timestamps
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test
(tarray timestamp WITH TIME ZONE[])")
(let [timestamp (-> (java-time/instant)
java-time/instant->sql-timestamp)]
(testing "result of inserting and array of timestamps"
(let [result (->> {:tarray [timestamp]}
(jdbc/insert! tx :test) first)]
(testing "is equal to input"
(is (= (:tarray result) [timestamp]))))))))
| null | https://raw.githubusercontent.com/DrTom/clj-pg-types/d847735c46b2da173fd50a6ebe492bead0d75dd5/test/pg_types/arrays_test.clj | clojure | (ns pg-types.arrays-test
(:require
[pg-types.connection :refer :all]
[pg-types.all]
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[java-time]))
(def db-spec (env-db-spec))
(deftest arrays
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test
(iarray integer[], tarray text[])")
(testing "result of inserting "
(let [result (->> {:iarray [1 2 3]
:tarray ["Foo" "Bar" "Baz"]}
(jdbc/insert! tx :test ) first)]
(testing "vector of integers is equal to input"
(is (= (:iarray result) [1 2 3])))
(testing "vector of strings is equal to input"
(is (= (:tarray result) ["Foo" "Bar" "Baz"])))))))
(deftest lazy-seqs
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test (iarray integer[])")
(testing "result of inserting "
(let [result (->> {:iarray (map identity [1 2 3])}
(jdbc/insert! tx :test) first)]
(testing "equal to input"
(is (= (:iarray result) [1 2 3])))))))
(deftest array-of-timestamps
(jdbc/with-db-transaction [tx db-spec]
(jdbc/db-do-commands tx "CREATE TEMP TABLE test
(tarray timestamp WITH TIME ZONE[])")
(let [timestamp (-> (java-time/instant)
java-time/instant->sql-timestamp)]
(testing "result of inserting and array of timestamps"
(let [result (->> {:tarray [timestamp]}
(jdbc/insert! tx :test) first)]
(testing "is equal to input"
(is (= (:tarray result) [timestamp]))))))))
|
|
1827811879dbefaf262c13beb5a35d5d062c23c81fc37432c4e4d20d64fa8d8c | gadfly361/reagent-figwheel | bundle.cljs | (ns {{ns-name}}.pages.bundle
(:require
[bide.core :as bide]
[{{ns-name}}.models.app.navigation.model :as nav-model]
[{{ns-name}}.pages.home.bundle :as home]
[{{ns-name}}.pages.about.bundle :as about]
[{{ns-name}}.pages.not-found.bundle :as not-found]
))
(def bundles
{:home home/main
:about about/main
:not-found not-found/main})
(def default-bundle
{:page (fn [] [:div ])
:route (fn [] )})
(defn get-bundle [page-key k]
(let [bundle (get bundles
page-key
default-bundle)]
(bundle k)))
| null | https://raw.githubusercontent.com/gadfly361/reagent-figwheel/4c40657b31a2b358be5697add2e96e8cac6f8535/src/leiningen/new/reagent_figwheel/gadfly/src/app/pages/bundle.cljs | clojure | (ns {{ns-name}}.pages.bundle
(:require
[bide.core :as bide]
[{{ns-name}}.models.app.navigation.model :as nav-model]
[{{ns-name}}.pages.home.bundle :as home]
[{{ns-name}}.pages.about.bundle :as about]
[{{ns-name}}.pages.not-found.bundle :as not-found]
))
(def bundles
{:home home/main
:about about/main
:not-found not-found/main})
(def default-bundle
{:page (fn [] [:div ])
:route (fn [] )})
(defn get-bundle [page-key k]
(let [bundle (get bundles
page-key
default-bundle)]
(bundle k)))
|
|
6d822c486adc97c42254449729187beca802ea651969f2e7294450cc8ba00354 | rmculpepper/crypto | main.rkt | Copyright 2020
SPDX - License - Identifier : Apache-2.0
#lang racket/base
(require racket/contract/base
racket/lazy-require
"private/interfaces.rkt"
"private/cert.rkt"
"private/store.rkt")
(lazy-require ["private/revocation.rkt"
(make-revocation-checker)])
(provide certificate<%>
certificate-chain<%>
certificate-store<%>
certificate?
certificate-chain?
certificate-store?
revocation-checker<%>
(struct-out exn:x509)
(struct-out exn:x509:certificate)
(struct-out exn:x509:chain)
x509-key-usage/c
x509-general-name-tag/c
(contract-out
[bytes->certificate
(-> bytes? certificate?)]
[read-pem-certificates
(->* [input-port?]
[#:count (or/c exact-nonnegative-integer? +inf.0)
#:allow-aux? boolean?]
(listof (or/c certificate? certificate+aux?)))]
[pem-file->certificates
(->* [path-string?]
[#:count (or/c exact-nonnegative-integer? +inf.0)
#:allow-aux? boolean?]
(listof (or/c certificate? certificate+aux?)))]
[make-revocation-checker
(->* [(or/c path-string? 'memory 'temporary)]
[#:trust-db? boolean?
#:fetch-ocsp? boolean?
#:fetch-crl? boolean?]
any)])
empty-store
default-store)
| null | https://raw.githubusercontent.com/rmculpepper/crypto/75138461a74d6b4bc26c65e981ccfba6b60719de/x509-lib/main.rkt | racket | Copyright 2020
SPDX - License - Identifier : Apache-2.0
#lang racket/base
(require racket/contract/base
racket/lazy-require
"private/interfaces.rkt"
"private/cert.rkt"
"private/store.rkt")
(lazy-require ["private/revocation.rkt"
(make-revocation-checker)])
(provide certificate<%>
certificate-chain<%>
certificate-store<%>
certificate?
certificate-chain?
certificate-store?
revocation-checker<%>
(struct-out exn:x509)
(struct-out exn:x509:certificate)
(struct-out exn:x509:chain)
x509-key-usage/c
x509-general-name-tag/c
(contract-out
[bytes->certificate
(-> bytes? certificate?)]
[read-pem-certificates
(->* [input-port?]
[#:count (or/c exact-nonnegative-integer? +inf.0)
#:allow-aux? boolean?]
(listof (or/c certificate? certificate+aux?)))]
[pem-file->certificates
(->* [path-string?]
[#:count (or/c exact-nonnegative-integer? +inf.0)
#:allow-aux? boolean?]
(listof (or/c certificate? certificate+aux?)))]
[make-revocation-checker
(->* [(or/c path-string? 'memory 'temporary)]
[#:trust-db? boolean?
#:fetch-ocsp? boolean?
#:fetch-crl? boolean?]
any)])
empty-store
default-store)
|
|
db5aac9bdc0832bd83e7f90bc9db26e9872196f84746898753ca6c5b3e50b010 | TempusMUD/cl-tempus | editor.lisp | (in-package #:tempus)
(defclass editor ()
((target :accessor target-of :initarg :target)
(target-desc :accessor target-desc-of :initarg :target-desc)
(old-buffer :accessor old-buffer-of :initarg :old-buffer)
(buffer :accessor buffer-of :initarg :buffer :initform '())
(state :accessor state-of :initform 'active)))
(defclass text-editor (editor)
((finalizer :accessor finalizer-of :initarg :finalizer)
(cancel-func :accessor cancel-func-of :initarg :cancel-func)))
(defclass mail-editor (editor)
((recipients :accessor recipients-of :initarg :recipients :initform nil)
(attachments :accessor attachments-of :initarg :attachments :initform nil)))
(defclass board-editor (editor)
((idnum :accessor idnum-of :initarg :idnum)
(board-name :accessor board-name-of :initarg :board-name)
(subject :accessor subject-of :initarg :subject)))
(defclass poll-editor (editor)
((header :accessor header-of :initarg :header)))
(defclass file-editor (editor)
((path :accessor path-of :initarg :path)
(loadedp :accessor loadedp :initarg :loadedp)))
(defun send-line-number (cxn num)
"Send the given line number to the actor."
(cxn-write cxn "&n~3d&b] &n" num))
(defun send-editor-header (cxn)
(cxn-write cxn "&C *&Y TUNED &B] ~
&nTerminate with @ on a new line. ~
&&H for help&C *&n~% &C0")
(dotimes (idx 7)
(cxn-write cxn "&B---------&C~d" (1+ idx)))
(cxn-write cxn "&n~%"))
(defmethod refresh-screen ((editor editor) cxn &optional (start-line 0) count)
"Sends the contents of the buffer to the screen"
(loop for line in (nthcdr start-line (buffer-of editor))
as line-num from 1
while (or (null count) (<= line-num (+ start-line count)))
do
(send-line-number cxn line-num)
(cxn-write cxn "~a~%" line)))
(defmethod editor-command ((editor editor) cxn cmd arg)
"Handles all the commands that the editor is capable of."
(case cmd
(#\h
(cxn-write cxn"~
&C *&B------------------------ &YH E L P &B------------------------&C*
&YS - &nSubstitute &YF - &nFind
&YE - &nSave && Exit &YQ - &nQuit (Cancel)
&YL - &nReplace Line &YD - &nDelete Line
&YI - &nInsert Line &YR - &nRefresh Screen
&YC - &nClear Buffer &YU - &nUndo Changes
&C *&B---------------------------------------------------------&C*
"))
(#\c
(setf (buffer-of editor) nil))
((#\l #\i #\d)
(with-words arg (param &rest new-line)
(cond
((or (null param) (notevery #'digit-char-p param))
(cxn-write cxn "You must specify a numeric line number.~%"))
(t
(let ((line-num (parse-integer param)))
(cond
((> line-num (length (buffer-of editor)))
(cxn-write cxn
"There are only ~d lines of text!~%"
(length (buffer-of editor))))
(t
(case cmd
(#\l
(setf (nth (1- line-num) (buffer-of editor)) new-line)
(cxn-write cxn "Line ~d replaced.~%" line-num))
(#\i
(setf (buffer-of editor)
(nconc (subseq (buffer-of editor) 0 (1- line-num))
(list new-line)
(subseq (buffer-of editor) (1- line-num))))
(cxn-write cxn
"New line inserted before line ~d.~%"
line-num))
(#\d
(setf (buffer-of editor)
(nconc (subseq (buffer-of editor) 0 (1- line-num))
(subseq (buffer-of editor) line-num)))
(cxn-write cxn "Line ~d deleted.~%" line-num))))))))))
(#\r
(refresh-screen editor cxn))
(#\u
(setf (buffer-of editor) (cl-ppcre:split "\\s+" (old-buffer-of editor)))
(refresh-screen editor cxn)
(cxn-write cxn "Reverted back to previous.~%"))
(#\e
(setf (state-of editor) 'finishing))
(#\q
(setf (state-of editor) 'aborting))
(#\s
(let* ((matching-delims "()[]<>{}")
(start-delim (find #\space arg :test-not #'char=))
(end-delim-pos (position start-delim matching-delims))
(end-delim (if end-delim-pos
(char matching-delims (1+ end-delim-pos))
start-delim))
(start1 (position start-delim arg))
(end1 (and start1 (position end-delim arg :start (1+ start1))))
(start2 (and end1 (position start-delim arg :start end1)))
(end2 (and start2 (position end-delim arg :start (1+ start2)))))
(cond
((= (1+ start1) end1)
(cxn-write cxn "You can't replace a zero-length search pattern.~%"))
((and start1 end1 start2 end2)
(let ((search-str (subseq arg (1+ start1) end1))
(replace-str (subseq arg (1+ start2) end2)))
(setf (buffer-of editor)
(loop for old-line in (buffer-of editor)
collect (string-replace search-str old-line replace-str)))
(cxn-write cxn
"All instances of [~a] have been replaced with [~a].~%"
search-str
replace-str)))
(t
(cxn-write cxn "The subsitution could not be made.~%")))))
(#\f
(loop for line in (buffer-of editor)
as linenum from 1
when (search arg line)
do
(send-line-number cxn linenum)
(cxn-write cxn "~a~%" line))
(cxn-write cxn "~%"))
(t
(cxn-write cxn "No such editor command.~%"))))
(defmethod editor-prompt ((editor editor) cxn)
(cxn-write cxn "&n~3d&B] &n"
(1+ (length (buffer-of editor)))))
(defmethod editor-start ((editor editor) cxn)
(send-editor-header cxn)
(refresh-screen editor cxn))
(defmethod editor-finish ((editor text-editor) cxn buf)
(funcall (finalizer-of editor) cxn (target-of editor) buf))
(defmethod editor-abort ((editor text-editor) cxn)
(funcall (cancel-func-of editor) cxn (target-of editor)))
(defun editor-word-wrap (string width)
"Given an initial string, returns the string broken up into lines breaking on word boundaries."
(loop
for raw-wrap-pos = width then (+ wrap-pos width)
until (> raw-wrap-pos (length string))
for wrap-pos = (or (position-if-not #'alpha-char-p string :end raw-wrap-pos :from-end t)
raw-wrap-pos)
for start-pos = 0 then (1+ wrap-pos)
collect (string-trim " " (subseq string start-pos wrap-pos)) into result
finally (return (nconc result
(list (string-trim " "
(subseq string (or wrap-pos 0))))))))
(defmethod editor-input ((editor editor) cxn line)
(let ((editor (mode-data-of cxn)))
(cond
((zerop (length line))
(setf (buffer-of editor) (nconc (buffer-of editor) (list line))))
((eql (char line 0) #\&)
(editor-command editor cxn
(char-downcase (char line 1))
(string-trim '(#\space) (subseq line 2))))
((eql (char line 0) #\@)
(setf (state-of editor) 'finished))
((eql (char line 0) #\.)
(refresh-screen editor cxn))
(t
(setf (buffer-of editor)
(if (and (actor-of cxn)
(not (pref-flagged (actor-of cxn) +pref-nowrap+)))
(nconc (buffer-of editor) (editor-word-wrap line 72))
(nconc (buffer-of editor) (list line))))))
(case (state-of editor)
(finished
(editor-finish editor cxn (format nil "~{~a~%~}" (buffer-of editor))))
(aborting
(editor-abort editor cxn)))))
(defparameter +mail-obj-vnum+ 1204)
(defmethod editor-start ((editor mail-editor) cxn)
(send-editor-header cxn)
(cxn-write cxn " &yTo&b:&c ~{~a~^, ~}&n~%~%"
(mapcar 'retrieve-player-name (recipients-of editor))))
(defmethod editor-command ((editor mail-editor) cxn cmd arg)
(case cmd
(#\h
(cxn-write cxn"~
&C *&B------------------------ &YH E L P &B------------------------&C*
&YS - &nSubstitute &YF - &nFind
&YE - &nSave && Exit &YQ - &nQuit (Cancel)
&YL - &nReplace Line &YD - &nDelete Line
&YI - &nInsert Line &YR - &nRefresh Screen
&YC - &nClear Buffer &YU - &nUndo Changes
&YA - &nAdd Recipient &YZ - &nZap Recipient
&YT - &nList Recipients
&C *&B---------------------------------------------------------&C*
"))
(#\a
(let* ((names (cl-ppcre:split "\\s+" arg))
(idnums (mapcar 'retrieve-player-idnum names)))
(if (null names)
(cxn-write cxn "You were going to add some recipients?~%")
(loop
for name in names
for idnum in idnums do
(cond
((null idnum)
(cxn-write cxn "Player '~a' was not found.~%" name))
(t
(cxn-write cxn "Added ~a to recipients.~%"
(retrieve-player-name idnum))
(setf (recipients-of editor) (remove-duplicates
(append (recipients-of editor)
(list idnum))))))))))
(#\z
(let* ((names (cl-ppcre:split "\\s+" arg))
(idnums (mapcar 'retrieve-player-idnum names)))
(if (null names)
(cxn-write cxn "You were going to remove some recipients?~%")
(loop
for name in names
for idnum in idnums do
(cond
((null idnum)
(cxn-write cxn "Player '~a' was not found.~%" name))
((not (member idnum (recipients-of editor)))
(cxn-write cxn "~a wasn't a recipient.~%"
(retrieve-player-name idnum)))
(t
(cxn-write cxn "Removed ~a from recipients.~%"
(retrieve-player-name idnum))
(setf (recipients-of editor) (delete idnum (recipients-of editor)))))))))
(#\t
(cxn-write cxn " &yTo&b:&c ~{~a~^, ~}&n~%" (mapcar 'retrieve-player-name (recipients-of editor))))
(t
(call-next-method))))
(defmethod editor-finish ((editor mail-editor) cxn buf)
(cond
((zerop (length buf))
(cxn-write cxn "Why would you send a blank message?~%"))
(t
(let ((mail (read-object +mail-obj-vnum+)))
(setf (creation-method-of mail) :unknown)
(setf (action-desc-of mail)
(format nil " * * * * Tempus Mail System * * * *~%Date: ~a~% To: ~{~a~^, ~}~%From: ~a~%~%~a"
(format-timestring nil (now)
:format '(:short-month #\space
(:day 2 #\space) #\space
:hour #\:
(:min 2) #\:
(:sec 2) #\space
:year))
(mapcar 'retrieve-player-name (recipients-of editor))
(name-of (actor-of cxn))
buf))
(when (and (actor-of cxn)
(immortal-level-p (actor-of cxn)))
(act (actor-of cxn)
:place-emit "$n postmarks and dispatches $s mail."))
(cxn-write cxn "Message sent!~%")
(dolist (recipient (recipients-of editor))
(let* ((mail-path (mail-pathname recipient))
(old-mail (ignore-errors
(when (probe-file mail-path)
(cddr (cxml:parse-file mail-path (cxml-xmls:make-xmls-builder)))))))
(with-open-file (ouf mail-path :direction :output
:if-exists :rename-and-delete
:if-does-not-exist :create)
(let ((sink (cxml:make-character-stream-sink ouf :canonical nil)))
(cxml-xmls:map-node sink `("objects" nil ,@old-mail ,(serialize-object mail))))))
(let ((target (gethash recipient *character-map*)))
(when target
(send-to-char target "A strange voice in your head says, 'You have new mail.'~%")))))))
(setf (mode-data-of cxn) nil)
(setf (state-of cxn) 'playing))
(defmethod editor-abort ((editor mail-editor) cxn)
(setf (mode-data-of cxn) nil)
(setf (state-of cxn) 'playing))
(defun start-text-editor (cxn target target-desc old-buffer finalizer cancel-func)
(let ((split-buffer (butlast (cl-ppcre:split "\\s+" old-buffer))))
(setf (mode-data-of cxn) (make-instance 'text-editor
:target target
:target-desc target-desc
:old-buffer old-buffer
:buffer split-buffer
:finalizer finalizer
:cancel-func cancel-func))
(setf (state-of cxn) 'editing)))
(defun start-mail-editor (cxn recipients)
(setf (mode-data-of cxn) (make-instance 'mail-editor
:recipients recipients))
(setf (state-of cxn) 'editing))
| null | https://raw.githubusercontent.com/TempusMUD/cl-tempus/c5008c8d782ba44373d89b77c23abaefec3aa6ff/src/support/editor.lisp | lisp | (in-package #:tempus)
(defclass editor ()
((target :accessor target-of :initarg :target)
(target-desc :accessor target-desc-of :initarg :target-desc)
(old-buffer :accessor old-buffer-of :initarg :old-buffer)
(buffer :accessor buffer-of :initarg :buffer :initform '())
(state :accessor state-of :initform 'active)))
(defclass text-editor (editor)
((finalizer :accessor finalizer-of :initarg :finalizer)
(cancel-func :accessor cancel-func-of :initarg :cancel-func)))
(defclass mail-editor (editor)
((recipients :accessor recipients-of :initarg :recipients :initform nil)
(attachments :accessor attachments-of :initarg :attachments :initform nil)))
(defclass board-editor (editor)
((idnum :accessor idnum-of :initarg :idnum)
(board-name :accessor board-name-of :initarg :board-name)
(subject :accessor subject-of :initarg :subject)))
(defclass poll-editor (editor)
((header :accessor header-of :initarg :header)))
(defclass file-editor (editor)
((path :accessor path-of :initarg :path)
(loadedp :accessor loadedp :initarg :loadedp)))
(defun send-line-number (cxn num)
"Send the given line number to the actor."
(cxn-write cxn "&n~3d&b] &n" num))
(defun send-editor-header (cxn)
(cxn-write cxn "&C *&Y TUNED &B] ~
&nTerminate with @ on a new line. ~
&&H for help&C *&n~% &C0")
(dotimes (idx 7)
(cxn-write cxn "&B---------&C~d" (1+ idx)))
(cxn-write cxn "&n~%"))
(defmethod refresh-screen ((editor editor) cxn &optional (start-line 0) count)
"Sends the contents of the buffer to the screen"
(loop for line in (nthcdr start-line (buffer-of editor))
as line-num from 1
while (or (null count) (<= line-num (+ start-line count)))
do
(send-line-number cxn line-num)
(cxn-write cxn "~a~%" line)))
(defmethod editor-command ((editor editor) cxn cmd arg)
"Handles all the commands that the editor is capable of."
(case cmd
(#\h
(cxn-write cxn"~
&C *&B------------------------ &YH E L P &B------------------------&C*
&YS - &nSubstitute &YF - &nFind
&YE - &nSave && Exit &YQ - &nQuit (Cancel)
&YL - &nReplace Line &YD - &nDelete Line
&YI - &nInsert Line &YR - &nRefresh Screen
&YC - &nClear Buffer &YU - &nUndo Changes
&C *&B---------------------------------------------------------&C*
"))
(#\c
(setf (buffer-of editor) nil))
((#\l #\i #\d)
(with-words arg (param &rest new-line)
(cond
((or (null param) (notevery #'digit-char-p param))
(cxn-write cxn "You must specify a numeric line number.~%"))
(t
(let ((line-num (parse-integer param)))
(cond
((> line-num (length (buffer-of editor)))
(cxn-write cxn
"There are only ~d lines of text!~%"
(length (buffer-of editor))))
(t
(case cmd
(#\l
(setf (nth (1- line-num) (buffer-of editor)) new-line)
(cxn-write cxn "Line ~d replaced.~%" line-num))
(#\i
(setf (buffer-of editor)
(nconc (subseq (buffer-of editor) 0 (1- line-num))
(list new-line)
(subseq (buffer-of editor) (1- line-num))))
(cxn-write cxn
"New line inserted before line ~d.~%"
line-num))
(#\d
(setf (buffer-of editor)
(nconc (subseq (buffer-of editor) 0 (1- line-num))
(subseq (buffer-of editor) line-num)))
(cxn-write cxn "Line ~d deleted.~%" line-num))))))))))
(#\r
(refresh-screen editor cxn))
(#\u
(setf (buffer-of editor) (cl-ppcre:split "\\s+" (old-buffer-of editor)))
(refresh-screen editor cxn)
(cxn-write cxn "Reverted back to previous.~%"))
(#\e
(setf (state-of editor) 'finishing))
(#\q
(setf (state-of editor) 'aborting))
(#\s
(let* ((matching-delims "()[]<>{}")
(start-delim (find #\space arg :test-not #'char=))
(end-delim-pos (position start-delim matching-delims))
(end-delim (if end-delim-pos
(char matching-delims (1+ end-delim-pos))
start-delim))
(start1 (position start-delim arg))
(end1 (and start1 (position end-delim arg :start (1+ start1))))
(start2 (and end1 (position start-delim arg :start end1)))
(end2 (and start2 (position end-delim arg :start (1+ start2)))))
(cond
((= (1+ start1) end1)
(cxn-write cxn "You can't replace a zero-length search pattern.~%"))
((and start1 end1 start2 end2)
(let ((search-str (subseq arg (1+ start1) end1))
(replace-str (subseq arg (1+ start2) end2)))
(setf (buffer-of editor)
(loop for old-line in (buffer-of editor)
collect (string-replace search-str old-line replace-str)))
(cxn-write cxn
"All instances of [~a] have been replaced with [~a].~%"
search-str
replace-str)))
(t
(cxn-write cxn "The subsitution could not be made.~%")))))
(#\f
(loop for line in (buffer-of editor)
as linenum from 1
when (search arg line)
do
(send-line-number cxn linenum)
(cxn-write cxn "~a~%" line))
(cxn-write cxn "~%"))
(t
(cxn-write cxn "No such editor command.~%"))))
(defmethod editor-prompt ((editor editor) cxn)
(cxn-write cxn "&n~3d&B] &n"
(1+ (length (buffer-of editor)))))
(defmethod editor-start ((editor editor) cxn)
(send-editor-header cxn)
(refresh-screen editor cxn))
(defmethod editor-finish ((editor text-editor) cxn buf)
(funcall (finalizer-of editor) cxn (target-of editor) buf))
(defmethod editor-abort ((editor text-editor) cxn)
(funcall (cancel-func-of editor) cxn (target-of editor)))
(defun editor-word-wrap (string width)
"Given an initial string, returns the string broken up into lines breaking on word boundaries."
(loop
for raw-wrap-pos = width then (+ wrap-pos width)
until (> raw-wrap-pos (length string))
for wrap-pos = (or (position-if-not #'alpha-char-p string :end raw-wrap-pos :from-end t)
raw-wrap-pos)
for start-pos = 0 then (1+ wrap-pos)
collect (string-trim " " (subseq string start-pos wrap-pos)) into result
finally (return (nconc result
(list (string-trim " "
(subseq string (or wrap-pos 0))))))))
(defmethod editor-input ((editor editor) cxn line)
(let ((editor (mode-data-of cxn)))
(cond
((zerop (length line))
(setf (buffer-of editor) (nconc (buffer-of editor) (list line))))
((eql (char line 0) #\&)
(editor-command editor cxn
(char-downcase (char line 1))
(string-trim '(#\space) (subseq line 2))))
((eql (char line 0) #\@)
(setf (state-of editor) 'finished))
((eql (char line 0) #\.)
(refresh-screen editor cxn))
(t
(setf (buffer-of editor)
(if (and (actor-of cxn)
(not (pref-flagged (actor-of cxn) +pref-nowrap+)))
(nconc (buffer-of editor) (editor-word-wrap line 72))
(nconc (buffer-of editor) (list line))))))
(case (state-of editor)
(finished
(editor-finish editor cxn (format nil "~{~a~%~}" (buffer-of editor))))
(aborting
(editor-abort editor cxn)))))
(defparameter +mail-obj-vnum+ 1204)
(defmethod editor-start ((editor mail-editor) cxn)
(send-editor-header cxn)
(cxn-write cxn " &yTo&b:&c ~{~a~^, ~}&n~%~%"
(mapcar 'retrieve-player-name (recipients-of editor))))
(defmethod editor-command ((editor mail-editor) cxn cmd arg)
(case cmd
(#\h
(cxn-write cxn"~
&C *&B------------------------ &YH E L P &B------------------------&C*
&YS - &nSubstitute &YF - &nFind
&YE - &nSave && Exit &YQ - &nQuit (Cancel)
&YL - &nReplace Line &YD - &nDelete Line
&YI - &nInsert Line &YR - &nRefresh Screen
&YC - &nClear Buffer &YU - &nUndo Changes
&YA - &nAdd Recipient &YZ - &nZap Recipient
&YT - &nList Recipients
&C *&B---------------------------------------------------------&C*
"))
(#\a
(let* ((names (cl-ppcre:split "\\s+" arg))
(idnums (mapcar 'retrieve-player-idnum names)))
(if (null names)
(cxn-write cxn "You were going to add some recipients?~%")
(loop
for name in names
for idnum in idnums do
(cond
((null idnum)
(cxn-write cxn "Player '~a' was not found.~%" name))
(t
(cxn-write cxn "Added ~a to recipients.~%"
(retrieve-player-name idnum))
(setf (recipients-of editor) (remove-duplicates
(append (recipients-of editor)
(list idnum))))))))))
(#\z
(let* ((names (cl-ppcre:split "\\s+" arg))
(idnums (mapcar 'retrieve-player-idnum names)))
(if (null names)
(cxn-write cxn "You were going to remove some recipients?~%")
(loop
for name in names
for idnum in idnums do
(cond
((null idnum)
(cxn-write cxn "Player '~a' was not found.~%" name))
((not (member idnum (recipients-of editor)))
(cxn-write cxn "~a wasn't a recipient.~%"
(retrieve-player-name idnum)))
(t
(cxn-write cxn "Removed ~a from recipients.~%"
(retrieve-player-name idnum))
(setf (recipients-of editor) (delete idnum (recipients-of editor)))))))))
(#\t
(cxn-write cxn " &yTo&b:&c ~{~a~^, ~}&n~%" (mapcar 'retrieve-player-name (recipients-of editor))))
(t
(call-next-method))))
(defmethod editor-finish ((editor mail-editor) cxn buf)
(cond
((zerop (length buf))
(cxn-write cxn "Why would you send a blank message?~%"))
(t
(let ((mail (read-object +mail-obj-vnum+)))
(setf (creation-method-of mail) :unknown)
(setf (action-desc-of mail)
(format nil " * * * * Tempus Mail System * * * *~%Date: ~a~% To: ~{~a~^, ~}~%From: ~a~%~%~a"
(format-timestring nil (now)
:format '(:short-month #\space
(:day 2 #\space) #\space
:hour #\:
(:min 2) #\:
(:sec 2) #\space
:year))
(mapcar 'retrieve-player-name (recipients-of editor))
(name-of (actor-of cxn))
buf))
(when (and (actor-of cxn)
(immortal-level-p (actor-of cxn)))
(act (actor-of cxn)
:place-emit "$n postmarks and dispatches $s mail."))
(cxn-write cxn "Message sent!~%")
(dolist (recipient (recipients-of editor))
(let* ((mail-path (mail-pathname recipient))
(old-mail (ignore-errors
(when (probe-file mail-path)
(cddr (cxml:parse-file mail-path (cxml-xmls:make-xmls-builder)))))))
(with-open-file (ouf mail-path :direction :output
:if-exists :rename-and-delete
:if-does-not-exist :create)
(let ((sink (cxml:make-character-stream-sink ouf :canonical nil)))
(cxml-xmls:map-node sink `("objects" nil ,@old-mail ,(serialize-object mail))))))
(let ((target (gethash recipient *character-map*)))
(when target
(send-to-char target "A strange voice in your head says, 'You have new mail.'~%")))))))
(setf (mode-data-of cxn) nil)
(setf (state-of cxn) 'playing))
(defmethod editor-abort ((editor mail-editor) cxn)
(setf (mode-data-of cxn) nil)
(setf (state-of cxn) 'playing))
(defun start-text-editor (cxn target target-desc old-buffer finalizer cancel-func)
(let ((split-buffer (butlast (cl-ppcre:split "\\s+" old-buffer))))
(setf (mode-data-of cxn) (make-instance 'text-editor
:target target
:target-desc target-desc
:old-buffer old-buffer
:buffer split-buffer
:finalizer finalizer
:cancel-func cancel-func))
(setf (state-of cxn) 'editing)))
(defun start-mail-editor (cxn recipients)
(setf (mode-data-of cxn) (make-instance 'mail-editor
:recipients recipients))
(setf (state-of cxn) 'editing))
|
|
0faa444de849cd6f0e02a037c36586adb60cbefffecd53543675f02239c86d45 | cedlemo/OCaml-GI-ctypes-bindings-generator | Handle_box.ml | open Ctypes
open Foreign
type t = unit ptr
let t_typ : t typ = ptr void
let create =
foreign "gtk_handle_box_new" (void @-> returning (ptr Widget.t_typ))
let get_child_detached =
foreign "gtk_handle_box_get_child_detached" (t_typ @-> returning (bool))
let get_handle_position =
foreign "gtk_handle_box_get_handle_position" (t_typ @-> returning (Position_type.t_view))
let get_shadow_type =
foreign "gtk_handle_box_get_shadow_type" (t_typ @-> returning (Shadow_type.t_view))
let get_snap_edge =
foreign "gtk_handle_box_get_snap_edge" (t_typ @-> returning (Position_type.t_view))
let set_handle_position =
foreign "gtk_handle_box_set_handle_position" (t_typ @-> Position_type.t_view @-> returning (void))
let set_shadow_type =
foreign "gtk_handle_box_set_shadow_type" (t_typ @-> Shadow_type.t_view @-> returning (void))
let set_snap_edge =
foreign "gtk_handle_box_set_snap_edge" (t_typ @-> Position_type.t_view @-> returning (void))
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Handle_box.ml | ocaml | open Ctypes
open Foreign
type t = unit ptr
let t_typ : t typ = ptr void
let create =
foreign "gtk_handle_box_new" (void @-> returning (ptr Widget.t_typ))
let get_child_detached =
foreign "gtk_handle_box_get_child_detached" (t_typ @-> returning (bool))
let get_handle_position =
foreign "gtk_handle_box_get_handle_position" (t_typ @-> returning (Position_type.t_view))
let get_shadow_type =
foreign "gtk_handle_box_get_shadow_type" (t_typ @-> returning (Shadow_type.t_view))
let get_snap_edge =
foreign "gtk_handle_box_get_snap_edge" (t_typ @-> returning (Position_type.t_view))
let set_handle_position =
foreign "gtk_handle_box_set_handle_position" (t_typ @-> Position_type.t_view @-> returning (void))
let set_shadow_type =
foreign "gtk_handle_box_set_shadow_type" (t_typ @-> Shadow_type.t_view @-> returning (void))
let set_snap_edge =
foreign "gtk_handle_box_set_snap_edge" (t_typ @-> Position_type.t_view @-> returning (void))
|
|
405db0171ca79b4743255ad173dbc7a1d08c1d329f4a454906bcb7cade8d423e | vrnithinkumar/ETC | simple_return.erl | -module(simple_return).
-spec foo(integer()) -> boolean().
foo (42) ->
X = false,
X and true.
| null | https://raw.githubusercontent.com/vrnithinkumar/ETC/5e5806975fe96a902dab830a0c8caadc5d61e62b/testsuit/test_cases/simple_return.erl | erlang | -module(simple_return).
-spec foo(integer()) -> boolean().
foo (42) ->
X = false,
X and true.
|
|
ede705289566c8037f9e3995ab8739696c692e0fa9a1c59508c5e001fa914b31 | grin-compiler/ghc-wpc-sample-programs | PrimType.hs | Module : Basement .
-- License : BSD-style
Maintainer : < >
-- Stability : experimental
-- Portability : portable
--
# LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE CPP #
module Basement.PrimType
( PrimType(..)
, PrimMemoryComparable
, primBaIndex
, primMbaRead
, primMbaWrite
, primArrayIndex
, primMutableArrayRead
, primMutableArrayWrite
, primOffsetOfE
, primOffsetRecast
, sizeRecast
, offsetAsSize
, sizeAsOffset
, sizeInBytes
, offsetInBytes
, offsetInElements
, offsetIsAligned
, primWordGetByteAndShift
, primWord64GetByteAndShift
, primWord64GetHiLo
) where
#include "MachDeps.h"
import GHC.Prim
import GHC.Int
import GHC.Types
import GHC.Word
import Data.Bits
import Data.Proxy
import Basement.Compat.Base
import Basement.Compat.C.Types
import Basement.Numerical.Subtractive
import Basement.Types.OffsetSize
import Basement.Types.Char7 (Char7(..))
import Basement.Endianness
import Basement.Types.Word128 (Word128(..))
import Basement.Types.Word256 (Word256(..))
import Basement.Monad
import Basement.Nat
import qualified Prelude (quot)
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
#ifdef FOUNDATION_BOUNDS_CHECK
divBytes :: PrimType ty => Offset ty -> (Int -> Int)
divBytes ofs = \x -> x `Prelude.quot` (getSize Proxy ofs)
where
getSize :: PrimType ty => Proxy ty -> Offset ty -> Int
getSize p _ = let (CountOf sz) = primSizeInBytes p in sz
baLength :: PrimType ty => Offset ty -> ByteArray# -> Int
baLength ofs ba = divBytes ofs (I# (sizeofByteArray# ba))
mbaLength :: PrimType ty => Offset ty -> MutableByteArray# st -> Int
mbaLength ofs ba = divBytes ofs (I# (sizeofMutableByteArray# ba))
aLength :: Array# ty -> Int
aLength ba = I# (sizeofArray# ba)
maLength :: MutableArray# st ty -> Int
maLength ba = I# (sizeofMutableArray# ba)
boundCheckError :: [Char] -> Offset ty -> Int -> a
boundCheckError ty (Offset ofs) len =
error (ty <> " offset=" <> show ofs <> " len=" <> show len)
baCheck :: PrimType ty => ByteArray# -> Offset ty -> Bool
baCheck ba ofs@(Offset o) = o < 0 || o >= baLength ofs ba
mbaCheck :: PrimType ty => MutableByteArray# st -> Offset ty -> Bool
mbaCheck mba ofs@(Offset o) = o < 0 || o >= mbaLength ofs mba
aCheck :: Array# ty -> Offset ty -> Bool
aCheck ba (Offset o) = o < 0 || o >= aLength ba
maCheck :: MutableArray# st ty -> Offset ty -> Bool
maCheck ma (Offset o) = o < 0 || o >= maLength ma
primBaIndex :: PrimType ty => ByteArray# -> Offset ty -> ty
primBaIndex ba ofs
| baCheck ba ofs = boundCheckError "bytearray-index" ofs (baLength ofs ba)
| otherwise = primBaUIndex ba ofs
# NOINLINE primBaIndex #
primMbaRead :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> prim ty
primMbaRead mba ofs
| mbaCheck mba ofs = boundCheckError "mutablebytearray-read" ofs (mbaLength ofs mba)
| otherwise = primMbaURead mba ofs
# NOINLINE primMbaRead #
primMbaWrite :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> ty -> prim ()
primMbaWrite mba ofs ty
| mbaCheck mba ofs = boundCheckError "mutablebytearray-write" ofs (mbaLength ofs mba)
| otherwise = primMbaUWrite mba ofs ty
# NOINLINE primMbaWrite #
primArrayIndex :: Array# ty -> Offset ty -> ty
primArrayIndex a o@(Offset (I# ofs))
| aCheck a o = boundCheckError "array-index" o (aLength a)
| otherwise = let !(# v #) = indexArray# a ofs in v
# NOINLINE primArrayIndex #
primMutableArrayRead :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> prim ty
primMutableArrayRead ma o@(Offset (I# ofs))
| maCheck ma o = boundCheckError "array-read" o (maLength ma)
| otherwise = primitive $ \s1 -> readArray# ma ofs s1
# NOINLINE primMutableArrayRead #
primMutableArrayWrite :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> ty -> prim ()
primMutableArrayWrite ma o@(Offset (I# ofs)) v
| maCheck ma o = boundCheckError "array-write" o (maLength ma)
| otherwise = primitive $ \s1 -> let !s2 = writeArray# ma ofs v s1 in (# s2, () #)
# NOINLINE primMutableArrayWrite #
#else
primBaIndex :: PrimType ty => ByteArray# -> Offset ty -> ty
primBaIndex = primBaUIndex
{-# INLINE primBaIndex #-}
primMbaRead :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> prim ty
primMbaRead = primMbaURead
# INLINE primMbaRead #
primMbaWrite :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> ty -> prim ()
primMbaWrite = primMbaUWrite
# INLINE primMbaWrite #
primArrayIndex :: Array# ty -> Offset ty -> ty
primArrayIndex a (Offset (I# ofs)) = let !(# v #) = indexArray# a ofs in v
# INLINE primArrayIndex #
primMutableArrayRead :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> prim ty
primMutableArrayRead ma (Offset (I# ofs)) = primitive $ \s1 -> readArray# ma ofs s1
# INLINE primMutableArrayRead #
primMutableArrayWrite :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> ty -> prim ()
primMutableArrayWrite ma (Offset (I# ofs)) v =
primitive $ \s1 -> let !s2 = writeArray# ma ofs v s1 in (# s2, () #)
# INLINE primMutableArrayWrite #
#endif
| Represent the accessor for types that can be stored in the UArray and MUArray .
--
-- Types need to be a instance of storable and have fixed sized.
class Eq ty => PrimType ty where
-- | type level size of the given `ty`
type PrimSize ty :: Nat
-- | get the size in bytes of a ty element
primSizeInBytes :: Proxy ty -> CountOf Word8
-- | get the shift size
primShiftToBytes :: Proxy ty -> Int
-----
ByteArray section
-----
-- | return the element stored at a specific index
primBaUIndex :: ByteArray# -> Offset ty -> ty
-----
-- MutableByteArray section
-----
-- | Read an element at an index in a mutable array
primMbaURead :: PrimMonad prim
=> MutableByteArray# (PrimState prim) -- ^ mutable array to read from
-> Offset ty -- ^ index of the element to retrieve
-> prim ty -- ^ the element returned
-- | Write an element to a specific cell in a mutable array.
primMbaUWrite :: PrimMonad prim
=> MutableByteArray# (PrimState prim) -- ^ mutable array to modify
-> Offset ty -- ^ index of the element to modify
-> ty -- ^ the new value to store
-> prim ()
-----
-- Addr# section
-----
-- | Read from Address, without a state. the value read should be considered a constant for all
-- pratical purpose, otherwise bad thing will happens.
primAddrIndex :: Addr# -> Offset ty -> ty
| Read a value from Addr in a specific primitive monad
primAddrRead :: PrimMonad prim
=> Addr#
-> Offset ty
-> prim ty
| Write a value to Addr in a specific primitive monad
primAddrWrite :: PrimMonad prim
=> Addr#
-> Offset ty
-> ty
-> prim ()
sizeInt, sizeWord :: CountOf Word8
shiftInt, shiftWord :: Int
#if WORD_SIZE_IN_BITS == 64
sizeInt = CountOf 8
sizeWord = CountOf 8
shiftInt = 3
shiftWord = 3
#else
sizeInt = CountOf 4
sizeWord = CountOf 4
shiftInt = 2
shiftWord = 2
#endif
# SPECIALIZE [ 3 ] primBaUIndex : : # - > Offset Word8 - > Word8 #
instance PrimType Int where
#if WORD_SIZE_IN_BITS == 64
type PrimSize Int = 8
#else
type PrimSize Int = 4
#endif
primSizeInBytes _ = sizeInt
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = shiftInt
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I# (indexIntArray# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readIntArray# mba n s1 in (# s2, I# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I# w) = primitive $ \s1 -> (# writeIntArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I# (indexIntOffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readIntOffAddr# addr n s1 in (# s2, I# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I# w) = primitive $ \s1 -> (# writeIntOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word where
#if WORD_SIZE_IN_BITS == 64
type PrimSize Word = 8
#else
type PrimSize Word = 4
#endif
primSizeInBytes _ = sizeWord
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = shiftWord
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W# (indexWordArray# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWordArray# mba n s1 in (# s2, W# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W# w) = primitive $ \s1 -> (# writeWordArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W# (indexWordOffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWordOffAddr# addr n s1 in (# s2, W# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W# w) = primitive $ \s1 -> (# writeWordOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word8 where
type PrimSize Word8 = 1
primSizeInBytes _ = CountOf 1
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W8# (indexWord8Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord8Array# mba n s1 in (# s2, W8# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W8# w) = primitive $ \s1 -> (# writeWord8Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W8# (indexWord8OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord8OffAddr# addr n s1 in (# s2, W8# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W8# w) = primitive $ \s1 -> (# writeWord8OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word16 where
type PrimSize Word16 = 2
primSizeInBytes _ = CountOf 2
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 1
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W16# (indexWord16Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord16Array# mba n s1 in (# s2, W16# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W16# w) = primitive $ \s1 -> (# writeWord16Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W16# (indexWord16OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord16OffAddr# addr n s1 in (# s2, W16# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W16# w) = primitive $ \s1 -> (# writeWord16OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word32 where
type PrimSize Word32 = 4
primSizeInBytes _ = CountOf 4
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W32# (indexWord32Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord32Array# mba n s1 in (# s2, W32# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W32# w) = primitive $ \s1 -> (# writeWord32Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W32# (indexWord32OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord32OffAddr# addr n s1 in (# s2, W32# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W32# w) = primitive $ \s1 -> (# writeWord32OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word64 where
type PrimSize Word64 = 8
primSizeInBytes _ = CountOf 8
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 3
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W64# (indexWord64Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord64Array# mba n s1 in (# s2, W64# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W64# w) = primitive $ \s1 -> (# writeWord64Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W64# (indexWord64OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord64OffAddr# addr n s1 in (# s2, W64# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W64# w) = primitive $ \s1 -> (# writeWord64OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word128 where
type PrimSize Word128 = 16
primSizeInBytes _ = CountOf 16
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 4
# INLINE primShiftToBytes #
primBaUIndex ba n =
Word128 (W64# (indexWord64Array# ba n1)) (W64# (indexWord64Array# ba n2))
where (# n1, n2 #) = offset128_64 n
{-# INLINE primBaUIndex #-}
primMbaURead mba n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64Array# mba n1 s1
!(# s3, r2 #) = readWord64Array# mba n2 s2
in (# s3, Word128 (W64# r1) (W64# r2) #)
where (# n1, n2 #) = offset128_64 n
# INLINE primMbaURead #
primMbaUWrite mba n (Word128 (W64# w1) (W64# w2)) = primitive $ \s1 ->
let !s2 = writeWord64Array# mba n1 w1 s1
in (# writeWord64Array# mba n2 w2 s2, () #)
where (# n1, n2 #) = offset128_64 n
# INLINE primMbaUWrite #
primAddrIndex addr n = Word128 (W64# (indexWord64OffAddr# addr n1)) (W64# (indexWord64OffAddr# addr n2))
where (# n1, n2 #) = offset128_64 n
{-# INLINE primAddrIndex #-}
primAddrRead addr n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64OffAddr# addr n1 s1
!(# s3, r2 #) = readWord64OffAddr# addr n2 s2
in (# s3, Word128 (W64# r1) (W64# r2) #)
where (# n1, n2 #) = offset128_64 n
# INLINE primAddrRead #
primAddrWrite addr n (Word128 (W64# w1) (W64# w2)) = primitive $ \s1 ->
let !s2 = writeWord64OffAddr# addr n1 w1 s1
in (# writeWord64OffAddr# addr n2 w2 s2, () #)
where (# n1, n2 #) = offset128_64 n
# INLINE primAddrWrite #
instance PrimType Word256 where
type PrimSize Word256 = 32
primSizeInBytes _ = CountOf 32
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 5
# INLINE primShiftToBytes #
primBaUIndex ba n =
Word256 (W64# (indexWord64Array# ba n1)) (W64# (indexWord64Array# ba n2))
(W64# (indexWord64Array# ba n3)) (W64# (indexWord64Array# ba n4))
where (# n1, n2, n3, n4 #) = offset256_64 n
{-# INLINE primBaUIndex #-}
primMbaURead mba n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64Array# mba n1 s1
!(# s3, r2 #) = readWord64Array# mba n2 s2
!(# s4, r3 #) = readWord64Array# mba n3 s3
!(# s5, r4 #) = readWord64Array# mba n4 s4
in (# s5, Word256 (W64# r1) (W64# r2) (W64# r3) (W64# r4) #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primMbaURead #
primMbaUWrite mba n (Word256 (W64# w1) (W64# w2) (W64# w3) (W64# w4)) = primitive $ \s1 ->
let !s2 = writeWord64Array# mba n1 w1 s1
!s3 = writeWord64Array# mba n2 w2 s2
!s4 = writeWord64Array# mba n3 w3 s3
in (# writeWord64Array# mba n4 w4 s4, () #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primMbaUWrite #
primAddrIndex addr n = Word256 (W64# (indexWord64OffAddr# addr n1)) (W64# (indexWord64OffAddr# addr n2))
(W64# (indexWord64OffAddr# addr n3)) (W64# (indexWord64OffAddr# addr n4))
where (# n1, n2, n3, n4 #) = offset256_64 n
{-# INLINE primAddrIndex #-}
primAddrRead addr n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64OffAddr# addr n1 s1
!(# s3, r2 #) = readWord64OffAddr# addr n2 s2
!(# s4, r3 #) = readWord64OffAddr# addr n3 s3
!(# s5, r4 #) = readWord64OffAddr# addr n4 s4
in (# s5, Word256 (W64# r1) (W64# r2) (W64# r3) (W64# r4) #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primAddrRead #
primAddrWrite addr n (Word256 (W64# w1) (W64# w2) (W64# w3) (W64# w4)) = primitive $ \s1 ->
let !s2 = writeWord64OffAddr# addr n1 w1 s1
!s3 = writeWord64OffAddr# addr n2 w2 s2
!s4 = writeWord64OffAddr# addr n3 w3 s3
in (# writeWord64OffAddr# addr n4 w4 s4, () #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primAddrWrite #
instance PrimType Int8 where
type PrimSize Int8 = 1
primSizeInBytes _ = CountOf 1
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I8# (indexInt8Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt8Array# mba n s1 in (# s2, I8# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I8# w) = primitive $ \s1 -> (# writeInt8Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I8# (indexInt8OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt8OffAddr# addr n s1 in (# s2, I8# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I8# w) = primitive $ \s1 -> (# writeInt8OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Int16 where
type PrimSize Int16 = 2
primSizeInBytes _ = CountOf 2
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 1
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I16# (indexInt16Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt16Array# mba n s1 in (# s2, I16# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I16# w) = primitive $ \s1 -> (# writeInt16Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I16# (indexInt16OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt16OffAddr# addr n s1 in (# s2, I16# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I16# w) = primitive $ \s1 -> (# writeInt16OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Int32 where
type PrimSize Int32 = 4
primSizeInBytes _ = CountOf 4
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I32# (indexInt32Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt32Array# mba n s1 in (# s2, I32# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I32# w) = primitive $ \s1 -> (# writeInt32Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I32# (indexInt32OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt32OffAddr# addr n s1 in (# s2, I32# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I32# w) = primitive $ \s1 -> (# writeInt32OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Int64 where
type PrimSize Int64 = 8
primSizeInBytes _ = CountOf 8
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 3
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I64# (indexInt64Array# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt64Array# mba n s1 in (# s2, I64# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I64# w) = primitive $ \s1 -> (# writeInt64Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I64# (indexInt64OffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt64OffAddr# addr n s1 in (# s2, I64# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I64# w) = primitive $ \s1 -> (# writeInt64OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Float where
type PrimSize Float = 4
primSizeInBytes _ = CountOf 4
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = F# (indexFloatArray# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readFloatArray# mba n s1 in (# s2, F# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (F# w) = primitive $ \s1 -> (# writeFloatArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = F# (indexFloatOffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readFloatOffAddr# addr n s1 in (# s2, F# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (F# w) = primitive $ \s1 -> (# writeFloatOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Double where
type PrimSize Double = 8
primSizeInBytes _ = CountOf 8
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 3
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = D# (indexDoubleArray# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readDoubleArray# mba n s1 in (# s2, D# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (D# w) = primitive $ \s1 -> (# writeDoubleArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = D# (indexDoubleOffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readDoubleOffAddr# addr n s1 in (# s2, D# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (D# w) = primitive $ \s1 -> (# writeDoubleOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Char where
type PrimSize Char = 4
primSizeInBytes _ = CountOf 4
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = C# (indexWideCharArray# ba n)
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWideCharArray# mba n s1 in (# s2, C# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (C# w) = primitive $ \s1 -> (# writeWideCharArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = C# (indexWideCharOffAddr# addr n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWideCharOffAddr# addr n s1 in (# s2, C# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (C# w) = primitive $ \s1 -> (# writeWideCharOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType CChar where
type PrimSize CChar = 1
primSizeInBytes _ = CountOf 1
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset n) = CChar (primBaUIndex ba (Offset n))
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset n) = CChar <$> primMbaURead mba (Offset n)
# INLINE primMbaURead #
primMbaUWrite mba (Offset n) (CChar int8) = primMbaUWrite mba (Offset n) int8
# INLINE primMbaUWrite #
primAddrIndex addr (Offset n) = CChar $ primAddrIndex addr (Offset n)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset n) = CChar <$> primAddrRead addr (Offset n)
# INLINE primAddrRead #
primAddrWrite addr (Offset n) (CChar int8) = primAddrWrite addr (Offset n) int8
# INLINE primAddrWrite #
instance PrimType CUChar where
type PrimSize CUChar = 1
primSizeInBytes _ = CountOf 1
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset n) = CUChar (primBaUIndex ba (Offset n :: Offset Word8))
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset n) = CUChar <$> primMbaURead mba (Offset n :: Offset Word8)
# INLINE primMbaURead #
primMbaUWrite mba (Offset n) (CUChar w8) = primMbaUWrite mba (Offset n) w8
# INLINE primMbaUWrite #
primAddrIndex addr (Offset n) = CUChar $ primAddrIndex addr (Offset n :: Offset Word8)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset n) = CUChar <$> primAddrRead addr (Offset n :: Offset Word8)
# INLINE primAddrRead #
primAddrWrite addr (Offset n) (CUChar w8) = primAddrWrite addr (Offset n) w8
# INLINE primAddrWrite #
instance PrimType Char7 where
type PrimSize Char7 = 1
primSizeInBytes _ = CountOf 1
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset n) = Char7 (primBaUIndex ba (Offset n :: Offset Word8))
{-# INLINE primBaUIndex #-}
primMbaURead mba (Offset n) = Char7 <$> primMbaURead mba (Offset n :: Offset Word8)
# INLINE primMbaURead #
primMbaUWrite mba (Offset n) (Char7 w8) = primMbaUWrite mba (Offset n) w8
# INLINE primMbaUWrite #
primAddrIndex addr (Offset n) = Char7 $ primAddrIndex addr (Offset n :: Offset Word8)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset n) = Char7 <$> primAddrRead addr (Offset n :: Offset Word8)
# INLINE primAddrRead #
primAddrWrite addr (Offset n) (Char7 w8) = primAddrWrite addr (Offset n) w8
# INLINE primAddrWrite #
instance PrimType a => PrimType (LE a) where
type PrimSize (LE a) = PrimSize a
primSizeInBytes _ = primSizeInBytes (Proxy :: Proxy a)
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = primShiftToBytes (Proxy :: Proxy a)
# INLINE primShiftToBytes #
primBaUIndex ba (Offset a) = LE $ primBaUIndex ba (Offset a)
{-# INLINE primBaUIndex #-}
primMbaURead ba (Offset a) = LE <$> primMbaURead ba (Offset a)
# INLINE primMbaURead #
primMbaUWrite mba (Offset a) (LE w) = primMbaUWrite mba (Offset a) w
# INLINE primMbaUWrite #
primAddrIndex addr (Offset a) = LE $ primAddrIndex addr (Offset a)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset a) = LE <$> primAddrRead addr (Offset a)
# INLINE primAddrRead #
primAddrWrite addr (Offset a) (LE w) = primAddrWrite addr (Offset a) w
# INLINE primAddrWrite #
instance PrimType a => PrimType (BE a) where
type PrimSize (BE a) = PrimSize a
primSizeInBytes _ = primSizeInBytes (Proxy :: Proxy a)
{-# INLINE primSizeInBytes #-}
primShiftToBytes _ = primShiftToBytes (Proxy :: Proxy a)
# INLINE primShiftToBytes #
primBaUIndex ba (Offset a) = BE $ primBaUIndex ba (Offset a)
{-# INLINE primBaUIndex #-}
primMbaURead ba (Offset a) = BE <$> primMbaURead ba (Offset a)
# INLINE primMbaURead #
primMbaUWrite mba (Offset a) (BE w) = primMbaUWrite mba (Offset a) w
# INLINE primMbaUWrite #
primAddrIndex addr (Offset a) = BE $ primAddrIndex addr (Offset a)
{-# INLINE primAddrIndex #-}
primAddrRead addr (Offset a) = BE <$> primAddrRead addr (Offset a)
# INLINE primAddrRead #
primAddrWrite addr (Offset a) (BE w) = primAddrWrite addr (Offset a) w
# INLINE primAddrWrite #
-- | A constraint class for serializable type that have an unique
-- memory compare representation
--
e.g. Float and Double have -0.0 and 0.0 which are Eq individual ,
-- yet have a different memory representation which doesn't allow
for memcmp operation
class PrimMemoryComparable ty where
instance PrimMemoryComparable Int where
instance PrimMemoryComparable Word where
instance PrimMemoryComparable Word8 where
instance PrimMemoryComparable Word16 where
instance PrimMemoryComparable Word32 where
instance PrimMemoryComparable Word64 where
instance PrimMemoryComparable Word128 where
instance PrimMemoryComparable Word256 where
instance PrimMemoryComparable Int8 where
instance PrimMemoryComparable Int16 where
instance PrimMemoryComparable Int32 where
instance PrimMemoryComparable Int64 where
instance PrimMemoryComparable Char where
instance PrimMemoryComparable CChar where
instance PrimMemoryComparable CUChar where
instance PrimMemoryComparable a => PrimMemoryComparable (LE a) where
instance PrimMemoryComparable a => PrimMemoryComparable (BE a) where
offset128_64 :: Offset Word128 -> (# Int#, Int# #)
offset128_64 (Offset (I# i)) = (# n , n +# 1# #)
where !n = uncheckedIShiftL# i 1#
offset256_64 :: Offset Word256 -> (# Int#, Int#, Int#, Int# #)
offset256_64 (Offset (I# i)) = (# n , n +# 1#, n +# 2#, n +# 3# #)
where !n = uncheckedIShiftL# i 2#
-- | Cast a CountOf linked to type A (CountOf A) to a CountOf linked to type B (CountOf B)
sizeRecast :: forall a b . (PrimType a, PrimType b) => CountOf a -> CountOf b
sizeRecast sz = CountOf (bytes `Prelude.quot` szB)
where !szA = primSizeInBytes (Proxy :: Proxy a)
!(CountOf szB) = primSizeInBytes (Proxy :: Proxy b)
!(CountOf bytes) = sizeOfE szA sz
# INLINE [ 1 ] sizeRecast #
# RULES " sizeRecast from " [ 2 ] forall a . sizeRecast a = sizeRecastBytes a #
sizeRecastBytes :: forall b . PrimType b => CountOf Word8 -> CountOf b
sizeRecastBytes (CountOf w) = CountOf (w `Prelude.quot` szB)
where !(CountOf szB) = primSizeInBytes (Proxy :: Proxy b)
# INLINE [ 1 ] sizeRecastBytes #
sizeInBytes :: forall a . PrimType a => CountOf a -> CountOf Word8
sizeInBytes sz = sizeOfE (primSizeInBytes (Proxy :: Proxy a)) sz
offsetInBytes :: forall a . PrimType a => Offset a -> Offset Word8
offsetInBytes ofs = offsetShiftL (primShiftToBytes (Proxy :: Proxy a)) ofs
# INLINE [ 2 ] offsetInBytes #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word64 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word32 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word16 - > Offset Word8 #
# RULES " offsetInBytes Bytes " [ 3 ] forall x . offsetInBytes x = x #
offsetInElements :: forall a . PrimType a => Offset Word8 -> Offset a
offsetInElements ofs = offsetShiftR (primShiftToBytes (Proxy :: Proxy a)) ofs
# INLINE [ 2 ] offsetInElements #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word64 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word32 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word16 - > Offset Word8 #
# RULES " offsetInElements Bytes " [ 3 ] forall x . offsetInElements x = x #
primOffsetRecast :: forall a b . (PrimType a, PrimType b) => Offset a -> Offset b
primOffsetRecast !ofs =
let !(Offset bytes) = offsetOfE szA ofs
in Offset (bytes `Prelude.quot` szB)
where
!szA = primSizeInBytes (Proxy :: Proxy a)
!(CountOf szB) = primSizeInBytes (Proxy :: Proxy b)
# INLINE [ 1 ] primOffsetRecast #
# RULES " primOffsetRecast W8 " [ 3 ] forall a . primOffsetRecast a = primOffsetRecastBytes a #
offsetIsAligned :: forall a . PrimType a => Proxy a -> Offset Word8 -> Bool
offsetIsAligned _ (Offset ofs) = (ofs .&. mask) == 0
where (CountOf sz) = primSizeInBytes (Proxy :: Proxy a)
mask = sz - 1
# INLINE [ 1 ] offsetIsAligned #
# SPECIALIZE [ 3 ] offsetIsAligned : : Proxy Word64 - > Offset Word8 - > Bool #
# RULES " offsetInAligned Bytes " [ 3 ] forall ( prx : : ) x . offsetIsAligned prx x = True #
primOffsetRecastBytes :: forall b . PrimType b => Offset Word8 -> Offset b
primOffsetRecastBytes (Offset 0) = Offset 0
primOffsetRecastBytes (Offset o) = Offset (szA `Prelude.quot` o)
where !(CountOf szA) = primSizeInBytes (Proxy :: Proxy b)
{-# INLINE [1] primOffsetRecastBytes #-}
primOffsetOfE :: forall a . PrimType a => Offset a -> Offset Word8
primOffsetOfE = offsetInBytes
{-# DEPRECATED primOffsetOfE "use offsetInBytes" #-}
primWordGetByteAndShift :: Word# -> (# Word#, Word# #)
primWordGetByteAndShift w = (# and# w 0xff##, uncheckedShiftRL# w 8# #)
# INLINE primWordGetByteAndShift #
#if WORD_SIZE_IN_BITS == 64
primWord64GetByteAndShift :: Word# -> (# Word#, Word# #)
primWord64GetByteAndShift = primWord64GetByteAndShift
primWord64GetHiLo :: Word# -> (# Word#, Word# #)
primWord64GetHiLo w = (# uncheckedShiftRL# w 32# , and# w 0xffffffff## #)
#else
primWord64GetByteAndShift :: Word64# -> (# Word#, Word64# #)
primWord64GetByteAndShift w = (# and# (word64ToWord# w) 0xff##, uncheckedShiftRL64# w 8# #)
primWord64GetHiLo :: Word64# -> (# Word#, Word# #)
primWord64GetHiLo w = (# word64ToWord# (uncheckedShiftRL64# w 32#), word64ToWord# w #)
#endif
# INLINE primWord64GetByteAndShift #
| null | https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/basement-0.0.11/Basement/PrimType.hs | haskell | License : BSD-style
Stability : experimental
Portability : portable
# INLINE primBaIndex #
Types need to be a instance of storable and have fixed sized.
| type level size of the given `ty`
| get the size in bytes of a ty element
| get the shift size
---
---
| return the element stored at a specific index
---
MutableByteArray section
---
| Read an element at an index in a mutable array
^ mutable array to read from
^ index of the element to retrieve
^ the element returned
| Write an element to a specific cell in a mutable array.
^ mutable array to modify
^ index of the element to modify
^ the new value to store
---
Addr# section
---
| Read from Address, without a state. the value read should be considered a constant for all
pratical purpose, otherwise bad thing will happens.
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
# INLINE primSizeInBytes #
# INLINE primBaUIndex #
# INLINE primAddrIndex #
| A constraint class for serializable type that have an unique
memory compare representation
yet have a different memory representation which doesn't allow
| Cast a CountOf linked to type A (CountOf A) to a CountOf linked to type B (CountOf B)
# INLINE [1] primOffsetRecastBytes #
# DEPRECATED primOffsetOfE "use offsetInBytes" # | Module : Basement .
Maintainer : < >
# LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
# LANGUAGE FlexibleInstances #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE CPP #
module Basement.PrimType
( PrimType(..)
, PrimMemoryComparable
, primBaIndex
, primMbaRead
, primMbaWrite
, primArrayIndex
, primMutableArrayRead
, primMutableArrayWrite
, primOffsetOfE
, primOffsetRecast
, sizeRecast
, offsetAsSize
, sizeAsOffset
, sizeInBytes
, offsetInBytes
, offsetInElements
, offsetIsAligned
, primWordGetByteAndShift
, primWord64GetByteAndShift
, primWord64GetHiLo
) where
#include "MachDeps.h"
import GHC.Prim
import GHC.Int
import GHC.Types
import GHC.Word
import Data.Bits
import Data.Proxy
import Basement.Compat.Base
import Basement.Compat.C.Types
import Basement.Numerical.Subtractive
import Basement.Types.OffsetSize
import Basement.Types.Char7 (Char7(..))
import Basement.Endianness
import Basement.Types.Word128 (Word128(..))
import Basement.Types.Word256 (Word256(..))
import Basement.Monad
import Basement.Nat
import qualified Prelude (quot)
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
#ifdef FOUNDATION_BOUNDS_CHECK
divBytes :: PrimType ty => Offset ty -> (Int -> Int)
divBytes ofs = \x -> x `Prelude.quot` (getSize Proxy ofs)
where
getSize :: PrimType ty => Proxy ty -> Offset ty -> Int
getSize p _ = let (CountOf sz) = primSizeInBytes p in sz
baLength :: PrimType ty => Offset ty -> ByteArray# -> Int
baLength ofs ba = divBytes ofs (I# (sizeofByteArray# ba))
mbaLength :: PrimType ty => Offset ty -> MutableByteArray# st -> Int
mbaLength ofs ba = divBytes ofs (I# (sizeofMutableByteArray# ba))
aLength :: Array# ty -> Int
aLength ba = I# (sizeofArray# ba)
maLength :: MutableArray# st ty -> Int
maLength ba = I# (sizeofMutableArray# ba)
boundCheckError :: [Char] -> Offset ty -> Int -> a
boundCheckError ty (Offset ofs) len =
error (ty <> " offset=" <> show ofs <> " len=" <> show len)
baCheck :: PrimType ty => ByteArray# -> Offset ty -> Bool
baCheck ba ofs@(Offset o) = o < 0 || o >= baLength ofs ba
mbaCheck :: PrimType ty => MutableByteArray# st -> Offset ty -> Bool
mbaCheck mba ofs@(Offset o) = o < 0 || o >= mbaLength ofs mba
aCheck :: Array# ty -> Offset ty -> Bool
aCheck ba (Offset o) = o < 0 || o >= aLength ba
maCheck :: MutableArray# st ty -> Offset ty -> Bool
maCheck ma (Offset o) = o < 0 || o >= maLength ma
primBaIndex :: PrimType ty => ByteArray# -> Offset ty -> ty
primBaIndex ba ofs
| baCheck ba ofs = boundCheckError "bytearray-index" ofs (baLength ofs ba)
| otherwise = primBaUIndex ba ofs
# NOINLINE primBaIndex #
primMbaRead :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> prim ty
primMbaRead mba ofs
| mbaCheck mba ofs = boundCheckError "mutablebytearray-read" ofs (mbaLength ofs mba)
| otherwise = primMbaURead mba ofs
# NOINLINE primMbaRead #
primMbaWrite :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> ty -> prim ()
primMbaWrite mba ofs ty
| mbaCheck mba ofs = boundCheckError "mutablebytearray-write" ofs (mbaLength ofs mba)
| otherwise = primMbaUWrite mba ofs ty
# NOINLINE primMbaWrite #
primArrayIndex :: Array# ty -> Offset ty -> ty
primArrayIndex a o@(Offset (I# ofs))
| aCheck a o = boundCheckError "array-index" o (aLength a)
| otherwise = let !(# v #) = indexArray# a ofs in v
# NOINLINE primArrayIndex #
primMutableArrayRead :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> prim ty
primMutableArrayRead ma o@(Offset (I# ofs))
| maCheck ma o = boundCheckError "array-read" o (maLength ma)
| otherwise = primitive $ \s1 -> readArray# ma ofs s1
# NOINLINE primMutableArrayRead #
primMutableArrayWrite :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> ty -> prim ()
primMutableArrayWrite ma o@(Offset (I# ofs)) v
| maCheck ma o = boundCheckError "array-write" o (maLength ma)
| otherwise = primitive $ \s1 -> let !s2 = writeArray# ma ofs v s1 in (# s2, () #)
# NOINLINE primMutableArrayWrite #
#else
primBaIndex :: PrimType ty => ByteArray# -> Offset ty -> ty
primBaIndex = primBaUIndex
primMbaRead :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> prim ty
primMbaRead = primMbaURead
# INLINE primMbaRead #
primMbaWrite :: (PrimType ty, PrimMonad prim) => MutableByteArray# (PrimState prim) -> Offset ty -> ty -> prim ()
primMbaWrite = primMbaUWrite
# INLINE primMbaWrite #
primArrayIndex :: Array# ty -> Offset ty -> ty
primArrayIndex a (Offset (I# ofs)) = let !(# v #) = indexArray# a ofs in v
# INLINE primArrayIndex #
primMutableArrayRead :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> prim ty
primMutableArrayRead ma (Offset (I# ofs)) = primitive $ \s1 -> readArray# ma ofs s1
# INLINE primMutableArrayRead #
primMutableArrayWrite :: PrimMonad prim => MutableArray# (PrimState prim) ty -> Offset ty -> ty -> prim ()
primMutableArrayWrite ma (Offset (I# ofs)) v =
primitive $ \s1 -> let !s2 = writeArray# ma ofs v s1 in (# s2, () #)
# INLINE primMutableArrayWrite #
#endif
| Represent the accessor for types that can be stored in the UArray and MUArray .
class Eq ty => PrimType ty where
type PrimSize ty :: Nat
primSizeInBytes :: Proxy ty -> CountOf Word8
primShiftToBytes :: Proxy ty -> Int
ByteArray section
primBaUIndex :: ByteArray# -> Offset ty -> ty
primMbaURead :: PrimMonad prim
primMbaUWrite :: PrimMonad prim
-> prim ()
primAddrIndex :: Addr# -> Offset ty -> ty
| Read a value from Addr in a specific primitive monad
primAddrRead :: PrimMonad prim
=> Addr#
-> Offset ty
-> prim ty
| Write a value to Addr in a specific primitive monad
primAddrWrite :: PrimMonad prim
=> Addr#
-> Offset ty
-> ty
-> prim ()
sizeInt, sizeWord :: CountOf Word8
shiftInt, shiftWord :: Int
#if WORD_SIZE_IN_BITS == 64
sizeInt = CountOf 8
sizeWord = CountOf 8
shiftInt = 3
shiftWord = 3
#else
sizeInt = CountOf 4
sizeWord = CountOf 4
shiftInt = 2
shiftWord = 2
#endif
# SPECIALIZE [ 3 ] primBaUIndex : : # - > Offset Word8 - > Word8 #
instance PrimType Int where
#if WORD_SIZE_IN_BITS == 64
type PrimSize Int = 8
#else
type PrimSize Int = 4
#endif
primSizeInBytes _ = sizeInt
primShiftToBytes _ = shiftInt
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I# (indexIntArray# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readIntArray# mba n s1 in (# s2, I# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I# w) = primitive $ \s1 -> (# writeIntArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I# (indexIntOffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readIntOffAddr# addr n s1 in (# s2, I# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I# w) = primitive $ \s1 -> (# writeIntOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word where
#if WORD_SIZE_IN_BITS == 64
type PrimSize Word = 8
#else
type PrimSize Word = 4
#endif
primSizeInBytes _ = sizeWord
primShiftToBytes _ = shiftWord
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W# (indexWordArray# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWordArray# mba n s1 in (# s2, W# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W# w) = primitive $ \s1 -> (# writeWordArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W# (indexWordOffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWordOffAddr# addr n s1 in (# s2, W# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W# w) = primitive $ \s1 -> (# writeWordOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word8 where
type PrimSize Word8 = 1
primSizeInBytes _ = CountOf 1
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W8# (indexWord8Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord8Array# mba n s1 in (# s2, W8# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W8# w) = primitive $ \s1 -> (# writeWord8Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W8# (indexWord8OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord8OffAddr# addr n s1 in (# s2, W8# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W8# w) = primitive $ \s1 -> (# writeWord8OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word16 where
type PrimSize Word16 = 2
primSizeInBytes _ = CountOf 2
primShiftToBytes _ = 1
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W16# (indexWord16Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord16Array# mba n s1 in (# s2, W16# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W16# w) = primitive $ \s1 -> (# writeWord16Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W16# (indexWord16OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord16OffAddr# addr n s1 in (# s2, W16# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W16# w) = primitive $ \s1 -> (# writeWord16OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word32 where
type PrimSize Word32 = 4
primSizeInBytes _ = CountOf 4
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W32# (indexWord32Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord32Array# mba n s1 in (# s2, W32# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W32# w) = primitive $ \s1 -> (# writeWord32Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W32# (indexWord32OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord32OffAddr# addr n s1 in (# s2, W32# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W32# w) = primitive $ \s1 -> (# writeWord32OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word64 where
type PrimSize Word64 = 8
primSizeInBytes _ = CountOf 8
primShiftToBytes _ = 3
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = W64# (indexWord64Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord64Array# mba n s1 in (# s2, W64# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (W64# w) = primitive $ \s1 -> (# writeWord64Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = W64# (indexWord64OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWord64OffAddr# addr n s1 in (# s2, W64# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (W64# w) = primitive $ \s1 -> (# writeWord64OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Word128 where
type PrimSize Word128 = 16
primSizeInBytes _ = CountOf 16
primShiftToBytes _ = 4
# INLINE primShiftToBytes #
primBaUIndex ba n =
Word128 (W64# (indexWord64Array# ba n1)) (W64# (indexWord64Array# ba n2))
where (# n1, n2 #) = offset128_64 n
primMbaURead mba n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64Array# mba n1 s1
!(# s3, r2 #) = readWord64Array# mba n2 s2
in (# s3, Word128 (W64# r1) (W64# r2) #)
where (# n1, n2 #) = offset128_64 n
# INLINE primMbaURead #
primMbaUWrite mba n (Word128 (W64# w1) (W64# w2)) = primitive $ \s1 ->
let !s2 = writeWord64Array# mba n1 w1 s1
in (# writeWord64Array# mba n2 w2 s2, () #)
where (# n1, n2 #) = offset128_64 n
# INLINE primMbaUWrite #
primAddrIndex addr n = Word128 (W64# (indexWord64OffAddr# addr n1)) (W64# (indexWord64OffAddr# addr n2))
where (# n1, n2 #) = offset128_64 n
primAddrRead addr n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64OffAddr# addr n1 s1
!(# s3, r2 #) = readWord64OffAddr# addr n2 s2
in (# s3, Word128 (W64# r1) (W64# r2) #)
where (# n1, n2 #) = offset128_64 n
# INLINE primAddrRead #
primAddrWrite addr n (Word128 (W64# w1) (W64# w2)) = primitive $ \s1 ->
let !s2 = writeWord64OffAddr# addr n1 w1 s1
in (# writeWord64OffAddr# addr n2 w2 s2, () #)
where (# n1, n2 #) = offset128_64 n
# INLINE primAddrWrite #
instance PrimType Word256 where
type PrimSize Word256 = 32
primSizeInBytes _ = CountOf 32
primShiftToBytes _ = 5
# INLINE primShiftToBytes #
primBaUIndex ba n =
Word256 (W64# (indexWord64Array# ba n1)) (W64# (indexWord64Array# ba n2))
(W64# (indexWord64Array# ba n3)) (W64# (indexWord64Array# ba n4))
where (# n1, n2, n3, n4 #) = offset256_64 n
primMbaURead mba n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64Array# mba n1 s1
!(# s3, r2 #) = readWord64Array# mba n2 s2
!(# s4, r3 #) = readWord64Array# mba n3 s3
!(# s5, r4 #) = readWord64Array# mba n4 s4
in (# s5, Word256 (W64# r1) (W64# r2) (W64# r3) (W64# r4) #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primMbaURead #
primMbaUWrite mba n (Word256 (W64# w1) (W64# w2) (W64# w3) (W64# w4)) = primitive $ \s1 ->
let !s2 = writeWord64Array# mba n1 w1 s1
!s3 = writeWord64Array# mba n2 w2 s2
!s4 = writeWord64Array# mba n3 w3 s3
in (# writeWord64Array# mba n4 w4 s4, () #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primMbaUWrite #
primAddrIndex addr n = Word256 (W64# (indexWord64OffAddr# addr n1)) (W64# (indexWord64OffAddr# addr n2))
(W64# (indexWord64OffAddr# addr n3)) (W64# (indexWord64OffAddr# addr n4))
where (# n1, n2, n3, n4 #) = offset256_64 n
primAddrRead addr n = primitive $ \s1 -> let !(# s2, r1 #) = readWord64OffAddr# addr n1 s1
!(# s3, r2 #) = readWord64OffAddr# addr n2 s2
!(# s4, r3 #) = readWord64OffAddr# addr n3 s3
!(# s5, r4 #) = readWord64OffAddr# addr n4 s4
in (# s5, Word256 (W64# r1) (W64# r2) (W64# r3) (W64# r4) #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primAddrRead #
primAddrWrite addr n (Word256 (W64# w1) (W64# w2) (W64# w3) (W64# w4)) = primitive $ \s1 ->
let !s2 = writeWord64OffAddr# addr n1 w1 s1
!s3 = writeWord64OffAddr# addr n2 w2 s2
!s4 = writeWord64OffAddr# addr n3 w3 s3
in (# writeWord64OffAddr# addr n4 w4 s4, () #)
where (# n1, n2, n3, n4 #) = offset256_64 n
# INLINE primAddrWrite #
instance PrimType Int8 where
type PrimSize Int8 = 1
primSizeInBytes _ = CountOf 1
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I8# (indexInt8Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt8Array# mba n s1 in (# s2, I8# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I8# w) = primitive $ \s1 -> (# writeInt8Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I8# (indexInt8OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt8OffAddr# addr n s1 in (# s2, I8# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I8# w) = primitive $ \s1 -> (# writeInt8OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Int16 where
type PrimSize Int16 = 2
primSizeInBytes _ = CountOf 2
primShiftToBytes _ = 1
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I16# (indexInt16Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt16Array# mba n s1 in (# s2, I16# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I16# w) = primitive $ \s1 -> (# writeInt16Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I16# (indexInt16OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt16OffAddr# addr n s1 in (# s2, I16# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I16# w) = primitive $ \s1 -> (# writeInt16OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Int32 where
type PrimSize Int32 = 4
primSizeInBytes _ = CountOf 4
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I32# (indexInt32Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt32Array# mba n s1 in (# s2, I32# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I32# w) = primitive $ \s1 -> (# writeInt32Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I32# (indexInt32OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt32OffAddr# addr n s1 in (# s2, I32# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I32# w) = primitive $ \s1 -> (# writeInt32OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Int64 where
type PrimSize Int64 = 8
primSizeInBytes _ = CountOf 8
primShiftToBytes _ = 3
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = I64# (indexInt64Array# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt64Array# mba n s1 in (# s2, I64# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (I64# w) = primitive $ \s1 -> (# writeInt64Array# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = I64# (indexInt64OffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readInt64OffAddr# addr n s1 in (# s2, I64# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (I64# w) = primitive $ \s1 -> (# writeInt64OffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Float where
type PrimSize Float = 4
primSizeInBytes _ = CountOf 4
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = F# (indexFloatArray# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readFloatArray# mba n s1 in (# s2, F# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (F# w) = primitive $ \s1 -> (# writeFloatArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = F# (indexFloatOffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readFloatOffAddr# addr n s1 in (# s2, F# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (F# w) = primitive $ \s1 -> (# writeFloatOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Double where
type PrimSize Double = 8
primSizeInBytes _ = CountOf 8
primShiftToBytes _ = 3
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = D# (indexDoubleArray# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readDoubleArray# mba n s1 in (# s2, D# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (D# w) = primitive $ \s1 -> (# writeDoubleArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = D# (indexDoubleOffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readDoubleOffAddr# addr n s1 in (# s2, D# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (D# w) = primitive $ \s1 -> (# writeDoubleOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType Char where
type PrimSize Char = 4
primSizeInBytes _ = CountOf 4
primShiftToBytes _ = 2
# INLINE primShiftToBytes #
primBaUIndex ba (Offset (I# n)) = C# (indexWideCharArray# ba n)
primMbaURead mba (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWideCharArray# mba n s1 in (# s2, C# r #)
# INLINE primMbaURead #
primMbaUWrite mba (Offset (I# n)) (C# w) = primitive $ \s1 -> (# writeWideCharArray# mba n w s1, () #)
# INLINE primMbaUWrite #
primAddrIndex addr (Offset (I# n)) = C# (indexWideCharOffAddr# addr n)
primAddrRead addr (Offset (I# n)) = primitive $ \s1 -> let !(# s2, r #) = readWideCharOffAddr# addr n s1 in (# s2, C# r #)
# INLINE primAddrRead #
primAddrWrite addr (Offset (I# n)) (C# w) = primitive $ \s1 -> (# writeWideCharOffAddr# addr n w s1, () #)
# INLINE primAddrWrite #
instance PrimType CChar where
type PrimSize CChar = 1
primSizeInBytes _ = CountOf 1
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset n) = CChar (primBaUIndex ba (Offset n))
primMbaURead mba (Offset n) = CChar <$> primMbaURead mba (Offset n)
# INLINE primMbaURead #
primMbaUWrite mba (Offset n) (CChar int8) = primMbaUWrite mba (Offset n) int8
# INLINE primMbaUWrite #
primAddrIndex addr (Offset n) = CChar $ primAddrIndex addr (Offset n)
primAddrRead addr (Offset n) = CChar <$> primAddrRead addr (Offset n)
# INLINE primAddrRead #
primAddrWrite addr (Offset n) (CChar int8) = primAddrWrite addr (Offset n) int8
# INLINE primAddrWrite #
instance PrimType CUChar where
type PrimSize CUChar = 1
primSizeInBytes _ = CountOf 1
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset n) = CUChar (primBaUIndex ba (Offset n :: Offset Word8))
primMbaURead mba (Offset n) = CUChar <$> primMbaURead mba (Offset n :: Offset Word8)
# INLINE primMbaURead #
primMbaUWrite mba (Offset n) (CUChar w8) = primMbaUWrite mba (Offset n) w8
# INLINE primMbaUWrite #
primAddrIndex addr (Offset n) = CUChar $ primAddrIndex addr (Offset n :: Offset Word8)
primAddrRead addr (Offset n) = CUChar <$> primAddrRead addr (Offset n :: Offset Word8)
# INLINE primAddrRead #
primAddrWrite addr (Offset n) (CUChar w8) = primAddrWrite addr (Offset n) w8
# INLINE primAddrWrite #
instance PrimType Char7 where
type PrimSize Char7 = 1
primSizeInBytes _ = CountOf 1
primShiftToBytes _ = 0
# INLINE primShiftToBytes #
primBaUIndex ba (Offset n) = Char7 (primBaUIndex ba (Offset n :: Offset Word8))
primMbaURead mba (Offset n) = Char7 <$> primMbaURead mba (Offset n :: Offset Word8)
# INLINE primMbaURead #
primMbaUWrite mba (Offset n) (Char7 w8) = primMbaUWrite mba (Offset n) w8
# INLINE primMbaUWrite #
primAddrIndex addr (Offset n) = Char7 $ primAddrIndex addr (Offset n :: Offset Word8)
primAddrRead addr (Offset n) = Char7 <$> primAddrRead addr (Offset n :: Offset Word8)
# INLINE primAddrRead #
primAddrWrite addr (Offset n) (Char7 w8) = primAddrWrite addr (Offset n) w8
# INLINE primAddrWrite #
instance PrimType a => PrimType (LE a) where
type PrimSize (LE a) = PrimSize a
primSizeInBytes _ = primSizeInBytes (Proxy :: Proxy a)
primShiftToBytes _ = primShiftToBytes (Proxy :: Proxy a)
# INLINE primShiftToBytes #
primBaUIndex ba (Offset a) = LE $ primBaUIndex ba (Offset a)
primMbaURead ba (Offset a) = LE <$> primMbaURead ba (Offset a)
# INLINE primMbaURead #
primMbaUWrite mba (Offset a) (LE w) = primMbaUWrite mba (Offset a) w
# INLINE primMbaUWrite #
primAddrIndex addr (Offset a) = LE $ primAddrIndex addr (Offset a)
primAddrRead addr (Offset a) = LE <$> primAddrRead addr (Offset a)
# INLINE primAddrRead #
primAddrWrite addr (Offset a) (LE w) = primAddrWrite addr (Offset a) w
# INLINE primAddrWrite #
instance PrimType a => PrimType (BE a) where
type PrimSize (BE a) = PrimSize a
primSizeInBytes _ = primSizeInBytes (Proxy :: Proxy a)
primShiftToBytes _ = primShiftToBytes (Proxy :: Proxy a)
# INLINE primShiftToBytes #
primBaUIndex ba (Offset a) = BE $ primBaUIndex ba (Offset a)
primMbaURead ba (Offset a) = BE <$> primMbaURead ba (Offset a)
# INLINE primMbaURead #
primMbaUWrite mba (Offset a) (BE w) = primMbaUWrite mba (Offset a) w
# INLINE primMbaUWrite #
primAddrIndex addr (Offset a) = BE $ primAddrIndex addr (Offset a)
primAddrRead addr (Offset a) = BE <$> primAddrRead addr (Offset a)
# INLINE primAddrRead #
primAddrWrite addr (Offset a) (BE w) = primAddrWrite addr (Offset a) w
# INLINE primAddrWrite #
e.g. Float and Double have -0.0 and 0.0 which are Eq individual ,
for memcmp operation
class PrimMemoryComparable ty where
instance PrimMemoryComparable Int where
instance PrimMemoryComparable Word where
instance PrimMemoryComparable Word8 where
instance PrimMemoryComparable Word16 where
instance PrimMemoryComparable Word32 where
instance PrimMemoryComparable Word64 where
instance PrimMemoryComparable Word128 where
instance PrimMemoryComparable Word256 where
instance PrimMemoryComparable Int8 where
instance PrimMemoryComparable Int16 where
instance PrimMemoryComparable Int32 where
instance PrimMemoryComparable Int64 where
instance PrimMemoryComparable Char where
instance PrimMemoryComparable CChar where
instance PrimMemoryComparable CUChar where
instance PrimMemoryComparable a => PrimMemoryComparable (LE a) where
instance PrimMemoryComparable a => PrimMemoryComparable (BE a) where
offset128_64 :: Offset Word128 -> (# Int#, Int# #)
offset128_64 (Offset (I# i)) = (# n , n +# 1# #)
where !n = uncheckedIShiftL# i 1#
offset256_64 :: Offset Word256 -> (# Int#, Int#, Int#, Int# #)
offset256_64 (Offset (I# i)) = (# n , n +# 1#, n +# 2#, n +# 3# #)
where !n = uncheckedIShiftL# i 2#
sizeRecast :: forall a b . (PrimType a, PrimType b) => CountOf a -> CountOf b
sizeRecast sz = CountOf (bytes `Prelude.quot` szB)
where !szA = primSizeInBytes (Proxy :: Proxy a)
!(CountOf szB) = primSizeInBytes (Proxy :: Proxy b)
!(CountOf bytes) = sizeOfE szA sz
# INLINE [ 1 ] sizeRecast #
# RULES " sizeRecast from " [ 2 ] forall a . sizeRecast a = sizeRecastBytes a #
sizeRecastBytes :: forall b . PrimType b => CountOf Word8 -> CountOf b
sizeRecastBytes (CountOf w) = CountOf (w `Prelude.quot` szB)
where !(CountOf szB) = primSizeInBytes (Proxy :: Proxy b)
# INLINE [ 1 ] sizeRecastBytes #
sizeInBytes :: forall a . PrimType a => CountOf a -> CountOf Word8
sizeInBytes sz = sizeOfE (primSizeInBytes (Proxy :: Proxy a)) sz
offsetInBytes :: forall a . PrimType a => Offset a -> Offset Word8
offsetInBytes ofs = offsetShiftL (primShiftToBytes (Proxy :: Proxy a)) ofs
# INLINE [ 2 ] offsetInBytes #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word64 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word32 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word16 - > Offset Word8 #
# RULES " offsetInBytes Bytes " [ 3 ] forall x . offsetInBytes x = x #
offsetInElements :: forall a . PrimType a => Offset Word8 -> Offset a
offsetInElements ofs = offsetShiftR (primShiftToBytes (Proxy :: Proxy a)) ofs
# INLINE [ 2 ] offsetInElements #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word64 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word32 - > Offset Word8 #
# SPECIALIZE INLINE [ 3 ] offsetInBytes : : Offset Word16 - > Offset Word8 #
# RULES " offsetInElements Bytes " [ 3 ] forall x . offsetInElements x = x #
primOffsetRecast :: forall a b . (PrimType a, PrimType b) => Offset a -> Offset b
primOffsetRecast !ofs =
let !(Offset bytes) = offsetOfE szA ofs
in Offset (bytes `Prelude.quot` szB)
where
!szA = primSizeInBytes (Proxy :: Proxy a)
!(CountOf szB) = primSizeInBytes (Proxy :: Proxy b)
# INLINE [ 1 ] primOffsetRecast #
# RULES " primOffsetRecast W8 " [ 3 ] forall a . primOffsetRecast a = primOffsetRecastBytes a #
offsetIsAligned :: forall a . PrimType a => Proxy a -> Offset Word8 -> Bool
offsetIsAligned _ (Offset ofs) = (ofs .&. mask) == 0
where (CountOf sz) = primSizeInBytes (Proxy :: Proxy a)
mask = sz - 1
# INLINE [ 1 ] offsetIsAligned #
# SPECIALIZE [ 3 ] offsetIsAligned : : Proxy Word64 - > Offset Word8 - > Bool #
# RULES " offsetInAligned Bytes " [ 3 ] forall ( prx : : ) x . offsetIsAligned prx x = True #
primOffsetRecastBytes :: forall b . PrimType b => Offset Word8 -> Offset b
primOffsetRecastBytes (Offset 0) = Offset 0
primOffsetRecastBytes (Offset o) = Offset (szA `Prelude.quot` o)
where !(CountOf szA) = primSizeInBytes (Proxy :: Proxy b)
primOffsetOfE :: forall a . PrimType a => Offset a -> Offset Word8
primOffsetOfE = offsetInBytes
primWordGetByteAndShift :: Word# -> (# Word#, Word# #)
primWordGetByteAndShift w = (# and# w 0xff##, uncheckedShiftRL# w 8# #)
# INLINE primWordGetByteAndShift #
#if WORD_SIZE_IN_BITS == 64
primWord64GetByteAndShift :: Word# -> (# Word#, Word# #)
primWord64GetByteAndShift = primWord64GetByteAndShift
primWord64GetHiLo :: Word# -> (# Word#, Word# #)
primWord64GetHiLo w = (# uncheckedShiftRL# w 32# , and# w 0xffffffff## #)
#else
primWord64GetByteAndShift :: Word64# -> (# Word#, Word64# #)
primWord64GetByteAndShift w = (# and# (word64ToWord# w) 0xff##, uncheckedShiftRL64# w 8# #)
primWord64GetHiLo :: Word64# -> (# Word#, Word# #)
primWord64GetHiLo w = (# word64ToWord# (uncheckedShiftRL64# w 32#), word64ToWord# w #)
#endif
# INLINE primWord64GetByteAndShift #
|
816a5cdb22dcdda48c49921b8f3cc15bd760b184922b73626ee076f059376575 | clj-kondo/config | config.clj | (ns clj-kondo.config
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.cli :refer [parse-opts]]
[cpath-clj.core :as cp]))
(def cli-options
[["-l" "--lib LIBRARY" "Library"
:default []
:assoc-fn (fn [m k v]
(update m k (fnil conj []) v))]])
(defn delete-files-recursively
([f1] (delete-files-recursively f1 false))
([f1 silently]
(when (.isDirectory (io/file f1))
(doseq [f2 (.listFiles (io/file f1))]
(delete-files-recursively f2 silently)))
(io/delete-file f1 silently)))
(defn -main [& args]
(let [{:keys [:lib ]} (:options (parse-opts args cli-options))]
(doseq [l lib]
(if-let [resource (io/resource (str "clj-kondo.exports/clj-kondo/" l))]
(let [config-dir (io/file ".clj-kondo" "configs" l)]
(when (.exists config-dir)
(println "Removing previous" l "config in" (.getPath config-dir))
(delete-files-recursively config-dir))
(println "Copying" l "config to" (.getPath config-dir))
(doseq [[path uris] (cp/resources resource)
:let [uri (first uris)
relative-path (subs path 1)
output-file (io/file config-dir relative-path)]]
(io/make-parents output-file)
(with-open [in (io/input-stream uri)]
(io/copy in output-file))))
(println "No config found for " l)))
(println "Add" (str/join
", "
(map (fn [lib]
(pr-str (.getPath (io/file "configs" lib))))
lib))
"to :config-paths in .clj-kondo/config.edn to activate configs.")))
| null | https://raw.githubusercontent.com/clj-kondo/config/b31c108bf13ece623850596363d2cb7350a5e5fe/src/clj_kondo/config.clj | clojure | (ns clj-kondo.config
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.tools.cli :refer [parse-opts]]
[cpath-clj.core :as cp]))
(def cli-options
[["-l" "--lib LIBRARY" "Library"
:default []
:assoc-fn (fn [m k v]
(update m k (fnil conj []) v))]])
(defn delete-files-recursively
([f1] (delete-files-recursively f1 false))
([f1 silently]
(when (.isDirectory (io/file f1))
(doseq [f2 (.listFiles (io/file f1))]
(delete-files-recursively f2 silently)))
(io/delete-file f1 silently)))
(defn -main [& args]
(let [{:keys [:lib ]} (:options (parse-opts args cli-options))]
(doseq [l lib]
(if-let [resource (io/resource (str "clj-kondo.exports/clj-kondo/" l))]
(let [config-dir (io/file ".clj-kondo" "configs" l)]
(when (.exists config-dir)
(println "Removing previous" l "config in" (.getPath config-dir))
(delete-files-recursively config-dir))
(println "Copying" l "config to" (.getPath config-dir))
(doseq [[path uris] (cp/resources resource)
:let [uri (first uris)
relative-path (subs path 1)
output-file (io/file config-dir relative-path)]]
(io/make-parents output-file)
(with-open [in (io/input-stream uri)]
(io/copy in output-file))))
(println "No config found for " l)))
(println "Add" (str/join
", "
(map (fn [lib]
(pr-str (.getPath (io/file "configs" lib))))
lib))
"to :config-paths in .clj-kondo/config.edn to activate configs.")))
|
|
fd37df7adccabff0dcb7f39651e6a3c57f7a19add9c849375ef924d386c66c0e | dscarpetti/codax | core_test.clj | (ns codax.core-test
(:require [clojure.test :refer :all]
[codax.test-logging :refer [logln]]
[codax.core :refer :all]
[codax.store :refer [destroy-database]]
[codax.swaps :refer :all]))
(def ^:dynamic *testing-database* nil)
(defn store-setup-and-teardown [f]
(binding [*testing-database* (open-database! "test-databases/core")]
( logln " SETUP " )
(f))
(destroy-database "test-databases/core"))
(use-fixtures :each store-setup-and-teardown)
(defmacro wrc [write-tx read-tx final-value]
`(is
(=
(do
(with-write-transaction [~'*testing-database* ~'tx]
~write-tx)
(let [x#
(with-read-transaction [~'*testing-database* ~'tx]
~read-tx)]
( logln x # )
x#))
~final-value)))
(defmacro rc [read-tx final-value]
`(is
(=
(let [x#
(with-read-transaction [~'*testing-database* ~'tx]
~read-tx)]
( logln x # )
x#)
~final-value)))
(deftest single-assoc-at
(wrc
(assoc-at tx [1 "a" :b 1.0 'c] ["x"])
(get-at tx [1 "a" :b 1.0 'c])
["x"])
(rc
(get-at tx [1 "a" :b 1.0])
{'c ["x"]})
(rc
(get-at tx [1 "a" :b])
{1.0 {'c ["x"]}})
(rc
(get-at tx [1 "a"])
{:b {1.0 {'c ["x"]}}})
(rc
(get-at tx [1])
{"a" {:b {1.0 {'c ["x"]}}}})
(rc
(get-at tx [])
{1 {"a" {:b {1.0 {'c ["x"]}}}}})
(rc
(get-at tx nil)
{1 {"a" {:b {1.0 {'c ["x"]}}}}}))
(deftest assoc-at+dissoc-at
(wrc
(assoc-at tx [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Mr"})
(rc
(get-at tx [-1])
{:people {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}}})
(wrc
(dissoc-at tx [-1 :people "Sam" :title])
(get-at tx [-1 :people "Sam"])
{:name "Sam"})
(wrc
(dissoc-at tx [-1 :people "Sam"])
(get-at tx [-1 :people "Sam"])
nil)
(rc
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}}}))
(deftest assoc-at+assoc-at-overwrite
(wrc
(assoc-at tx [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Mr"})
(rc
(get-at tx [-1])
{:people {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}}})
(wrc
(assoc-at tx [-1 :people "Sam" :title] "Sir")
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Sir"})
(wrc
(assoc-at tx [-1 :people "Sam"] {:name "Sammy" :profession "Go"})
(get-at tx [-1 :people "Sam"])
{:name "Sammy"
:profession "Go"})
(rc
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:profession "Go"}}}))
(deftest assoc-at+merge-at-overwrite
(wrc
(assoc-at tx [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Mr"})
(rc
(get-at tx [-1])
{:people {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}}})
(wrc
(merge-at tx [-1 :people "Sam"] {:title "Sir"})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Sir"})
(wrc
(merge-at tx [-1 :people "Sam"] {:name "Sammy" :profession "Go"})
(get-at tx [-1 :people "Sam"])
{:name "Sammy"
:title "Sir"
:profession "Go"})
(rc
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:title "Sir"
:profession "Go"}}}))
;;;;;
(deftest one-write-assoc-at+dissoc-at
(wrc
(-> tx
(assoc-at [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(dissoc-at [-1 :people "Sam" :title])
(dissoc-at [-1 :people "Sam"]))
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}}}))
(deftest one-write-assoc-at+assoc-at-overwrite
(wrc
(-> tx
(assoc-at [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(assoc-at [-1 :people "Sam" :title] "Sir")
(assoc-at [-1 :people "Sam"] {:name "Sammy" :profession "Go"}))
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:profession "Go"}}}))
(deftest one-write-assoc-at+merge-at
(wrc
(-> tx
(assoc-at [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(merge-at [-1 :people "Sam"] {:title "Sir"})
(merge-at [-1 :people "Sam"] {:name "Sammy" :profession "Go"}))
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:title "Sir"
:profession "Go"}}}))
(deftest write-transaction-without-final-tx
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Transaction"
(with-write-transaction [*testing-database* tx]))))
(deftest write-transaction-with-invalid-database-nil
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Database"
(with-write-transaction [nil tx]))))
(deftest write-transaction-with-invalid-database-2
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Database"
(with-write-transaction [2 tx]))))
(deftest write-transaction-with-invalid-database-map
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Database"
(with-write-transaction [{} tx]))))
(deftest assoc-at-without-txn
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Transaction"
(assoc-at "no-tx" [:a] "something"))))
(deftest failed-assoc-empty-path
(try
(with-write-transaction [*testing-database* tx]
(assoc-at tx [] "failure"))
(catch clojure.lang.ExceptionInfo e
(let [{:keys [cause] :as data} (ex-data e)]
(logln data)
(is (= (.getMessage e) "Invalid Path"))
(is (= cause :empty-path))))))
(deftest failed-assoc+extended-past-existing
(try
(with-write-transaction [*testing-database* tx]
(-> tx
(assoc-at [:hello] "value here")
(assoc-at [:hello :world] "failure")))
(catch clojure.lang.ExceptionInfo e
(let [{:keys [cause] :as data} (ex-data e)]
(logln data)
(is (= (.getMessage e) "Occupied Path"))
(is (= cause :non-map-element))))))
(deftest failed-assoc+extended-past-existing-separate-transactions
(try
(do
(with-write-transaction [*testing-database* tx]
(assoc-at tx [:something] "value here"))
(with-write-transaction [*testing-database* tx]
(assoc-at tx [:hello :world] "failure")))
(catch clojure.lang.ExceptionInfo e
(let [{:keys [cause] :as data} (ex-data e)]
(logln data)
(is (= (.getMessage e) "Occupied Path"))
(is (= cause :non-map-element))))))
(defn increment-path [db]
(with-write-transaction [db tx]
(update-at tx [:metrics :user-counts :all] inc-count)))
(defn increment-test [db n]
(let [database db
ops (repeat n #(increment-path database))]
(doall (pmap #(%) ops))
(is (=
n
(with-read-transaction [database tx]
(get-at tx [:metrics :user-counts :all]))))))
(deftest inc-test
(increment-test *testing-database* 1000))
;;;; convenience function tests
(deftest assoc-at!-test
(is (=
(assoc-at! *testing-database* [:letters] {:a 1 :b 2})
(get-at! *testing-database* [:letters])
{:a 1 :b 2}))
(is (=
(get-at! *testing-database*)
{:letters {:a 1 :b 2}})))
(deftest update-at!-test
(let [add (fn [x y] (+ x y))
subtract (fn [x y] (- x y))]
(is (= 1 (update-at! *testing-database* [:count] inc-count)))
(is (= 2 (update-at! *testing-database* [:count] inc-count)))
(is (= 12 (update-at! *testing-database* [:count] add 10)))
(is (= 7 (update-at! *testing-database* [:count] subtract 5)))
(is (= 7 (get-at! *testing-database* [:count])))))
(deftest merge-at!-test
(is (=
(assoc-at! *testing-database* [:letters] {:a 1 :b 2})
(get-at! *testing-database* [:letters])
{:a 1 :b 2}))
(is (=
(merge-at! *testing-database* [:letters] {:c 3 :d 4})
(get-at! *testing-database* [:letters])
{:a 1 :b 2 :c 3 :d 4}))
(is (=
(get-at! *testing-database*)
{:letters {:a 1 :b 2 :c 3 :d 4}})))
(deftest dissoc-at!-test
(is (=
(assoc-at! *testing-database* [:letters] {:a 1 :b 2 :c 3})
(get-at! *testing-database* [:letters])
{:a 1 :b 2 :c 3}))
(is (=
(dissoc-at! *testing-database* [:letters :c])
nil))
(is (=
(get-at! *testing-database* [:letters])
{:a 1 :b 2}))
(is (=
(dissoc-at! *testing-database* [:letters])
(get-at! *testing-database* [:letters])
nil))
(is (=
(get-at! *testing-database*)
{})))
(deftest is-open?-and-close-all
(is (not (is-open? "test-databases/coreA")))
(is (not (is-open? "test-databases/coreB")))
(is (not (is-open? "test-databases/coreC")))
(let [a (open-database! "test-databases/coreA")
b (open-database! "test-databases/coreB")
c (open-database! "test-databases/coreC")]
(is (is-open? a))
(is (is-open? b))
(is (is-open? c))
(is (is-open? "test-databases/coreA"))
(is (is-open? "test-databases/coreB"))
(is (is-open? "test-databases/coreC"))
(close-all-databases!)
(is (not (is-open? a)))
(is (not (is-open? b)))
(is (not (is-open? c)))
(is (not (is-open? "test-databases/coreA")))
(is (not (is-open? "test-databases/coreB")))
(is (not (is-open? "test-databases/coreC")))))
;; -- consistency validation --
(deftest extend-nil-path-with-val
(is (=
(assoc-at! *testing-database* [:a] nil)
nil))
(is (=
(assoc-at! *testing-database* [:a :b] "val")
"val"))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-nil-path-with-map
(is (=
(assoc-at! *testing-database* [:a] nil)
nil))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-val-path-with-val
(is (=
(assoc-at! *testing-database* [:a] "anything")
"anything"))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b] "val")))
(is (=
(get-at! *testing-database*)
{:a "anything"})))
(deftest extend-val-path-with-map
(is (=
(assoc-at! *testing-database* [:a] "anything")
"anything"))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-val-path-with-val-long
(is (=
(assoc-at! *testing-database* [:a :b] "anything")
"anything"))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b :c] "val")))
(is (=
(get-at! *testing-database*)
{:a {:b "anything"}})))
(deftest extend-val-path-with-partial-val-long
(is (=
(assoc-at! *testing-database* [:a] "anything")
"anything"))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b :c] "val")))
(is (=
(get-at! *testing-database*)
{:a "anything"})))
(deftest extend-val-path-with-partial-map-long
(is (=
(assoc-at! *testing-database* [:a :b] "anything")
"anything"))
(is (=
(assoc-at! *testing-database* [:a] {:b {:c "val"}})
{:b {:c "val"}}))
(is (=
(get-at! *testing-database*)
{:a {:b {:c "val"}}})))
(deftest extend-val-path-with-map-long
(is (=
(assoc-at! *testing-database* [:a :b] "anything")
"anything"))
(is (=
(assoc-at! *testing-database* [:a :b] {:c "val"})
{:c "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b {:c "val"}}})))
(deftest extend-false-path-with-val
(is (=
(assoc-at! *testing-database* [:a] false)
false))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b] "val")))
(is (=
(get-at! *testing-database*)
{:a false})))
(deftest extend-false-path-with-map
(is (=
(assoc-at! *testing-database* [:a] false)
false))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-vec-path-with-val
(is (=
(assoc-at! *testing-database* [:a] [])
[]))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b] "val")))
(is (=
(get-at! *testing-database*)
{:a []})))
(deftest extend-vec-path-with-map
(is (=
(assoc-at! *testing-database* [:a] [])
[]))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
;; --- path conversions ---
(deftest path-conversion-from-val
(is (=
(assoc-at! *testing-database* :foo "bar")
"bar"))
(is (=
(get-at! *testing-database*))
{:foo "bar"}))
(deftest path-conversion-from-list
(is (=
(assoc-at! *testing-database* (list :foo :bar) "baz")
"baz"))
(is (=
(get-at! *testing-database*))
{:foo {:bar "baz"}}))
(deftest path-conversion-from-seq
(is (=
(assoc-at! *testing-database* (map identity [:foo :bar]) "baz")
"baz"))
(is (=
(get-at! *testing-database*))
{:foo {:bar "baz"}}))
(deftest manifest-overgrowth
(let [put! (fn []
(doseq [n (range 500)]
(assoc-at! *testing-database* n n)))
get-manifest-size #(-> *testing-database* :data deref :manifest count)
_ (put!)
presize (get-manifest-size)
_ (put!)
postsize (get-manifest-size)]
(is (= presize postsize))))
| null | https://raw.githubusercontent.com/dscarpetti/codax/68edc73dbdfe4d33f5d08f658052edbc3de85121/test/codax/core_test.clj | clojure |
convenience function tests
-- consistency validation --
--- path conversions --- | (ns codax.core-test
(:require [clojure.test :refer :all]
[codax.test-logging :refer [logln]]
[codax.core :refer :all]
[codax.store :refer [destroy-database]]
[codax.swaps :refer :all]))
(def ^:dynamic *testing-database* nil)
(defn store-setup-and-teardown [f]
(binding [*testing-database* (open-database! "test-databases/core")]
( logln " SETUP " )
(f))
(destroy-database "test-databases/core"))
(use-fixtures :each store-setup-and-teardown)
(defmacro wrc [write-tx read-tx final-value]
`(is
(=
(do
(with-write-transaction [~'*testing-database* ~'tx]
~write-tx)
(let [x#
(with-read-transaction [~'*testing-database* ~'tx]
~read-tx)]
( logln x # )
x#))
~final-value)))
(defmacro rc [read-tx final-value]
`(is
(=
(let [x#
(with-read-transaction [~'*testing-database* ~'tx]
~read-tx)]
( logln x # )
x#)
~final-value)))
(deftest single-assoc-at
(wrc
(assoc-at tx [1 "a" :b 1.0 'c] ["x"])
(get-at tx [1 "a" :b 1.0 'c])
["x"])
(rc
(get-at tx [1 "a" :b 1.0])
{'c ["x"]})
(rc
(get-at tx [1 "a" :b])
{1.0 {'c ["x"]}})
(rc
(get-at tx [1 "a"])
{:b {1.0 {'c ["x"]}}})
(rc
(get-at tx [1])
{"a" {:b {1.0 {'c ["x"]}}}})
(rc
(get-at tx [])
{1 {"a" {:b {1.0 {'c ["x"]}}}}})
(rc
(get-at tx nil)
{1 {"a" {:b {1.0 {'c ["x"]}}}}}))
(deftest assoc-at+dissoc-at
(wrc
(assoc-at tx [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Mr"})
(rc
(get-at tx [-1])
{:people {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}}})
(wrc
(dissoc-at tx [-1 :people "Sam" :title])
(get-at tx [-1 :people "Sam"])
{:name "Sam"})
(wrc
(dissoc-at tx [-1 :people "Sam"])
(get-at tx [-1 :people "Sam"])
nil)
(rc
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}}}))
(deftest assoc-at+assoc-at-overwrite
(wrc
(assoc-at tx [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Mr"})
(rc
(get-at tx [-1])
{:people {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}}})
(wrc
(assoc-at tx [-1 :people "Sam" :title] "Sir")
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Sir"})
(wrc
(assoc-at tx [-1 :people "Sam"] {:name "Sammy" :profession "Go"})
(get-at tx [-1 :people "Sam"])
{:name "Sammy"
:profession "Go"})
(rc
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:profession "Go"}}}))
(deftest assoc-at+merge-at-overwrite
(wrc
(assoc-at tx [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Mr"})
(rc
(get-at tx [-1])
{:people {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}}})
(wrc
(merge-at tx [-1 :people "Sam"] {:title "Sir"})
(get-at tx [-1 :people "Sam"])
{:name "Sam"
:title "Sir"})
(wrc
(merge-at tx [-1 :people "Sam"] {:name "Sammy" :profession "Go"})
(get-at tx [-1 :people "Sam"])
{:name "Sammy"
:title "Sir"
:profession "Go"})
(rc
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:title "Sir"
:profession "Go"}}}))
(deftest one-write-assoc-at+dissoc-at
(wrc
(-> tx
(assoc-at [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(dissoc-at [-1 :people "Sam" :title])
(dissoc-at [-1 :people "Sam"]))
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}}}))
(deftest one-write-assoc-at+assoc-at-overwrite
(wrc
(-> tx
(assoc-at [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(assoc-at [-1 :people "Sam" :title] "Sir")
(assoc-at [-1 :people "Sam"] {:name "Sammy" :profession "Go"}))
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:profession "Go"}}}))
(deftest one-write-assoc-at+merge-at
(wrc
(-> tx
(assoc-at [-1 :people] {"Sam" {:name "Sam"
:title "Mr"}
"Sally" {:name "Sally"
:title "Mrs"}})
(merge-at [-1 :people "Sam"] {:title "Sir"})
(merge-at [-1 :people "Sam"] {:name "Sammy" :profession "Go"}))
(get-at tx [-1])
{:people {"Sally" {:name "Sally"
:title "Mrs"}
"Sam" {:name "Sammy"
:title "Sir"
:profession "Go"}}}))
(deftest write-transaction-without-final-tx
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Transaction"
(with-write-transaction [*testing-database* tx]))))
(deftest write-transaction-with-invalid-database-nil
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Database"
(with-write-transaction [nil tx]))))
(deftest write-transaction-with-invalid-database-2
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Database"
(with-write-transaction [2 tx]))))
(deftest write-transaction-with-invalid-database-map
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Database"
(with-write-transaction [{} tx]))))
(deftest assoc-at-without-txn
(is
(thrown-with-msg?
clojure.lang.ExceptionInfo #"Invalid Transaction"
(assoc-at "no-tx" [:a] "something"))))
(deftest failed-assoc-empty-path
(try
(with-write-transaction [*testing-database* tx]
(assoc-at tx [] "failure"))
(catch clojure.lang.ExceptionInfo e
(let [{:keys [cause] :as data} (ex-data e)]
(logln data)
(is (= (.getMessage e) "Invalid Path"))
(is (= cause :empty-path))))))
(deftest failed-assoc+extended-past-existing
(try
(with-write-transaction [*testing-database* tx]
(-> tx
(assoc-at [:hello] "value here")
(assoc-at [:hello :world] "failure")))
(catch clojure.lang.ExceptionInfo e
(let [{:keys [cause] :as data} (ex-data e)]
(logln data)
(is (= (.getMessage e) "Occupied Path"))
(is (= cause :non-map-element))))))
(deftest failed-assoc+extended-past-existing-separate-transactions
(try
(do
(with-write-transaction [*testing-database* tx]
(assoc-at tx [:something] "value here"))
(with-write-transaction [*testing-database* tx]
(assoc-at tx [:hello :world] "failure")))
(catch clojure.lang.ExceptionInfo e
(let [{:keys [cause] :as data} (ex-data e)]
(logln data)
(is (= (.getMessage e) "Occupied Path"))
(is (= cause :non-map-element))))))
(defn increment-path [db]
(with-write-transaction [db tx]
(update-at tx [:metrics :user-counts :all] inc-count)))
(defn increment-test [db n]
(let [database db
ops (repeat n #(increment-path database))]
(doall (pmap #(%) ops))
(is (=
n
(with-read-transaction [database tx]
(get-at tx [:metrics :user-counts :all]))))))
(deftest inc-test
(increment-test *testing-database* 1000))
(deftest assoc-at!-test
(is (=
(assoc-at! *testing-database* [:letters] {:a 1 :b 2})
(get-at! *testing-database* [:letters])
{:a 1 :b 2}))
(is (=
(get-at! *testing-database*)
{:letters {:a 1 :b 2}})))
(deftest update-at!-test
(let [add (fn [x y] (+ x y))
subtract (fn [x y] (- x y))]
(is (= 1 (update-at! *testing-database* [:count] inc-count)))
(is (= 2 (update-at! *testing-database* [:count] inc-count)))
(is (= 12 (update-at! *testing-database* [:count] add 10)))
(is (= 7 (update-at! *testing-database* [:count] subtract 5)))
(is (= 7 (get-at! *testing-database* [:count])))))
(deftest merge-at!-test
(is (=
(assoc-at! *testing-database* [:letters] {:a 1 :b 2})
(get-at! *testing-database* [:letters])
{:a 1 :b 2}))
(is (=
(merge-at! *testing-database* [:letters] {:c 3 :d 4})
(get-at! *testing-database* [:letters])
{:a 1 :b 2 :c 3 :d 4}))
(is (=
(get-at! *testing-database*)
{:letters {:a 1 :b 2 :c 3 :d 4}})))
(deftest dissoc-at!-test
(is (=
(assoc-at! *testing-database* [:letters] {:a 1 :b 2 :c 3})
(get-at! *testing-database* [:letters])
{:a 1 :b 2 :c 3}))
(is (=
(dissoc-at! *testing-database* [:letters :c])
nil))
(is (=
(get-at! *testing-database* [:letters])
{:a 1 :b 2}))
(is (=
(dissoc-at! *testing-database* [:letters])
(get-at! *testing-database* [:letters])
nil))
(is (=
(get-at! *testing-database*)
{})))
(deftest is-open?-and-close-all
(is (not (is-open? "test-databases/coreA")))
(is (not (is-open? "test-databases/coreB")))
(is (not (is-open? "test-databases/coreC")))
(let [a (open-database! "test-databases/coreA")
b (open-database! "test-databases/coreB")
c (open-database! "test-databases/coreC")]
(is (is-open? a))
(is (is-open? b))
(is (is-open? c))
(is (is-open? "test-databases/coreA"))
(is (is-open? "test-databases/coreB"))
(is (is-open? "test-databases/coreC"))
(close-all-databases!)
(is (not (is-open? a)))
(is (not (is-open? b)))
(is (not (is-open? c)))
(is (not (is-open? "test-databases/coreA")))
(is (not (is-open? "test-databases/coreB")))
(is (not (is-open? "test-databases/coreC")))))
(deftest extend-nil-path-with-val
(is (=
(assoc-at! *testing-database* [:a] nil)
nil))
(is (=
(assoc-at! *testing-database* [:a :b] "val")
"val"))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-nil-path-with-map
(is (=
(assoc-at! *testing-database* [:a] nil)
nil))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-val-path-with-val
(is (=
(assoc-at! *testing-database* [:a] "anything")
"anything"))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b] "val")))
(is (=
(get-at! *testing-database*)
{:a "anything"})))
(deftest extend-val-path-with-map
(is (=
(assoc-at! *testing-database* [:a] "anything")
"anything"))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-val-path-with-val-long
(is (=
(assoc-at! *testing-database* [:a :b] "anything")
"anything"))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b :c] "val")))
(is (=
(get-at! *testing-database*)
{:a {:b "anything"}})))
(deftest extend-val-path-with-partial-val-long
(is (=
(assoc-at! *testing-database* [:a] "anything")
"anything"))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b :c] "val")))
(is (=
(get-at! *testing-database*)
{:a "anything"})))
(deftest extend-val-path-with-partial-map-long
(is (=
(assoc-at! *testing-database* [:a :b] "anything")
"anything"))
(is (=
(assoc-at! *testing-database* [:a] {:b {:c "val"}})
{:b {:c "val"}}))
(is (=
(get-at! *testing-database*)
{:a {:b {:c "val"}}})))
(deftest extend-val-path-with-map-long
(is (=
(assoc-at! *testing-database* [:a :b] "anything")
"anything"))
(is (=
(assoc-at! *testing-database* [:a :b] {:c "val"})
{:c "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b {:c "val"}}})))
(deftest extend-false-path-with-val
(is (=
(assoc-at! *testing-database* [:a] false)
false))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b] "val")))
(is (=
(get-at! *testing-database*)
{:a false})))
(deftest extend-false-path-with-map
(is (=
(assoc-at! *testing-database* [:a] false)
false))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest extend-vec-path-with-val
(is (=
(assoc-at! *testing-database* [:a] [])
[]))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"Occupied Path"
(assoc-at! *testing-database* [:a :b] "val")))
(is (=
(get-at! *testing-database*)
{:a []})))
(deftest extend-vec-path-with-map
(is (=
(assoc-at! *testing-database* [:a] [])
[]))
(is (=
(assoc-at! *testing-database* [:a] {:b "val"})
{:b "val"}))
(is (=
(get-at! *testing-database*)
{:a {:b "val"}})))
(deftest path-conversion-from-val
(is (=
(assoc-at! *testing-database* :foo "bar")
"bar"))
(is (=
(get-at! *testing-database*))
{:foo "bar"}))
(deftest path-conversion-from-list
(is (=
(assoc-at! *testing-database* (list :foo :bar) "baz")
"baz"))
(is (=
(get-at! *testing-database*))
{:foo {:bar "baz"}}))
(deftest path-conversion-from-seq
(is (=
(assoc-at! *testing-database* (map identity [:foo :bar]) "baz")
"baz"))
(is (=
(get-at! *testing-database*))
{:foo {:bar "baz"}}))
(deftest manifest-overgrowth
(let [put! (fn []
(doseq [n (range 500)]
(assoc-at! *testing-database* n n)))
get-manifest-size #(-> *testing-database* :data deref :manifest count)
_ (put!)
presize (get-manifest-size)
_ (put!)
postsize (get-manifest-size)]
(is (= presize postsize))))
|
127407d16f6628555b9ec912f35eab8cefb985c05bcc35b6c32311fa7830a8a8 | juspay/atlas | Quote.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Domain . Types . Quote
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Domain.Types.Quote
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Domain.Types.Quote where
import Beckn.Types.Amount
import Beckn.Types.Id
import Data.Time
import qualified Domain.Types.FareProduct as DFareProduct
import qualified Domain.Types.Organization as DOrg
import Domain.Types.Products (Products)
import qualified Domain.Types.RentalFarePolicy as DRentalFP
import qualified Domain.Types.SearchRequest as DSR
import qualified Domain.Types.Vehicle as DVeh
import EulerHS.Prelude hiding (id)
import GHC.Records.Extra
data Quote = Quote
{ id :: Id Quote,
requestId :: Id DSR.SearchRequest,
productId :: Id Products, -- do we need this field?
estimatedFare :: Amount,
discount :: Maybe Amount,
estimatedTotalFare :: Amount,
providerId :: Id DOrg.Organization,
vehicleVariant :: DVeh.Variant,
createdAt :: UTCTime,
quoteDetails :: QuoteDetails
}
data QuoteDetails = OneWayDetails OneWayQuoteDetails | RentalDetails RentalQuoteDetails
data OneWayQuoteDetails = OneWayQuoteDetails
{ distance :: Double,
distanceToNearestDriver :: Double
}
data RentalQuoteDetails = RentalQuoteDetails
{ rentalFarePolicyId :: Id DRentalFP.RentalFarePolicy,
baseDistance :: Double,
baseDurationHr :: Int,
descriptions :: [Text]
}
getFareProductType :: QuoteDetails -> DFareProduct.FareProductType
getFareProductType = \case
OneWayDetails _ -> DFareProduct.ONE_WAY
RentalDetails _ -> DFareProduct.RENTAL
mkRentalQuoteDetails :: DRentalFP.RentalFarePolicy -> QuoteDetails
mkRentalQuoteDetails {..} =
RentalDetails $
RentalQuoteDetails
{ descriptions = mkDescriptions rentalFarePolicy,
rentalFarePolicyId = id,
..
}
mkDescriptions :: DRentalFP.RentalFarePolicy -> [Text]
mkDescriptions DRentalFP.RentalFarePolicy {..} =
[ "Extra km fare: " <> show extraKmFare,
"Extra min fare: " <> show extraMinuteFare,
"Extra fare for day: " <> maybe "not allowed" show driverAllowanceForDay,
"A rider can choose this package for a trip where the rider may not have a pre-decided destination and may not want to return to the origin location",
"The rider may want to stop at multiple destinations and have the taxi wait for the rider at these locations"
]
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/atlas-transport/src/Domain/Types/Quote.hs | haskell | do we need this field? | |
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Module : Domain . Types . Quote
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module : Domain.Types.Quote
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Domain.Types.Quote where
import Beckn.Types.Amount
import Beckn.Types.Id
import Data.Time
import qualified Domain.Types.FareProduct as DFareProduct
import qualified Domain.Types.Organization as DOrg
import Domain.Types.Products (Products)
import qualified Domain.Types.RentalFarePolicy as DRentalFP
import qualified Domain.Types.SearchRequest as DSR
import qualified Domain.Types.Vehicle as DVeh
import EulerHS.Prelude hiding (id)
import GHC.Records.Extra
data Quote = Quote
{ id :: Id Quote,
requestId :: Id DSR.SearchRequest,
estimatedFare :: Amount,
discount :: Maybe Amount,
estimatedTotalFare :: Amount,
providerId :: Id DOrg.Organization,
vehicleVariant :: DVeh.Variant,
createdAt :: UTCTime,
quoteDetails :: QuoteDetails
}
data QuoteDetails = OneWayDetails OneWayQuoteDetails | RentalDetails RentalQuoteDetails
data OneWayQuoteDetails = OneWayQuoteDetails
{ distance :: Double,
distanceToNearestDriver :: Double
}
data RentalQuoteDetails = RentalQuoteDetails
{ rentalFarePolicyId :: Id DRentalFP.RentalFarePolicy,
baseDistance :: Double,
baseDurationHr :: Int,
descriptions :: [Text]
}
getFareProductType :: QuoteDetails -> DFareProduct.FareProductType
getFareProductType = \case
OneWayDetails _ -> DFareProduct.ONE_WAY
RentalDetails _ -> DFareProduct.RENTAL
mkRentalQuoteDetails :: DRentalFP.RentalFarePolicy -> QuoteDetails
mkRentalQuoteDetails {..} =
RentalDetails $
RentalQuoteDetails
{ descriptions = mkDescriptions rentalFarePolicy,
rentalFarePolicyId = id,
..
}
mkDescriptions :: DRentalFP.RentalFarePolicy -> [Text]
mkDescriptions DRentalFP.RentalFarePolicy {..} =
[ "Extra km fare: " <> show extraKmFare,
"Extra min fare: " <> show extraMinuteFare,
"Extra fare for day: " <> maybe "not allowed" show driverAllowanceForDay,
"A rider can choose this package for a trip where the rider may not have a pre-decided destination and may not want to return to the origin location",
"The rider may want to stop at multiple destinations and have the taxi wait for the rider at these locations"
]
|
a0af6dadd700aa060a85b2245b3dee9ce161d8f91739f6b3b7c3a877d0cfb2e2 | dom96/ElysiaBot | GDict.hs | {-# LANGUAGE OverloadedStrings #-}
import PluginUtils
import Network.SimpleIRC.Messages
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import GDictParse
main = do
initPlugin ["dict"] [] onDict
onDict mInfo (MsgCmd cMsg server prefix cmd rest) = do
evalResult <- lookupDict (B.unpack rest)
either (\err -> sendMsg $ (B.pack err))
(\res -> sendMsg $ B.pack $ limitMsg 200 (formatParsed res))
evalResult
where addr = address server
msg = mMsg cMsg
sendMsg m = sendPrivmsg addr (fromJust $ mOrigin cMsg) m
onDict _ _ = return ()
limitMsg limit xs =
if length xs > limit
then take limit xs ++ "..."
else xs
formatParsed :: ParsedDict -> String
formatParsed dict
| not $ null $ related dict =
(related dict !! 0) ++ " - " ++ (meanings dict !! 0)
| otherwise = (meanings dict !! 0)
| null | https://raw.githubusercontent.com/dom96/ElysiaBot/3accf5825e67880c7f1696fc81e3fc449efe3294/src/Plugins/GDict/GDict.hs | haskell | # LANGUAGE OverloadedStrings # | import PluginUtils
import Network.SimpleIRC.Messages
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)
import GDictParse
main = do
initPlugin ["dict"] [] onDict
onDict mInfo (MsgCmd cMsg server prefix cmd rest) = do
evalResult <- lookupDict (B.unpack rest)
either (\err -> sendMsg $ (B.pack err))
(\res -> sendMsg $ B.pack $ limitMsg 200 (formatParsed res))
evalResult
where addr = address server
msg = mMsg cMsg
sendMsg m = sendPrivmsg addr (fromJust $ mOrigin cMsg) m
onDict _ _ = return ()
limitMsg limit xs =
if length xs > limit
then take limit xs ++ "..."
else xs
formatParsed :: ParsedDict -> String
formatParsed dict
| not $ null $ related dict =
(related dict !! 0) ++ " - " ++ (meanings dict !! 0)
| otherwise = (meanings dict !! 0)
|
3b5b068ff4c6bed433089093eaa8ed74aca37178f1114007458b605ba1abaa43 | xsc/ancient-clj | zip_test.clj | (ns ancient-clj.zip-test
(:require [ancient-clj.zip
:refer [dependencies
update-dependencies
project-clj
profiles-clj]]
[ancient-clj.artifact :as artifact]
[ancient-clj.test
[zip :refer [form->zloc]]
[generators :as test]]
[rewrite-clj.zip :as z]
[clojure.test.check
[generators :as gen]
[properties :as prop]
[clojure-test :refer [defspec]]]
[com.gfredericks.test.chuck :as chuck]))
;; ## Helpers
(def gen-deps-vector
(gen/vector (test/gen-dependency (test/maybe test/gen-version))))
(def gen-form-and-visitor
(gen/one-of
[(gen/tuple
test/gen-defproject
(gen/return (project-clj)))
(gen/tuple
test/gen-profiles-map
(gen/return (profiles-clj)))]))
(defn- vector-visitor
[zloc f]
(assert (= (z/tag zloc) :vector))
(z/map f zloc))
(def opts
{:visitor vector-visitor
:sexpr->artifact artifact/read-artifact})
;; ## Tests
(defspec t-dependencies (chuck/times 50)
(prop/for-all
[deps gen-deps-vector]
(let [zloc (form->zloc deps)
found (dependencies opts zloc)]
(= deps (map ::artifact/form found)))))
(defspec t-update-dependencies (chuck/times 50)
(prop/for-all
[deps gen-deps-vector
version test/gen-version]
(let [zloc (form->zloc deps)
zloc' (update-dependencies opts zloc (constantly version))]
(every? (comp #{version} second) (z/sexpr zloc')))))
(defspec t-update-dependencies-with-selective-version (chuck/times 50)
(prop/for-all
[deps (->> gen-deps-vector
(gen/such-that seq)
(gen/fmap distinct)
(gen/fmap vec))
version test/gen-version]
(let [zloc (form->zloc deps)
zloc' (->> (fn [dep]
(when (= (::artifact/form dep) (first deps))
version))
(update-dependencies opts zloc))
deps' (z/sexpr zloc')]
(and (= (next deps) (next deps'))
(= version (second (first deps')))))))
(defspec t-dependencies-known-formats (chuck/times 50)
(prop/for-all
[[form visitor] gen-form-and-visitor]
(let [zloc (form->zloc form)]
(dependencies visitor zloc))))
(defspec t-update-dependencies-known-formats (chuck/times 50)
(prop/for-all
[[form visitor] gen-form-and-visitor
version test/gen-version]
(let [zloc (form->zloc form)]
(update-dependencies visitor zloc (constantly version)))))
| null | https://raw.githubusercontent.com/xsc/ancient-clj/c34d96553c74ee1909a71e014e54a718933d1dd0/test/ancient_clj/zip_test.clj | clojure | ## Helpers
## Tests | (ns ancient-clj.zip-test
(:require [ancient-clj.zip
:refer [dependencies
update-dependencies
project-clj
profiles-clj]]
[ancient-clj.artifact :as artifact]
[ancient-clj.test
[zip :refer [form->zloc]]
[generators :as test]]
[rewrite-clj.zip :as z]
[clojure.test.check
[generators :as gen]
[properties :as prop]
[clojure-test :refer [defspec]]]
[com.gfredericks.test.chuck :as chuck]))
(def gen-deps-vector
(gen/vector (test/gen-dependency (test/maybe test/gen-version))))
(def gen-form-and-visitor
(gen/one-of
[(gen/tuple
test/gen-defproject
(gen/return (project-clj)))
(gen/tuple
test/gen-profiles-map
(gen/return (profiles-clj)))]))
(defn- vector-visitor
[zloc f]
(assert (= (z/tag zloc) :vector))
(z/map f zloc))
(def opts
{:visitor vector-visitor
:sexpr->artifact artifact/read-artifact})
(defspec t-dependencies (chuck/times 50)
(prop/for-all
[deps gen-deps-vector]
(let [zloc (form->zloc deps)
found (dependencies opts zloc)]
(= deps (map ::artifact/form found)))))
(defspec t-update-dependencies (chuck/times 50)
(prop/for-all
[deps gen-deps-vector
version test/gen-version]
(let [zloc (form->zloc deps)
zloc' (update-dependencies opts zloc (constantly version))]
(every? (comp #{version} second) (z/sexpr zloc')))))
(defspec t-update-dependencies-with-selective-version (chuck/times 50)
(prop/for-all
[deps (->> gen-deps-vector
(gen/such-that seq)
(gen/fmap distinct)
(gen/fmap vec))
version test/gen-version]
(let [zloc (form->zloc deps)
zloc' (->> (fn [dep]
(when (= (::artifact/form dep) (first deps))
version))
(update-dependencies opts zloc))
deps' (z/sexpr zloc')]
(and (= (next deps) (next deps'))
(= version (second (first deps')))))))
(defspec t-dependencies-known-formats (chuck/times 50)
(prop/for-all
[[form visitor] gen-form-and-visitor]
(let [zloc (form->zloc form)]
(dependencies visitor zloc))))
(defspec t-update-dependencies-known-formats (chuck/times 50)
(prop/for-all
[[form visitor] gen-form-and-visitor
version test/gen-version]
(let [zloc (form->zloc form)]
(update-dependencies visitor zloc (constantly version)))))
|
9b7eb408d017ecb44a3801b93fa08f2da0023198a63f135d708f95479872a439 | pfeiferj/nvim-hurl | indents.scm | ; indents.scm
[
(json_object)
(json_array)
] @indent
[
"}"
"]"
] @branch
(xml_tag) @indent
(xml_close_tag) @branch
| null | https://raw.githubusercontent.com/pfeiferj/nvim-hurl/e22d346edcb56fe07a96df5f6a83670e4e648d0b/queries/hurl/indents.scm | scheme | indents.scm |
[
(json_object)
(json_array)
] @indent
[
"}"
"]"
] @branch
(xml_tag) @indent
(xml_close_tag) @branch
|
91b63268be75a688aa3537918d55ad4e1823757261b2b61d253068cdfcb9fb50 | turquoise-hexagon/euler | solution.scm | (import
(chicken flonum)
(chicken format)
(chicken sort)
(euler))
(define (make-generator)
(set! i 290797)
(define (generator)
(let ((_ i))
(set! i (modulo (* i i) 50515093))
_))
generator)
(define (generate n)
(let ((generator (make-generator)))
(let loop ((i 1) (acc '()))
(if (> i n)
acc
(loop (+ i 1) (cons (list (generator) (generator)) acc))))))
(define (distance a b)
(sqrt
(apply +
(map
(lambda (i)
(* i i))
(map - a b)))))
(define (solve n)
(let ((l (map car
(sort
(map
(lambda (i)
(cons i (distance i '(0 0))))
(generate n))
(lambda (a b)
(< (cdr a)
(cdr b)))))))
(foldl min +inf.0 (map distance l (cdr l)))))
(define (output n)
(flonum-print-precision 11) (format "~a" n))
(let ((_ (output (solve #e2e6))))
(print _) (assert (string=? _ "20.880613018")))
| null | https://raw.githubusercontent.com/turquoise-hexagon/euler/a5a8d06d9090754fdf5d9d52c7c87d4833fb2c38/src/spoilers/816/solution.scm | scheme | (import
(chicken flonum)
(chicken format)
(chicken sort)
(euler))
(define (make-generator)
(set! i 290797)
(define (generator)
(let ((_ i))
(set! i (modulo (* i i) 50515093))
_))
generator)
(define (generate n)
(let ((generator (make-generator)))
(let loop ((i 1) (acc '()))
(if (> i n)
acc
(loop (+ i 1) (cons (list (generator) (generator)) acc))))))
(define (distance a b)
(sqrt
(apply +
(map
(lambda (i)
(* i i))
(map - a b)))))
(define (solve n)
(let ((l (map car
(sort
(map
(lambda (i)
(cons i (distance i '(0 0))))
(generate n))
(lambda (a b)
(< (cdr a)
(cdr b)))))))
(foldl min +inf.0 (map distance l (cdr l)))))
(define (output n)
(flonum-print-precision 11) (format "~a" n))
(let ((_ (output (solve #e2e6))))
(print _) (assert (string=? _ "20.880613018")))
|
|
05d30dadc7e8a3247bfe2b774329bfac8b07d1ebb348dbba6c58ce23e5ed31ca | hbr/albatross | typecheck.mli | module Problem:
sig
type t =
| Out_of_bound of int * Gamma.t
| Argument_type
| Typed
| Lambda
| No_type
| Name of string
end
type path = int list
val is_valid_context: Gamma.t -> bool
(**
[is_valid_context gamma]
[gamma] is wellformed if
- every type is valid, i.e. it typechecks using only entries of [gamma] with a smaller level (this is true by contruction, since we are using de bruijn indices)
- the same holds for all definition terms
- {b TODO}: every type is a type (and not an object)
@return true, if [gamma] is wellformed, false otherwise
*)
val equivalent: Term.typ -> Term.typ -> Gamma.t -> bool
val check: Term.t -> Gamma.t -> (Term.typ, path * Problem.t) result
(**
[check term gamma]
Verify if [term] is welltyped in the valid context [gamma]. If yes,
return its type.
Precondition:
{[is_valid_context gamma]}
*)
| null | https://raw.githubusercontent.com/hbr/albatross/8f28ef97951f92f30dc69cf94c0bbe20d64fba21/ocaml/core/typecheck.mli | ocaml | *
[is_valid_context gamma]
[gamma] is wellformed if
- every type is valid, i.e. it typechecks using only entries of [gamma] with a smaller level (this is true by contruction, since we are using de bruijn indices)
- the same holds for all definition terms
- {b TODO}: every type is a type (and not an object)
@return true, if [gamma] is wellformed, false otherwise
*
[check term gamma]
Verify if [term] is welltyped in the valid context [gamma]. If yes,
return its type.
Precondition:
{[is_valid_context gamma]}
| module Problem:
sig
type t =
| Out_of_bound of int * Gamma.t
| Argument_type
| Typed
| Lambda
| No_type
| Name of string
end
type path = int list
val is_valid_context: Gamma.t -> bool
val equivalent: Term.typ -> Term.typ -> Gamma.t -> bool
val check: Term.t -> Gamma.t -> (Term.typ, path * Problem.t) result
|
41ec9086bf63df5c8063710e51941fa0300a626bf385e4be9e2a6fc5579063d5 | unsplash/intlc | Compiler.hs | module Intlc.Backend.JavaScript.Compiler (InterpStrat (..), Overrides (..), emptyOverrides, compileStmt, buildReactImport, emptyModule, validateKey) where
import Control.Monad.Extra (pureIf)
import Data.Char (isAlpha, isDigit)
import qualified Data.Text as T
import Intlc.Backend.JavaScript.Language
import Intlc.Core (Backend (..), Dataset,
Locale (Locale),
Translation (backend))
import qualified Intlc.ICU as ICU
import Prelude
import Utils (apply2, (<>^))
type Compiler = Reader Cfg
-- Allow other compilers to leverage this one, overriding only specific parts
-- of it. What's here and in what form is merely ad hoc.
data Overrides = Overrides
{ stmtOverride :: Maybe (Text -> Text -> Text)
, matchLitCondOverride :: Maybe (Text -> Text)
}
emptyOverrides :: Overrides
emptyOverrides = Overrides mempty mempty
fromOverride :: (Overrides -> Maybe a) -> a -> Compiler a
fromOverride f x = fromMaybe x <$> asks (f . overrides)
override :: (Overrides -> Maybe (a -> a)) -> a -> Compiler a
override f x = maybe x ($ x) <$> asks (f . overrides)
data Cfg = Cfg
{ locale :: Locale
, interp :: InterpStrat
, overrides :: Overrides
}
compileStmt :: Overrides -> InterpStrat -> Locale -> Text -> ICU.Message ICU.Node -> Text
compileStmt o s l k m = f' fromKeyedMsg'
where f' = flip runReader (Cfg l s o) . stmt
fromKeyedMsg' = runReader (fromKeyedMsg k m) l
data InterpStrat
= TemplateLit
| JSX
data Interp = Interp
{ open :: Text
, close :: Text
, interpOpen :: Text
, interpClose :: Text
}
fromStrat :: InterpStrat -> Interp
fromStrat TemplateLit = Interp
{ open = "`"
, close = "`"
, interpOpen = "${"
, interpClose = "}"
}
fromStrat JSX = Interp
{ open = "<>"
, close = "</>"
, interpOpen = "{"
, interpClose = "}"
}
-- | Everything shares a single argument object whence we can access
-- interpolations.
argName :: Text
argName = "x"
prop :: ICU.Arg -> Text
prop (ICU.Arg x) = argName <> "." <> x
wrap :: Text -> Compiler Text
wrap x = do
(o, c) <- asks ((open &&& close) . fromStrat . interp)
pure $ o <> x <> c
interpc :: Text -> Compiler Text
interpc x = do
(o, c) <- asks ((interpOpen &&& interpClose) . fromStrat . interp)
pure $ o <> x <> c
stmt :: Stmt -> Compiler Text
stmt (Stmt n xs) = do
r <- wrap =<< exprs xs
(fmap (apply2 n r) . stmtOverride) `fromOverride` ("export const " <> n <> " = " <> r)
exprs :: Foldable f => f Expr -> Compiler Text
exprs = foldMapM expr
expr :: Expr -> Compiler Text
expr (TPrint x) = asks interp <&> \case
TemplateLit -> T.concatMap escape x
_ -> x
where escape '`' = "\\`"
escape c = T.singleton c
expr (TStr x) = interpc (prop x)
expr (TNum x) = do
(Locale l) <- asks locale
interpc $ "new Intl.NumberFormat('" <> l <> "').format(" <> prop x <> ")"
expr (TDate x fmt) = interpc =<< date x fmt
expr (TTime x fmt) = interpc =<< time x fmt
expr (TApply x ys) = interpc =<< apply x ys
expr (TMatch x) = interpc =<< match x
apply :: ICU.Arg -> [Expr] -> Compiler Text
apply x ys = pure (prop x <> "(") <>^ (wrap =<< exprs ys) <>^ pure ")"
match :: Match -> Compiler Text
match = fmap iife . go where
go (Match n c m) = case m of
LitMatchRet bs -> switch <$> cond <*> branches bs
NonLitMatchRet bs w -> switch <$> cond <*> wildBranches bs w
RecMatchRet bs m' -> switch <$> cond <*> recBranches bs (go m')
where cond = matchCond n c
iife x = "(() => { " <> x <> " })()"
switch x ys = "switch (" <> x <> ") { " <> ys <> " }"
branches xs = concatBranches . toList <$> mapM branch xs
where branch (Branch x ys) = pure ("case " <> x <> ": return ") <>^ (wrap =<< exprs ys) <>^ pure ";"
concatBranches = unwords
wildBranches xs w = (<>) <$> branches xs <*> ((" " <>) <$> wildcard w)
where wildcard (Wildcard xs') = pure "default: return " <>^ (wrap =<< exprs xs') <>^ pure ";"
recBranches xs y = (<>) <$> branches xs <*> ((" " <>) . nest <$> y)
where nest x = "default: { " <> x <> " }"
matchCond :: ICU.Arg -> MatchCond -> Compiler Text
matchCond n LitCond = override matchLitCondOverride (prop n)
matchCond n CardinalPluralRuleCond = f <$> asks locale
where f (Locale l) = "new Intl.PluralRules('" <> l <> "').select(" <> prop n <> ")"
matchCond n OrdinalPluralRuleCond = f <$> asks locale
where f (Locale l) = "new Intl.PluralRules('" <> l <> "', { type: 'ordinal' }).select(" <> prop n <> ")"
date :: ICU.Arg -> ICU.DateTimeFmt -> Compiler Text
date n d = do
(Locale l) <- asks locale
pure $ "new Intl.DateTimeFormat('" <> l <> "', { dateStyle: '" <> dateTimeFmt d <> "' }).format(" <> prop n <> ")"
time :: ICU.Arg -> ICU.DateTimeFmt -> Compiler Text
time n d = do
(Locale l) <- asks locale
pure $ "new Intl.DateTimeFormat('" <> l <> "', { timeStyle: '" <> dateTimeFmt d <> "' }).format(" <> prop n <> ")"
dateTimeFmt :: ICU.DateTimeFmt -> Text
dateTimeFmt ICU.Short = "short"
dateTimeFmt ICU.Medium = "medium"
dateTimeFmt ICU.Long = "long"
dateTimeFmt ICU.Full = "full"
A no - op that clarifies a JS / TS file as an ES module .
emptyModule :: Text
emptyModule = "export {}"
buildReactImport :: Dataset (Translation a) -> Maybe Text
buildReactImport = flip pureIf text . any ((TypeScriptReact ==) . backend)
where text = "import { ReactElement } from 'react'"
validateKey :: Text -> Either Text ()
validateKey k
| T.null k = Left "[Empty identifier found.]"
| k `elem` reservedWords = Left $ k <> ": reserved word."
| not (isValidIdent (T.unpack k)) = Left $ k <> ": invalid identifier."
| otherwise = Right ()
-- -US/docs/Glossary/identifier
where isValidIdent [] = False -- Technically already caught by `T.null`.
isValidIdent (c:cs) = isValidIdentHeadChar c && all isValidIdentTailChar cs
isValidIdentHeadChar = liftA2 (||) isAlpha (`elem` ['$', '_'])
isValidIdentTailChar = liftA2 (||) isValidIdentHeadChar isDigit
-- Useful docs:
-- -US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords
reservedWords :: [Text]
reservedWords = es2015 <> future <> module' <> legacy <> literals where
es2015 =
[ "break"
, "case"
, "catch"
, "class"
, "const"
, "continue"
, "debugger"
, "default"
, "delete"
, "do"
, "else"
, "export"
, "extends"
, "finally"
, "for"
, "function"
, "if"
, "import"
, "in"
, "instanceof"
, "new"
, "return"
, "super"
, "switch"
, "this"
, "throw"
, "try"
, "typeof"
, "var"
, "void"
, "while"
, "with"
, "yield"
]
future =
[ "enum"
, "implements"
, "interface"
, "let"
, "package"
, "private"
, "protected"
, "public"
, "static"
, "yield"
]
module' =
[ "await"
]
legacy =
[ "abstract"
, "boolean"
, "byte"
, "char"
, "double"
, "final"
, "float"
, "goto"
, "int"
, "long"
, "native"
, "short"
, "synchronized"
, "throws"
, "transient"
, "volatile"
]
literals =
[ "null"
, "true"
, "false"
]
| null | https://raw.githubusercontent.com/unsplash/intlc/cde1ada3fc472953bd484e9a668a8bb906c2e982/lib/Intlc/Backend/JavaScript/Compiler.hs | haskell | Allow other compilers to leverage this one, overriding only specific parts
of it. What's here and in what form is merely ad hoc.
| Everything shares a single argument object whence we can access
interpolations.
-US/docs/Glossary/identifier
Technically already caught by `T.null`.
Useful docs:
-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords | module Intlc.Backend.JavaScript.Compiler (InterpStrat (..), Overrides (..), emptyOverrides, compileStmt, buildReactImport, emptyModule, validateKey) where
import Control.Monad.Extra (pureIf)
import Data.Char (isAlpha, isDigit)
import qualified Data.Text as T
import Intlc.Backend.JavaScript.Language
import Intlc.Core (Backend (..), Dataset,
Locale (Locale),
Translation (backend))
import qualified Intlc.ICU as ICU
import Prelude
import Utils (apply2, (<>^))
type Compiler = Reader Cfg
data Overrides = Overrides
{ stmtOverride :: Maybe (Text -> Text -> Text)
, matchLitCondOverride :: Maybe (Text -> Text)
}
emptyOverrides :: Overrides
emptyOverrides = Overrides mempty mempty
fromOverride :: (Overrides -> Maybe a) -> a -> Compiler a
fromOverride f x = fromMaybe x <$> asks (f . overrides)
override :: (Overrides -> Maybe (a -> a)) -> a -> Compiler a
override f x = maybe x ($ x) <$> asks (f . overrides)
data Cfg = Cfg
{ locale :: Locale
, interp :: InterpStrat
, overrides :: Overrides
}
compileStmt :: Overrides -> InterpStrat -> Locale -> Text -> ICU.Message ICU.Node -> Text
compileStmt o s l k m = f' fromKeyedMsg'
where f' = flip runReader (Cfg l s o) . stmt
fromKeyedMsg' = runReader (fromKeyedMsg k m) l
data InterpStrat
= TemplateLit
| JSX
data Interp = Interp
{ open :: Text
, close :: Text
, interpOpen :: Text
, interpClose :: Text
}
fromStrat :: InterpStrat -> Interp
fromStrat TemplateLit = Interp
{ open = "`"
, close = "`"
, interpOpen = "${"
, interpClose = "}"
}
fromStrat JSX = Interp
{ open = "<>"
, close = "</>"
, interpOpen = "{"
, interpClose = "}"
}
argName :: Text
argName = "x"
prop :: ICU.Arg -> Text
prop (ICU.Arg x) = argName <> "." <> x
wrap :: Text -> Compiler Text
wrap x = do
(o, c) <- asks ((open &&& close) . fromStrat . interp)
pure $ o <> x <> c
interpc :: Text -> Compiler Text
interpc x = do
(o, c) <- asks ((interpOpen &&& interpClose) . fromStrat . interp)
pure $ o <> x <> c
stmt :: Stmt -> Compiler Text
stmt (Stmt n xs) = do
r <- wrap =<< exprs xs
(fmap (apply2 n r) . stmtOverride) `fromOverride` ("export const " <> n <> " = " <> r)
exprs :: Foldable f => f Expr -> Compiler Text
exprs = foldMapM expr
expr :: Expr -> Compiler Text
expr (TPrint x) = asks interp <&> \case
TemplateLit -> T.concatMap escape x
_ -> x
where escape '`' = "\\`"
escape c = T.singleton c
expr (TStr x) = interpc (prop x)
expr (TNum x) = do
(Locale l) <- asks locale
interpc $ "new Intl.NumberFormat('" <> l <> "').format(" <> prop x <> ")"
expr (TDate x fmt) = interpc =<< date x fmt
expr (TTime x fmt) = interpc =<< time x fmt
expr (TApply x ys) = interpc =<< apply x ys
expr (TMatch x) = interpc =<< match x
apply :: ICU.Arg -> [Expr] -> Compiler Text
apply x ys = pure (prop x <> "(") <>^ (wrap =<< exprs ys) <>^ pure ")"
match :: Match -> Compiler Text
match = fmap iife . go where
go (Match n c m) = case m of
LitMatchRet bs -> switch <$> cond <*> branches bs
NonLitMatchRet bs w -> switch <$> cond <*> wildBranches bs w
RecMatchRet bs m' -> switch <$> cond <*> recBranches bs (go m')
where cond = matchCond n c
iife x = "(() => { " <> x <> " })()"
switch x ys = "switch (" <> x <> ") { " <> ys <> " }"
branches xs = concatBranches . toList <$> mapM branch xs
where branch (Branch x ys) = pure ("case " <> x <> ": return ") <>^ (wrap =<< exprs ys) <>^ pure ";"
concatBranches = unwords
wildBranches xs w = (<>) <$> branches xs <*> ((" " <>) <$> wildcard w)
where wildcard (Wildcard xs') = pure "default: return " <>^ (wrap =<< exprs xs') <>^ pure ";"
recBranches xs y = (<>) <$> branches xs <*> ((" " <>) . nest <$> y)
where nest x = "default: { " <> x <> " }"
matchCond :: ICU.Arg -> MatchCond -> Compiler Text
matchCond n LitCond = override matchLitCondOverride (prop n)
matchCond n CardinalPluralRuleCond = f <$> asks locale
where f (Locale l) = "new Intl.PluralRules('" <> l <> "').select(" <> prop n <> ")"
matchCond n OrdinalPluralRuleCond = f <$> asks locale
where f (Locale l) = "new Intl.PluralRules('" <> l <> "', { type: 'ordinal' }).select(" <> prop n <> ")"
date :: ICU.Arg -> ICU.DateTimeFmt -> Compiler Text
date n d = do
(Locale l) <- asks locale
pure $ "new Intl.DateTimeFormat('" <> l <> "', { dateStyle: '" <> dateTimeFmt d <> "' }).format(" <> prop n <> ")"
time :: ICU.Arg -> ICU.DateTimeFmt -> Compiler Text
time n d = do
(Locale l) <- asks locale
pure $ "new Intl.DateTimeFormat('" <> l <> "', { timeStyle: '" <> dateTimeFmt d <> "' }).format(" <> prop n <> ")"
dateTimeFmt :: ICU.DateTimeFmt -> Text
dateTimeFmt ICU.Short = "short"
dateTimeFmt ICU.Medium = "medium"
dateTimeFmt ICU.Long = "long"
dateTimeFmt ICU.Full = "full"
A no - op that clarifies a JS / TS file as an ES module .
emptyModule :: Text
emptyModule = "export {}"
buildReactImport :: Dataset (Translation a) -> Maybe Text
buildReactImport = flip pureIf text . any ((TypeScriptReact ==) . backend)
where text = "import { ReactElement } from 'react'"
validateKey :: Text -> Either Text ()
validateKey k
| T.null k = Left "[Empty identifier found.]"
| k `elem` reservedWords = Left $ k <> ": reserved word."
| not (isValidIdent (T.unpack k)) = Left $ k <> ": invalid identifier."
| otherwise = Right ()
isValidIdent (c:cs) = isValidIdentHeadChar c && all isValidIdentTailChar cs
isValidIdentHeadChar = liftA2 (||) isAlpha (`elem` ['$', '_'])
isValidIdentTailChar = liftA2 (||) isValidIdentHeadChar isDigit
reservedWords :: [Text]
reservedWords = es2015 <> future <> module' <> legacy <> literals where
es2015 =
[ "break"
, "case"
, "catch"
, "class"
, "const"
, "continue"
, "debugger"
, "default"
, "delete"
, "do"
, "else"
, "export"
, "extends"
, "finally"
, "for"
, "function"
, "if"
, "import"
, "in"
, "instanceof"
, "new"
, "return"
, "super"
, "switch"
, "this"
, "throw"
, "try"
, "typeof"
, "var"
, "void"
, "while"
, "with"
, "yield"
]
future =
[ "enum"
, "implements"
, "interface"
, "let"
, "package"
, "private"
, "protected"
, "public"
, "static"
, "yield"
]
module' =
[ "await"
]
legacy =
[ "abstract"
, "boolean"
, "byte"
, "char"
, "double"
, "final"
, "float"
, "goto"
, "int"
, "long"
, "native"
, "short"
, "synchronized"
, "throws"
, "transient"
, "volatile"
]
literals =
[ "null"
, "true"
, "false"
]
|
2ab200d172c9d12cc98599cfdb6e241669acd7fce1ebb3f434c02c283326aeff | Shirakumo/kandria | environment.lisp | (in-package #:org.shirakumo.fraf.kandria)
(defvar *environments* (make-hash-table :test 'eql))
(defclass audible-entity (listener entity)
((voice :initarg :voice :accessor voice)))
(defmethod stage :after ((entity audible-entity) (area staging-area))
(when (typep (voice entity) 'placeholder-resource)
(let ((generator (generator (voice entity))))
(setf (voice entity) (apply #'generate-resources generator (input* generator) :resource NIL (trial::generation-arguments generator)))))
(stage (voice entity) area))
(defmethod active-p ((entity audible-entity)) T)
(defmethod handle :after ((ev tick) (entity audible-entity))
(when (active-p entity)
(let* ((voice (voice entity))
(max (expt (mixed:max-distance voice) 2))
(dist (vsqrdistance (location entity) (location (unit 'player +world+)))))
(cond ((< dist (+ max 32)) ; Start a bit before the entrance to ensure we have a smooth ramp up.
(harmony:play voice :location (location entity)))
((< (+ max 128) dist) ; Stop even farther out to ensure we don't accidentally flip-flop and overburden the sound server.
(harmony:stop voice))))))
(defclass switch-music-state (event)
((area :initarg :area :initform NIL :reader area)
(state :initarg :state :initform NIL :reader state)))
(defun (setf music-state) (state area)
(if (eql T area)
(dolist (area (delete-duplicates (mapcar #'area (list-environments))))
(issue +world+ 'switch-music-state :area area :state state))
(issue +world+ 'switch-music-state :area area :state state)))
(defclass environment () ()) ; Early def
(defclass environment-controller (entity listener)
((name :initform 'environment)
(environment :initarg :environment :initform NIL :accessor environment)
(area-states :initarg :area-states :initform NIL :accessor area-states)
(override :initarg :override :initform NIL :accessor override)))
(defmethod stage :after ((controller environment-controller) (area staging-area))
(when (environment controller) (stage (environment controller) area))
(when (override controller) (stage (override controller) area)))
(defmethod reset ((controller environment-controller))
(setf (area-states controller) ())
(when (override controller)
(harmony:transition (override controller) 0.0 :in 0.1)
(setf (slot-value controller 'override) NIL))
(let ((env (environment controller)))
(when env
(when (music env)
(harmony:transition (music env) 0.0 :in 0.1))
(when (ambience env)
(harmony:transition (ambience env) 0.0 :in 0.1))
(setf (environment controller) NIL))))
(defmethod handle ((ev switch-chunk) (controller environment-controller))
(switch-environment controller (environment (chunk ev))))
(defmethod handle ((ev switch-music-state) (controller environment-controller))
(let* ((env (environment controller))
(area (or (area ev) (area env)))
(state (state ev))
(cons (assoc area (area-states controller))))
(v:info :kandria.harmony "Switching music state of ~s to ~s." area state)
(if cons
(setf (cdr cons) state)
(push (cons area state) (area-states controller)))
(when (and env
(eql area (area env))
(null (override controller)))
(when (music env)
(harmony:transition (music env) state :in 5.0))
(when (ambience env)
(harmony:transition (ambience env) state :in 3.0 :error NIL)))))
(defmethod switch-environment ((controller environment-controller) (name symbol))
(cond (name
(switch-environment controller (environment name)))
(T
(switch-environment (environment controller) NIL)
(setf (environment controller) NIL))))
(defmethod switch-environment ((controller environment-controller) (environment environment))
(unless (override controller)
(when (allocated-p environment)
(switch-environment (environment controller) environment)))
(setf (environment controller) environment))
(defmethod (setf override) :before ((override null) (controller environment-controller))
(when (override controller)
(harmony:transition (override controller) 0.0 :in 5.0))
(switch-environment NIL (environment controller)))
(defmethod (setf override) :before ((override (eql 'null)) (controller environment-controller))
(when (override controller)
(harmony:transition (override controller) 0.0 :in 5.0))
(switch-environment (environment controller) NIL))
(defmethod (setf override) :before ((override resource) (controller environment-controller))
(when (allocated-p override)
(unless (eq override (override controller))
(if (override controller)
(harmony:transition (override controller) 0.0 :in 3.0)
(switch-environment (environment controller) NIL))
(harmony:transition override 1.0 :in 3.0))))
(defmethod harmony:transition ((controller environment-controller) (to real) &key (in 1.0))
(cond ((override controller)
(harmony:transition (override controller) to :in in))
((environment controller)
(harmony:transition (environment controller) to :in in))))
(defmethod handle ((event load-complete) (controller environment-controller))
(let ((override (override controller))
(environment (environment controller)))
(setf (slot-value controller 'environment) NIL)
(setf (slot-value controller 'override) NIL)
(setf (override controller) override)
(switch-environment controller environment)))
(defmethod harmony:transition ((nothing (eql 'null)) to &key in)
(declare (ignore nothing to in)))
#+kandria-release
(defmethod harmony:transition ((nothing placeholder-resource) to &key in)
(declare (ignore nothing to in)))
(defun override-music (track)
(setf (override (unit 'environment +world+)) (when track (// 'music track))))
(defclass environment ()
((name :initarg :name :initform NIL :accessor name)
(music :initarg :music :initform NIL :accessor music)
(ambience :initarg :ambience :initform NIL :accessor ambience)
(area :initarg :area :initform NIL :accessor area)))
(defmethod print-object ((environment environment) stream)
(print-unreadable-object (environment stream :type T)
(format stream "~s" (name environment))))
(defmethod allocated-p ((environment environment))
(let ((music (music environment))
(ambience (ambience environment)))
(and (or (null ambience) (allocated-p ambience))
(or (null music) (allocated-p music)))))
(defmethod stage ((environment environment) (area staging-area))
(when (music environment) (stage (music environment) area))
(when (ambience environment) (stage (ambience environment) area)))
(defmethod state ((environment environment))
(let* ((controller (unit 'environment +world+))
(cons (assoc (area environment) (area-states controller))))
(if cons
(cdr cons)
:normal)))
(defmethod (setf state) (state (environment environment))
(issue +world+ 'switch-area-state :area (area environment) :state state))
(defmethod quest:activate ((environment environment))
(let ((controller (unit 'environment +world+)))
(when (not (eq environment (environment controller)))
(switch-environment (environment controller) environment))))
(defmethod switch-environment ((a null) (b null)))
(defmethod switch-environment ((none null) (environment environment))
(let ((state (state environment)))
(when (music environment)
(harmony:transition (music environment) state :in 5.0 :error NIL))
(when (ambience environment)
(harmony:transition (ambience environment) state :in 3.0 :error NIL))))
(defmethod switch-environment ((environment environment) (none null))
(when (music environment)
(harmony:transition (music environment) NIL :in 3.0))
(when (ambience environment)
(harmony:transition (ambience environment) NIL :in 5.0)))
(defmethod switch-environment ((from environment) (to environment))
(let ((state (state to)))
(flet ((tx (a b in &optional (state state))
(unless (eq a b)
(when a
(harmony:transition a NIL :in in)))
(when b
(harmony:transition b state :in in :error NIL))))
(tx (music from) (music to) 5.0)
(tx (ambience from) (ambience to) 3.0 :normal))))
(defmethod harmony:transition ((environment environment) (to real) &key (in 1.0))
(when (music environment)
(harmony:transition (music environment) to :in in))
(when (ambience environment)
(harmony:transition (ambience environment) to :in in)))
(defmethod environment ((name symbol))
(gethash name *environments*))
(defmethod (setf environment) ((value environment) (name symbol))
(setf (gethash name *environments*) value))
(defun remove-environment (name)
(remhash name *environments*))
(defun list-environments ()
(loop for env being the hash-values of *environments*
collect env))
(defmacro define-environment ((area name) &body initargs)
(let ((music (getf initargs :music))
(ambience (getf initargs :ambience))
(initargs (remf* initargs :music :ambience))
(name (trial::mksym *package* area '/ name)))
`(setf (environment ',name)
(ensure-instance (environment ',name) 'environment
:area ',area
:name ',name
:music ,(when music `(// 'music ,music))
:ambience ,(when ambience `(// 'music ,ambience))
,@initargs))))
(defmethod harmony:transition :before ((voice harmony::voice) (to real) &key)
(v:info :kandria.harmony "Transitioning ~a to ~a" voice to))
(trial-alloy:define-set-representation environment/combo
:represents environment
:item-text (string (when alloy:value (name alloy:value)))
(list-environments))
| null | https://raw.githubusercontent.com/Shirakumo/kandria/94fd727bd93e302c6a28fae33815043d486d794b/environment.lisp | lisp | Start a bit before the entrance to ensure we have a smooth ramp up.
Stop even farther out to ensure we don't accidentally flip-flop and overburden the sound server.
Early def | (in-package #:org.shirakumo.fraf.kandria)
(defvar *environments* (make-hash-table :test 'eql))
(defclass audible-entity (listener entity)
((voice :initarg :voice :accessor voice)))
(defmethod stage :after ((entity audible-entity) (area staging-area))
(when (typep (voice entity) 'placeholder-resource)
(let ((generator (generator (voice entity))))
(setf (voice entity) (apply #'generate-resources generator (input* generator) :resource NIL (trial::generation-arguments generator)))))
(stage (voice entity) area))
(defmethod active-p ((entity audible-entity)) T)
(defmethod handle :after ((ev tick) (entity audible-entity))
(when (active-p entity)
(let* ((voice (voice entity))
(max (expt (mixed:max-distance voice) 2))
(dist (vsqrdistance (location entity) (location (unit 'player +world+)))))
(harmony:play voice :location (location entity)))
(harmony:stop voice))))))
(defclass switch-music-state (event)
((area :initarg :area :initform NIL :reader area)
(state :initarg :state :initform NIL :reader state)))
(defun (setf music-state) (state area)
(if (eql T area)
(dolist (area (delete-duplicates (mapcar #'area (list-environments))))
(issue +world+ 'switch-music-state :area area :state state))
(issue +world+ 'switch-music-state :area area :state state)))
(defclass environment-controller (entity listener)
((name :initform 'environment)
(environment :initarg :environment :initform NIL :accessor environment)
(area-states :initarg :area-states :initform NIL :accessor area-states)
(override :initarg :override :initform NIL :accessor override)))
(defmethod stage :after ((controller environment-controller) (area staging-area))
(when (environment controller) (stage (environment controller) area))
(when (override controller) (stage (override controller) area)))
(defmethod reset ((controller environment-controller))
(setf (area-states controller) ())
(when (override controller)
(harmony:transition (override controller) 0.0 :in 0.1)
(setf (slot-value controller 'override) NIL))
(let ((env (environment controller)))
(when env
(when (music env)
(harmony:transition (music env) 0.0 :in 0.1))
(when (ambience env)
(harmony:transition (ambience env) 0.0 :in 0.1))
(setf (environment controller) NIL))))
(defmethod handle ((ev switch-chunk) (controller environment-controller))
(switch-environment controller (environment (chunk ev))))
(defmethod handle ((ev switch-music-state) (controller environment-controller))
(let* ((env (environment controller))
(area (or (area ev) (area env)))
(state (state ev))
(cons (assoc area (area-states controller))))
(v:info :kandria.harmony "Switching music state of ~s to ~s." area state)
(if cons
(setf (cdr cons) state)
(push (cons area state) (area-states controller)))
(when (and env
(eql area (area env))
(null (override controller)))
(when (music env)
(harmony:transition (music env) state :in 5.0))
(when (ambience env)
(harmony:transition (ambience env) state :in 3.0 :error NIL)))))
(defmethod switch-environment ((controller environment-controller) (name symbol))
(cond (name
(switch-environment controller (environment name)))
(T
(switch-environment (environment controller) NIL)
(setf (environment controller) NIL))))
(defmethod switch-environment ((controller environment-controller) (environment environment))
(unless (override controller)
(when (allocated-p environment)
(switch-environment (environment controller) environment)))
(setf (environment controller) environment))
(defmethod (setf override) :before ((override null) (controller environment-controller))
(when (override controller)
(harmony:transition (override controller) 0.0 :in 5.0))
(switch-environment NIL (environment controller)))
(defmethod (setf override) :before ((override (eql 'null)) (controller environment-controller))
(when (override controller)
(harmony:transition (override controller) 0.0 :in 5.0))
(switch-environment (environment controller) NIL))
(defmethod (setf override) :before ((override resource) (controller environment-controller))
(when (allocated-p override)
(unless (eq override (override controller))
(if (override controller)
(harmony:transition (override controller) 0.0 :in 3.0)
(switch-environment (environment controller) NIL))
(harmony:transition override 1.0 :in 3.0))))
(defmethod harmony:transition ((controller environment-controller) (to real) &key (in 1.0))
(cond ((override controller)
(harmony:transition (override controller) to :in in))
((environment controller)
(harmony:transition (environment controller) to :in in))))
(defmethod handle ((event load-complete) (controller environment-controller))
(let ((override (override controller))
(environment (environment controller)))
(setf (slot-value controller 'environment) NIL)
(setf (slot-value controller 'override) NIL)
(setf (override controller) override)
(switch-environment controller environment)))
(defmethod harmony:transition ((nothing (eql 'null)) to &key in)
(declare (ignore nothing to in)))
#+kandria-release
(defmethod harmony:transition ((nothing placeholder-resource) to &key in)
(declare (ignore nothing to in)))
(defun override-music (track)
(setf (override (unit 'environment +world+)) (when track (// 'music track))))
(defclass environment ()
((name :initarg :name :initform NIL :accessor name)
(music :initarg :music :initform NIL :accessor music)
(ambience :initarg :ambience :initform NIL :accessor ambience)
(area :initarg :area :initform NIL :accessor area)))
(defmethod print-object ((environment environment) stream)
(print-unreadable-object (environment stream :type T)
(format stream "~s" (name environment))))
(defmethod allocated-p ((environment environment))
(let ((music (music environment))
(ambience (ambience environment)))
(and (or (null ambience) (allocated-p ambience))
(or (null music) (allocated-p music)))))
(defmethod stage ((environment environment) (area staging-area))
(when (music environment) (stage (music environment) area))
(when (ambience environment) (stage (ambience environment) area)))
(defmethod state ((environment environment))
(let* ((controller (unit 'environment +world+))
(cons (assoc (area environment) (area-states controller))))
(if cons
(cdr cons)
:normal)))
(defmethod (setf state) (state (environment environment))
(issue +world+ 'switch-area-state :area (area environment) :state state))
(defmethod quest:activate ((environment environment))
(let ((controller (unit 'environment +world+)))
(when (not (eq environment (environment controller)))
(switch-environment (environment controller) environment))))
(defmethod switch-environment ((a null) (b null)))
(defmethod switch-environment ((none null) (environment environment))
(let ((state (state environment)))
(when (music environment)
(harmony:transition (music environment) state :in 5.0 :error NIL))
(when (ambience environment)
(harmony:transition (ambience environment) state :in 3.0 :error NIL))))
(defmethod switch-environment ((environment environment) (none null))
(when (music environment)
(harmony:transition (music environment) NIL :in 3.0))
(when (ambience environment)
(harmony:transition (ambience environment) NIL :in 5.0)))
(defmethod switch-environment ((from environment) (to environment))
(let ((state (state to)))
(flet ((tx (a b in &optional (state state))
(unless (eq a b)
(when a
(harmony:transition a NIL :in in)))
(when b
(harmony:transition b state :in in :error NIL))))
(tx (music from) (music to) 5.0)
(tx (ambience from) (ambience to) 3.0 :normal))))
(defmethod harmony:transition ((environment environment) (to real) &key (in 1.0))
(when (music environment)
(harmony:transition (music environment) to :in in))
(when (ambience environment)
(harmony:transition (ambience environment) to :in in)))
(defmethod environment ((name symbol))
(gethash name *environments*))
(defmethod (setf environment) ((value environment) (name symbol))
(setf (gethash name *environments*) value))
(defun remove-environment (name)
(remhash name *environments*))
(defun list-environments ()
(loop for env being the hash-values of *environments*
collect env))
(defmacro define-environment ((area name) &body initargs)
(let ((music (getf initargs :music))
(ambience (getf initargs :ambience))
(initargs (remf* initargs :music :ambience))
(name (trial::mksym *package* area '/ name)))
`(setf (environment ',name)
(ensure-instance (environment ',name) 'environment
:area ',area
:name ',name
:music ,(when music `(// 'music ,music))
:ambience ,(when ambience `(// 'music ,ambience))
,@initargs))))
(defmethod harmony:transition :before ((voice harmony::voice) (to real) &key)
(v:info :kandria.harmony "Transitioning ~a to ~a" voice to))
(trial-alloy:define-set-representation environment/combo
:represents environment
:item-text (string (when alloy:value (name alloy:value)))
(list-environments))
|
f958ff5eef3a0ed6f074e2f0c95532c0e0c61c6bf81a38b9cd953b688fcf18eb | mtt-lang/mtt-lang | Evaluator.ml | open Base
open Result.Let_syntax
open Ast
type error = [ `EvaluationError of string | Env.error ]
let rec free_vars_m Location.{ data = term; _ } =
let open Expr in
match term with
| Unit -> Set.empty (module Id.M)
| Pair { e1; e2 } -> Set.union (free_vars_m e1) (free_vars_m e2)
| Fst { e } | Snd { e } -> free_vars_m e
| Nat _ -> Set.empty (module Id.M)
| BinOp { op = _; e1; e2 } -> Set.union (free_vars_m e1) (free_vars_m e2)
| VarR _ -> Set.empty (module Id.M)
| VarM { idm } -> Set.singleton (module Id.M) idm
| Fun { idr = _; ty_id = _; body } -> free_vars_m body
| App { fe; arge } -> Set.union (free_vars_m fe) (free_vars_m arge)
| Box { e } -> free_vars_m e
| Let { idr = _; bound; body } ->
Set.union (free_vars_m bound) (free_vars_m body)
| Letbox { idm; boxed; body } ->
Set.union (free_vars_m boxed)
(Set.diff (free_vars_m body) (Set.singleton (module Id.M) idm))
| Match { matched; zbranch; pred = _; sbranch } ->
Set.union (free_vars_m matched)
@@ Set.union (free_vars_m zbranch) (free_vars_m sbranch)
let refresh_m idm fvs =
let rec loop (idm : Id.M.t) =
if Set.mem fvs idm then loop (Id.M.mk (Id.M.to_string idm ^ "'")) else idm
(* it's fresh enough already :) *)
in
if Set.mem fvs idm then Some (loop idm) else None
(* modal (modal) substitution *)
let rec subst_m term identm Location.{ data = body; _ } =
let open Expr in
match body with
| Unit -> Location.locate body
| Pair { e1; e2 } -> pair (subst_m term identm e1) (subst_m term identm e2)
| Fst { e } -> fst (subst_m term identm e)
| Snd { e } -> snd (subst_m term identm e)
| Nat _n -> Location.locate body
| BinOp { op; e1; e2 } ->
binop op (subst_m term identm e1) (subst_m term identm e2)
| VarR _i -> Location.locate body
| VarM { idm } ->
if [%equal: Id.M.t] identm idm then term else Location.locate body
| Fun { idr; ty_id; body } -> func idr ty_id (subst_m term identm body)
| App { fe; arge } -> app (subst_m term identm fe) (subst_m term identm arge)
| Box { e } -> box (subst_m term identm e)
| Let { idr; bound; body } ->
letc idr (subst_m term identm bound) (subst_m term identm body)
| Letbox { idm; boxed; body } ->
Location.locate
(if [%equal: Id.M.t] identm idm then
Letbox { idm; boxed = subst_m term identm boxed; body }
else
match refresh_m idm (free_vars_m term) with
| Some new_i ->
let body_with_renamed_bound_var =
subst_m (var_m new_i) idm body
in
Letbox
{
idm = new_i;
boxed = subst_m term identm boxed;
body = subst_m term identm body_with_renamed_bound_var;
}
| None ->
(* no need to rename the bound var *)
Letbox
{
idm;
boxed = subst_m term identm boxed;
body = subst_m term identm body;
})
| Match { matched; zbranch; pred; sbranch } ->
match_with
(subst_m term identm matched)
(subst_m term identm zbranch)
pred
(subst_m term identm sbranch)
let rec eval_open gamma Location.{ data = expr; _ } =
let open Expr in
match expr with
| Unit -> return Val.Unit
| Pair { e1; e2 } ->
let%map v1 = eval_open gamma e1 and v2 = eval_open gamma e2 in
Val.Pair { v1; v2 }
| Fst { e } -> (
let%bind pv = eval_open gamma e in
match pv with
| Val.Pair { v1; v2 = _ } -> return v1
| _ -> Result.fail @@ `EvaluationError "fst is stuck")
| Snd { e } -> (
let%bind pv = eval_open gamma e in
match pv with
| Val.Pair { v1 = _; v2 } -> return v2
| _ -> Result.fail @@ `EvaluationError "snd is stuck")
| Nat { n } -> return @@ Val.Nat { n }
| BinOp { op; e1; e2 } -> (
let%bind lhs = eval_open gamma e1 in
let%bind rhs = eval_open gamma e2 in
match (lhs, rhs) with
| Val.Nat { n = n1 }, Val.Nat { n = n2 } -> (
match op with
| Add -> return @@ Val.Nat { n = Nat.add n1 n2 }
| Sub -> return @@ Val.Nat { n = Nat.sub n1 n2 }
| Mul -> return @@ Val.Nat { n = Nat.mul n1 n2 }
| Div ->
if Nat.equal n2 Nat.zero then
Result.fail @@ `EvaluationError "Division by zero"
else return @@ Val.Nat { n = Nat.div n1 n2 })
| _, _ ->
Result.fail
@@ `EvaluationError "Only numbers can be used in arithmetics")
| VarR { idr } -> Env.R.lookup gamma idr
| VarM _ ->
Result.fail
@@ `EvaluationError
"Modal variable access is not possible in a well-typed term"
| Fun { idr; ty_id = _; body } ->
return @@ Val.Clos { idr; body; env = gamma }
| App { fe; arge } -> (
let%bind fv = eval_open gamma fe in
let%bind argv = eval_open gamma arge in
match fv with
| Val.Clos { idr; body; env } ->
eval_open (Env.R.extend env idr argv) body
| _ ->
Result.fail
@@ `EvaluationError "Trying to apply an argument to a non-function")
| Box { e } -> return @@ Val.Box { e }
| Let { idr; bound; body } ->
let%bind bound_v = eval_open gamma bound in
eval_open (Env.R.extend gamma idr bound_v) body
| Letbox { idm; boxed; body } -> (
let%bind boxed_v = eval_open gamma boxed in
match boxed_v with
| Val.Box { e } -> eval_open gamma (subst_m e idm body)
| _ ->
Result.fail @@ `EvaluationError "Trying to unbox a non-box expression"
)
| Match { matched; zbranch; pred; sbranch } -> (
let%bind v = eval_open gamma matched in
match v with
| Nat { n } ->
let predn = Val.Nat { n = Nat.pred n } in
if Nat.equal n Nat.zero then eval_open gamma zbranch
else eval_open (Env.R.extend gamma pred predn) sbranch
| _ ->
Result.fail
@@ `EvaluationError "Pattern matching is supported for Nat now")
let eval expr = eval_open Env.R.emp expr
| null | https://raw.githubusercontent.com/mtt-lang/mtt-lang/2d330efccd154e1c158dc673ca3ec4f64b9dd09e/core/Evaluator.ml | ocaml | it's fresh enough already :)
modal (modal) substitution
no need to rename the bound var | open Base
open Result.Let_syntax
open Ast
type error = [ `EvaluationError of string | Env.error ]
let rec free_vars_m Location.{ data = term; _ } =
let open Expr in
match term with
| Unit -> Set.empty (module Id.M)
| Pair { e1; e2 } -> Set.union (free_vars_m e1) (free_vars_m e2)
| Fst { e } | Snd { e } -> free_vars_m e
| Nat _ -> Set.empty (module Id.M)
| BinOp { op = _; e1; e2 } -> Set.union (free_vars_m e1) (free_vars_m e2)
| VarR _ -> Set.empty (module Id.M)
| VarM { idm } -> Set.singleton (module Id.M) idm
| Fun { idr = _; ty_id = _; body } -> free_vars_m body
| App { fe; arge } -> Set.union (free_vars_m fe) (free_vars_m arge)
| Box { e } -> free_vars_m e
| Let { idr = _; bound; body } ->
Set.union (free_vars_m bound) (free_vars_m body)
| Letbox { idm; boxed; body } ->
Set.union (free_vars_m boxed)
(Set.diff (free_vars_m body) (Set.singleton (module Id.M) idm))
| Match { matched; zbranch; pred = _; sbranch } ->
Set.union (free_vars_m matched)
@@ Set.union (free_vars_m zbranch) (free_vars_m sbranch)
let refresh_m idm fvs =
let rec loop (idm : Id.M.t) =
if Set.mem fvs idm then loop (Id.M.mk (Id.M.to_string idm ^ "'")) else idm
in
if Set.mem fvs idm then Some (loop idm) else None
let rec subst_m term identm Location.{ data = body; _ } =
let open Expr in
match body with
| Unit -> Location.locate body
| Pair { e1; e2 } -> pair (subst_m term identm e1) (subst_m term identm e2)
| Fst { e } -> fst (subst_m term identm e)
| Snd { e } -> snd (subst_m term identm e)
| Nat _n -> Location.locate body
| BinOp { op; e1; e2 } ->
binop op (subst_m term identm e1) (subst_m term identm e2)
| VarR _i -> Location.locate body
| VarM { idm } ->
if [%equal: Id.M.t] identm idm then term else Location.locate body
| Fun { idr; ty_id; body } -> func idr ty_id (subst_m term identm body)
| App { fe; arge } -> app (subst_m term identm fe) (subst_m term identm arge)
| Box { e } -> box (subst_m term identm e)
| Let { idr; bound; body } ->
letc idr (subst_m term identm bound) (subst_m term identm body)
| Letbox { idm; boxed; body } ->
Location.locate
(if [%equal: Id.M.t] identm idm then
Letbox { idm; boxed = subst_m term identm boxed; body }
else
match refresh_m idm (free_vars_m term) with
| Some new_i ->
let body_with_renamed_bound_var =
subst_m (var_m new_i) idm body
in
Letbox
{
idm = new_i;
boxed = subst_m term identm boxed;
body = subst_m term identm body_with_renamed_bound_var;
}
| None ->
Letbox
{
idm;
boxed = subst_m term identm boxed;
body = subst_m term identm body;
})
| Match { matched; zbranch; pred; sbranch } ->
match_with
(subst_m term identm matched)
(subst_m term identm zbranch)
pred
(subst_m term identm sbranch)
let rec eval_open gamma Location.{ data = expr; _ } =
let open Expr in
match expr with
| Unit -> return Val.Unit
| Pair { e1; e2 } ->
let%map v1 = eval_open gamma e1 and v2 = eval_open gamma e2 in
Val.Pair { v1; v2 }
| Fst { e } -> (
let%bind pv = eval_open gamma e in
match pv with
| Val.Pair { v1; v2 = _ } -> return v1
| _ -> Result.fail @@ `EvaluationError "fst is stuck")
| Snd { e } -> (
let%bind pv = eval_open gamma e in
match pv with
| Val.Pair { v1 = _; v2 } -> return v2
| _ -> Result.fail @@ `EvaluationError "snd is stuck")
| Nat { n } -> return @@ Val.Nat { n }
| BinOp { op; e1; e2 } -> (
let%bind lhs = eval_open gamma e1 in
let%bind rhs = eval_open gamma e2 in
match (lhs, rhs) with
| Val.Nat { n = n1 }, Val.Nat { n = n2 } -> (
match op with
| Add -> return @@ Val.Nat { n = Nat.add n1 n2 }
| Sub -> return @@ Val.Nat { n = Nat.sub n1 n2 }
| Mul -> return @@ Val.Nat { n = Nat.mul n1 n2 }
| Div ->
if Nat.equal n2 Nat.zero then
Result.fail @@ `EvaluationError "Division by zero"
else return @@ Val.Nat { n = Nat.div n1 n2 })
| _, _ ->
Result.fail
@@ `EvaluationError "Only numbers can be used in arithmetics")
| VarR { idr } -> Env.R.lookup gamma idr
| VarM _ ->
Result.fail
@@ `EvaluationError
"Modal variable access is not possible in a well-typed term"
| Fun { idr; ty_id = _; body } ->
return @@ Val.Clos { idr; body; env = gamma }
| App { fe; arge } -> (
let%bind fv = eval_open gamma fe in
let%bind argv = eval_open gamma arge in
match fv with
| Val.Clos { idr; body; env } ->
eval_open (Env.R.extend env idr argv) body
| _ ->
Result.fail
@@ `EvaluationError "Trying to apply an argument to a non-function")
| Box { e } -> return @@ Val.Box { e }
| Let { idr; bound; body } ->
let%bind bound_v = eval_open gamma bound in
eval_open (Env.R.extend gamma idr bound_v) body
| Letbox { idm; boxed; body } -> (
let%bind boxed_v = eval_open gamma boxed in
match boxed_v with
| Val.Box { e } -> eval_open gamma (subst_m e idm body)
| _ ->
Result.fail @@ `EvaluationError "Trying to unbox a non-box expression"
)
| Match { matched; zbranch; pred; sbranch } -> (
let%bind v = eval_open gamma matched in
match v with
| Nat { n } ->
let predn = Val.Nat { n = Nat.pred n } in
if Nat.equal n Nat.zero then eval_open gamma zbranch
else eval_open (Env.R.extend gamma pred predn) sbranch
| _ ->
Result.fail
@@ `EvaluationError "Pattern matching is supported for Nat now")
let eval expr = eval_open Env.R.emp expr
|
782242214e20b45b325077c2c8d1498eeb902cc506ed64c6f591b1c10f036ae2 | robrix/Manifold | REPL.hs | # LANGUAGE DeriveFunctor , FlexibleContexts , FlexibleInstances , LambdaCase , MultiParamTypeClasses , PolyKinds , TypeOperators , UndecidableInstances #
module Manifold.REPL where
import Control.Applicative (Alternative(..))
import Control.Effect
import Data.Functor (($>))
import Data.Semilattice.Lower
import Data.Semiring
import qualified GHC.Generics as G
import Manifold.Abstract.Address.Precise as Precise (AllocatorC, EnvC, Precise, runAllocator, runEnv)
import Manifold.Abstract.Env (Environment, EnvError)
import Manifold.Abstract.Evaluator (Evaluator(..))
import Manifold.Abstract.Store (Store, StoreError, runStore)
import Manifold.Constraint
import Manifold.Context
import Manifold.Eval (EvalC, eval, runEval)
import Manifold.Name
import Manifold.Name.Annotated
import Manifold.Parser as Parser
import Manifold.Pretty (Pretty, prettyShow)
import Manifold.Prompt
import Manifold.Proof
import Manifold.Proof.Checking
import Manifold.Purpose
import Manifold.Substitution
import Manifold.Term
import Manifold.Type
import Manifold.Unification
import Manifold.Value as Value
import System.Console.Haskeline (InputT)
import Text.Trifecta as Trifecta
repl :: (Member Prompt sig, Member (REPL usage) sig, Monoid usage, Pretty usage, Carrier sig m) => Proof usage m ()
repl = prompt >>= maybe repl handleInput
handleInput :: (Member Prompt sig, Member (REPL usage) sig, Monoid usage, Pretty usage, Carrier sig m) => String -> Proof usage m ()
handleInput str = case Parser.parseString command str of
Left err -> output err *> repl
Right action -> action
command :: (Member Prompt sig, Member (REPL usage) sig, Monoid usage, Pretty usage, Carrier sig m) => Parser.Parser (Proof usage m ())
command = whole (meta <|> eval <$> term) <?> "command"
where meta = colon
*> ((long "help" <|> short 'h' <|> short '?' <?> "help") $> (sendREPL (Help (gen ())) *> repl)
<|> (long "quit" <|> short 'q' <?> "quit") $> pure ()
<|> (typeOf <$> ((long "type" <|> short 't') *> term) <?> "type of")
<?> "command; use :? for help")
eval term = sendREPL (Eval term gen) >>= output . either prettyShow (either prettyShow prettyShow) >> repl
typeOf term = sendREPL (TypeOf term gen) >>= output . either prettyShow prettyShow >> repl
short = symbol . (:[])
long = symbol
sendREPL :: (Member (REPL usage) sig, Carrier sig m) => REPL usage (Proof usage m) (Proof usage m result) -> Proof usage m result
sendREPL = send
data REPL usage m k
= Help k
| TypeOf (Term Name) (Either (ProofError (Annotated usage)) (Type (Annotated usage)) -> k)
| Eval
(Term Name)
(Either
(ProofError (Annotated usage))
(Either
(SomeError
( EnvError Precise
G.:+: StoreError Precise (Value Precise (ValueC (Eff VoidC)))
G.:+: ValueError Precise (ValueC (Eff VoidC))))
(Value Precise (ValueC (Eff VoidC))))
-> k)
deriving (Functor)
instance HFunctor (REPL usage) where
hfmap _ (Help k) = Help k
hfmap _ (TypeOf tm k) = TypeOf tm k
hfmap _ (Eval tm k) = Eval tm k
instance Effect (REPL usage) where
handle state handler (Help k) = Help (handler . (<$ state) $ k)
handle state handler (TypeOf t k) = TypeOf t (handler . (<$ state) . k)
handle state handler (Eval t k) = Eval t (handler . (<$ state) . k)
newtype ValueC m a
= ValueC (Evaluator Precise (Value Precise (ValueC m)) (Precise.EnvC
(Evaluator Precise (Value Precise (ValueC m)) (ReaderC (Environment Precise)
(Evaluator Precise (Value Precise (ValueC m)) (Precise.AllocatorC
(Evaluator Precise (Value Precise (ValueC m)) (StateC (Store Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (FreshC
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (EnvError Precise)
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (StoreError Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (ValueError Precise (ValueC m))
m))))))))))))))) a)
type Prelude var = Context (Constraint var (Type var))
runREPL :: (Eq usage, Member Prompt sig, Monoid usage, Unital usage, Carrier sig m, Effect sig) => Prelude (Annotated usage) -> Proof usage (REPLC usage (Proof usage m)) a -> Proof usage m a
runREPL prelude = flip runREPLC prelude . interpret . runProof
newtype REPLC usage m a = REPLC { runREPLC :: Prelude (Annotated usage) -> m a }
instance (Eq usage, Member Prompt sig, Carrier sig m, Monoid usage, Unital usage, Effect sig) => Carrier (REPL usage :+: sig) (REPLC usage (Proof usage m)) where
gen a = REPLC (\ _ -> pure a)
alg = algR \/ algOther
where algR (Help k) = REPLC (\ prelude -> output (unlines
[ ":help, :h, :? - print this help text"
, ":quit, :q - exit the REPL"
, ":type, :t <expr> - print the type of <expr>"
, "<expr> - typecheck & evaluate <expr>"
]) >> runREPLC k prelude)
algR (TypeOf term k) = REPLC (\ prelude -> runCheck' Intensional (local (const prelude) (infer term)) >>= flip runREPLC prelude . k)
algR (Eval term k) = REPLC (\ prelude -> do
res <- runCheck' Intensional (local (const prelude) (infer term))
case res of
Left err -> runREPLC (k (Left err)) prelude
_ -> runREPLC (k (Right (run (runEval' (eval term))))) prelude)
algOther op = REPLC (\ prelude -> alg (handlePure (flip runREPLC prelude) op))
runCheck' :: ( Effectful sig m'
, Eq usage
, Monoid usage
, Unital usage
)
=> Purpose
-> Proof usage (CheckC usage
(Proof usage (UnifyC usage
(Proof usage (ReaderC (Context (Constraint (Annotated usage) (Type (Annotated usage))))
(Proof usage (ReaderC usage
(Proof usage (FreshC
(Proof usage (StateC (Substitution (Type (Annotated usage)))
(Proof usage (ErrorC (ProofError (Annotated usage))
m'))))))))))))) (Type (Annotated usage))
-> m'
(Either
(ProofError (Annotated usage))
(Type (Annotated usage)))
runCheck' purpose = runError . runProof . runSubstitution . runFresh . runProof . runSigma purpose . runContext . runUnify . runCheck
runEval' :: Effectful sig m
=> Evaluator Precise (Value Precise (ValueC m)) (EvalC
(Evaluator Precise (Value Precise (ValueC m)) (Value.DataC
(Evaluator Precise (Value Precise (ValueC m)) (Value.FunctionC
(Evaluator Precise (Value Precise (ValueC m)) (Precise.EnvC
(Evaluator Precise (Value Precise (ValueC m)) (ReaderC (Environment Precise)
(Evaluator Precise (Value Precise (ValueC m)) (Precise.AllocatorC
(Evaluator Precise (Value Precise (ValueC m)) (StateC (Store Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (FreshC
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (EnvError Precise)
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (StoreError Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (ValueError Precise (ValueC m))
m))))))))))))))))))))) a
-> m
(Either
(SomeError
( EnvError Precise
G.:+: StoreError Precise (Value Precise (ValueC m))
G.:+: ValueError Precise (ValueC m)))
a)
runEval' = fmap (merge . merge) . runResumable . runEvaluator . runResumable . runEvaluator . runResumable . runEvaluator . runFresh . runEvaluator . fmap snd . runStore . Precise.runAllocator . runReader lowerBound . runEvaluator . Precise.runEnv . Value.runFunction . Value.runData . runEval
where merge :: Either (SomeError sum) (Either (SomeError exc) a) -> Either (SomeError (exc G.:+: sum)) a
merge (Left (SomeError exc)) = Left (SomeError (G.R1 exc))
merge (Right (Left (SomeError exc))) = Left (SomeError (G.L1 exc))
merge (Right (Right a)) = Right a
runIO :: (Eq usage, Monoid usage, Unital usage) => Prelude (Annotated usage) -> Proof usage (REPLC usage (Proof usage (PromptC (Eff (LiftC (InputT IO)))))) a -> IO a
runIO prelude = runPrompt "λ: " . runProof . runREPL prelude
| null | https://raw.githubusercontent.com/robrix/Manifold/3cc7a49c90b9cc7d1da61c532d0ee526ccdd3474/src/Manifold/REPL.hs | haskell | # LANGUAGE DeriveFunctor , FlexibleContexts , FlexibleInstances , LambdaCase , MultiParamTypeClasses , PolyKinds , TypeOperators , UndecidableInstances #
module Manifold.REPL where
import Control.Applicative (Alternative(..))
import Control.Effect
import Data.Functor (($>))
import Data.Semilattice.Lower
import Data.Semiring
import qualified GHC.Generics as G
import Manifold.Abstract.Address.Precise as Precise (AllocatorC, EnvC, Precise, runAllocator, runEnv)
import Manifold.Abstract.Env (Environment, EnvError)
import Manifold.Abstract.Evaluator (Evaluator(..))
import Manifold.Abstract.Store (Store, StoreError, runStore)
import Manifold.Constraint
import Manifold.Context
import Manifold.Eval (EvalC, eval, runEval)
import Manifold.Name
import Manifold.Name.Annotated
import Manifold.Parser as Parser
import Manifold.Pretty (Pretty, prettyShow)
import Manifold.Prompt
import Manifold.Proof
import Manifold.Proof.Checking
import Manifold.Purpose
import Manifold.Substitution
import Manifold.Term
import Manifold.Type
import Manifold.Unification
import Manifold.Value as Value
import System.Console.Haskeline (InputT)
import Text.Trifecta as Trifecta
repl :: (Member Prompt sig, Member (REPL usage) sig, Monoid usage, Pretty usage, Carrier sig m) => Proof usage m ()
repl = prompt >>= maybe repl handleInput
handleInput :: (Member Prompt sig, Member (REPL usage) sig, Monoid usage, Pretty usage, Carrier sig m) => String -> Proof usage m ()
handleInput str = case Parser.parseString command str of
Left err -> output err *> repl
Right action -> action
command :: (Member Prompt sig, Member (REPL usage) sig, Monoid usage, Pretty usage, Carrier sig m) => Parser.Parser (Proof usage m ())
command = whole (meta <|> eval <$> term) <?> "command"
where meta = colon
*> ((long "help" <|> short 'h' <|> short '?' <?> "help") $> (sendREPL (Help (gen ())) *> repl)
<|> (long "quit" <|> short 'q' <?> "quit") $> pure ()
<|> (typeOf <$> ((long "type" <|> short 't') *> term) <?> "type of")
<?> "command; use :? for help")
eval term = sendREPL (Eval term gen) >>= output . either prettyShow (either prettyShow prettyShow) >> repl
typeOf term = sendREPL (TypeOf term gen) >>= output . either prettyShow prettyShow >> repl
short = symbol . (:[])
long = symbol
sendREPL :: (Member (REPL usage) sig, Carrier sig m) => REPL usage (Proof usage m) (Proof usage m result) -> Proof usage m result
sendREPL = send
data REPL usage m k
= Help k
| TypeOf (Term Name) (Either (ProofError (Annotated usage)) (Type (Annotated usage)) -> k)
| Eval
(Term Name)
(Either
(ProofError (Annotated usage))
(Either
(SomeError
( EnvError Precise
G.:+: StoreError Precise (Value Precise (ValueC (Eff VoidC)))
G.:+: ValueError Precise (ValueC (Eff VoidC))))
(Value Precise (ValueC (Eff VoidC))))
-> k)
deriving (Functor)
instance HFunctor (REPL usage) where
hfmap _ (Help k) = Help k
hfmap _ (TypeOf tm k) = TypeOf tm k
hfmap _ (Eval tm k) = Eval tm k
instance Effect (REPL usage) where
handle state handler (Help k) = Help (handler . (<$ state) $ k)
handle state handler (TypeOf t k) = TypeOf t (handler . (<$ state) . k)
handle state handler (Eval t k) = Eval t (handler . (<$ state) . k)
newtype ValueC m a
= ValueC (Evaluator Precise (Value Precise (ValueC m)) (Precise.EnvC
(Evaluator Precise (Value Precise (ValueC m)) (ReaderC (Environment Precise)
(Evaluator Precise (Value Precise (ValueC m)) (Precise.AllocatorC
(Evaluator Precise (Value Precise (ValueC m)) (StateC (Store Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (FreshC
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (EnvError Precise)
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (StoreError Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (ValueError Precise (ValueC m))
m))))))))))))))) a)
type Prelude var = Context (Constraint var (Type var))
runREPL :: (Eq usage, Member Prompt sig, Monoid usage, Unital usage, Carrier sig m, Effect sig) => Prelude (Annotated usage) -> Proof usage (REPLC usage (Proof usage m)) a -> Proof usage m a
runREPL prelude = flip runREPLC prelude . interpret . runProof
newtype REPLC usage m a = REPLC { runREPLC :: Prelude (Annotated usage) -> m a }
instance (Eq usage, Member Prompt sig, Carrier sig m, Monoid usage, Unital usage, Effect sig) => Carrier (REPL usage :+: sig) (REPLC usage (Proof usage m)) where
gen a = REPLC (\ _ -> pure a)
alg = algR \/ algOther
where algR (Help k) = REPLC (\ prelude -> output (unlines
[ ":help, :h, :? - print this help text"
, ":quit, :q - exit the REPL"
, ":type, :t <expr> - print the type of <expr>"
, "<expr> - typecheck & evaluate <expr>"
]) >> runREPLC k prelude)
algR (TypeOf term k) = REPLC (\ prelude -> runCheck' Intensional (local (const prelude) (infer term)) >>= flip runREPLC prelude . k)
algR (Eval term k) = REPLC (\ prelude -> do
res <- runCheck' Intensional (local (const prelude) (infer term))
case res of
Left err -> runREPLC (k (Left err)) prelude
_ -> runREPLC (k (Right (run (runEval' (eval term))))) prelude)
algOther op = REPLC (\ prelude -> alg (handlePure (flip runREPLC prelude) op))
runCheck' :: ( Effectful sig m'
, Eq usage
, Monoid usage
, Unital usage
)
=> Purpose
-> Proof usage (CheckC usage
(Proof usage (UnifyC usage
(Proof usage (ReaderC (Context (Constraint (Annotated usage) (Type (Annotated usage))))
(Proof usage (ReaderC usage
(Proof usage (FreshC
(Proof usage (StateC (Substitution (Type (Annotated usage)))
(Proof usage (ErrorC (ProofError (Annotated usage))
m'))))))))))))) (Type (Annotated usage))
-> m'
(Either
(ProofError (Annotated usage))
(Type (Annotated usage)))
runCheck' purpose = runError . runProof . runSubstitution . runFresh . runProof . runSigma purpose . runContext . runUnify . runCheck
runEval' :: Effectful sig m
=> Evaluator Precise (Value Precise (ValueC m)) (EvalC
(Evaluator Precise (Value Precise (ValueC m)) (Value.DataC
(Evaluator Precise (Value Precise (ValueC m)) (Value.FunctionC
(Evaluator Precise (Value Precise (ValueC m)) (Precise.EnvC
(Evaluator Precise (Value Precise (ValueC m)) (ReaderC (Environment Precise)
(Evaluator Precise (Value Precise (ValueC m)) (Precise.AllocatorC
(Evaluator Precise (Value Precise (ValueC m)) (StateC (Store Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (FreshC
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (EnvError Precise)
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (StoreError Precise (Value Precise (ValueC m)))
(Evaluator Precise (Value Precise (ValueC m)) (ResumableC (ValueError Precise (ValueC m))
m))))))))))))))))))))) a
-> m
(Either
(SomeError
( EnvError Precise
G.:+: StoreError Precise (Value Precise (ValueC m))
G.:+: ValueError Precise (ValueC m)))
a)
runEval' = fmap (merge . merge) . runResumable . runEvaluator . runResumable . runEvaluator . runResumable . runEvaluator . runFresh . runEvaluator . fmap snd . runStore . Precise.runAllocator . runReader lowerBound . runEvaluator . Precise.runEnv . Value.runFunction . Value.runData . runEval
where merge :: Either (SomeError sum) (Either (SomeError exc) a) -> Either (SomeError (exc G.:+: sum)) a
merge (Left (SomeError exc)) = Left (SomeError (G.R1 exc))
merge (Right (Left (SomeError exc))) = Left (SomeError (G.L1 exc))
merge (Right (Right a)) = Right a
runIO :: (Eq usage, Monoid usage, Unital usage) => Prelude (Annotated usage) -> Proof usage (REPLC usage (Proof usage (PromptC (Eff (LiftC (InputT IO)))))) a -> IO a
runIO prelude = runPrompt "λ: " . runProof . runREPL prelude
|
|
4d5184a6733fdee665a7e8e81fa09d27c8de498f700c46068e32b6e477d76317 | johnwhitington/ocamli | curry.ml | let f x y = x + y in
f 3 (f (1 + 1) (2 + 2))
| null | https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/examples/curry.ml | ocaml | let f x y = x + y in
f 3 (f (1 + 1) (2 + 2))
|
|
78bb82218b33561e1b0f69ed7d0f26a50fa71bf3473becde4550975ccadf7594 | mgajda/syntaxnet-haskell | SyntaxNet.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE RecordWildCards #-}
module NLP.SyntaxNet.SyntaxNet
( readCnll
, readParseTree
, SnConllToken(..)
, Data.ConllToken.ConllToken (..)
, NLP.SyntaxNet.Types.CoNLL.PosCG(..)
, Model.PennTreebank.POS (..)
, Model.UniversalTreebank.REL (..)
) where
import Control.Applicative
import Control.Concurrent
import qualified Control.Exception as E
import Control.Lens hiding (at)
import Control.Monad
import Control.Monad.IO.Class
import Data.Aeson
import Data.Char
import qualified Data.Csv as Csv
import Data.Tree
import Data.Maybe
import Protolude
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy as BSL
import Data.Functor ((<$>))
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TEL
import qualified Data.Vector as V
import Safe as S
import Data.String
import Data.ConllToken
import Data.ParsedSentence
import Data.SyntaxTree
import Data.TagLabel
import NLP.SyntaxNet.Types.CoNLL
import NLP.SyntaxNet.Types.ParseTree
import Model.PennTreebank (POS(..))
import Model.UniversalTreebank(REL(..))
--------------------------------------------------------------------------------
readCnll :: FilePath -> IO [SnConllToken Text]
readCnll fpath = do
csvData <- BSL.readFile fpath
case TEL.decodeUtf8' csvData of
Left err -> do
putStrLn $ "error decoding" ++ (show err)
return []
Right dat -> do
let res = (Csv.decodeWith cnllOptions Csv.NoHeader $ TEL.encodeUtf8 dat) :: Either String (V.Vector (SnConllToken Text))
case res of
Left err -> do
putStrLn $ "error decoding" ++ (show err)
return []
Right vals ->
return $ V.toList vals
preprocess :: TL.Text -> TL.Text
preprocess txt = TL.cons '\"' $ TL.snoc escaped '\"'
where escaped = TL.concatMap escaper txt
escaper :: Char -> TL.Text
escaper c
| c == '\t' = "\"\t\""
| c == '\n' = "\"\n\""
| c == '\"' = "\"\""
| otherwise = TL.singleton c
-- | Define custom options to read tab-delimeted files
cnllOptions =
Csv.defaultDecodeOptions
{ Csv.decDelimiter = fromIntegral (ord '\t')
}
--------------------------------------------------------------------------------
-- Dealing with trees
readParseTree :: FilePath -> IO (Maybe (Tree (SnConllToken Text)))
readParseTree fpath = do
treeData <- BSC.readFile fpath
let ls = BSC.lines treeData
let lls = map ( \x -> BSC.split ' ' x) ls
lln = map parseNode lls
let tree = fromList lln
return $ tree
-- | Same as readParseTree but for debugging
--
readParseTree' :: FilePath -> IO ()
readParseTree' fpath = do
treeData <- BSC.readFile fpath
let ls = BSC.lines treeData
mapM_ (putStrLn . T.pack . show ) ls
let lls = map ( \x -> BSC.split ' ' x) ls
lln <- mapM parseNode' ls
tree <- fromList' $ lln
mapM_ (putStrLn . T.pack . show ) lln
putStrLn $ T.pack $ "----\n"
putStrLn $ T.pack $ show $ drawTree' $ fromJust tree
return $ ()
parseNode :: [BSC.ByteString] -> SnConllToken Text
parseNode llbs = do
let llss = map BSC.unpack llbs
useful labels like TOKEN POS ER
each identation takes 2 spaces
let lls = map T.pack llss
lvl = (length lls) - lenLB - lenWP -- calculate actual level
lbls = drop ((length lls) - 3) lls -- extract only lables
ConllToken lvl -- reuse id to indicate level, when working with trees
(lbls `at` 0)
""
UnkCg
(parsePosFg $ lbls `at` 1)
""
0
(parseGER $ lbls `at` 2)
""
""
parseNode' :: BSC.ByteString -> IO (SnConllToken Text)
parseNode' bs = do
let llbs = filter (/="|") $ BSC.split ' ' bs
llss = map BSC.unpack llbs
useful labels like TOKEN POS ER
always have 1 in front , each identation takes 2 spaces
let llt = map T.pack llss
llsf = filter (/="") llt
lvl = ((mod lenWP 2))+1 -- calculate actual level
lbls = drop ((length llt) - 3) llt -- extract only lables
putStrLn $ T.pack $ show $ llss
putStrLn $ T.pack $ show $ llsf
putStrLn $ T.pack $ show $ lenWP
putStrLn $ T.pack $ show $ lvl
return $ ConllToken lvl -- reuse id to indicate level, when working with trees
(lbls `at` 0)
""
UnkCg
(parsePosFg $ lbls `at` 1)
""
0
(parseGER $ lbls `at` 2)
""
""
| null | https://raw.githubusercontent.com/mgajda/syntaxnet-haskell/c29f41721672f48bb8a308ca7e7a81ee84e279d4/src/NLP/SyntaxNet/SyntaxNet.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
------------------------------------------------------------------------------
| Define custom options to read tab-delimeted files
------------------------------------------------------------------------------
Dealing with trees
| Same as readParseTree but for debugging
calculate actual level
extract only lables
reuse id to indicate level, when working with trees
calculate actual level
extract only lables
reuse id to indicate level, when working with trees | # LANGUAGE ScopedTypeVariables #
module NLP.SyntaxNet.SyntaxNet
( readCnll
, readParseTree
, SnConllToken(..)
, Data.ConllToken.ConllToken (..)
, NLP.SyntaxNet.Types.CoNLL.PosCG(..)
, Model.PennTreebank.POS (..)
, Model.UniversalTreebank.REL (..)
) where
import Control.Applicative
import Control.Concurrent
import qualified Control.Exception as E
import Control.Lens hiding (at)
import Control.Monad
import Control.Monad.IO.Class
import Data.Aeson
import Data.Char
import qualified Data.Csv as Csv
import Data.Tree
import Data.Maybe
import Protolude
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy as BSL
import Data.Functor ((<$>))
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TEL
import qualified Data.Vector as V
import Safe as S
import Data.String
import Data.ConllToken
import Data.ParsedSentence
import Data.SyntaxTree
import Data.TagLabel
import NLP.SyntaxNet.Types.CoNLL
import NLP.SyntaxNet.Types.ParseTree
import Model.PennTreebank (POS(..))
import Model.UniversalTreebank(REL(..))
readCnll :: FilePath -> IO [SnConllToken Text]
readCnll fpath = do
csvData <- BSL.readFile fpath
case TEL.decodeUtf8' csvData of
Left err -> do
putStrLn $ "error decoding" ++ (show err)
return []
Right dat -> do
let res = (Csv.decodeWith cnllOptions Csv.NoHeader $ TEL.encodeUtf8 dat) :: Either String (V.Vector (SnConllToken Text))
case res of
Left err -> do
putStrLn $ "error decoding" ++ (show err)
return []
Right vals ->
return $ V.toList vals
preprocess :: TL.Text -> TL.Text
preprocess txt = TL.cons '\"' $ TL.snoc escaped '\"'
where escaped = TL.concatMap escaper txt
escaper :: Char -> TL.Text
escaper c
| c == '\t' = "\"\t\""
| c == '\n' = "\"\n\""
| c == '\"' = "\"\""
| otherwise = TL.singleton c
cnllOptions =
Csv.defaultDecodeOptions
{ Csv.decDelimiter = fromIntegral (ord '\t')
}
readParseTree :: FilePath -> IO (Maybe (Tree (SnConllToken Text)))
readParseTree fpath = do
treeData <- BSC.readFile fpath
let ls = BSC.lines treeData
let lls = map ( \x -> BSC.split ' ' x) ls
lln = map parseNode lls
let tree = fromList lln
return $ tree
readParseTree' :: FilePath -> IO ()
readParseTree' fpath = do
treeData <- BSC.readFile fpath
let ls = BSC.lines treeData
mapM_ (putStrLn . T.pack . show ) ls
let lls = map ( \x -> BSC.split ' ' x) ls
lln <- mapM parseNode' ls
tree <- fromList' $ lln
mapM_ (putStrLn . T.pack . show ) lln
putStrLn $ T.pack $ "----\n"
putStrLn $ T.pack $ show $ drawTree' $ fromJust tree
return $ ()
parseNode :: [BSC.ByteString] -> SnConllToken Text
parseNode llbs = do
let llss = map BSC.unpack llbs
useful labels like TOKEN POS ER
each identation takes 2 spaces
let lls = map T.pack llss
(lbls `at` 0)
""
UnkCg
(parsePosFg $ lbls `at` 1)
""
0
(parseGER $ lbls `at` 2)
""
""
parseNode' :: BSC.ByteString -> IO (SnConllToken Text)
parseNode' bs = do
let llbs = filter (/="|") $ BSC.split ' ' bs
llss = map BSC.unpack llbs
useful labels like TOKEN POS ER
always have 1 in front , each identation takes 2 spaces
let llt = map T.pack llss
llsf = filter (/="") llt
putStrLn $ T.pack $ show $ llss
putStrLn $ T.pack $ show $ llsf
putStrLn $ T.pack $ show $ lenWP
putStrLn $ T.pack $ show $ lvl
(lbls `at` 0)
""
UnkCg
(parsePosFg $ lbls `at` 1)
""
0
(parseGER $ lbls `at` 2)
""
""
|
cd182de3a3ac9dfcb898b328349c913c791a95779f25097cf514ce41cc8c0a5a | herd/herdtools7 | X86Arch_gen.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2010 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
open Code
include X86Base
let tr_endian = Misc.identity
module ScopeGen = ScopeGen.NoGen
let bellatom = false
module SIMD = NoSIMD
type atom = Atomic
let default_atom = Atomic
let applies_atom a d = match a,d with
| Atomic,W -> true
| _,_ -> false
let compare_atom = compare
include MachMixed.No
let merge_atoms Atomic Atomic = Some Atomic
let overlap_atoms _ _ = true
let pp_plain = Code.plain
let pp_as_a = None
let pp_atom = function
| Atomic -> "A"
let fold_non_mixed f k = f Atomic k
let fold_atom f k = fold_non_mixed f k
let worth_final _ = true
let varatom_dir _d f = f None
let atom_to_bank _ = Code.Ord
include NoMixed
include NoWide
module PteVal = PteVal_gen.No(struct type arch_atom = atom end)
(**********)
(* Fences *)
(**********)
type fence = MFence
let is_isync _ = false
let compare_fence = compare
let default = MFence
let strong = default
let pp_fence = function
| MFence -> "MFence"
let fold_all_fences f r = f MFence r
let fold_cumul_fences f r = f MFence r
let fold_some_fences f r = f MFence r
let orders f d1 d2 = match f,d1,d2 with
| MFence,_,_ -> true
let var_fence f r = f default r
(********)
(********)
type dp
let pp_dp _ = assert false
let fold_dpr _f r = r
let fold_dpw _f r = r
let ddr_default = None
let ddw_default = None
let ctrlr_default = None
let ctrlw_default = None
let is_ctrlr _ = assert false
let is_addr _ = assert false
let fst_dp _ = assert false
let sequence_dp _ _ = assert false
(*******)
RWM
(*******)
include Exch.Exch(struct type arch_atom = atom end)
include NoEdge
include
ArchExtra_gen.Make
(struct
type arch_reg = reg
let is_symbolic = function
| Symbolic_reg _ -> true
| _ -> false
let pp_reg = pp_reg
let free_registers = allowed_for_symb
include NoSpecial
end)
| null | https://raw.githubusercontent.com/herd/herdtools7/36806ac2b4139957a14fd90512727f2d51a1a096/gen/X86Arch_gen.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
********
Fences
********
******
******
*****
***** | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2010 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
open Code
include X86Base
let tr_endian = Misc.identity
module ScopeGen = ScopeGen.NoGen
let bellatom = false
module SIMD = NoSIMD
type atom = Atomic
let default_atom = Atomic
let applies_atom a d = match a,d with
| Atomic,W -> true
| _,_ -> false
let compare_atom = compare
include MachMixed.No
let merge_atoms Atomic Atomic = Some Atomic
let overlap_atoms _ _ = true
let pp_plain = Code.plain
let pp_as_a = None
let pp_atom = function
| Atomic -> "A"
let fold_non_mixed f k = f Atomic k
let fold_atom f k = fold_non_mixed f k
let worth_final _ = true
let varatom_dir _d f = f None
let atom_to_bank _ = Code.Ord
include NoMixed
include NoWide
module PteVal = PteVal_gen.No(struct type arch_atom = atom end)
type fence = MFence
let is_isync _ = false
let compare_fence = compare
let default = MFence
let strong = default
let pp_fence = function
| MFence -> "MFence"
let fold_all_fences f r = f MFence r
let fold_cumul_fences f r = f MFence r
let fold_some_fences f r = f MFence r
let orders f d1 d2 = match f,d1,d2 with
| MFence,_,_ -> true
let var_fence f r = f default r
type dp
let pp_dp _ = assert false
let fold_dpr _f r = r
let fold_dpw _f r = r
let ddr_default = None
let ddw_default = None
let ctrlr_default = None
let ctrlw_default = None
let is_ctrlr _ = assert false
let is_addr _ = assert false
let fst_dp _ = assert false
let sequence_dp _ _ = assert false
RWM
include Exch.Exch(struct type arch_atom = atom end)
include NoEdge
include
ArchExtra_gen.Make
(struct
type arch_reg = reg
let is_symbolic = function
| Symbolic_reg _ -> true
| _ -> false
let pp_reg = pp_reg
let free_registers = allowed_for_symb
include NoSpecial
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.