_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
|
---|---|---|---|---|---|---|---|---|
fe5138fc4873de214a26c0afa3f4db1d3fd6062473fa614f22e78d4d37a9a239 | realworldocaml/mdx | library.mli |
* Copyright ( c ) 2019 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2019 Nathan Rebours <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
type t = { base_name : string; sub_lib : string option }
* The type to represent dune libraries as referred to in ' # require ' statements
or in dune files .
I.e. lib.sub_lib is [ { base_name = " lib " ; sub_lib = Some " sub_lib " } ] .
or in dune files.
I.e. lib.sub_lib is [{base_name = "lib"; sub_lib = Some "sub_lib"}].
*)
val equal : t -> t -> bool
val compare : t -> t -> int
val pp : t Fmt.t
val from_string : string -> (t, string) result
(** [from_string s] returns the library represented by [s] or an error if [s]
isn't a valid library. *)
(** Set of libraries *)
module Set : sig
include Set.S with type elt = t
val to_package_set : t -> Astring.String.Set.t
(** [to_package_set lib_set] returns the set of dune packages needed to get
all the libraries in [lib_set].
I.e. it's the set of basenames for all the libraries in [lib_set]. *)
end
| null | https://raw.githubusercontent.com/realworldocaml/mdx/4d8e7e8321faeeabe7091fbe2e901e64ab19dc06/lib/library.mli | ocaml | * [from_string s] returns the library represented by [s] or an error if [s]
isn't a valid library.
* Set of libraries
* [to_package_set lib_set] returns the set of dune packages needed to get
all the libraries in [lib_set].
I.e. it's the set of basenames for all the libraries in [lib_set]. |
* Copyright ( c ) 2019 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2019 Nathan Rebours <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
type t = { base_name : string; sub_lib : string option }
* The type to represent dune libraries as referred to in ' # require ' statements
or in dune files .
I.e. lib.sub_lib is [ { base_name = " lib " ; sub_lib = Some " sub_lib " } ] .
or in dune files.
I.e. lib.sub_lib is [{base_name = "lib"; sub_lib = Some "sub_lib"}].
*)
val equal : t -> t -> bool
val compare : t -> t -> int
val pp : t Fmt.t
val from_string : string -> (t, string) result
module Set : sig
include Set.S with type elt = t
val to_package_set : t -> Astring.String.Set.t
end
|
ebab1e56bc196e46c3f109629fe87728df4717f73f6e2528e83af5505c41b290 | sdiehl/elliptic-curve | SECT571K1.hs | module Data.Curve.Binary.SECT571K1
( module Data.Curve.Binary
, Point(..)
-- * SECT571K1 curve
, module Data.Curve.Binary.SECT571K1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Binary
-------------------------------------------------------------------------------
-- Types
-------------------------------------------------------------------------------
-- | SECT571K1 curve.
data SECT571K1
-- | Field of points of SECT571K1 curve.
type F2m = Binary P
type P = 0x80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425
| Field of coefficients of SECT571K1 curve .
type Fr = Prime R
type R = 0x20000000000000000000000000000000000000000000000000000000000000000000000131850e1f19a63e4b391a8db917f4138b630d84be5d639381e91deb45cfe778f637c1001
-- SECT571K1 curve is a binary curve.
instance Curve 'Binary c SECT571K1 F2m Fr => BCurve c SECT571K1 F2m Fr where
a_ = const _a
{-# INLINABLE a_ #-}
b_ = const _b
# INLINABLE b _ #
h_ = const _h
{-# INLINABLE h_ #-}
p_ = const _p
{-# INLINABLE p_ #-}
r_ = const _r
# INLINABLE r _ #
-- | Affine SECT571K1 curve point.
type PA = BAPoint SECT571K1 F2m Fr
Affine SECT571K1 curve is a binary affine curve .
instance BACurve SECT571K1 F2m Fr where
gA_ = gA
# INLINABLE gA _ #
-- | Projective SECT571K1 point.
type PP = BPPoint SECT571K1 F2m Fr
Projective SECT571K1 curve is a binary projective curve .
instance BPCurve SECT571K1 F2m Fr where
gP_ = gP
# INLINABLE gP _ #
-------------------------------------------------------------------------------
-- Parameters
-------------------------------------------------------------------------------
-- | Coefficient @A@ of SECT571K1 curve.
_a :: F2m
_a = 0x0
# INLINABLE _ a #
-- | Coefficient @B@ of SECT571K1 curve.
_b :: F2m
_b = 0x1
{-# INLINABLE _b #-}
-- | Cofactor of SECT571K1 curve.
_h :: Natural
_h = 0x4
# INLINABLE _ h #
-- | Polynomial of SECT571K1 curve.
_p :: Natural
_p = 0x80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425
{-# INLINABLE _p #-}
-- | Order of SECT571K1 curve.
_r :: Natural
_r = 0x20000000000000000000000000000000000000000000000000000000000000000000000131850e1f19a63e4b391a8db917f4138b630d84be5d639381e91deb45cfe778f637c1001
{-# INLINABLE _r #-}
-- | Coordinate @X@ of SECT571K1 curve.
_x :: F2m
_x = 0x26eb7a859923fbc82189631f8103fe4ac9ca2970012d5d46024804801841ca44370958493b205e647da304db4ceb08cbbd1ba39494776fb988b47174dca88c7e2945283a01c8972
{-# INLINABLE _x #-}
-- | Coordinate @Y@ of SECT571K1 curve.
_y :: F2m
_y = 0x349dc807f4fbf374f4aeade3bca95314dd58cec9f307a54ffc61efc006d8a2c9d4979c0ac44aea74fbebbb9f772aedcb620b01a7ba7af1b320430c8591984f601cd4c143ef1c7a3
{-# INLINABLE _y #-}
| Generator of affine SECT571K1 curve .
gA :: PA
gA = A _x _y
# INLINABLE gA #
-- | Generator of projective SECT571K1 curve.
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
| null | https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Binary/SECT571K1.hs | haskell | * SECT571K1 curve
-----------------------------------------------------------------------------
Types
-----------------------------------------------------------------------------
| SECT571K1 curve.
| Field of points of SECT571K1 curve.
SECT571K1 curve is a binary curve.
# INLINABLE a_ #
# INLINABLE h_ #
# INLINABLE p_ #
| Affine SECT571K1 curve point.
| Projective SECT571K1 point.
-----------------------------------------------------------------------------
Parameters
-----------------------------------------------------------------------------
| Coefficient @A@ of SECT571K1 curve.
| Coefficient @B@ of SECT571K1 curve.
# INLINABLE _b #
| Cofactor of SECT571K1 curve.
| Polynomial of SECT571K1 curve.
# INLINABLE _p #
| Order of SECT571K1 curve.
# INLINABLE _r #
| Coordinate @X@ of SECT571K1 curve.
# INLINABLE _x #
| Coordinate @Y@ of SECT571K1 curve.
# INLINABLE _y #
| Generator of projective SECT571K1 curve. | module Data.Curve.Binary.SECT571K1
( module Data.Curve.Binary
, Point(..)
, module Data.Curve.Binary.SECT571K1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Binary
data SECT571K1
type F2m = Binary P
type P = 0x80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425
| Field of coefficients of SECT571K1 curve .
type Fr = Prime R
type R = 0x20000000000000000000000000000000000000000000000000000000000000000000000131850e1f19a63e4b391a8db917f4138b630d84be5d639381e91deb45cfe778f637c1001
instance Curve 'Binary c SECT571K1 F2m Fr => BCurve c SECT571K1 F2m Fr where
a_ = const _a
b_ = const _b
# INLINABLE b _ #
h_ = const _h
p_ = const _p
r_ = const _r
# INLINABLE r _ #
type PA = BAPoint SECT571K1 F2m Fr
Affine SECT571K1 curve is a binary affine curve .
instance BACurve SECT571K1 F2m Fr where
gA_ = gA
# INLINABLE gA _ #
type PP = BPPoint SECT571K1 F2m Fr
Projective SECT571K1 curve is a binary projective curve .
instance BPCurve SECT571K1 F2m Fr where
gP_ = gP
# INLINABLE gP _ #
_a :: F2m
_a = 0x0
# INLINABLE _ a #
_b :: F2m
_b = 0x1
_h :: Natural
_h = 0x4
# INLINABLE _ h #
_p :: Natural
_p = 0x80000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425
_r :: Natural
_r = 0x20000000000000000000000000000000000000000000000000000000000000000000000131850e1f19a63e4b391a8db917f4138b630d84be5d639381e91deb45cfe778f637c1001
_x :: F2m
_x = 0x26eb7a859923fbc82189631f8103fe4ac9ca2970012d5d46024804801841ca44370958493b205e647da304db4ceb08cbbd1ba39494776fb988b47174dca88c7e2945283a01c8972
_y :: F2m
_y = 0x349dc807f4fbf374f4aeade3bca95314dd58cec9f307a54ffc61efc006d8a2c9d4979c0ac44aea74fbebbb9f772aedcb620b01a7ba7af1b320430c8591984f601cd4c143ef1c7a3
| Generator of affine SECT571K1 curve .
gA :: PA
gA = A _x _y
# INLINABLE gA #
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
|
c332ab0b96d89c41b82b6deabe175cbe6e14677688bf1931a3f17e60e42a74f6 | rajasegar/cl-warehouse | cl-warehouse.lisp | (in-package :cl-user)
(defpackage cl-warehouse-test
(:use :cl
:cl-warehouse
:prove))
(in-package :cl-warehouse-test)
(plan nil)
;; blah blah blah.
(finalize)
| null | https://raw.githubusercontent.com/rajasegar/cl-warehouse/cb6313d42ba5df49c54f9bf7a9e30734c6f6cbd9/tests/cl-warehouse.lisp | lisp | blah blah blah. | (in-package :cl-user)
(defpackage cl-warehouse-test
(:use :cl
:cl-warehouse
:prove))
(in-package :cl-warehouse-test)
(plan nil)
(finalize)
|
ecbde65535236fd6d489c2283e7aa74c06298d94f72f09f29fc8ac5466f64132 | hjcapple/reading-sicp | exercise_2_85.scm | #lang racket
P137 - [ 练习 2.85 ]
(require "ch2support.scm")
(require (submod "complex_number_data_directed.scm" complex-op))
;;;;;;;;;;;;;;;;;;;;;;;;
(define (attach-tag type-tag contents)
(cons type-tag contents))
(define (type-tag datum)
(if (pair? datum)
(car datum)
(error "Bad tagged datum -- TYPE-TAG" datum)))
(define (contents datum)
(if (pair? datum)
(cdr datum)
(error "Bad tagged datum -- CONTENTS" datum)))
(define (raise-into x type)
(let ((x-type (type-tag x)))
(if (equal? x-type type)
x
(let ((x-raise (raise x)))
(if x-raise
(raise-into x-raise type)
#f)))))
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(drop (apply proc (map contents args)))
(if (and (= (length args) 2)
防止 a1、a2 类型相同时死循环,见[练习 2.81 ]
(let ((a1 (car args))
(a2 (cadr args)))
(let ((a1-raise (raise-into a1 (type-tag a2))))
(if a1-raise
(apply-generic op a1-raise a2)
(let ((a2-raise (raise-into a2 (type-tag a1))))
(if a2-raise
(apply-generic op a1 a2-raise)
(error "No method for these types -- APPLY-GENERIC"
(list op type-tags)))))))
(error "No method for these types -- APPLY-GENERIC"
(list op type-tags)))))))
;;;;;;;;;;;;;;;;;;;;;;;;
(define (raise x)
(let ((raise-proc (get 'raise (list (type-tag x)))))
(if raise-proc
(raise-proc (contents x))
#f)))
(define (project x)
(let ((proc (get 'project (list (type-tag x)))))
(if proc
(proc (contents x))
#f)))
(define (drop x)
(if (pair? x) ; 过滤 #t、#f 等没有 type-tag 的参数
(let ((x-project (project x)))
(if (and x-project
(equ? (raise x-project) x))
(drop x-project)
x))
x))
(define (add x y) (apply-generic 'add x y))
(define (equ? x y) (apply-generic 'equ? x y))
(define (install-raise-package)
(put 'raise '(integer)
(lambda (x) (make-rational x 1)))
(put 'raise '(rational)
(lambda (x) (make-real (/ (number x) (denom x)))))
(put 'raise '(real)
(lambda (x) (make-complex-from-real-imag x 0)))
'done)
(define (install-project-package)
(define (real->rational x)
(let ((rat (rationalize (inexact->exact x) 1/100)))
(make-rational (numerator rat) (denominator rat))))
(put 'project '(rational)
(lambda (x) (make-integer (number x))))
(put 'project '(real) real->rational)
(put 'project '(complex)
(lambda (x) (make-real (real-part x))))
'done)
;;;;;;;;;;;;;;;;;;;;;;;;
(define (install-integer-package)
(define (tag x) (attach-tag 'integer x))
(put 'add '(integer integer)
(lambda (x y) (tag (+ x y))))
(put 'equ? '(integer integer)
(lambda (x y) (= x y)))
(put 'make 'integer
(lambda (x) (tag x)))
'done)
(define (make-integer n)
((get 'make 'integer) n))
;;;;;;;;;;;;;;;;;;;;;;;;;
(define (number x) (car x))
(define (denom x) (cdr x))
(define (install-rational-package)
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (add-rat x y)
(make-rat (+ (* (number x) (denom y))
(* (number y) (denom x)))
(* (denom x) (denom y))))
(define (equal-rat? x y)
(= (* (number x) (denom y))
(* (number y) (denom x))))
(define (tag x) (attach-tag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (add-rat x y))))
(put 'equ? '(rational rational)
(lambda (x y) (equal-rat? x y)))
(put 'make 'rational
(lambda (n d) (tag (make-rat n d))))
'done)
(define (make-rational n d)
((get 'make 'rational) n d))
;;;;;;;;;;;;;;;;;;;;;;;;;
(define (install-real-package)
(define (tag x) (attach-tag 'real x))
(put 'add '(real real)
(lambda (x y) (tag (+ x y))))
(put 'equ? '(real real)
(lambda (x y) (= x y)))
(put 'make 'real
(lambda (x) (tag x)))
'done)
(define (make-real n)
((get 'make 'real) n))
;;;;;;;;;;;;;;;;;;;;;;;;;
(define (install-complex-package)
(define (make-from-real-imag x y)
((get 'make-from-real-imag '(rectangular)) x y))
(define (add-complex z1 z2)
(make-from-real-imag (+ (real-part z1) (real-part z2))
(+ (imag-part z1) (imag-part z2))))
(define (equ-complex? z1 z2)
(and (= (real-part z1) (real-part z2))
(= (imag-part z1) (imag-part z2))))
(define (tag z) (attach-tag 'complex z))
(put 'add '(complex complex)
(lambda (x y) (tag (add-complex x y))))
(put 'equ? '(complex complex)
(lambda (x y) (equ-complex? x y)))
(put 'make-from-real-imag 'complex
(lambda (x y) (tag (make-from-real-imag x y))))
'done)
(define (make-complex-from-real-imag x y)
((get 'make-from-real-imag 'complex) x y))
;;;;;;;;;;;;;;;;;;;;;;;;;
(module* main #f
(install-rectangular-package)
(install-integer-package)
(install-rational-package)
(install-real-package)
(install-complex-package)
(install-raise-package)
(install-project-package)
(define int-val (make-integer 10))
(define rat-val (make-rational 1 2))
(define real-val (make-real 0.5))
(define complex-val (make-complex-from-real-imag 10 20))
(define complex-val-2 (make-complex-from-real-imag 10 -20))
(equ? (project (raise int-val)) int-val)
(equ? (project (raise rat-val)) rat-val)
(equ? (project (raise real-val)) real-val)
(add int-val int-val)
(add rat-val rat-val)
(add real-val real-val)
(add complex-val complex-val-2)
(add int-val complex-val)
(add complex-val int-val)
(add int-val real-val)
(add real-val int-val)
)
| null | https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_2/exercise_2_85.scm | scheme |
过滤 #t、#f 等没有 type-tag 的参数
| #lang racket
P137 - [ 练习 2.85 ]
(require "ch2support.scm")
(require (submod "complex_number_data_directed.scm" complex-op))
(define (attach-tag type-tag contents)
(cons type-tag contents))
(define (type-tag datum)
(if (pair? datum)
(car datum)
(error "Bad tagged datum -- TYPE-TAG" datum)))
(define (contents datum)
(if (pair? datum)
(cdr datum)
(error "Bad tagged datum -- CONTENTS" datum)))
(define (raise-into x type)
(let ((x-type (type-tag x)))
(if (equal? x-type type)
x
(let ((x-raise (raise x)))
(if x-raise
(raise-into x-raise type)
#f)))))
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(drop (apply proc (map contents args)))
(if (and (= (length args) 2)
防止 a1、a2 类型相同时死循环,见[练习 2.81 ]
(let ((a1 (car args))
(a2 (cadr args)))
(let ((a1-raise (raise-into a1 (type-tag a2))))
(if a1-raise
(apply-generic op a1-raise a2)
(let ((a2-raise (raise-into a2 (type-tag a1))))
(if a2-raise
(apply-generic op a1 a2-raise)
(error "No method for these types -- APPLY-GENERIC"
(list op type-tags)))))))
(error "No method for these types -- APPLY-GENERIC"
(list op type-tags)))))))
(define (raise x)
(let ((raise-proc (get 'raise (list (type-tag x)))))
(if raise-proc
(raise-proc (contents x))
#f)))
(define (project x)
(let ((proc (get 'project (list (type-tag x)))))
(if proc
(proc (contents x))
#f)))
(define (drop x)
(let ((x-project (project x)))
(if (and x-project
(equ? (raise x-project) x))
(drop x-project)
x))
x))
(define (add x y) (apply-generic 'add x y))
(define (equ? x y) (apply-generic 'equ? x y))
(define (install-raise-package)
(put 'raise '(integer)
(lambda (x) (make-rational x 1)))
(put 'raise '(rational)
(lambda (x) (make-real (/ (number x) (denom x)))))
(put 'raise '(real)
(lambda (x) (make-complex-from-real-imag x 0)))
'done)
(define (install-project-package)
(define (real->rational x)
(let ((rat (rationalize (inexact->exact x) 1/100)))
(make-rational (numerator rat) (denominator rat))))
(put 'project '(rational)
(lambda (x) (make-integer (number x))))
(put 'project '(real) real->rational)
(put 'project '(complex)
(lambda (x) (make-real (real-part x))))
'done)
(define (install-integer-package)
(define (tag x) (attach-tag 'integer x))
(put 'add '(integer integer)
(lambda (x y) (tag (+ x y))))
(put 'equ? '(integer integer)
(lambda (x y) (= x y)))
(put 'make 'integer
(lambda (x) (tag x)))
'done)
(define (make-integer n)
((get 'make 'integer) n))
(define (number x) (car x))
(define (denom x) (cdr x))
(define (install-rational-package)
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (add-rat x y)
(make-rat (+ (* (number x) (denom y))
(* (number y) (denom x)))
(* (denom x) (denom y))))
(define (equal-rat? x y)
(= (* (number x) (denom y))
(* (number y) (denom x))))
(define (tag x) (attach-tag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (add-rat x y))))
(put 'equ? '(rational rational)
(lambda (x y) (equal-rat? x y)))
(put 'make 'rational
(lambda (n d) (tag (make-rat n d))))
'done)
(define (make-rational n d)
((get 'make 'rational) n d))
(define (install-real-package)
(define (tag x) (attach-tag 'real x))
(put 'add '(real real)
(lambda (x y) (tag (+ x y))))
(put 'equ? '(real real)
(lambda (x y) (= x y)))
(put 'make 'real
(lambda (x) (tag x)))
'done)
(define (make-real n)
((get 'make 'real) n))
(define (install-complex-package)
(define (make-from-real-imag x y)
((get 'make-from-real-imag '(rectangular)) x y))
(define (add-complex z1 z2)
(make-from-real-imag (+ (real-part z1) (real-part z2))
(+ (imag-part z1) (imag-part z2))))
(define (equ-complex? z1 z2)
(and (= (real-part z1) (real-part z2))
(= (imag-part z1) (imag-part z2))))
(define (tag z) (attach-tag 'complex z))
(put 'add '(complex complex)
(lambda (x y) (tag (add-complex x y))))
(put 'equ? '(complex complex)
(lambda (x y) (equ-complex? x y)))
(put 'make-from-real-imag 'complex
(lambda (x y) (tag (make-from-real-imag x y))))
'done)
(define (make-complex-from-real-imag x y)
((get 'make-from-real-imag 'complex) x y))
(module* main #f
(install-rectangular-package)
(install-integer-package)
(install-rational-package)
(install-real-package)
(install-complex-package)
(install-raise-package)
(install-project-package)
(define int-val (make-integer 10))
(define rat-val (make-rational 1 2))
(define real-val (make-real 0.5))
(define complex-val (make-complex-from-real-imag 10 20))
(define complex-val-2 (make-complex-from-real-imag 10 -20))
(equ? (project (raise int-val)) int-val)
(equ? (project (raise rat-val)) rat-val)
(equ? (project (raise real-val)) real-val)
(add int-val int-val)
(add rat-val rat-val)
(add real-val real-val)
(add complex-val complex-val-2)
(add int-val complex-val)
(add complex-val int-val)
(add int-val real-val)
(add real-val int-val)
)
|
aba071e44543245003ff0df7c60c0101ac0e686079a787af0a951bd534ee6d56 | cram2/cram | quasi.lisp | ;; Quasi-random sequences in arbitrary dimensions.
, Sun Jul 16 2006 - 15:54
Time - stamp : < 2012 - 01 - 13 12:01:20EST quasi.lisp >
;;
Copyright 2006 , 2007 , 2008 , 2009 , 2011
Distributed under the terms of the GNU General Public License
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(in-package :gsl)
;;; /usr/include/gsl/gsl_qrng.h
(defmobject quasi-random-number-generator
"gsl_qrng"
((rng-type :pointer) (dimension :uint))
"quasi random number generator"
"Make and optionally initialize the generator q to its starting point.
Note that quasi-random sequences do not use a seed and always produce
the same set of values."
:initialize-suffix "init"
:ri-c-return :void
:initialize-args nil)
(defmfun qrng-get (generator return-vector)
"gsl_qrng_get"
(((mpointer generator) :pointer) ((grid:foreign-pointer return-vector) :pointer))
:outputs (return-vector)
:return (return-vector)
"Store the next point from the sequence generator q
in the array. The space available for it must match the
dimension of the generator. The point will lie in the range
0 < x_i < 1 for each x_i.")
(defmfun name ((instance quasi-random-number-generator))
"gsl_qrng_name" (((mpointer instance) :pointer))
:definition :method
:c-return :string)
(defmfun rng-state ((instance quasi-random-number-generator))
"gsl_qrng_state" (((mpointer instance) :pointer))
:definition :method
:c-return :pointer
:export nil
:index gsl-random-state)
(defmfun size ((instance quasi-random-number-generator))
"gsl_qrng_size" (((mpointer instance) :pointer))
:definition :method
:c-return :sizet
:export nil
:index gsl-random-state)
(defmfun quasi-copy (source destination)
"gsl_qrng_memcpy"
(((mpointer destination) :pointer) ((mpointer source) :pointer))
:export nil
:index grid:copy
"Copy the quasi-random sequence generator src into the
pre-existing generator dest, making dest into an exact copy
of src. The two generators must be of the same type.")
(defmfun quasi-clone (instance)
"gsl_qrng_clone" (((mpointer instance) :pointer))
:c-return (crtn :pointer)
:return ((make-instance 'quasi-random-number-generator :mpointer crtn))
:export nil
:index grid:copy)
(defmethod grid:copy
((source quasi-random-number-generator) &key destination &allow-other-keys)
(if destination
(quasi-copy source destination)
(quasi-clone source)))
(def-rng-type +niederreiter2+
"Described in Bratley, Fox, Niederreiter,
ACM Trans. Model. Comp. Sim. 2, 195 (1992). It is
valid up to 12 dimensions."
"gsl_qrng_niederreiter_2")
(def-rng-type +sobol+
"This generator uses the Sobol sequence described in Antonov, Saleev,
USSR Comput. Maths. Math. Phys. 19, 252 (1980). It is valid up to
40 dimensions."
"gsl_qrng_sobol")
(def-rng-type +halton+
"The Halton sequence described in J.H. Halton, Numerische
Mathematik 2, 84-90 (1960) and B. Vandewoestyne and R. Cools
Computational and Applied Mathematics 189, 1&2, 341-361 (2006). They
are valid up to 1229 dimensions. "
"gsl_qrng_halton"
(1 11))
(def-rng-type +reverse-halton+
"The reverse Halton sequence described in J.H. Halton, Numerische
Mathematik 2, 84-90 (1960) and B. Vandewoestyne and R. Cools
Computational and Applied Mathematics 189, 1&2, 341-361 (2006). They
are valid up to 1229 dimensions. "
"gsl_qrng_reversehalton"
(1 11))
;;; Examples and unit test
(save-test quasi-random-number-generators
This example is given in the GSL documentation
(let ((gen (make-quasi-random-number-generator +sobol+ 2))
(vec (grid:make-foreign-array 'double-float :dimensions 2)))
(loop repeat 5
do (qrng-get gen vec)
append (coerce (grid:copy-to vec) 'list))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/random/quasi.lisp | lisp | Quasi-random sequences in arbitrary dimensions.
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
/usr/include/gsl/gsl_qrng.h
Examples and unit test | , Sun Jul 16 2006 - 15:54
Time - stamp : < 2012 - 01 - 13 12:01:20EST quasi.lisp >
Copyright 2006 , 2007 , 2008 , 2009 , 2011
Distributed under the terms of the GNU General Public License
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :gsl)
(defmobject quasi-random-number-generator
"gsl_qrng"
((rng-type :pointer) (dimension :uint))
"quasi random number generator"
"Make and optionally initialize the generator q to its starting point.
Note that quasi-random sequences do not use a seed and always produce
the same set of values."
:initialize-suffix "init"
:ri-c-return :void
:initialize-args nil)
(defmfun qrng-get (generator return-vector)
"gsl_qrng_get"
(((mpointer generator) :pointer) ((grid:foreign-pointer return-vector) :pointer))
:outputs (return-vector)
:return (return-vector)
"Store the next point from the sequence generator q
in the array. The space available for it must match the
dimension of the generator. The point will lie in the range
0 < x_i < 1 for each x_i.")
(defmfun name ((instance quasi-random-number-generator))
"gsl_qrng_name" (((mpointer instance) :pointer))
:definition :method
:c-return :string)
(defmfun rng-state ((instance quasi-random-number-generator))
"gsl_qrng_state" (((mpointer instance) :pointer))
:definition :method
:c-return :pointer
:export nil
:index gsl-random-state)
(defmfun size ((instance quasi-random-number-generator))
"gsl_qrng_size" (((mpointer instance) :pointer))
:definition :method
:c-return :sizet
:export nil
:index gsl-random-state)
(defmfun quasi-copy (source destination)
"gsl_qrng_memcpy"
(((mpointer destination) :pointer) ((mpointer source) :pointer))
:export nil
:index grid:copy
"Copy the quasi-random sequence generator src into the
pre-existing generator dest, making dest into an exact copy
of src. The two generators must be of the same type.")
(defmfun quasi-clone (instance)
"gsl_qrng_clone" (((mpointer instance) :pointer))
:c-return (crtn :pointer)
:return ((make-instance 'quasi-random-number-generator :mpointer crtn))
:export nil
:index grid:copy)
(defmethod grid:copy
((source quasi-random-number-generator) &key destination &allow-other-keys)
(if destination
(quasi-copy source destination)
(quasi-clone source)))
(def-rng-type +niederreiter2+
"Described in Bratley, Fox, Niederreiter,
ACM Trans. Model. Comp. Sim. 2, 195 (1992). It is
valid up to 12 dimensions."
"gsl_qrng_niederreiter_2")
(def-rng-type +sobol+
"This generator uses the Sobol sequence described in Antonov, Saleev,
USSR Comput. Maths. Math. Phys. 19, 252 (1980). It is valid up to
40 dimensions."
"gsl_qrng_sobol")
(def-rng-type +halton+
"The Halton sequence described in J.H. Halton, Numerische
Mathematik 2, 84-90 (1960) and B. Vandewoestyne and R. Cools
Computational and Applied Mathematics 189, 1&2, 341-361 (2006). They
are valid up to 1229 dimensions. "
"gsl_qrng_halton"
(1 11))
(def-rng-type +reverse-halton+
"The reverse Halton sequence described in J.H. Halton, Numerische
Mathematik 2, 84-90 (1960) and B. Vandewoestyne and R. Cools
Computational and Applied Mathematics 189, 1&2, 341-361 (2006). They
are valid up to 1229 dimensions. "
"gsl_qrng_reversehalton"
(1 11))
(save-test quasi-random-number-generators
This example is given in the GSL documentation
(let ((gen (make-quasi-random-number-generator +sobol+ 2))
(vec (grid:make-foreign-array 'double-float :dimensions 2)))
(loop repeat 5
do (qrng-get gen vec)
append (coerce (grid:copy-to vec) 'list))))
|
fdfd8b751d0b19520afdf1263ed4bf4ab65b9652806a5a46ddbc2e92f76962cd | smahood/re-frame-conj-2016 | step9.cljs | (ns show.steps.step9
(:require
[reagent.core :as reagent]
[re-frame.core :as re-frame]
[re-frisk.core :as re-frisk]
[cljs.spec :as s]
[show.slides.views :as views]))
(declare slides)
(def initial-state
{:slideshow/current-slide 0})
(re-frame/reg-event-fx
:slideshow/next-slide
(fn [context]
{}))
#_(re-frame/dispatch
[:slideshow/next-slide])
(defn slideshow []
[:div.slideshow-half-width
[:div.slide
[(nth slides 0)]]])
(defn slide-footer
[footer-text]
[:div.slide-footer
[:span ""]
[:span footer-text]
[:span.controls
[:i.material-icons.control.left
{:on-click
#(re-frame/dispatch
[:slideshow/prev-slide])}
"chevron_left"]
[:i.material-icons.control.right
{:on-click
#(re-frame/dispatch
[:slideshow/next-slide])}
"chevron_right"]]])
(defn title-slide []
[:div.title-slide
[:div.slide-body
[:br]
[:div "Building a "]
[:div "Presentation with"]
[:img.re-frame-logo
{:src "img/re-frame-logo.png"
:style {:margin-top "20px"}}]
[:div "and"]
[:img.cljs-logo
{:src "img/cljs-logo.png"}]]
[slide-footer "Clojure/conj 2016"]])
(defn intro-slide []
[:div.intro-slide
[:div.slide-header "marketing slide"]
[:div.slide-body
[:div.list "- Great for beginners and quick prototypes!"]
[:div.list "- Great for large, complex apps!"]
[:div.list "- Performant at scale!"]
[:div.list "- Multiple production apps of 50,000 lines and more!"]]
[slide-footer ""]])
(defn mount-root []
(reagent/render
[slideshow]
(js/document.getElementById "app")))
(defn on-jsload []
(mount-root))
(defn ^:export run []
(re-frisk/enable-re-frisk!
{:x 0 :y 0})
(mount-root))
(defn intro-slide-1 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
[:div.slide-body
[:div.list "- Mutation is fundamental to SPAs"
[:div.list "- Change the DOM"]
[:div.list "- Change our application state"]
[:div.list "- Change the World"
[:div.list "- Local Storage"]
[:div.list "- Cookies"]
[:div.list "- APIs"]
[:div.list "- Databases"]]]]
[slide-footer ""]])
(defn intro-slide-2 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
[:div.slide-body
[:div.list "- But we want to program functionally"
[:div.list "- To change the DOM"]
[:div.list "- To change our application state"]
[:div.list "- To change the World!"]
[:br] [:br]
[:div.list "re-frame can help us do this"]]]
[slide-footer ""]])
(defn domino-1 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-1
[slide-footer ""]])
(defn domino-2 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-2
[slide-footer ""]])
(defn domino-3 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-3
[slide-footer ""]])
(defn domino-4 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-4
[slide-footer ""]])
(defn domino-5 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-5
[slide-footer ""]])
(defn domino-6 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-6
[slide-footer ""]])
(defn our-job []
[:div.intro-slide
[:div.slide-header "Getting Started"]
[:div.slide-body
[:div.list "- Define Views"]
[:div.list "- Define the Initial Shape of App State"]
[:div.list "- Register Events"]
[:div.list "- Register Subscription Queries"]
[:div.list "- Link Queries to Views"]
[:div.list "- Link Events to Views"]]
[slide-footer ""]])
(defn other-things []
[:div.intro-slide
[:div.slide-header "Growing Your App"]
[:div.slide-body
[:div.list "- Build Context with Coeffects"
[:div.list [:a {:href "/"}
"/"]]]
[:div.list "- Define your own effects"]
[:div.list "- Interceptors (inspired by Pedestal)"]]
[slide-footer ""]])
(defn ending-slide []
[:div.intro-slide
[:div.slide-header "Thank You!"]
[:div.slide-body
[:div.list [:a {:href "-frame"}
"-frame"]]
[:div.list [:a {:href "-frame.org"}
"-frame.org"]]
[:div.list "#re-frame on Clojurians Slack"]
[:div.list "#re-frame on Conj Slack"]
[:br] [:br] [:br] [:br]
[:div.list "@shaun-mahood on Clojurians Slack"]
]
[slide-footer ""]])
(def slides
[title-slide
intro-slide
intro-slide-1
intro-slide-2
domino-1
domino-2
domino-3
domino-4
domino-5
domino-6
our-job
other-things
ending-slide]) | null | https://raw.githubusercontent.com/smahood/re-frame-conj-2016/51fe544a5f4e95f28c26995c11d64301ba9a2142/show/src/show/steps/step9.cljs | clojure | (ns show.steps.step9
(:require
[reagent.core :as reagent]
[re-frame.core :as re-frame]
[re-frisk.core :as re-frisk]
[cljs.spec :as s]
[show.slides.views :as views]))
(declare slides)
(def initial-state
{:slideshow/current-slide 0})
(re-frame/reg-event-fx
:slideshow/next-slide
(fn [context]
{}))
#_(re-frame/dispatch
[:slideshow/next-slide])
(defn slideshow []
[:div.slideshow-half-width
[:div.slide
[(nth slides 0)]]])
(defn slide-footer
[footer-text]
[:div.slide-footer
[:span ""]
[:span footer-text]
[:span.controls
[:i.material-icons.control.left
{:on-click
#(re-frame/dispatch
[:slideshow/prev-slide])}
"chevron_left"]
[:i.material-icons.control.right
{:on-click
#(re-frame/dispatch
[:slideshow/next-slide])}
"chevron_right"]]])
(defn title-slide []
[:div.title-slide
[:div.slide-body
[:br]
[:div "Building a "]
[:div "Presentation with"]
[:img.re-frame-logo
{:src "img/re-frame-logo.png"
:style {:margin-top "20px"}}]
[:div "and"]
[:img.cljs-logo
{:src "img/cljs-logo.png"}]]
[slide-footer "Clojure/conj 2016"]])
(defn intro-slide []
[:div.intro-slide
[:div.slide-header "marketing slide"]
[:div.slide-body
[:div.list "- Great for beginners and quick prototypes!"]
[:div.list "- Great for large, complex apps!"]
[:div.list "- Performant at scale!"]
[:div.list "- Multiple production apps of 50,000 lines and more!"]]
[slide-footer ""]])
(defn mount-root []
(reagent/render
[slideshow]
(js/document.getElementById "app")))
(defn on-jsload []
(mount-root))
(defn ^:export run []
(re-frisk/enable-re-frisk!
{:x 0 :y 0})
(mount-root))
(defn intro-slide-1 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
[:div.slide-body
[:div.list "- Mutation is fundamental to SPAs"
[:div.list "- Change the DOM"]
[:div.list "- Change our application state"]
[:div.list "- Change the World"
[:div.list "- Local Storage"]
[:div.list "- Cookies"]
[:div.list "- APIs"]
[:div.list "- Databases"]]]]
[slide-footer ""]])
(defn intro-slide-2 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
[:div.slide-body
[:div.list "- But we want to program functionally"
[:div.list "- To change the DOM"]
[:div.list "- To change our application state"]
[:div.list "- To change the World!"]
[:br] [:br]
[:div.list "re-frame can help us do this"]]]
[slide-footer ""]])
(defn domino-1 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-1
[slide-footer ""]])
(defn domino-2 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-2
[slide-footer ""]])
(defn domino-3 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-3
[slide-footer ""]])
(defn domino-4 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-4
[slide-footer ""]])
(defn domino-5 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-5
[slide-footer ""]])
(defn domino-6 []
[:div.intro-slide
[:div.slide-header "re-frame intro"]
views/domino-6
[slide-footer ""]])
(defn our-job []
[:div.intro-slide
[:div.slide-header "Getting Started"]
[:div.slide-body
[:div.list "- Define Views"]
[:div.list "- Define the Initial Shape of App State"]
[:div.list "- Register Events"]
[:div.list "- Register Subscription Queries"]
[:div.list "- Link Queries to Views"]
[:div.list "- Link Events to Views"]]
[slide-footer ""]])
(defn other-things []
[:div.intro-slide
[:div.slide-header "Growing Your App"]
[:div.slide-body
[:div.list "- Build Context with Coeffects"
[:div.list [:a {:href "/"}
"/"]]]
[:div.list "- Define your own effects"]
[:div.list "- Interceptors (inspired by Pedestal)"]]
[slide-footer ""]])
(defn ending-slide []
[:div.intro-slide
[:div.slide-header "Thank You!"]
[:div.slide-body
[:div.list [:a {:href "-frame"}
"-frame"]]
[:div.list [:a {:href "-frame.org"}
"-frame.org"]]
[:div.list "#re-frame on Clojurians Slack"]
[:div.list "#re-frame on Conj Slack"]
[:br] [:br] [:br] [:br]
[:div.list "@shaun-mahood on Clojurians Slack"]
]
[slide-footer ""]])
(def slides
[title-slide
intro-slide
intro-slide-1
intro-slide-2
domino-1
domino-2
domino-3
domino-4
domino-5
domino-6
our-job
other-things
ending-slide]) |
|
3ddfa2d5839e0ab64953dd8318e948859caf47faff14dd203fa3ae16207b8f17 | pingles/bandit | ucb_test.clj | (ns bandit.algo.ucb_test
(:use [expectations]
[bandit.arms :only (arm exploit unpulled)]
[bandit.algo.ucb]))
;; picking unpulled arms
(expect 2 (count (unpulled [(arm :arm1) (arm :arm2)])))
(expect empty? (unpulled [(arm :arm1 :pulls 1)]))
;; selecting best performing
(expect (arm :arm1 :ucb-value 1)
(exploit :ucb-value [(arm :arm1 :ucb-value 1) (arm :arm2 :ucb-value 0)]))
;; ucb bonus values
(expect 1.2389740629499462 (bonus-value 10 3))
(given (ucb-value (arm :arm1 :pulls 1)
[(arm :arm1 :pulls 1) (arm :arm2 :pulls 2)])
(expect :name :arm1
:pulls 1
:ucb-value 1.4823038073675112))
;; selecting arms
(given (select-arm [(arm :arm1) (arm :arm2 :pulls 1)])
(expect :name :arm1))
(given (select-arm [(arm :arm1 :pulls 1 :value 1)
(arm :arm2 :pulls 10 :value 10)])
(expect :name :arm2
:pulls 10
:ucb-value 10.692516465190305))
| null | https://raw.githubusercontent.com/pingles/bandit/795666f3938e28f389691094bb1e07e4202290f6/bandit-core/test/bandit/algo/ucb_test.clj | clojure | picking unpulled arms
selecting best performing
ucb bonus values
selecting arms | (ns bandit.algo.ucb_test
(:use [expectations]
[bandit.arms :only (arm exploit unpulled)]
[bandit.algo.ucb]))
(expect 2 (count (unpulled [(arm :arm1) (arm :arm2)])))
(expect empty? (unpulled [(arm :arm1 :pulls 1)]))
(expect (arm :arm1 :ucb-value 1)
(exploit :ucb-value [(arm :arm1 :ucb-value 1) (arm :arm2 :ucb-value 0)]))
(expect 1.2389740629499462 (bonus-value 10 3))
(given (ucb-value (arm :arm1 :pulls 1)
[(arm :arm1 :pulls 1) (arm :arm2 :pulls 2)])
(expect :name :arm1
:pulls 1
:ucb-value 1.4823038073675112))
(given (select-arm [(arm :arm1) (arm :arm2 :pulls 1)])
(expect :name :arm1))
(given (select-arm [(arm :arm1 :pulls 1 :value 1)
(arm :arm2 :pulls 10 :value 10)])
(expect :name :arm2
:pulls 10
:ucb-value 10.692516465190305))
|
1d5bb2c9e291d9c94f23f8a222e2808f9e1ee594818b15e788ea76a560448e28 | input-output-hk/cardano-base | Main.hs | module Main (main) where
import Criterion.Main
import Cardano.Crypto.Libsodium.Init
import qualified Bench.Crypto.DSIGN (benchmarks)
import qualified Bench.Crypto.KES (benchmarks)
import qualified Bench.Crypto.VRF (benchmarks)
main :: IO ()
main = do
sodiumInit
defaultMain benchmarks
benchmarks :: [Benchmark]
benchmarks =
[ Bench.Crypto.DSIGN.benchmarks
, Bench.Crypto.KES.benchmarks
, Bench.Crypto.VRF.benchmarks
]
| null | https://raw.githubusercontent.com/input-output-hk/cardano-base/eee4b00005284582faa79ad8a49b98d12aded6f6/cardano-crypto-tests/bench/Main.hs | haskell | module Main (main) where
import Criterion.Main
import Cardano.Crypto.Libsodium.Init
import qualified Bench.Crypto.DSIGN (benchmarks)
import qualified Bench.Crypto.KES (benchmarks)
import qualified Bench.Crypto.VRF (benchmarks)
main :: IO ()
main = do
sodiumInit
defaultMain benchmarks
benchmarks :: [Benchmark]
benchmarks =
[ Bench.Crypto.DSIGN.benchmarks
, Bench.Crypto.KES.benchmarks
, Bench.Crypto.VRF.benchmarks
]
|
|
04dda8d439cb87da9a3ba5fbf2bf98db0cb2c99117272107cbb43d1c29010c59 | autolwe/autolwe | SimpRules.mli | (* * Simplification rules *)
open Tactic
val t_simp : bool -> int -> tactic
val t_ctx_ev_maybe : int option -> tactic
val t_split_ineq : int -> tactic
| null | https://raw.githubusercontent.com/autolwe/autolwe/3452c3dae06fc8e9815d94133fdeb8f3b8315f32/src/Derived/SimpRules.mli | ocaml | * Simplification rules |
open Tactic
val t_simp : bool -> int -> tactic
val t_ctx_ev_maybe : int option -> tactic
val t_split_ineq : int -> tactic
|
8a68d12304c2e3a489df53ac4361f9c6b97da7548f7991cf84d9583ad131e08b | petertseng/adventofcode-hs-2015 | 03_delivery_grid.hs | import AdventOfCode (readInputFile)
import Data.Containers.ListUtils (nubOrd)
tested to be faster than using a Set ,
-- and also faster than using group . sort
type Pos = (Int, Int)
houses :: String -> [Pos]
houses = scanl move (0, 0)
move :: Pos -> Char -> Pos
move (x, y) c = case c of
'^' -> (x, y + 1)
'v' -> (x, y - 1)
'<' -> (x - 1, y)
'>' -> (x + 1, y)
'\n' -> (x, y)
_ -> error (c : ": illegal character")
-- foldr because must preserve order
-- ~ lazy pattern match:
-- (doesn't really matter for this input, but keep for education)
split :: [a] -> ([a], [a])
split = foldr (\a ~(x, y) -> (a : y, x)) ([], [])
main :: IO ()
main = do
s <- readInputFile
let (s1, s2) = split s
countUnique = length . nubOrd
print (countUnique (houses s))
print (countUnique (houses s1 ++ houses s2))
| null | https://raw.githubusercontent.com/petertseng/adventofcode-hs-2015/999f29d40230f731ec9ac34f3daf9ef50802616d/bin/03_delivery_grid.hs | haskell | and also faster than using group . sort
foldr because must preserve order
~ lazy pattern match:
(doesn't really matter for this input, but keep for education) | import AdventOfCode (readInputFile)
import Data.Containers.ListUtils (nubOrd)
tested to be faster than using a Set ,
type Pos = (Int, Int)
houses :: String -> [Pos]
houses = scanl move (0, 0)
move :: Pos -> Char -> Pos
move (x, y) c = case c of
'^' -> (x, y + 1)
'v' -> (x, y - 1)
'<' -> (x - 1, y)
'>' -> (x + 1, y)
'\n' -> (x, y)
_ -> error (c : ": illegal character")
split :: [a] -> ([a], [a])
split = foldr (\a ~(x, y) -> (a : y, x)) ([], [])
main :: IO ()
main = do
s <- readInputFile
let (s1, s2) = split s
countUnique = length . nubOrd
print (countUnique (houses s))
print (countUnique (houses s1 ++ houses s2))
|
0c761eb3f711fd581cc753de674e9304dfbd8cbb0581ae2c5ce5427baa681e80 | chiroptical/snailscheme | IOSpec.hs | module Snail.IOSpec where
import Data.Either
import Snail.IO
import Test.Hspec
spec :: Spec
spec = do
describe "successfully lexes some basic snail files" $ do
it "lex a basic snail file" $ do
eResults <- readSnailFile "examples/basic.snail"
eResults `shouldSatisfy` isRight
it "lex an empty snail file" $ do
eResults <- readSnailFile "examples/fail-empty.snail"
eResults `shouldSatisfy` isLeft
it "lex should fail with bad comment" $ do
eResults <- readSnailFile "examples/fail-comment.snail"
eResults `shouldSatisfy` isLeft
it "lex should fail with non-terminated s-expression" $ do
eResults <- readSnailFile "examples/fail.snail"
eResults `shouldSatisfy` isLeft
it "lex should fail with non-escaped quote" $ do
eResults <- readSnailFile "examples/fail-quotes.snail"
eResults `shouldSatisfy` isLeft
| null | https://raw.githubusercontent.com/chiroptical/snailscheme/da7fbce2b9a29c1e9562467d913583ba1c6d62c9/test/Snail/IOSpec.hs | haskell | module Snail.IOSpec where
import Data.Either
import Snail.IO
import Test.Hspec
spec :: Spec
spec = do
describe "successfully lexes some basic snail files" $ do
it "lex a basic snail file" $ do
eResults <- readSnailFile "examples/basic.snail"
eResults `shouldSatisfy` isRight
it "lex an empty snail file" $ do
eResults <- readSnailFile "examples/fail-empty.snail"
eResults `shouldSatisfy` isLeft
it "lex should fail with bad comment" $ do
eResults <- readSnailFile "examples/fail-comment.snail"
eResults `shouldSatisfy` isLeft
it "lex should fail with non-terminated s-expression" $ do
eResults <- readSnailFile "examples/fail.snail"
eResults `shouldSatisfy` isLeft
it "lex should fail with non-escaped quote" $ do
eResults <- readSnailFile "examples/fail-quotes.snail"
eResults `shouldSatisfy` isLeft
|
|
e1dcb0469e5a8c2b356152c5a47f8f2debd8e0128e5f882148d2bc06ea36e8fc | thephoeron/quipper-language | QWTFP.hs | This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the
-- file COPYRIGHT for a list of authors, copyright holders, licensing,
-- and other details. All rights reserved.
--
-- ======================================================================
# LANGUAGE FlexibleContexts #
{-# OPTIONS -fcontext-stack=50 #-}
| This module provides an implementation of the Quantum Walk for
the Triangle Finding Problem .
--
-- The algorithm works by performing a Grover-based quantum walk on
a larger graph /H/ , called the Hamming graph associated to
-- We refer to this part of the algorithm as the /outer/ walk.
-- The subroutine used to check whether a triangle has been found
-- is itself a quantum walk, the /inner/ walk.
--
The overall algorithm is parameterized on integers /l/ , /n/ and /r/
-- specifying respectively the length /l/ of the integers used by the
oracle , the number 2[sup /n/ ] of nodes of /G/ and the size 2[sup /r/ ]
-- of Hamming graph tuples.
module Algorithms.TF.QWTFP where
import Prelude hiding (mapM, mapM_)
import Quipper
import Quipper.Internal (BType)
import QuipperLib.Arith
import Algorithms.TF.Definitions
import Data.IntMap (IntMap, adjust, insert, size)
import qualified Data.IntMap as IntMap
import Data.Traversable (mapM)
import Data.Foldable (mapM_)
import Control.Monad (foldM)
-- ======================================================================
* Main TF algorithm
| Algorithm 1 . Do a quantum walk on the Hamming graph associated with /G/.
Returns a quadruple /(testTMeasure , wMeasure , TMeasure , EMeasure)/
-- where /wMeasure/ contains a node of the triangle with the
other two nodes in /TMeasure/.
a1_QWTFP :: QWTFP_spec -> Circ (Bit,CNode,IntMap CNode,IntMap (IntMap Bit))
a1_QWTFP oracle@(n,r,edgeOracle,_) = do
comment "ENTER: a1_QWTFP"
let nn = 2^n
let rr = 2^r
let rbar = max ((2 * r) `div` 3) 1
let rrbar = 2^rbar
let tm = 2^(n - r)
let tw = floor $ sqrt $ fromIntegral rr
testTEdge <- a2_ZERO False
tt <- a3_INITIALIZE (intMap_replicate rr (replicate n False))
i <- a3_INITIALIZE (intm r 0)
v <- a3_INITIALIZE (replicate n False)
(tt, ee) <- a5_SETUP oracle tt
(tt,i,v,ee) <- box_loopM "a1_loop1" tm (tt,i,v,ee)
(\(tt,i,v,ee) -> do
((tt,ee),_) <- with_computed_fun (tt,ee)
(\(tt,ee) -> a15_TestTriangleEdges oracle tt ee)
(\(tt,ee,w,triTestT,triTestTw) -> do
phaseFlipUnless (triTestT .==. 0 .&&. triTestTw .==. 0)
return ((tt,ee,w,triTestT,triTestTw),()))
(tt,i,v,ee) <- box_loopM "a1_loop2" tw (tt,i,v,ee) (\(a,b,c,d) -> a6_QWSH oracle a b c d)
return (tt,i,v,ee))
(tt,ee,w,triTestT,triTestTw) <- a15_TestTriangleEdges oracle tt ee
testTEdge <- qor testTEdge [(triTestT, True), (triTestTw, True)]
testTMeasure <- measure testTEdge
wMeasure <- measure w
ttMeasure <- measure tt
eeMeasure <- measure ee
qdiscard (i,v,triTestT,triTestTw)
comment_with_label "EXIT: a1_QWTFP" (testTMeasure, wMeasure, ttMeasure, eeMeasure) ("testTMeasure", "wMeasure", "ttMeasure", "eeMeasure")
return (testTMeasure, wMeasure, ttMeasure, eeMeasure)
-- ======================================================================
-- *Utility subroutines
| Algorithm 2 .
Initialize the qubits in a register to a specified state .
-- Defined using the more generic 'qinit'.
a2_ZERO :: QShape a qa ca => a -> Circ qa
a2_ZERO b = do
comment "ENTER: a2_ZERO"
q <- qinit b
comment_with_label "EXIT: a2_ZERO" q "q"
return q
| Algorithm 3 .
Initialize to a specified state then apply a Hadamard gate to
-- the qubits in a register.
a3_INITIALIZE :: QShape a qa ca => a -> Circ qa
a3_INITIALIZE reg = do
comment "ENTER: a3_INITIALIZE"
zreg <- a2_ZERO reg
hzreg <- a4_HADAMARD zreg
comment_with_label "EXIT: a3_INITIALIZE" hzreg "hzreg"
return hzreg
| Algorithm 4 .
-- Apply a Hadamard gate to every qubit in the given quantum data.
-- Defined using the more generic 'map_hadamard'.
a4_HADAMARD :: QData qa => qa -> Circ qa
a4_HADAMARD q = do
comment_with_label "ENTER: a4_HADAMARD" q "q"
q <- map_hadamard q
comment_with_label "EXIT: a4_HADAMARD" q "q"
return q
| Algorithm 5 .
-- Set up the register /ee/ with the edge information
-- for the nodes contained in /tt/.
a5_SETUP :: QWTFP_spec -> (IntMap QNode) -> Circ (IntMap QNode, IntMap (IntMap Qubit))
a5_SETUP oracle@(n,r,edgeOracle,_) = box "a5" $ \tt -> do
comment_with_label "ENTER: a5_SETUP" tt "tt"
let rr = 2^r
ee <- qinit $ IntMap.fromList [(j,(intMap_replicate j False)) | j <- [0..(rr-1)]]
ee <- loop_with_indexM (rr) ee (\k ee ->
loop_with_indexM k ee (\j ee -> do
edgejk <- edgeOracle (tt ! j) (tt ! k) (ee ! k ! j)
ee <- return $ adjust (insert j edgejk) k ee
return ee))
comment_with_label "EXIT: a5_SETUP" (tt,ee) ("tt","ee")
return (tt, ee)
-- ======================================================================
* * The outer quantum walk and the standard Qram
| Algorithm 6 .
-- Do a quantum walk step on the Hamming graph.
a6_QWSH :: QWTFP_spec -> (IntMap QNode) -> QDInt -> QNode -> (IntMap (IntMap Qubit))
-> Circ (IntMap QNode, QDInt, QNode, IntMap (IntMap Qubit))
a6_QWSH oracle@(n,r,edgeOracle,qram) = box "a6" $ \tt i v ee -> do
comment_with_label "ENTER: a6_QWSH" (tt, i, v, ee) ("tt", "i", "v", "ee")
with_ancilla_init (replicate n False) $ \ttd -> do
with_ancilla_init (intMap_replicate (2^r) False) $ \eed -> do
(i,v) <- a7_DIFFUSE (i,v)
((tt,i,v,ee,ttd,eed),_) <- with_computed_fun (tt,i,v,ee,ttd,eed)
(\(tt,i,v,ee,ttd,eed) -> do
(i,tt,ttd) <- qram_fetch qram i tt ttd
(i,ee,eed) <- a12_FetchStoreE i ee eed
(tt,ttd,eed) <- a13_UPDATE oracle tt ttd eed
(i,tt,ttd) <- qram_store qram i tt ttd
return (tt,i,v,ee,ttd,eed))
(\(tt,i,v,ee,ttd,eed) -> do
(ttd,v) <- a14_SWAP ttd v
return ((tt,i,v,ee,ttd,eed),()))
comment_with_label "EXIT: a6_QWSH" (tt, i, v, ee) ("tt", "i", "v", "ee")
return (tt,i,v,ee)
| Algorithm 7 .
Diffuse a piece of quantum data , in the Grover search sense of
-- reflecting about the average.
--
Note : relies on @'shape ' q@ corresponding to the “ all false ” state .
a7_DIFFUSE :: (QData qa) => qa -> Circ qa
a7_DIFFUSE = box "a7" $ \q -> do
comment_with_label "ENTER: a7_DIFFUSE" q "q"
q <- a4_HADAMARD q
phaseFlipUnless $ q .==. qc_false q
q <- a4_HADAMARD q
comment_with_label "EXIT: a7_DIFFUSE" q "q"
return q
| Algorithm 8 .
-- Perform a quantum-addressed fetch operation.
-- This fetches the /i/-th element from /tt/ into /ttd/.
-- Precondition: /ttd/ = 0.
--
This could be implemented more efficiently using the qRAM implementation
-- in "Alternatives".
a8_FetchT :: (QData qa) => QDInt -> IntMap qa -> qa -> Circ (QDInt, IntMap qa, qa)
a8_FetchT = box "a8" $ \i tt ttd -> do
comment_with_label "ENTER: a8_FetchT" (i,tt,ttd) ("i","tt","ttd")
let r = qdint_length i
(i,tt,ttd) <- loop_with_indexM (2^r) (i,tt,ttd)
(\j (i,tt,ttd) -> do
let ttj = tt ! j
(ttj,ttd) <- mapBinary
(\q p -> do
p <- qnot p `controlled` q .&&. i .==. (fromIntegral j)
return (q,p))
(tt ! j) ttd
return (i, insert j ttj tt, ttd))
comment_with_label "EXIT: a8_FetchT" (i,tt,ttd) ("i","tt","ttd")
return (i,tt,ttd)
| Algorithms 9 .
-- Perform a quantum-addressed store operation:
-- store /ttd/ into the /i/-th element from /tt/.
-- Analogous to 'a8_FetchT'.
a9_StoreT :: (QData qa) => QDInt -> IntMap qa -> qa -> Circ (QDInt, IntMap qa, qa)
a9_StoreT = box "a9" $ \i tt ttd -> do
comment_with_label "ENTER: a9_StoreT" (i,tt,ttd) ("i","tt","ttd")
let r = qdint_length i
(i,tt,ttd) <- loop_with_indexM (2^r) (i,tt,ttd)
(\j (i,tt,ttd) -> do
(ttj,ttd) <- mapBinary
(\q p -> do
q <- qnot q `controlled` p .&&. i .==. (fromIntegral j)
return (q,p))
(tt ! j) ttd
return (i, insert j ttj tt, ttd))
comment_with_label "EXIT: a9_StoreT" (i,tt,ttd) ("i","tt","ttd")
return (i,tt,ttd)
| Algorithm 10 .
-- Perform a quantum-addressed swap:
-- swap /ttd/ with the /i/-th element of /tt/.
-- Analogous to 'a8_FetchT' and 'a9_StoreT'.
a10_FetchStoreT :: (QData qa) => QDInt -> IntMap qa -> qa -> Circ (QDInt, IntMap qa, qa)
a10_FetchStoreT = box "a10" $ \i tt ttd -> do
comment_with_label "ENTER: a10_FetchStoreT" (i,tt,ttd) ("i","tt","ttd")
let r = qdint_length i
(i,tt,ttd) <- loop_with_indexM (2^r) (i,tt,ttd)
(\j (i,tt,ttd) -> do
(qq,ttd) <- a14_SWAP (tt ! j) ttd
`controlled` i .==. (fromIntegral j)
return (i,(insert j qq tt), ttd))
comment_with_label "EXIT: a10_FetchStoreT" (i,tt,ttd) ("i","tt","ttd")
return (i,tt,ttd)
| Algorithm 11 . Perform a quantum - addressed fetch operation . This
-- is a somewhat specialized addressed fetching operation.
a11_FetchE :: QDInt -> IntMap (IntMap Qubit) -> IntMap Qubit
-> Circ (QDInt, IntMap (IntMap Qubit), IntMap Qubit)
a11_FetchE = box "a11" $ \i qs ps -> do
comment_with_label "ENTER: a11_FetchE" (i, qs, ps) ("i", "qs", "ps")
let r = qdint_length i
(i,qs,ps) <- loop_with_indexM (2^r) (i,qs,ps) (\j (i,qs,ps) ->
loop_with_indexM j (i,qs,ps) (\k (i,qs,ps) -> do
pk <- qnot (ps ! k) `controlled`
(qs ! j ! k) .&&. i .==. (fromIntegral j)
ps <- return $ insert k pk ps
pj <- qnot (ps ! j) `controlled`
(qs ! j ! k) .&&. i .==. (fromIntegral k)
ps <- return $ insert j pj ps
return (i,qs,ps)))
comment_with_label "EXIT: a11_FetchE" (i, qs, ps) ("i", "qs", "ps")
return (i,qs,ps)
| Algorithm 12 .
-- Perform a quantum-addressed swap. Analogous to 'a11_FetchE'.
a12_FetchStoreE :: QDInt -> IntMap (IntMap Qubit) -> IntMap Qubit
-> Circ (QDInt, IntMap (IntMap Qubit), IntMap Qubit)
a12_FetchStoreE = box "a12" $ \i qs ps -> do
comment_with_label "ENTER: a12_FetchStoreE" (i, qs, ps) ("i", "qs", "ps")
let r = qdint_length i
(i,qs,ps) <- loop_with_indexM (2^r) (i,qs,ps) (\j (i,qs, ps) ->
loop_with_indexM j (i,qs, ps) (\k (i,qs, ps) -> do
(q,p) <- a14_SWAP (qs ! j ! k) (ps ! k)
`controlled` i .==. (fromIntegral j)
(qs,ps) <- return (adjust (insert k q) j qs, insert k p ps)
(q,p) <- a14_SWAP (qs ! j ! k) (ps ! j)
`controlled` i .==. (fromIntegral k)
(qs,ps) <- return (adjust (insert k q) j qs, insert j p ps)
return (i,qs,ps)))
comment_with_label "EXIT: a12_FetchStoreE" (i, qs, ps) ("i", "qs", "ps")
return (i,qs,ps)
| Algorithm 13 .
-- Given a list of nodes /tt/, a distinguished node /ttd/,
-- and a list of bits /eed/, either:
--
-- * store the edge information for /(ttd,tt)/ into /eed/, if /eed/ is initially 0; or
--
* zero /eed/ , if it initially holds the edge information .
a13_UPDATE :: QWTFP_spec -> IntMap QNode -> QNode -> IntMap Qubit
-> Circ (IntMap QNode, QNode, IntMap Qubit)
a13_UPDATE oracle@(n,r,edgeOracle,_) = box "a13" $ \tt ttd eed -> do
comment_with_label "ENTER: a13_UPDATE" (tt,ttd,eed) ("tt","ttd","eed")
(tt,ttd,eed) <- loop_with_indexM (2^r) (tt,ttd,eed) (\j (tt,ttd,eed) -> do
e <- edgeOracle (tt ! j) ttd (eed ! j)
return (tt,ttd,insert j e eed))
comment_with_label "EXIT: a13_UPDATE" (tt,ttd,eed) ("tt","ttd","eed")
return (tt,ttd,eed)
| Algorithm 14 . Swap two registers of equal size . This is a
-- generic function and works for any quantum data type.
a14_SWAP :: QCData qa => qa -> qa -> Circ (qa, qa)
a14_SWAP q r = do
comment_with_label "ENTER: a14_SWAP" (q,r) ("q", "r")
(q,r) <- swap q r
comment_with_label "EXIT: a14_SWAP" (q,r) ("q", "r")
return (q,r)
| The qRAM operations from Algorithms 8–10 wrapped into a ' Qram ' object .
standard_qram :: Qram
standard_qram = Qram {
qram_fetch = a8_FetchT,
qram_store = a9_StoreT,
qram_swap = a10_FetchStoreT
}
-- ======================================================================
-- ** The inner quantum walk
| A type to hold the Graph Collision Quantum Walk Registers
/(tau , iota , sigma , eew , cTri , triTestT)/ , used in ' a20_GCQWStep ' .
type GCQWRegs = (IntMap QDInt, QDInt, QDInt, IntMap Qubit, QDInt, Qubit)
| Algorithm 15 : /TestTriangleEdges/.
-- Test whether the nodes /tt/ contain a pair that can be extended to a
-- triangle in the graph. Used as the test function in the outer quantum
walk . Seeks triangles in two different ways :
--
1 . Entirely within the nodes /tt/. If found , set qubit /triTestT/.
--
2 . With two vertices from /tt/ , a third anywhere in the graph . If found ,
set qubit /triTestTw/ , and return the third vertex as /w/. This is
-- implemented using an “inner quantum walk” to seek /w/.
a15_TestTriangleEdges ::
QWTFP_spec -- ^ The ambient oracle.
-> IntMap QNode -- ^ /tt/, an /R/-tuple of nodes.
-> IntMap (IntMap Qubit) -- ^ /ee/, a cache of the edge information between nodes in /tt/.
-> Circ (IntMap QNode, IntMap (IntMap Qubit), QNode, Qubit,Qubit) -- ^ Return /(tt, ee, w, triTestT,triTestTw)/.
a15_TestTriangleEdges oracle = box "a15" $ \tt ee -> do
comment_with_label "ENTER: a15_TestTriangleEdges" (tt,ee) ("tt","ee")
(ee,triTestT) <- a16_TriangleTestT ee
(tt,ee,w,triTestT) <- a18_TriangleEdgeSearch oracle tt ee triTestT
(tt,ee,w,triTestTw) <- a17_TriangleTestTw oracle tt ee w
comment_with_label "EXIT: a15_TestTriangleEdges" (tt,ee,w,triTestT,triTestTw) ("tt","ee","w","triTestT","triTestTw")
return (tt,ee,w,triTestT,triTestTw)
| Algorithm 16 : /TriangleTestT ee
-- Search exhaustively over the array /ee/ of edge data, seeking a triangle.
-- Whenever one is found, flip the qubit /triTestT/.
a16_TriangleTestT :: IntMap (IntMap Qubit) -> Circ (IntMap (IntMap Qubit), Qubit)
a16_TriangleTestT = box "a16" $ \ee -> do
comment_with_label "ENTER: a16_TriangleTestT" ee "ee"
let rr = size ee
(ee,triTestT) <- with_computed_fun ee
(\ee -> do
cTri <- qinit (intm (ceiling (logBase 2 (fromIntegral (rr `choose` 3)))) 0)
cTri <- foldM (\cTri (i,j,k) -> do
cTri <- increment cTri `controlled` (ee ! j ! i) .&&. (ee ! k ! i) .&&. (ee ! k ! j)
return cTri)
cTri [(i,j,k) | i <- [0..rr-1], j <- [i+1..rr-1], k <- [j+1..rr-1]]
return (ee,cTri))
(\(ee,cTri) -> do
triTestT <- qinit True
triTestT <- qnot triTestT `controlled` cTri .==. 0
return ((ee,cTri),triTestT))
comment_with_label "EXIT: a16_TriangleTestT" (ee,triTestT) ("ee","triTestT")
return (ee,triTestT)
Alternative implementation , using ( a lot of ) extra ancillas instead of a counter :
a16_TriangleTestT : : [ [ Qubit ] ] - > Qubit - > Circ ( [ [ Qubit ] ] , Qubit )
a16_TriangleTestT ee triTestT = do
let rr = length ee
( ( ee , triTestT ) , _ ) < - with_computed_fun
( \(ee , triTestT ) - > do
tests < - mapM ( \(i , j , k ) - > do
t < - a2_ZERO False
t < - qnot t ` controlled `
[ ( ee ! ! j ! ! i),(ee ! ! k ! ! i),(ee ! ! k ! ! j ) ]
return(t ) )
[ ( i , j , k ) | i < - [ 0 .. rr-1 ] , j < - [ i+1 .. rr-1 ] , k < - [ j+1 .. rr-1 ] ]
return ( ee , triTestT , tests ) )
( ee , triTestT )
( \(ee , triTestT , tests ) - > do
triTestT < - qor triTestT ( map ( - > ( p , True ) ) tests )
return ( ( ee , triTestT , tests ) , ( ) ) )
return ( ee , triTestT )
a16_TriangleTestT :: [[Qubit]] -> Qubit -> Circ ([[Qubit]], Qubit)
a16_TriangleTestT ee triTestT = do
let rr = length ee
((ee,triTestT),_) <- with_computed_fun
(\(ee,triTestT) -> do
tests <- mapM (\(i,j,k) -> do
t <- a2_ZERO False
t <- qnot t `controlled`
[(ee !! j !! i),(ee !! k !! i),(ee !! k !! j)]
return(t))
[(i,j,k) | i <- [0..rr-1], j <- [i+1..rr-1], k <- [j+1..rr-1]]
return (ee,triTestT,tests))
(ee,triTestT)
(\(ee,triTestT,tests) -> do
triTestT <- qor triTestT (map (\p -> (p,True)) tests)
return ((ee,triTestT,tests),()))
return (ee,triTestT)-}
| Algorithm 17 : /TriangleTestTw ee triTestTw/.
-- Search exhaustively for a pair of nodes in /tt/ that form a triangle with /w/.
-- Whenever a triangle found, flip qubit /triTestTw/.
a17_TriangleTestTw :: QWTFP_spec -- ^ The ambient oracle.
-> IntMap QNode -- ^ /tt/, an /R/-tuple of nodes.
-> IntMap (IntMap Qubit) -- ^ /ee/, a cache of the edge data for /T/.
-> QNode -- ^ /w/, another node.
-> Circ (IntMap QNode, IntMap (IntMap Qubit), QNode, Qubit) -- ^ return /(tt,ee,w,triTestTw)/.
a17_TriangleTestTw oracle@(n,r,edgeOracle,_) = box "a17" $ \tt ee w -> do
comment_with_label "ENTER: a17_TriangleTestTw" (tt,ee,w) ("tt","ee","w")
let rr = size ee
with_ancilla_init (intMap_replicate rr False) $ \eed -> do
((tt,ee,w,eed),triTestTw) <- with_computed_fun (tt,ee,w,eed)
(\(tt,ee,w,eed) -> do
eed <- mapWithKeyM (\k e -> do
e <- edgeOracle (tt ! k) w e
return e)
eed
cTri <- qinit (intm (ceiling (logBase 2 (fromIntegral (rr `choose` 2)))) 0)
cTri <- foldM
(\cTri (i,j) ->
increment cTri `controlled` (ee ! j ! i) .&&. (eed ! i) .&&. (eed ! j))
cTri
[(i,j) | i <- [0..rr-1], j <- [i+1..rr-1]]
return (tt,ee,w,eed,cTri))
(\(tt,ee,w,eed,cTri) -> do
triTestTw <- qinit True
triTestTw <- qnot triTestTw `controlled` cTri .==. 0
return ((tt,ee,w,eed,cTri),triTestTw))
comment_with_label "EXIT: a17_TriangleTestTw" (tt,ee,w,triTestTw) ("tt","ee","w","triTestTw")
return (tt,ee,w,triTestTw)
Alternative implementation , using ( a lot of ) extra ancillas instead of a counter :
a17_TriangleTestTw oracle@(n , r , ) tt ee w = do
let rr = length ee
with_ancilla_list rr $ \eed - > do
( ( tt , ee , w , , ) , _ ) < - with_computed_fun
( \(tt , ee , w , , ) - > do
< - mapM ( \(b , a ) - > do
b < - edgeOracle ( tt ! ! a ) w b
return ( b ) )
( zip ( eed ) [ 0 .. rr-1 ] )
tests < - mapM ( \(i , j ) - > do
t < - a2_ZERO False
t < - qnot t ` controlled ` ( ee ! ! j ! ! i ) . & & . ( eed ! ! i ) . & & . ( eed ! ! j )
return(t ) )
[ ( i , j ) | i < - [ 0 .. rr-1 ] , j < - [ i+1 .. rr-1 ] ]
return ( tt , ee , w , , eed , tests ) )
( tt , ee , w , , )
( \(tt , ee , w , , eed , tests ) - > do
( map ( - > ( p , True ) ) tests )
return ( ( tt , ee , w , , eed , tests ) , ( ) ) )
return ( tt , ee , w , )
a17_TriangleTestTw oracle@(n,r,edgeOracle) tt ee w triTestTw = do
let rr = length ee
with_ancilla_list rr $ \eed -> do
((tt,ee,w,triTestTw,eed),_) <- with_computed_fun
(\(tt,ee,w,triTestTw,eed) -> do
eed <- mapM (\(b,a) -> do
b <- edgeOracle (tt !! a) w b
return (b))
(zip (eed) [0..rr-1])
tests <- mapM (\(i,j) -> do
t <- a2_ZERO False
t <- qnot t `controlled` (ee !! j !! i) .&&. (eed !! i) .&&. (eed !! j)
return(t))
[(i,j) | i <- [0..rr-1], j <- [i+1..rr-1]]
return (tt,ee,w,triTestTw,eed,tests))
(tt,ee,w,triTestTw,eed)
(\(tt,ee,w,triTestTw,eed,tests) -> do
triTestTw <- qor triTestTw (map (\p -> (p,True)) tests)
return ((tt,ee,w,triTestTw,eed,tests),()))
return (tt,ee,w,triTestTw)-}
| Algorithm 18 : /TriangleEdgeSearch/.
-- Use Grover search to seek a node /w/ that forms a triangle with some pair of
-- nodes in /tt/, unless a triangle has already been found (recorded in /triTestT/),
-- in which case do nothing.
a18_TriangleEdgeSearch :: QWTFP_spec -- ^ The ambient oracle.
-> IntMap QNode -- ^ /tt/, an /R/-tuple of nodes.
-> IntMap (IntMap Qubit) -- ^ /ee/, a cache of edge data for /R/.
-> Qubit -- ^ /triTestT/, test qubit recording if a triangle has already been found.
-> Circ (IntMap QNode, IntMap (IntMap Qubit), QNode, Qubit) -- ^ Return /(tt, ee, w, regs)/.
a18_TriangleEdgeSearch oracle@(n,r,edgeOracle,_) = box "a18" $ \tt ee triTestT -> do
comment_with_label "ENTER: a18_TriangleEdgeSearch" (tt,ee,triTestT) ("tt","ee","triTestT")
let nn = 2^n
tG = floor (pi/4 *( sqrt ( fromIntegral nn)))
w <- a2_ZERO (replicate n False)
w <- a4_HADAMARD w
box_loopM "a18_loop" tG (tt,ee,w,triTestT) (\(tt,ee,w,triTestT) -> do
((tt,ee,w,triTestT),()) <- with_computed_fun (tt,ee,w,triTestT)
(\(tt,ee,w,triTestT) -> do
(tt,ee,w,triTestT,cTri) <- a19_GCQWalk oracle tt ee w triTestT
cTri_nonzero <- qinit True
cTri_nonzero <- qnot cTri_nonzero `controlled` cTri .==. 0
return (tt,ee,w,triTestT,cTri,cTri_nonzero))
(\(tt,ee,w,triTestT,cTri,cTri_nonzero) -> do
phaseFlipIf $ (triTestT .==. 0) .&&. cTri_nonzero
return ((tt,ee,w,triTestT,cTri,cTri_nonzero),()))
w <- a7_DIFFUSE w
return (tt,ee,w,triTestT))
comment_with_label "EXIT: a18_TriangleEdgeSearch" (tt,ee,w,triTestT) ("tt","ee","w","triTestT")
return (tt,ee,w,triTestT)
| Algorithm 19 : /GCQWalk/ ( “ Graph Collision Quantum Walk ” )
--
-- Perform graph collision on the /R/-tuple /tt/ and the node /w/, to determine
-- (with high probability) whether /w/ forms a triangle with some pair of nodes
-- in /tt/.
a19_GCQWalk :: QWTFP_spec -- ^ The ambient oracle.
-> IntMap QNode -- ^ /tt/, an /R/-tuple of nodes.
-> IntMap (IntMap Qubit) -- ^ /ee/, a cache of the edge data for /tt/.
-> QNode -- ^ /w/, a node.
-> Qubit -- ^ /triTestT/, test qubit to record if a triangle has already been found.
^ Return /(tt , ee , w , triTestT , cTri)/.
a19_GCQWalk oracle@(n,r,edgeOracle,qram) = box "a19" $ \tt ee w triTestT -> do
comment_with_label "ENTER: a19_GCQWalk" (tt,ee,w,triTestT) ("tt","ee","w","triTestT")
let nn = 2^n
rr = 2^r
rbar = max ((2 * r) `div` 3) 1
rrbar = 2^rbar
tbarm = max (rr `div` rrbar) 1
tbarw = floor $ sqrt $ fromIntegral rrbar
cTri <- qinit (intm (2*rbar - 1) 0)
with_ancilla_init
((intMap_replicate rrbar (intm r 0)),
(intm rbar 0),
(intm r 0),
(intMap_replicate rrbar False))
$ \(tau,iota,sigma,eew) -> do
tau <- a4_HADAMARD tau
iota <- a4_HADAMARD iota
sigma <- a4_HADAMARD sigma
eew <- mapWithKeyM (\j eew_j -> do
let taub = tau ! j
ttd <- qinit (replicate n False)
(taub, tt, ttd) <- qram_fetch qram taub tt ttd
eew_j <- edgeOracle ttd w eew_j
(taub, tt, ttd) <- qram_fetch qram taub tt ttd
qterm (replicate n False) ttd
return eew_j)
eew
cTri <- foldM (\cTri j -> do
let tau_j = tau ! j
eed <- qinit (intMap_replicate rr False)
(taub,ee,eed) <- a11_FetchE tau_j ee eed
cTri <- foldM (\cTri k -> do
let tau_k = tau ! k
Note : the Fetch to eedd_k seems redundant here ; why not control on ( eedd ! ! k ) directly ?
eedd_k <- qinit False
(tauc, eed, eedd_k) <- qram_fetch qram tau_k eed eedd_k
cTri <- increment cTri `controlled` eedd_k .&&. (eew ! j) .&&. (eew ! k)
(tauc, eed, eedd_k) <- qram_fetch qram tau_k eed eedd_k
qterm False eedd_k
return cTri)
cTri [j+1..rrbar-1]
(taub,ee,eed) <- a11_FetchE tau_j ee eed
qterm (intMap_replicate rr False) eed
return cTri)
cTri [0..rrbar-1]
(tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT)) <- box_loopM "a19_loop1" tbarm
(tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT))
(\(tt,ee,w,(e1,e2,e3,e4,cTri,triTestT)) -> do
((cTri,triTestT),()) <- with_computed_fun (cTri,triTestT)
(\(cTri,triTestT) -> do
cTri_nonzero <- qinit True
cTri_nonzero <- qnot cTri_nonzero `controlled` cTri .==. 0
return (cTri,triTestT,cTri_nonzero))
(\(cTri,triTestT,cTri_nonzero) -> do
phaseFlipIf $ (triTestT .==. 0) .&&. cTri_nonzero
return ((cTri,triTestT,cTri_nonzero),()))
box_loopM "a19_loop2" tbarw (tt,ee,w,(e1,e2,e3,e4,cTri,triTestT)) (\(b,c,d,e) -> a20_GCQWStep oracle b c d e))
comment_with_label "EXIT: a19_GCQWalk" (tt,ee,w,triTestT,cTri) ("tt","ee","w","triTestT","cTri")
return (tt,ee,w,triTestT,cTri)
| Algorithm 20 : /GCQWStep/
Take one step in the graph collision walk ( used in ' a19_GCQWalk ' above ) .
-- Uses many auxiliary registers.
-- The arguments are, in this order:
--
-- * The ambient oracle.
--
-- * /tt/, an /R/-tuple of nodes.
--
-- * /ee/, a cache of the edge data for /tt/.
--
-- * /w/, a node.
--
-- * /regs/, various workspace\/output registers.
--
-- * /ttd/, /eed/, /taud/, /eewd/, and /eedd/, local ancillas.
--
-- The function returns /(tt, ee, w, regs)/.
a20_GCQWStep :: QWTFP_spec
-> IntMap QNode
-> IntMap (IntMap Qubit)
-> QNode
-> GCQWRegs
-> Circ (IntMap QNode, IntMap (IntMap Qubit), QNode, GCQWRegs)
a20_GCQWStep oracle@(n,r,edgeOracle,qram) = box "a20" $
\tt ee w gcqwRegs@(tau,iota,sigma,eew,cTri,triTestT) -> do
comment_with_label "ENTER: a20_GCQWStep" (tt,ee,w,tau,iota,sigma,eew,cTri,triTestT) ("tt","ee","w","tau","iota","sigma","eew","cTri","triTestT")
let rr = 2^r
rbar = max ((2 * r) `div` 3) 1
rrbar = 2^rbar
(iota, sigma) <- a7_DIFFUSE (iota, sigma)
((tt,ee,w,gcqwRegs),_) <- with_computed_fun (tt,ee,w,gcqwRegs)
(\(tt,ee,w,gcqwRegs@(tau,iota,sigma,eew,cTri,triTestT)) -> do
ttd <- qinit (replicate n False)
eed <- qinit (intMap_replicate rr False)
taud <- qinit (intm r 0)
eewd <- qinit False
eedd <- qinit (intMap_replicate rrbar False)
(iota, tau, taud) <- qram_fetch qram iota tau taud
(taud, tt, ttd) <- qram_fetch qram taud tt ttd
(iota,eew,eewd) <- qram_swap qram iota eew eewd
(taud,ee,eed) <- a11_FetchE taud ee eed
eedd <- mapWithKeyM (\k eeddb -> do
let taub = tau ! k
(taub, eed, eeddb) <- qram_fetch qram taub eed eeddb
return eeddb)
eedd
cTri <- loop_with_indexM (rrbar-1) cTri (\a cTri -> do
decrement cTri `controlled` (eedd ! a) .&&. (eewd) .&&. (eew ! a))
eewd <- edgeOracle ttd w eewd
eedd <- mapWithKeyM (\k e -> do
let taub = tau ! k
let eeddb = eedd ! k
(taub, eed, eeddb) <- qram_fetch qram taub eed eeddb
return e)
eedd
(taud,ee,eed) <- a11_FetchE taud ee eed
(taud,tt,ttd) <- qram_fetch qram taud tt ttd
(iota,tau,taud) <- qram_store qram iota tau taud
return (tt,ee,w,gcqwRegs,ttd,eed,taud,eewd,eedd))
(\(tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT),ttd,eed,taud,eewd,eedd) -> do
(taud,sigma) <- a14_SWAP taud sigma
return ((tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT),ttd,eed,taud,eewd,eedd),()))
comment_with_label "ENTER: a20_GCQWStep" (tt,ee,w,gcqwRegs) ("tt","ee","w",("tau","iota","sigma","eew","cTri","triTestT"))
return (tt,ee,w,gcqwRegs)
| null | https://raw.githubusercontent.com/thephoeron/quipper-language/15e555343a15c07b9aa97aced1ada22414f04af6/Algorithms/TF/QWTFP.hs | haskell | file COPYRIGHT for a list of authors, copyright holders, licensing,
and other details. All rights reserved.
======================================================================
# OPTIONS -fcontext-stack=50 #
The algorithm works by performing a Grover-based quantum walk on
We refer to this part of the algorithm as the /outer/ walk.
The subroutine used to check whether a triangle has been found
is itself a quantum walk, the /inner/ walk.
specifying respectively the length /l/ of the integers used by the
of Hamming graph tuples.
======================================================================
where /wMeasure/ contains a node of the triangle with the
======================================================================
*Utility subroutines
Defined using the more generic 'qinit'.
the qubits in a register.
Apply a Hadamard gate to every qubit in the given quantum data.
Defined using the more generic 'map_hadamard'.
Set up the register /ee/ with the edge information
for the nodes contained in /tt/.
======================================================================
Do a quantum walk step on the Hamming graph.
reflecting about the average.
Perform a quantum-addressed fetch operation.
This fetches the /i/-th element from /tt/ into /ttd/.
Precondition: /ttd/ = 0.
in "Alternatives".
Perform a quantum-addressed store operation:
store /ttd/ into the /i/-th element from /tt/.
Analogous to 'a8_FetchT'.
Perform a quantum-addressed swap:
swap /ttd/ with the /i/-th element of /tt/.
Analogous to 'a8_FetchT' and 'a9_StoreT'.
is a somewhat specialized addressed fetching operation.
Perform a quantum-addressed swap. Analogous to 'a11_FetchE'.
Given a list of nodes /tt/, a distinguished node /ttd/,
and a list of bits /eed/, either:
* store the edge information for /(ttd,tt)/ into /eed/, if /eed/ is initially 0; or
generic function and works for any quantum data type.
======================================================================
** The inner quantum walk
Test whether the nodes /tt/ contain a pair that can be extended to a
triangle in the graph. Used as the test function in the outer quantum
implemented using an “inner quantum walk” to seek /w/.
^ The ambient oracle.
^ /tt/, an /R/-tuple of nodes.
^ /ee/, a cache of the edge information between nodes in /tt/.
^ Return /(tt, ee, w, triTestT,triTestTw)/.
Search exhaustively over the array /ee/ of edge data, seeking a triangle.
Whenever one is found, flip the qubit /triTestT/.
Search exhaustively for a pair of nodes in /tt/ that form a triangle with /w/.
Whenever a triangle found, flip qubit /triTestTw/.
^ The ambient oracle.
^ /tt/, an /R/-tuple of nodes.
^ /ee/, a cache of the edge data for /T/.
^ /w/, another node.
^ return /(tt,ee,w,triTestTw)/.
Use Grover search to seek a node /w/ that forms a triangle with some pair of
nodes in /tt/, unless a triangle has already been found (recorded in /triTestT/),
in which case do nothing.
^ The ambient oracle.
^ /tt/, an /R/-tuple of nodes.
^ /ee/, a cache of edge data for /R/.
^ /triTestT/, test qubit recording if a triangle has already been found.
^ Return /(tt, ee, w, regs)/.
Perform graph collision on the /R/-tuple /tt/ and the node /w/, to determine
(with high probability) whether /w/ forms a triangle with some pair of nodes
in /tt/.
^ The ambient oracle.
^ /tt/, an /R/-tuple of nodes.
^ /ee/, a cache of the edge data for /tt/.
^ /w/, a node.
^ /triTestT/, test qubit to record if a triangle has already been found.
Uses many auxiliary registers.
The arguments are, in this order:
* The ambient oracle.
* /tt/, an /R/-tuple of nodes.
* /ee/, a cache of the edge data for /tt/.
* /w/, a node.
* /regs/, various workspace\/output registers.
* /ttd/, /eed/, /taud/, /eewd/, and /eedd/, local ancillas.
The function returns /(tt, ee, w, regs)/. | This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the
# LANGUAGE FlexibleContexts #
| This module provides an implementation of the Quantum Walk for
the Triangle Finding Problem .
a larger graph /H/ , called the Hamming graph associated to
The overall algorithm is parameterized on integers /l/ , /n/ and /r/
oracle , the number 2[sup /n/ ] of nodes of /G/ and the size 2[sup /r/ ]
module Algorithms.TF.QWTFP where
import Prelude hiding (mapM, mapM_)
import Quipper
import Quipper.Internal (BType)
import QuipperLib.Arith
import Algorithms.TF.Definitions
import Data.IntMap (IntMap, adjust, insert, size)
import qualified Data.IntMap as IntMap
import Data.Traversable (mapM)
import Data.Foldable (mapM_)
import Control.Monad (foldM)
* Main TF algorithm
| Algorithm 1 . Do a quantum walk on the Hamming graph associated with /G/.
Returns a quadruple /(testTMeasure , wMeasure , TMeasure , EMeasure)/
other two nodes in /TMeasure/.
a1_QWTFP :: QWTFP_spec -> Circ (Bit,CNode,IntMap CNode,IntMap (IntMap Bit))
a1_QWTFP oracle@(n,r,edgeOracle,_) = do
comment "ENTER: a1_QWTFP"
let nn = 2^n
let rr = 2^r
let rbar = max ((2 * r) `div` 3) 1
let rrbar = 2^rbar
let tm = 2^(n - r)
let tw = floor $ sqrt $ fromIntegral rr
testTEdge <- a2_ZERO False
tt <- a3_INITIALIZE (intMap_replicate rr (replicate n False))
i <- a3_INITIALIZE (intm r 0)
v <- a3_INITIALIZE (replicate n False)
(tt, ee) <- a5_SETUP oracle tt
(tt,i,v,ee) <- box_loopM "a1_loop1" tm (tt,i,v,ee)
(\(tt,i,v,ee) -> do
((tt,ee),_) <- with_computed_fun (tt,ee)
(\(tt,ee) -> a15_TestTriangleEdges oracle tt ee)
(\(tt,ee,w,triTestT,triTestTw) -> do
phaseFlipUnless (triTestT .==. 0 .&&. triTestTw .==. 0)
return ((tt,ee,w,triTestT,triTestTw),()))
(tt,i,v,ee) <- box_loopM "a1_loop2" tw (tt,i,v,ee) (\(a,b,c,d) -> a6_QWSH oracle a b c d)
return (tt,i,v,ee))
(tt,ee,w,triTestT,triTestTw) <- a15_TestTriangleEdges oracle tt ee
testTEdge <- qor testTEdge [(triTestT, True), (triTestTw, True)]
testTMeasure <- measure testTEdge
wMeasure <- measure w
ttMeasure <- measure tt
eeMeasure <- measure ee
qdiscard (i,v,triTestT,triTestTw)
comment_with_label "EXIT: a1_QWTFP" (testTMeasure, wMeasure, ttMeasure, eeMeasure) ("testTMeasure", "wMeasure", "ttMeasure", "eeMeasure")
return (testTMeasure, wMeasure, ttMeasure, eeMeasure)
| Algorithm 2 .
Initialize the qubits in a register to a specified state .
a2_ZERO :: QShape a qa ca => a -> Circ qa
a2_ZERO b = do
comment "ENTER: a2_ZERO"
q <- qinit b
comment_with_label "EXIT: a2_ZERO" q "q"
return q
| Algorithm 3 .
Initialize to a specified state then apply a Hadamard gate to
a3_INITIALIZE :: QShape a qa ca => a -> Circ qa
a3_INITIALIZE reg = do
comment "ENTER: a3_INITIALIZE"
zreg <- a2_ZERO reg
hzreg <- a4_HADAMARD zreg
comment_with_label "EXIT: a3_INITIALIZE" hzreg "hzreg"
return hzreg
| Algorithm 4 .
a4_HADAMARD :: QData qa => qa -> Circ qa
a4_HADAMARD q = do
comment_with_label "ENTER: a4_HADAMARD" q "q"
q <- map_hadamard q
comment_with_label "EXIT: a4_HADAMARD" q "q"
return q
| Algorithm 5 .
a5_SETUP :: QWTFP_spec -> (IntMap QNode) -> Circ (IntMap QNode, IntMap (IntMap Qubit))
a5_SETUP oracle@(n,r,edgeOracle,_) = box "a5" $ \tt -> do
comment_with_label "ENTER: a5_SETUP" tt "tt"
let rr = 2^r
ee <- qinit $ IntMap.fromList [(j,(intMap_replicate j False)) | j <- [0..(rr-1)]]
ee <- loop_with_indexM (rr) ee (\k ee ->
loop_with_indexM k ee (\j ee -> do
edgejk <- edgeOracle (tt ! j) (tt ! k) (ee ! k ! j)
ee <- return $ adjust (insert j edgejk) k ee
return ee))
comment_with_label "EXIT: a5_SETUP" (tt,ee) ("tt","ee")
return (tt, ee)
* * The outer quantum walk and the standard Qram
| Algorithm 6 .
a6_QWSH :: QWTFP_spec -> (IntMap QNode) -> QDInt -> QNode -> (IntMap (IntMap Qubit))
-> Circ (IntMap QNode, QDInt, QNode, IntMap (IntMap Qubit))
a6_QWSH oracle@(n,r,edgeOracle,qram) = box "a6" $ \tt i v ee -> do
comment_with_label "ENTER: a6_QWSH" (tt, i, v, ee) ("tt", "i", "v", "ee")
with_ancilla_init (replicate n False) $ \ttd -> do
with_ancilla_init (intMap_replicate (2^r) False) $ \eed -> do
(i,v) <- a7_DIFFUSE (i,v)
((tt,i,v,ee,ttd,eed),_) <- with_computed_fun (tt,i,v,ee,ttd,eed)
(\(tt,i,v,ee,ttd,eed) -> do
(i,tt,ttd) <- qram_fetch qram i tt ttd
(i,ee,eed) <- a12_FetchStoreE i ee eed
(tt,ttd,eed) <- a13_UPDATE oracle tt ttd eed
(i,tt,ttd) <- qram_store qram i tt ttd
return (tt,i,v,ee,ttd,eed))
(\(tt,i,v,ee,ttd,eed) -> do
(ttd,v) <- a14_SWAP ttd v
return ((tt,i,v,ee,ttd,eed),()))
comment_with_label "EXIT: a6_QWSH" (tt, i, v, ee) ("tt", "i", "v", "ee")
return (tt,i,v,ee)
| Algorithm 7 .
Diffuse a piece of quantum data , in the Grover search sense of
Note : relies on @'shape ' q@ corresponding to the “ all false ” state .
a7_DIFFUSE :: (QData qa) => qa -> Circ qa
a7_DIFFUSE = box "a7" $ \q -> do
comment_with_label "ENTER: a7_DIFFUSE" q "q"
q <- a4_HADAMARD q
phaseFlipUnless $ q .==. qc_false q
q <- a4_HADAMARD q
comment_with_label "EXIT: a7_DIFFUSE" q "q"
return q
| Algorithm 8 .
This could be implemented more efficiently using the qRAM implementation
a8_FetchT :: (QData qa) => QDInt -> IntMap qa -> qa -> Circ (QDInt, IntMap qa, qa)
a8_FetchT = box "a8" $ \i tt ttd -> do
comment_with_label "ENTER: a8_FetchT" (i,tt,ttd) ("i","tt","ttd")
let r = qdint_length i
(i,tt,ttd) <- loop_with_indexM (2^r) (i,tt,ttd)
(\j (i,tt,ttd) -> do
let ttj = tt ! j
(ttj,ttd) <- mapBinary
(\q p -> do
p <- qnot p `controlled` q .&&. i .==. (fromIntegral j)
return (q,p))
(tt ! j) ttd
return (i, insert j ttj tt, ttd))
comment_with_label "EXIT: a8_FetchT" (i,tt,ttd) ("i","tt","ttd")
return (i,tt,ttd)
| Algorithms 9 .
a9_StoreT :: (QData qa) => QDInt -> IntMap qa -> qa -> Circ (QDInt, IntMap qa, qa)
a9_StoreT = box "a9" $ \i tt ttd -> do
comment_with_label "ENTER: a9_StoreT" (i,tt,ttd) ("i","tt","ttd")
let r = qdint_length i
(i,tt,ttd) <- loop_with_indexM (2^r) (i,tt,ttd)
(\j (i,tt,ttd) -> do
(ttj,ttd) <- mapBinary
(\q p -> do
q <- qnot q `controlled` p .&&. i .==. (fromIntegral j)
return (q,p))
(tt ! j) ttd
return (i, insert j ttj tt, ttd))
comment_with_label "EXIT: a9_StoreT" (i,tt,ttd) ("i","tt","ttd")
return (i,tt,ttd)
| Algorithm 10 .
a10_FetchStoreT :: (QData qa) => QDInt -> IntMap qa -> qa -> Circ (QDInt, IntMap qa, qa)
a10_FetchStoreT = box "a10" $ \i tt ttd -> do
comment_with_label "ENTER: a10_FetchStoreT" (i,tt,ttd) ("i","tt","ttd")
let r = qdint_length i
(i,tt,ttd) <- loop_with_indexM (2^r) (i,tt,ttd)
(\j (i,tt,ttd) -> do
(qq,ttd) <- a14_SWAP (tt ! j) ttd
`controlled` i .==. (fromIntegral j)
return (i,(insert j qq tt), ttd))
comment_with_label "EXIT: a10_FetchStoreT" (i,tt,ttd) ("i","tt","ttd")
return (i,tt,ttd)
| Algorithm 11 . Perform a quantum - addressed fetch operation . This
a11_FetchE :: QDInt -> IntMap (IntMap Qubit) -> IntMap Qubit
-> Circ (QDInt, IntMap (IntMap Qubit), IntMap Qubit)
a11_FetchE = box "a11" $ \i qs ps -> do
comment_with_label "ENTER: a11_FetchE" (i, qs, ps) ("i", "qs", "ps")
let r = qdint_length i
(i,qs,ps) <- loop_with_indexM (2^r) (i,qs,ps) (\j (i,qs,ps) ->
loop_with_indexM j (i,qs,ps) (\k (i,qs,ps) -> do
pk <- qnot (ps ! k) `controlled`
(qs ! j ! k) .&&. i .==. (fromIntegral j)
ps <- return $ insert k pk ps
pj <- qnot (ps ! j) `controlled`
(qs ! j ! k) .&&. i .==. (fromIntegral k)
ps <- return $ insert j pj ps
return (i,qs,ps)))
comment_with_label "EXIT: a11_FetchE" (i, qs, ps) ("i", "qs", "ps")
return (i,qs,ps)
| Algorithm 12 .
a12_FetchStoreE :: QDInt -> IntMap (IntMap Qubit) -> IntMap Qubit
-> Circ (QDInt, IntMap (IntMap Qubit), IntMap Qubit)
a12_FetchStoreE = box "a12" $ \i qs ps -> do
comment_with_label "ENTER: a12_FetchStoreE" (i, qs, ps) ("i", "qs", "ps")
let r = qdint_length i
(i,qs,ps) <- loop_with_indexM (2^r) (i,qs,ps) (\j (i,qs, ps) ->
loop_with_indexM j (i,qs, ps) (\k (i,qs, ps) -> do
(q,p) <- a14_SWAP (qs ! j ! k) (ps ! k)
`controlled` i .==. (fromIntegral j)
(qs,ps) <- return (adjust (insert k q) j qs, insert k p ps)
(q,p) <- a14_SWAP (qs ! j ! k) (ps ! j)
`controlled` i .==. (fromIntegral k)
(qs,ps) <- return (adjust (insert k q) j qs, insert j p ps)
return (i,qs,ps)))
comment_with_label "EXIT: a12_FetchStoreE" (i, qs, ps) ("i", "qs", "ps")
return (i,qs,ps)
| Algorithm 13 .
* zero /eed/ , if it initially holds the edge information .
a13_UPDATE :: QWTFP_spec -> IntMap QNode -> QNode -> IntMap Qubit
-> Circ (IntMap QNode, QNode, IntMap Qubit)
a13_UPDATE oracle@(n,r,edgeOracle,_) = box "a13" $ \tt ttd eed -> do
comment_with_label "ENTER: a13_UPDATE" (tt,ttd,eed) ("tt","ttd","eed")
(tt,ttd,eed) <- loop_with_indexM (2^r) (tt,ttd,eed) (\j (tt,ttd,eed) -> do
e <- edgeOracle (tt ! j) ttd (eed ! j)
return (tt,ttd,insert j e eed))
comment_with_label "EXIT: a13_UPDATE" (tt,ttd,eed) ("tt","ttd","eed")
return (tt,ttd,eed)
| Algorithm 14 . Swap two registers of equal size . This is a
a14_SWAP :: QCData qa => qa -> qa -> Circ (qa, qa)
a14_SWAP q r = do
comment_with_label "ENTER: a14_SWAP" (q,r) ("q", "r")
(q,r) <- swap q r
comment_with_label "EXIT: a14_SWAP" (q,r) ("q", "r")
return (q,r)
| The qRAM operations from Algorithms 8–10 wrapped into a ' Qram ' object .
standard_qram :: Qram
standard_qram = Qram {
qram_fetch = a8_FetchT,
qram_store = a9_StoreT,
qram_swap = a10_FetchStoreT
}
| A type to hold the Graph Collision Quantum Walk Registers
/(tau , iota , sigma , eew , cTri , triTestT)/ , used in ' a20_GCQWStep ' .
type GCQWRegs = (IntMap QDInt, QDInt, QDInt, IntMap Qubit, QDInt, Qubit)
| Algorithm 15 : /TestTriangleEdges/.
walk . Seeks triangles in two different ways :
1 . Entirely within the nodes /tt/. If found , set qubit /triTestT/.
2 . With two vertices from /tt/ , a third anywhere in the graph . If found ,
set qubit /triTestTw/ , and return the third vertex as /w/. This is
a15_TestTriangleEdges ::
a15_TestTriangleEdges oracle = box "a15" $ \tt ee -> do
comment_with_label "ENTER: a15_TestTriangleEdges" (tt,ee) ("tt","ee")
(ee,triTestT) <- a16_TriangleTestT ee
(tt,ee,w,triTestT) <- a18_TriangleEdgeSearch oracle tt ee triTestT
(tt,ee,w,triTestTw) <- a17_TriangleTestTw oracle tt ee w
comment_with_label "EXIT: a15_TestTriangleEdges" (tt,ee,w,triTestT,triTestTw) ("tt","ee","w","triTestT","triTestTw")
return (tt,ee,w,triTestT,triTestTw)
| Algorithm 16 : /TriangleTestT ee
a16_TriangleTestT :: IntMap (IntMap Qubit) -> Circ (IntMap (IntMap Qubit), Qubit)
a16_TriangleTestT = box "a16" $ \ee -> do
comment_with_label "ENTER: a16_TriangleTestT" ee "ee"
let rr = size ee
(ee,triTestT) <- with_computed_fun ee
(\ee -> do
cTri <- qinit (intm (ceiling (logBase 2 (fromIntegral (rr `choose` 3)))) 0)
cTri <- foldM (\cTri (i,j,k) -> do
cTri <- increment cTri `controlled` (ee ! j ! i) .&&. (ee ! k ! i) .&&. (ee ! k ! j)
return cTri)
cTri [(i,j,k) | i <- [0..rr-1], j <- [i+1..rr-1], k <- [j+1..rr-1]]
return (ee,cTri))
(\(ee,cTri) -> do
triTestT <- qinit True
triTestT <- qnot triTestT `controlled` cTri .==. 0
return ((ee,cTri),triTestT))
comment_with_label "EXIT: a16_TriangleTestT" (ee,triTestT) ("ee","triTestT")
return (ee,triTestT)
Alternative implementation , using ( a lot of ) extra ancillas instead of a counter :
a16_TriangleTestT : : [ [ Qubit ] ] - > Qubit - > Circ ( [ [ Qubit ] ] , Qubit )
a16_TriangleTestT ee triTestT = do
let rr = length ee
( ( ee , triTestT ) , _ ) < - with_computed_fun
( \(ee , triTestT ) - > do
tests < - mapM ( \(i , j , k ) - > do
t < - a2_ZERO False
t < - qnot t ` controlled `
[ ( ee ! ! j ! ! i),(ee ! ! k ! ! i),(ee ! ! k ! ! j ) ]
return(t ) )
[ ( i , j , k ) | i < - [ 0 .. rr-1 ] , j < - [ i+1 .. rr-1 ] , k < - [ j+1 .. rr-1 ] ]
return ( ee , triTestT , tests ) )
( ee , triTestT )
( \(ee , triTestT , tests ) - > do
triTestT < - qor triTestT ( map ( - > ( p , True ) ) tests )
return ( ( ee , triTestT , tests ) , ( ) ) )
return ( ee , triTestT )
a16_TriangleTestT :: [[Qubit]] -> Qubit -> Circ ([[Qubit]], Qubit)
a16_TriangleTestT ee triTestT = do
let rr = length ee
((ee,triTestT),_) <- with_computed_fun
(\(ee,triTestT) -> do
tests <- mapM (\(i,j,k) -> do
t <- a2_ZERO False
t <- qnot t `controlled`
[(ee !! j !! i),(ee !! k !! i),(ee !! k !! j)]
return(t))
[(i,j,k) | i <- [0..rr-1], j <- [i+1..rr-1], k <- [j+1..rr-1]]
return (ee,triTestT,tests))
(ee,triTestT)
(\(ee,triTestT,tests) -> do
triTestT <- qor triTestT (map (\p -> (p,True)) tests)
return ((ee,triTestT,tests),()))
return (ee,triTestT)-}
| Algorithm 17 : /TriangleTestTw ee triTestTw/.
a17_TriangleTestTw oracle@(n,r,edgeOracle,_) = box "a17" $ \tt ee w -> do
comment_with_label "ENTER: a17_TriangleTestTw" (tt,ee,w) ("tt","ee","w")
let rr = size ee
with_ancilla_init (intMap_replicate rr False) $ \eed -> do
((tt,ee,w,eed),triTestTw) <- with_computed_fun (tt,ee,w,eed)
(\(tt,ee,w,eed) -> do
eed <- mapWithKeyM (\k e -> do
e <- edgeOracle (tt ! k) w e
return e)
eed
cTri <- qinit (intm (ceiling (logBase 2 (fromIntegral (rr `choose` 2)))) 0)
cTri <- foldM
(\cTri (i,j) ->
increment cTri `controlled` (ee ! j ! i) .&&. (eed ! i) .&&. (eed ! j))
cTri
[(i,j) | i <- [0..rr-1], j <- [i+1..rr-1]]
return (tt,ee,w,eed,cTri))
(\(tt,ee,w,eed,cTri) -> do
triTestTw <- qinit True
triTestTw <- qnot triTestTw `controlled` cTri .==. 0
return ((tt,ee,w,eed,cTri),triTestTw))
comment_with_label "EXIT: a17_TriangleTestTw" (tt,ee,w,triTestTw) ("tt","ee","w","triTestTw")
return (tt,ee,w,triTestTw)
Alternative implementation , using ( a lot of ) extra ancillas instead of a counter :
a17_TriangleTestTw oracle@(n , r , ) tt ee w = do
let rr = length ee
with_ancilla_list rr $ \eed - > do
( ( tt , ee , w , , ) , _ ) < - with_computed_fun
( \(tt , ee , w , , ) - > do
< - mapM ( \(b , a ) - > do
b < - edgeOracle ( tt ! ! a ) w b
return ( b ) )
( zip ( eed ) [ 0 .. rr-1 ] )
tests < - mapM ( \(i , j ) - > do
t < - a2_ZERO False
t < - qnot t ` controlled ` ( ee ! ! j ! ! i ) . & & . ( eed ! ! i ) . & & . ( eed ! ! j )
return(t ) )
[ ( i , j ) | i < - [ 0 .. rr-1 ] , j < - [ i+1 .. rr-1 ] ]
return ( tt , ee , w , , eed , tests ) )
( tt , ee , w , , )
( \(tt , ee , w , , eed , tests ) - > do
( map ( - > ( p , True ) ) tests )
return ( ( tt , ee , w , , eed , tests ) , ( ) ) )
return ( tt , ee , w , )
a17_TriangleTestTw oracle@(n,r,edgeOracle) tt ee w triTestTw = do
let rr = length ee
with_ancilla_list rr $ \eed -> do
((tt,ee,w,triTestTw,eed),_) <- with_computed_fun
(\(tt,ee,w,triTestTw,eed) -> do
eed <- mapM (\(b,a) -> do
b <- edgeOracle (tt !! a) w b
return (b))
(zip (eed) [0..rr-1])
tests <- mapM (\(i,j) -> do
t <- a2_ZERO False
t <- qnot t `controlled` (ee !! j !! i) .&&. (eed !! i) .&&. (eed !! j)
return(t))
[(i,j) | i <- [0..rr-1], j <- [i+1..rr-1]]
return (tt,ee,w,triTestTw,eed,tests))
(tt,ee,w,triTestTw,eed)
(\(tt,ee,w,triTestTw,eed,tests) -> do
triTestTw <- qor triTestTw (map (\p -> (p,True)) tests)
return ((tt,ee,w,triTestTw,eed,tests),()))
return (tt,ee,w,triTestTw)-}
| Algorithm 18 : /TriangleEdgeSearch/.
a18_TriangleEdgeSearch oracle@(n,r,edgeOracle,_) = box "a18" $ \tt ee triTestT -> do
comment_with_label "ENTER: a18_TriangleEdgeSearch" (tt,ee,triTestT) ("tt","ee","triTestT")
let nn = 2^n
tG = floor (pi/4 *( sqrt ( fromIntegral nn)))
w <- a2_ZERO (replicate n False)
w <- a4_HADAMARD w
box_loopM "a18_loop" tG (tt,ee,w,triTestT) (\(tt,ee,w,triTestT) -> do
((tt,ee,w,triTestT),()) <- with_computed_fun (tt,ee,w,triTestT)
(\(tt,ee,w,triTestT) -> do
(tt,ee,w,triTestT,cTri) <- a19_GCQWalk oracle tt ee w triTestT
cTri_nonzero <- qinit True
cTri_nonzero <- qnot cTri_nonzero `controlled` cTri .==. 0
return (tt,ee,w,triTestT,cTri,cTri_nonzero))
(\(tt,ee,w,triTestT,cTri,cTri_nonzero) -> do
phaseFlipIf $ (triTestT .==. 0) .&&. cTri_nonzero
return ((tt,ee,w,triTestT,cTri,cTri_nonzero),()))
w <- a7_DIFFUSE w
return (tt,ee,w,triTestT))
comment_with_label "EXIT: a18_TriangleEdgeSearch" (tt,ee,w,triTestT) ("tt","ee","w","triTestT")
return (tt,ee,w,triTestT)
| Algorithm 19 : /GCQWalk/ ( “ Graph Collision Quantum Walk ” )
^ Return /(tt , ee , w , triTestT , cTri)/.
a19_GCQWalk oracle@(n,r,edgeOracle,qram) = box "a19" $ \tt ee w triTestT -> do
comment_with_label "ENTER: a19_GCQWalk" (tt,ee,w,triTestT) ("tt","ee","w","triTestT")
let nn = 2^n
rr = 2^r
rbar = max ((2 * r) `div` 3) 1
rrbar = 2^rbar
tbarm = max (rr `div` rrbar) 1
tbarw = floor $ sqrt $ fromIntegral rrbar
cTri <- qinit (intm (2*rbar - 1) 0)
with_ancilla_init
((intMap_replicate rrbar (intm r 0)),
(intm rbar 0),
(intm r 0),
(intMap_replicate rrbar False))
$ \(tau,iota,sigma,eew) -> do
tau <- a4_HADAMARD tau
iota <- a4_HADAMARD iota
sigma <- a4_HADAMARD sigma
eew <- mapWithKeyM (\j eew_j -> do
let taub = tau ! j
ttd <- qinit (replicate n False)
(taub, tt, ttd) <- qram_fetch qram taub tt ttd
eew_j <- edgeOracle ttd w eew_j
(taub, tt, ttd) <- qram_fetch qram taub tt ttd
qterm (replicate n False) ttd
return eew_j)
eew
cTri <- foldM (\cTri j -> do
let tau_j = tau ! j
eed <- qinit (intMap_replicate rr False)
(taub,ee,eed) <- a11_FetchE tau_j ee eed
cTri <- foldM (\cTri k -> do
let tau_k = tau ! k
Note : the Fetch to eedd_k seems redundant here ; why not control on ( eedd ! ! k ) directly ?
eedd_k <- qinit False
(tauc, eed, eedd_k) <- qram_fetch qram tau_k eed eedd_k
cTri <- increment cTri `controlled` eedd_k .&&. (eew ! j) .&&. (eew ! k)
(tauc, eed, eedd_k) <- qram_fetch qram tau_k eed eedd_k
qterm False eedd_k
return cTri)
cTri [j+1..rrbar-1]
(taub,ee,eed) <- a11_FetchE tau_j ee eed
qterm (intMap_replicate rr False) eed
return cTri)
cTri [0..rrbar-1]
(tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT)) <- box_loopM "a19_loop1" tbarm
(tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT))
(\(tt,ee,w,(e1,e2,e3,e4,cTri,triTestT)) -> do
((cTri,triTestT),()) <- with_computed_fun (cTri,triTestT)
(\(cTri,triTestT) -> do
cTri_nonzero <- qinit True
cTri_nonzero <- qnot cTri_nonzero `controlled` cTri .==. 0
return (cTri,triTestT,cTri_nonzero))
(\(cTri,triTestT,cTri_nonzero) -> do
phaseFlipIf $ (triTestT .==. 0) .&&. cTri_nonzero
return ((cTri,triTestT,cTri_nonzero),()))
box_loopM "a19_loop2" tbarw (tt,ee,w,(e1,e2,e3,e4,cTri,triTestT)) (\(b,c,d,e) -> a20_GCQWStep oracle b c d e))
comment_with_label "EXIT: a19_GCQWalk" (tt,ee,w,triTestT,cTri) ("tt","ee","w","triTestT","cTri")
return (tt,ee,w,triTestT,cTri)
| Algorithm 20 : /GCQWStep/
Take one step in the graph collision walk ( used in ' a19_GCQWalk ' above ) .
a20_GCQWStep :: QWTFP_spec
-> IntMap QNode
-> IntMap (IntMap Qubit)
-> QNode
-> GCQWRegs
-> Circ (IntMap QNode, IntMap (IntMap Qubit), QNode, GCQWRegs)
a20_GCQWStep oracle@(n,r,edgeOracle,qram) = box "a20" $
\tt ee w gcqwRegs@(tau,iota,sigma,eew,cTri,triTestT) -> do
comment_with_label "ENTER: a20_GCQWStep" (tt,ee,w,tau,iota,sigma,eew,cTri,triTestT) ("tt","ee","w","tau","iota","sigma","eew","cTri","triTestT")
let rr = 2^r
rbar = max ((2 * r) `div` 3) 1
rrbar = 2^rbar
(iota, sigma) <- a7_DIFFUSE (iota, sigma)
((tt,ee,w,gcqwRegs),_) <- with_computed_fun (tt,ee,w,gcqwRegs)
(\(tt,ee,w,gcqwRegs@(tau,iota,sigma,eew,cTri,triTestT)) -> do
ttd <- qinit (replicate n False)
eed <- qinit (intMap_replicate rr False)
taud <- qinit (intm r 0)
eewd <- qinit False
eedd <- qinit (intMap_replicate rrbar False)
(iota, tau, taud) <- qram_fetch qram iota tau taud
(taud, tt, ttd) <- qram_fetch qram taud tt ttd
(iota,eew,eewd) <- qram_swap qram iota eew eewd
(taud,ee,eed) <- a11_FetchE taud ee eed
eedd <- mapWithKeyM (\k eeddb -> do
let taub = tau ! k
(taub, eed, eeddb) <- qram_fetch qram taub eed eeddb
return eeddb)
eedd
cTri <- loop_with_indexM (rrbar-1) cTri (\a cTri -> do
decrement cTri `controlled` (eedd ! a) .&&. (eewd) .&&. (eew ! a))
eewd <- edgeOracle ttd w eewd
eedd <- mapWithKeyM (\k e -> do
let taub = tau ! k
let eeddb = eedd ! k
(taub, eed, eeddb) <- qram_fetch qram taub eed eeddb
return e)
eedd
(taud,ee,eed) <- a11_FetchE taud ee eed
(taud,tt,ttd) <- qram_fetch qram taud tt ttd
(iota,tau,taud) <- qram_store qram iota tau taud
return (tt,ee,w,gcqwRegs,ttd,eed,taud,eewd,eedd))
(\(tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT),ttd,eed,taud,eewd,eedd) -> do
(taud,sigma) <- a14_SWAP taud sigma
return ((tt,ee,w,(tau,iota,sigma,eew,cTri,triTestT),ttd,eed,taud,eewd,eedd),()))
comment_with_label "ENTER: a20_GCQWStep" (tt,ee,w,gcqwRegs) ("tt","ee","w",("tau","iota","sigma","eew","cTri","triTestT"))
return (tt,ee,w,gcqwRegs)
|
ba33959f958507b3a57e9aba66de50a84c3c6a0ab3a05858d8326127bc628dd0 | ribelo/doxa | pick_api.cljc | (ns ribelo.doxa.pick-api
(:require
[ribelo.extropy :as ex]
[ribelo.doxa.util :as u]))
(defn -pick
([db ref]
(-pick db :* ref))
([db query ^clojure.lang.IPersistentVector ref]
(let [xs (persistent! (-pick db query (transient []) ref))]
(when (seq xs)
(if (= 1 (count xs))
(first xs)
xs))))
([db query ^clojure.lang.ITransientVector acc ^clojure.lang.IPersistentVector ref]
(when db
(cond
(= :* query)
(ex/conj-some! acc (get db ref))
(keyword? query)
(ex/conj-some! acc (get-in db [ref query]))
(vector? query)
(ex/conj-some! acc
(not-empty
(ex/ensure-persisten!
(reduce
(fn [acc' q]
(cond
(keyword? q)
(if-let [v (get-in db [ref q])]
(assoc! acc' q v)
(reduced nil))
(map? q)
(if-let [m (not-empty (-pick db q ref))]
(reduce conj! acc' m)
(reduced nil))))
(transient {})
query))))
(map? query)
(ex/loop-it [[k query'] query :let [acc acc]]
(recur
(if-let [v (get-in db [ref k])]
(cond
(u/-ref-lookup? v)
(-pick db query' acc v)
(u/-ref-lookups? v)
(reduce (fn [acc ref] (-pick db query' acc ref)) acc v))
acc))
acc)))))
| null | https://raw.githubusercontent.com/ribelo/doxa/9739ad4b0f3f17503b203204fd5bdce8dfe3f439/src/main/ribelo/doxa/pick_api.cljc | clojure | (ns ribelo.doxa.pick-api
(:require
[ribelo.extropy :as ex]
[ribelo.doxa.util :as u]))
(defn -pick
([db ref]
(-pick db :* ref))
([db query ^clojure.lang.IPersistentVector ref]
(let [xs (persistent! (-pick db query (transient []) ref))]
(when (seq xs)
(if (= 1 (count xs))
(first xs)
xs))))
([db query ^clojure.lang.ITransientVector acc ^clojure.lang.IPersistentVector ref]
(when db
(cond
(= :* query)
(ex/conj-some! acc (get db ref))
(keyword? query)
(ex/conj-some! acc (get-in db [ref query]))
(vector? query)
(ex/conj-some! acc
(not-empty
(ex/ensure-persisten!
(reduce
(fn [acc' q]
(cond
(keyword? q)
(if-let [v (get-in db [ref q])]
(assoc! acc' q v)
(reduced nil))
(map? q)
(if-let [m (not-empty (-pick db q ref))]
(reduce conj! acc' m)
(reduced nil))))
(transient {})
query))))
(map? query)
(ex/loop-it [[k query'] query :let [acc acc]]
(recur
(if-let [v (get-in db [ref k])]
(cond
(u/-ref-lookup? v)
(-pick db query' acc v)
(u/-ref-lookups? v)
(reduce (fn [acc ref] (-pick db query' acc ref)) acc v))
acc))
acc)))))
|
|
34d0733f9c56a8f0457727a2228a6ec9cb2e9a54df39e47a74b4cbdac40709e7 | malcolmreynolds/GSLL | chebyshev.lisp | Regression test CHEBYSHEV for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST CHEBYSHEV
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
(LIST 0.7159209901689866d0 -1.5019966658054353d0
0.17239719403979925d0))
(MULTIPLE-VALUE-LIST (CHEBYSHEV-POINT-EXAMPLE 0.55d0))))
| null | https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/tests/chebyshev.lisp | lisp | Regression test CHEBYSHEV for GSLL , automatically generated
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST CHEBYSHEV
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
(LIST 0.7159209901689866d0 -1.5019966658054353d0
0.17239719403979925d0))
(MULTIPLE-VALUE-LIST (CHEBYSHEV-POINT-EXAMPLE 0.55d0))))
|
|
ce4dbce620327f0b2c6936bae3c08eeb6efae8aaaa008945d5f2083fec370a1e | modular-macros/ocaml-macros | scanf.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open CamlinternalFormatBasics
open CamlinternalFormat
(* alias to avoid warning for ambiguity between
Pervasives.format6
and CamlinternalFormatBasics.format6
(the former is in fact an alias for the latter,
but the ambiguity warning doesn't care)
*)
type ('a, 'b, 'c, 'd, 'e, 'f) format6 =
('a, 'b, 'c, 'd, 'e, 'f) Pervasives.format6
(* The run-time library for scanners. *)
(* Scanning buffers. *)
module type SCANNING = sig
type in_channel
type scanbuf = in_channel
type file_name = string
val stdin : in_channel
(* The scanning buffer reading from [Pervasives.stdin].
[stdib] is equivalent to [Scanning.from_channel Pervasives.stdin]. *)
val stdib : in_channel
(* An alias for [Scanf.stdin], the scanning buffer reading from
[Pervasives.stdin]. *)
val next_char : scanbuf -> char
[ ib ] advance the scanning buffer for
one character .
If no more character can be read , sets a end of file condition and
returns ' \000 ' .
one character.
If no more character can be read, sets a end of file condition and
returns '\000'. *)
val invalidate_current_char : scanbuf -> unit
(* [Scanning.invalidate_current_char ib] mark the current_char as already
scanned. *)
val peek_char : scanbuf -> char
[ Scanning.peek_char ib ] returns the current char available in
the buffer or reads one if necessary ( when the current character is
already scanned ) .
If no character can be read , sets an end of file condition and
returns ' \000 ' .
the buffer or reads one if necessary (when the current character is
already scanned).
If no character can be read, sets an end of file condition and
returns '\000'. *)
val checked_peek_char : scanbuf -> char
(* Same as [Scanning.peek_char] above but always returns a valid char or
fails: instead of returning a null char when the reading method of the
input buffer has reached an end of file, the function raises exception
[End_of_file]. *)
val store_char : int -> scanbuf -> char -> int
[ Scanning.store_char ] adds [ c ] to the token buffer
of the scanning buffer [ ib ] . It also advances the scanning buffer for
one character and returns [ lim - 1 ] , indicating the new limit for the
length of the current token .
of the scanning buffer [ib]. It also advances the scanning buffer for
one character and returns [lim - 1], indicating the new limit for the
length of the current token. *)
val skip_char : int -> scanbuf -> int
[ ignores the current character .
val ignore_char : int -> scanbuf -> int
(* [Scanning.ignore_char ib lim] ignores the current character and
decrements the limit. *)
val token : scanbuf -> string
(* [Scanning.token ib] returns the string stored into the token
buffer of the scanning buffer: it returns the token matched by the
format. *)
val reset_token : scanbuf -> unit
[ ib ] resets the token buffer of
the given scanning buffer .
the given scanning buffer. *)
val char_count : scanbuf -> int
[ Scanning.char_count ib ] returns the number of characters
read so far from the given buffer .
read so far from the given buffer. *)
val line_count : scanbuf -> int
[ Scanning.line_count ib ] returns the number of new line
characters read so far from the given buffer .
characters read so far from the given buffer. *)
val token_count : scanbuf -> int
(* [Scanning.token_count ib] returns the number of tokens read
so far from [ib]. *)
val eof : scanbuf -> bool
[ Scanning.eof ib ] returns the end of input condition
of the given buffer .
of the given buffer. *)
val end_of_input : scanbuf -> bool
(* [Scanning.end_of_input ib] tests the end of input condition
of the given buffer (if no char has ever been read, an attempt to
read one is performed). *)
val beginning_of_input : scanbuf -> bool
(* [Scanning.beginning_of_input ib] tests the beginning of input
condition of the given buffer. *)
val name_of_input : scanbuf -> string
(* [Scanning.name_of_input ib] returns the name of the character
source for input buffer [ib]. *)
val open_in : file_name -> in_channel
val open_in_bin : file_name -> in_channel
val from_file : file_name -> in_channel
val from_file_bin : file_name -> in_channel
val from_string : string -> in_channel
val from_function : (unit -> char) -> in_channel
val from_channel : Pervasives.in_channel -> in_channel
val close_in : in_channel -> unit
val memo_from_channel : Pervasives.in_channel -> in_channel
(* Obsolete. *)
end
module Scanning : SCANNING = struct
(* The run-time library for scanf. *)
type file_name = string
type in_channel_name =
| From_channel of Pervasives.in_channel
| From_file of file_name * Pervasives.in_channel
| From_function
| From_string
type in_channel = {
mutable ic_eof : bool;
mutable ic_current_char : char;
mutable ic_current_char_is_valid : bool;
mutable ic_char_count : int;
mutable ic_line_count : int;
mutable ic_token_count : int;
mutable ic_get_next_char : unit -> char;
ic_token_buffer : Buffer.t;
ic_input_name : in_channel_name;
}
type scanbuf = in_channel
let null_char = '\000'
(* Reads a new character from input buffer.
Next_char never fails, even in case of end of input:
it then simply sets the end of file condition. *)
let next_char ib =
try
let c = ib.ic_get_next_char () in
ib.ic_current_char <- c;
ib.ic_current_char_is_valid <- true;
ib.ic_char_count <- succ ib.ic_char_count;
if c = '\n' then ib.ic_line_count <- succ ib.ic_line_count;
c with
| End_of_file ->
let c = null_char in
ib.ic_current_char <- c;
ib.ic_current_char_is_valid <- false;
ib.ic_eof <- true;
c
let peek_char ib =
if ib.ic_current_char_is_valid
then ib.ic_current_char
else next_char ib
(* Returns a valid current char for the input buffer. In particular
no irrelevant null character (as set by [next_char] in case of end
of input) is returned, since [End_of_file] is raised when
[next_char] sets the end of file condition while trying to read a
new character. *)
let checked_peek_char ib =
let c = peek_char ib in
if ib.ic_eof then raise End_of_file;
c
let end_of_input ib =
ignore (peek_char ib);
ib.ic_eof
let eof ib = ib.ic_eof
let beginning_of_input ib = ib.ic_char_count = 0
let name_of_input ib =
match ib.ic_input_name with
| From_channel _ic -> "unnamed Pervasives input channel"
| From_file (fname, _ic) -> fname
| From_function -> "unnamed function"
| From_string -> "unnamed character string"
let char_count ib =
if ib.ic_current_char_is_valid
then ib.ic_char_count - 1
else ib.ic_char_count
let line_count ib = ib.ic_line_count
let reset_token ib = Buffer.reset ib.ic_token_buffer
let invalidate_current_char ib = ib.ic_current_char_is_valid <- false
let token ib =
let token_buffer = ib.ic_token_buffer in
let tok = Buffer.contents token_buffer in
Buffer.clear token_buffer;
ib.ic_token_count <- succ ib.ic_token_count;
tok
let token_count ib = ib.ic_token_count
let skip_char width ib =
invalidate_current_char ib;
width
let ignore_char width ib = skip_char (width - 1) ib
let store_char width ib c =
Buffer.add_char ib.ic_token_buffer c;
ignore_char width ib
let default_token_buffer_size = 1024
let create iname next = {
ic_eof = false;
ic_current_char = null_char;
ic_current_char_is_valid = false;
ic_char_count = 0;
ic_line_count = 0;
ic_token_count = 0;
ic_get_next_char = next;
ic_token_buffer = Buffer.create default_token_buffer_size;
ic_input_name = iname;
}
let from_string s =
let i = ref 0 in
let len = String.length s in
let next () =
if !i >= len then raise End_of_file else
let c = s.[!i] in
incr i;
c in
create From_string next
let from_function = create From_function
(* Scanning from an input channel. *)
Position of the problem :
We can not prevent the scanning mechanism to use one lookahead character ,
if needed by the semantics of the format string specifications ( e.g. a
trailing ' skip space ' specification in the format string ) ; in this case ,
the mandatory lookahead character is indeed read from the input and not
used to return the token read . It is thus mandatory to be able to store
an unused lookahead character somewhere to get it as the first character
of the next scan .
To circumvent this problem , all the scanning functions get a low level
input buffer argument where they store the lookahead character when
needed ; additionally , the input buffer is the only source of character of
a scanner . The [ scanbuf ] input buffers are defined in module { ! Scanning } .
Now we understand that it is extremely important that related and
successive calls to scanners indeed read from the same input buffer .
In effect , if a scanner [ scan1 ] is reading from [ ib1 ] and stores an
unused lookahead character [ c1 ] into its input buffer [ ib1 ] , then
another scanner [ scan2 ] not reading from the same buffer [ ib1 ] will miss
the character [ c1 ] , seemingly vanished in the air from the point of view
of [ scan2 ] .
This mechanism works perfectly to read from strings , from files , and from
functions , since in those cases , allocating two buffers reading from the
same source is unnatural .
Still , there is a difficulty in the case of scanning from an input
channel . In effect , when scanning from an input channel [ ic ] , this channel
may not have been allocated from within this library . Hence , it may be
shared ( two functions of the user 's program may successively read from
[ ic ] ) . This is highly error prone since , one of the function may seek the
input channel , while the other function has still an unused lookahead
character in its input buffer . In conclusion , you should never mix direct
low level reading and high level scanning from the same input channel .
We cannot prevent the scanning mechanism to use one lookahead character,
if needed by the semantics of the format string specifications (e.g. a
trailing 'skip space' specification in the format string); in this case,
the mandatory lookahead character is indeed read from the input and not
used to return the token read. It is thus mandatory to be able to store
an unused lookahead character somewhere to get it as the first character
of the next scan.
To circumvent this problem, all the scanning functions get a low level
input buffer argument where they store the lookahead character when
needed; additionally, the input buffer is the only source of character of
a scanner. The [scanbuf] input buffers are defined in module {!Scanning}.
Now we understand that it is extremely important that related and
successive calls to scanners indeed read from the same input buffer.
In effect, if a scanner [scan1] is reading from [ib1] and stores an
unused lookahead character [c1] into its input buffer [ib1], then
another scanner [scan2] not reading from the same buffer [ib1] will miss
the character [c1], seemingly vanished in the air from the point of view
of [scan2].
This mechanism works perfectly to read from strings, from files, and from
functions, since in those cases, allocating two buffers reading from the
same source is unnatural.
Still, there is a difficulty in the case of scanning from an input
channel. In effect, when scanning from an input channel [ic], this channel
may not have been allocated from within this library. Hence, it may be
shared (two functions of the user's program may successively read from
[ic]). This is highly error prone since, one of the function may seek the
input channel, while the other function has still an unused lookahead
character in its input buffer. In conclusion, you should never mix direct
low level reading and high level scanning from the same input channel.
*)
(* Perform bufferized input to improve efficiency. *)
let file_buffer_size = ref 1024
(* The scanner closes the input channel at end of input. *)
let scan_close_at_end ic = Pervasives.close_in ic; raise End_of_file
(* The scanner does not close the input channel at end of input:
it just raises [End_of_file]. *)
let scan_raise_at_end _ic = raise End_of_file
let from_ic scan_close_ic iname ic =
let len = !file_buffer_size in
let buf = Bytes.create len in
let i = ref 0 in
let lim = ref 0 in
let eof = ref false in
let next () =
if !i < !lim then begin let c = Bytes.get buf !i in incr i; c end else
if !eof then raise End_of_file else begin
lim := input ic buf 0 len;
if !lim = 0 then begin eof := true; scan_close_ic ic end else begin
i := 1;
Bytes.get buf 0
end
end in
create iname next
let from_ic_close_at_end = from_ic scan_close_at_end
let from_ic_raise_at_end = from_ic scan_raise_at_end
The scanning buffer reading from [ Pervasives.stdin ] .
One could try to define [ stdib ] as a scanning buffer reading a character
at a time ( no bufferization at all ) , but unfortunately the top - level
interaction would be wrong . This is due to some kind of
' race condition ' when reading from [ Pervasives.stdin ] ,
since the interactive compiler and [ Scanf.scanf ] will simultaneously
read the material they need from [ Pervasives.stdin ] ; then , confusion
will result from what should be read by the top - level and what should be
read by [ Scanf.scanf ] .
This is even more complicated by the one character lookahead that
[ Scanf.scanf ] is sometimes obliged to maintain : the lookahead character
will be available for the next [ Scanf.scanf ] entry , seemingly coming from
nowhere .
Also no [ End_of_file ] is raised when reading from stdin : if not enough
characters have been read , we simply ask to read more .
One could try to define [stdib] as a scanning buffer reading a character
at a time (no bufferization at all), but unfortunately the top-level
interaction would be wrong. This is due to some kind of
'race condition' when reading from [Pervasives.stdin],
since the interactive compiler and [Scanf.scanf] will simultaneously
read the material they need from [Pervasives.stdin]; then, confusion
will result from what should be read by the top-level and what should be
read by [Scanf.scanf].
This is even more complicated by the one character lookahead that
[Scanf.scanf] is sometimes obliged to maintain: the lookahead character
will be available for the next [Scanf.scanf] entry, seemingly coming from
nowhere.
Also no [End_of_file] is raised when reading from stdin: if not enough
characters have been read, we simply ask to read more. *)
let stdin =
from_ic scan_raise_at_end
(From_file ("-", Pervasives.stdin)) Pervasives.stdin
let stdib = stdin
let open_in_file open_in fname =
match fname with
| "-" -> stdin
| fname ->
let ic = open_in fname in
from_ic_close_at_end (From_file (fname, ic)) ic
let open_in = open_in_file Pervasives.open_in
let open_in_bin = open_in_file Pervasives.open_in_bin
let from_file = open_in
let from_file_bin = open_in_bin
let from_channel ic =
from_ic_raise_at_end (From_channel ic) ic
let close_in ib =
match ib.ic_input_name with
| From_channel ic ->
Pervasives.close_in ic
| From_file (_fname, ic) -> Pervasives.close_in ic
| From_function | From_string -> ()
(*
Obsolete: a memo [from_channel] version to build a [Scanning.in_channel]
scanning buffer out of a [Pervasives.in_channel].
This function was used to try to preserve the scanning
semantics for the (now obsolete) function [fscanf].
Given that all scanner must read from a [Scanning.in_channel] scanning
buffer, [fscanf] must read from one!
More precisely, given [ic], all successive calls [fscanf ic] must read
from the same scanning buffer.
This obliged this library to allocated scanning buffers that were
not properly garbbage collectable, hence leading to memory leaks.
If you need to read from a [Pervasives.in_channel] input channel
[ic], simply define a [Scanning.in_channel] formatted input channel as in
[let ib = Scanning.from_channel ic], then use [Scanf.bscanf ib] as usual.
*)
let memo_from_ic =
let memo = ref [] in
(fun scan_close_ic ic ->
try List.assq ic !memo with
| Not_found ->
let ib =
from_ic scan_close_ic (From_channel ic) ic in
memo := (ic, ib) :: !memo;
ib)
(* Obsolete: see {!memo_from_ic} above. *)
let memo_from_channel = memo_from_ic scan_raise_at_end
end
(* Formatted input functions. *)
type ('a, 'b, 'c, 'd) scanner =
('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c
(* Reporting errors. *)
exception Scan_failure of string
let bad_input s = raise (Scan_failure s)
let bad_input_escape c =
bad_input (Printf.sprintf "illegal escape character %C" c)
let bad_token_length message =
bad_input
(Printf.sprintf
"scanning of %s failed: \
the specified length was too short for token"
message)
let bad_end_of_input message =
bad_input
(Printf.sprintf
"scanning of %s failed: \
premature end of file occurred before end of token"
message)
let bad_float () =
bad_input "no dot or exponent part found in float token"
let bad_hex_float () =
bad_input "not a valid float in hexadecimal notation"
let character_mismatch_err c ci =
Printf.sprintf "looking for %C, found %C" c ci
let character_mismatch c ci =
bad_input (character_mismatch_err c ci)
let rec skip_whites ib =
let c = Scanning.peek_char ib in
if not (Scanning.eof ib) then begin
match c with
| ' ' | '\t' | '\n' | '\r' ->
Scanning.invalidate_current_char ib; skip_whites ib
| _ -> ()
end
(* Checking that [c] is indeed in the input, then skips it.
In this case, the character [c] has been explicitly specified in the
format as being mandatory in the input; hence we should fail with
[End_of_file] in case of end_of_input.
(Remember that [Scan_failure] is raised only when (we can prove by
evidence) that the input does not match the format string given. We must
thus differentiate [End_of_file] as an error due to lack of input, and
[Scan_failure] which is due to provably wrong input. I am not sure this is
worth the burden: it is complex and somehow subliminal; should be clearer
to fail with Scan_failure "Not enough input to complete scanning"!)
That's why, waiting for a better solution, we use checked_peek_char here.
We are also careful to treat "\r\n" in the input as an end of line marker:
it always matches a '\n' specification in the input format string. *)
let rec check_char ib c =
match c with
| ' ' -> skip_whites ib
| '\n' -> check_newline ib
| c -> check_this_char ib c
and check_this_char ib c =
let ci = Scanning.checked_peek_char ib in
if ci = c then Scanning.invalidate_current_char ib else
character_mismatch c ci
and check_newline ib =
let ci = Scanning.checked_peek_char ib in
match ci with
| '\n' -> Scanning.invalidate_current_char ib
| '\r' -> Scanning.invalidate_current_char ib; check_this_char ib '\n'
| _ -> character_mismatch '\n' ci
(* Extracting tokens from the output token buffer. *)
let token_char ib = (Scanning.token ib).[0]
let token_string = Scanning.token
let token_bool ib =
match Scanning.token ib with
| "true" -> true
| "false" -> false
| s -> bad_input (Printf.sprintf "invalid boolean '%s'" s)
(* The type of integer conversions. *)
type integer_conversion =
| B_conversion (* Unsigned binary conversion *)
| D_conversion (* Signed decimal conversion *)
| I_conversion (* Signed integer conversion *)
| O_conversion (* Unsigned octal conversion *)
| U_conversion (* Unsigned decimal conversion *)
| X_conversion (* Unsigned hexadecimal conversion *)
let integer_conversion_of_char = function
| 'b' -> B_conversion
| 'd' -> D_conversion
| 'i' -> I_conversion
| 'o' -> O_conversion
| 'u' -> U_conversion
| 'x' | 'X' -> X_conversion
| _ -> assert false
Extract an integer literal token .
Since the functions Pervasives.*int*_of_string do not accept a leading + ,
we skip it if necessary .
Since the functions Pervasives.*int*_of_string do not accept a leading +,
we skip it if necessary. *)
let token_int_literal conv ib =
let tok =
match conv with
| D_conversion | I_conversion -> Scanning.token ib
| U_conversion -> "0u" ^ Scanning.token ib
| O_conversion -> "0o" ^ Scanning.token ib
| X_conversion -> "0x" ^ Scanning.token ib
| B_conversion -> "0b" ^ Scanning.token ib in
let l = String.length tok in
if l = 0 || tok.[0] <> '+' then tok else String.sub tok 1 (l - 1)
All the functions that convert a string to a number raise the exception
Failure when the conversion is not possible .
This exception is then trapped in [ kscanf ] .
Failure when the conversion is not possible.
This exception is then trapped in [kscanf]. *)
let token_int conv ib = int_of_string (token_int_literal conv ib)
let token_float ib = float_of_string (Scanning.token ib)
To scan native ints , int32 and int64 integers .
We can not access to conversions to / from strings for those types ,
Nativeint.of_string , Int32.of_string , and Int64.of_string ,
since those modules are not available to [ Scanf ] .
However , we can bind and use the corresponding primitives that are
available in the runtime .
We cannot access to conversions to/from strings for those types,
Nativeint.of_string, Int32.of_string, and Int64.of_string,
since those modules are not available to [Scanf].
However, we can bind and use the corresponding primitives that are
available in the runtime. *)
external nativeint_of_string : string -> nativeint
= "caml_nativeint_of_string"
external int32_of_string : string -> int32
= "caml_int32_of_string"
external int64_of_string : string -> int64
= "caml_int64_of_string"
let token_nativeint conv ib = nativeint_of_string (token_int_literal conv ib)
let token_int32 conv ib = int32_of_string (token_int_literal conv ib)
let token_int64 conv ib = int64_of_string (token_int_literal conv ib)
(* Scanning numbers. *)
Digits scanning functions suppose that one character has been checked and
is available , since they return at end of file with the currently found
token selected .
Put it in another way , the digits scanning functions scan for a possibly
empty sequence of digits , ( hence , a successful scanning from one of those
functions does not imply that the token is a well - formed number : to get a
true number , it is mandatory to check that at least one valid digit is
available before calling one of the digit scanning functions ) .
is available, since they return at end of file with the currently found
token selected.
Put it in another way, the digits scanning functions scan for a possibly
empty sequence of digits, (hence, a successful scanning from one of those
functions does not imply that the token is a well-formed number: to get a
true number, it is mandatory to check that at least one valid digit is
available before calling one of the digit scanning functions). *)
(* The decimal case is treated especially for optimization purposes. *)
let rec scan_decimal_digit_star width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| '0' .. '9' as c ->
let width = Scanning.store_char width ib c in
scan_decimal_digit_star width ib
| '_' ->
let width = Scanning.ignore_char width ib in
scan_decimal_digit_star width ib
| _ -> width
let scan_decimal_digit_plus width ib =
if width = 0 then bad_token_length "decimal digits" else
let c = Scanning.checked_peek_char ib in
match c with
| '0' .. '9' ->
let width = Scanning.store_char width ib c in
scan_decimal_digit_star width ib
| c ->
bad_input (Printf.sprintf "character %C is not a decimal digit" c)
(* To scan numbers from other bases, we use a predicate argument to
scan digits. *)
let scan_digit_star digitp width ib =
let rec scan_digits width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| c when digitp c ->
let width = Scanning.store_char width ib c in
scan_digits width ib
| '_' ->
let width = Scanning.ignore_char width ib in
scan_digits width ib
| _ -> width in
scan_digits width ib
let scan_digit_plus basis digitp width ib =
Ensure we have got enough width left ,
and read at list one digit .
and read at list one digit. *)
if width = 0 then bad_token_length "digits" else
let c = Scanning.checked_peek_char ib in
if digitp c then
let width = Scanning.store_char width ib c in
scan_digit_star digitp width ib
else
bad_input (Printf.sprintf "character %C is not a valid %s digit" c basis)
let is_binary_digit = function
| '0' .. '1' -> true
| _ -> false
let scan_binary_int = scan_digit_plus "binary" is_binary_digit
let is_octal_digit = function
| '0' .. '7' -> true
| _ -> false
let scan_octal_int = scan_digit_plus "octal" is_octal_digit
let is_hexa_digit = function
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
| _ -> false
let scan_hexadecimal_int = scan_digit_plus "hexadecimal" is_hexa_digit
(* Scan a decimal integer. *)
let scan_unsigned_decimal_int = scan_decimal_digit_plus
let scan_sign width ib =
let c = Scanning.checked_peek_char ib in
match c with
| '+' -> Scanning.store_char width ib c
| '-' -> Scanning.store_char width ib c
| _ -> width
let scan_optionally_signed_decimal_int width ib =
let width = scan_sign width ib in
scan_unsigned_decimal_int width ib
Scan an unsigned integer that could be given in any ( common ) basis .
If digits are prefixed by one of 0x , 0X , 0o , or 0b , the number is
assumed to be written respectively in hexadecimal , hexadecimal ,
octal , or binary .
If digits are prefixed by one of 0x, 0X, 0o, or 0b, the number is
assumed to be written respectively in hexadecimal, hexadecimal,
octal, or binary. *)
let scan_unsigned_int width ib =
match Scanning.checked_peek_char ib with
| '0' as c ->
let width = Scanning.store_char width ib c in
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
begin match c with
| 'x' | 'X' -> scan_hexadecimal_int (Scanning.store_char width ib c) ib
| 'o' -> scan_octal_int (Scanning.store_char width ib c) ib
| 'b' -> scan_binary_int (Scanning.store_char width ib c) ib
| _ -> scan_decimal_digit_star width ib end
| _ -> scan_unsigned_decimal_int width ib
let scan_optionally_signed_int width ib =
let width = scan_sign width ib in
scan_unsigned_int width ib
let scan_int_conversion conv width ib =
match conv with
| B_conversion -> scan_binary_int width ib
| D_conversion -> scan_optionally_signed_decimal_int width ib
| I_conversion -> scan_optionally_signed_int width ib
| O_conversion -> scan_octal_int width ib
| U_conversion -> scan_unsigned_decimal_int width ib
| X_conversion -> scan_hexadecimal_int width ib
(* Scanning floating point numbers. *)
(* Fractional part is optional and can be reduced to 0 digits. *)
let scan_fractional_part width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| '0' .. '9' as c ->
scan_decimal_digit_star (Scanning.store_char width ib c) ib
| _ -> width
(* Exp part is optional and can be reduced to 0 digits. *)
let scan_exponent_part width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| 'e' | 'E' as c ->
scan_optionally_signed_decimal_int (Scanning.store_char width ib c) ib
| _ -> width
Scan the integer part of a floating point number , ( not using the
OCaml lexical convention since the integer part can be empty ):
an optional sign , followed by a possibly empty sequence of decimal
digits ( e.g. -.1 ) .
OCaml lexical convention since the integer part can be empty):
an optional sign, followed by a possibly empty sequence of decimal
digits (e.g. -.1). *)
let scan_integer_part width ib =
let width = scan_sign width ib in
scan_decimal_digit_star width ib
For the time being we have ( as found in scanf.mli ):
the field width is composed of an optional integer literal
indicating the maximal width of the token to read .
Unfortunately , the type - checker let the user write an optional precision ,
since this is valid for printf format strings .
Thus , the next step for is to support a full width and precision
indication , more or less similar to the one for printf , possibly extended
to the specification of a [ max , min ] range for the width of the token read
for strings . Something like the following spec for scanf.mli :
The optional [ width ] is an integer indicating the maximal
width of the token read . For instance , [ % 6d ] reads an integer ,
having at most 6 characters .
The optional [ precision ] is a dot [ . ] followed by an integer :
- in the floating point number conversions ( [ % f ] , [ % e ] , [ % g ] , [ % F ] , [ % E ] ,
and [ % F ] conversions , the [ precision ] indicates the maximum number of
digits that may follow the decimal point . For instance , [ % .4f ] reads a
[ float ] with at most 4 fractional digits ,
- in the string conversions ( [ % s ] , [ % S ] , [ % \ [ range \ ] ] ) , and in the
integer number conversions ( [ % i ] , [ % d ] , [ % u ] , [ % x ] , [ % o ] , and their
[ int32 ] , [ int64 ] , and [ native_int ] correspondent ) , the [ precision ]
indicates the required minimum width of the token read ,
- on all other conversions , the width and precision specify the [ max , min ]
range for the width of the token read .
For the time being we have (as found in scanf.mli):
the field width is composed of an optional integer literal
indicating the maximal width of the token to read.
Unfortunately, the type-checker let the user write an optional precision,
since this is valid for printf format strings.
Thus, the next step for Scanf is to support a full width and precision
indication, more or less similar to the one for printf, possibly extended
to the specification of a [max, min] range for the width of the token read
for strings. Something like the following spec for scanf.mli:
The optional [width] is an integer indicating the maximal
width of the token read. For instance, [%6d] reads an integer,
having at most 6 characters.
The optional [precision] is a dot [.] followed by an integer:
- in the floating point number conversions ([%f], [%e], [%g], [%F], [%E],
and [%F] conversions, the [precision] indicates the maximum number of
digits that may follow the decimal point. For instance, [%.4f] reads a
[float] with at most 4 fractional digits,
- in the string conversions ([%s], [%S], [%\[ range \]]), and in the
integer number conversions ([%i], [%d], [%u], [%x], [%o], and their
[int32], [int64], and [native_int] correspondent), the [precision]
indicates the required minimum width of the token read,
- on all other conversions, the width and precision specify the [max, min]
range for the width of the token read.
*)
let scan_float width precision ib =
let width = scan_integer_part width ib in
if width = 0 then width, precision else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width, precision else
match c with
| '.' ->
let width = Scanning.store_char width ib c in
let precision = min width precision in
let width = width - (precision - scan_fractional_part precision ib) in
scan_exponent_part width ib, precision
| _ ->
scan_exponent_part width ib, precision
let check_case_insensitive_string width ib error str =
let lowercase c =
match c with
| 'A' .. 'Z' ->
char_of_int (int_of_char c - int_of_char 'A' + int_of_char 'a')
| _ -> c in
let len = String.length str in
let width = ref width in
for i = 0 to len - 1 do
let c = Scanning.peek_char ib in
if lowercase c <> lowercase str.[i] then error ();
if !width = 0 then error ();
width := Scanning.store_char !width ib c;
done;
!width
let scan_hex_float width precision ib =
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
let width = scan_sign width ib in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
match Scanning.peek_char ib with
| '0' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
let width = check_case_insensitive_string width ib bad_hex_float "x" in
if width = 0 || Scanning.end_of_input ib then width else
let width = match Scanning.peek_char ib with
| '.' | 'p' | 'P' -> width
| _ -> scan_hexadecimal_int width ib in
if width = 0 || Scanning.end_of_input ib then width else
let width = match Scanning.peek_char ib with
| '.' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' -> width
| _ ->
let precision = min width precision in
width - (precision - scan_hexadecimal_int precision ib)
)
| _ -> width in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
scan_optionally_signed_decimal_int width ib
| _ -> width
)
| 'n' | 'N' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
check_case_insensitive_string width ib bad_hex_float "an"
| 'i' | 'I' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
check_case_insensitive_string width ib bad_hex_float "nfinity"
| _ -> bad_hex_float ()
let scan_caml_float_rest width precision ib =
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = scan_decimal_digit_star width ib in
if width = 0 || Scanning.end_of_input ib then bad_float ();
let c = Scanning.peek_char ib in
match c with
| '.' ->
let width = Scanning.store_char width ib c in
(* The effective width available for scanning the fractional part is
the minimum of declared precision and width left. *)
let precision = min width precision in
(* After scanning the fractional part with [precision] provisional width,
[width_precision] is left. *)
let width_precision = scan_fractional_part precision ib in
(* Hence, scanning the fractional part took exactly
[precision - width_precision] chars. *)
let frac_width = precision - width_precision in
(* And new provisional width is [width - width_precision. *)
let width = width - frac_width in
scan_exponent_part width ib
| 'e' | 'E' ->
scan_exponent_part width ib
| _ -> bad_float ()
let scan_caml_float width precision ib =
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = scan_sign width ib in
if width = 0 || Scanning.end_of_input ib then bad_float ();
match Scanning.peek_char ib with
| '0' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_float ();
match Scanning.peek_char ib with
| 'x' | 'X' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = scan_hexadecimal_int width ib in
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = match Scanning.peek_char ib with
| '.' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' -> width
| _ ->
let precision = min width precision in
width - (precision - scan_hexadecimal_int precision ib)
)
| 'p' | 'P' -> width
| _ -> bad_float () in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
scan_optionally_signed_decimal_int width ib
| _ -> width
)
| _ ->
scan_caml_float_rest width precision ib
)
| '1' .. '9' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_float ();
scan_caml_float_rest width precision ib
Special case of and infinity :
| ' i ' - >
| ' n ' - >
| 'i' ->
| 'n' ->
*)
| _ -> bad_float ()
(* Scan a regular string:
stops when encountering a space, if no scanning indication has been given;
otherwise, stops when encountering the characters in the scanning
indication [stp].
It also stops at end of file or when the maximum number of characters has
been read. *)
let scan_string stp width ib =
let rec loop width =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match stp with
| Some c' when c = c' -> Scanning.skip_char width ib
| Some _ -> loop (Scanning.store_char width ib c)
| None ->
match c with
| ' ' | '\t' | '\n' | '\r' -> width
| _ -> loop (Scanning.store_char width ib c) in
loop width
Scan a char : peek strictly one character in the input , whatsoever .
let scan_char width ib =
(* The case width = 0 could not happen here, since it is tested before
calling scan_char, in the main scanning function.
if width = 0 then bad_token_length "a character" else *)
Scanning.store_char width ib (Scanning.checked_peek_char ib)
let char_for_backslash = function
| 'n' -> '\010'
| 'r' -> '\013'
| 'b' -> '\008'
| 't' -> '\009'
| c -> c
(* The integer value corresponding to the facial value of a valid
decimal digit character. *)
let decimal_value_of_char c = int_of_char c - int_of_char '0'
let char_for_decimal_code c0 c1 c2 =
let c =
100 * decimal_value_of_char c0 +
10 * decimal_value_of_char c1 +
decimal_value_of_char c2 in
if c < 0 || c > 255 then
bad_input
(Printf.sprintf
"bad character decimal encoding \\%c%c%c" c0 c1 c2) else
char_of_int c
(* The integer value corresponding to the facial value of a valid
hexadecimal digit character. *)
let hexadecimal_value_of_char c =
let d = int_of_char c in
(* Could also be:
if d <= int_of_char '9' then d - int_of_char '0' else
if d <= int_of_char 'F' then 10 + d - int_of_char 'A' else
if d <= int_of_char 'f' then 10 + d - int_of_char 'a' else assert false
*)
if d >= int_of_char 'a' then
d - 87 (* 10 + int_of_char c - int_of_char 'a' *) else
if d >= int_of_char 'A' then
d - 55 (* 10 + int_of_char c - int_of_char 'A' *) else
d - int_of_char '0'
let char_for_hexadecimal_code c1 c2 =
let c =
16 * hexadecimal_value_of_char c1 +
hexadecimal_value_of_char c2 in
if c < 0 || c > 255 then
bad_input
(Printf.sprintf "bad character hexadecimal encoding \\%c%c" c1 c2) else
char_of_int c
(* Called in particular when encountering '\\' as starter of a char.
Stops before the corresponding '\''. *)
let check_next_char message width ib =
if width = 0 then bad_token_length message else
let c = Scanning.peek_char ib in
if Scanning.eof ib then bad_end_of_input message else
c
let check_next_char_for_char = check_next_char "a Char"
let check_next_char_for_string = check_next_char "a String"
let scan_backslash_char width ib =
match check_next_char_for_char width ib with
| '\\' | '\'' | '\"' | 'n' | 't' | 'b' | 'r' as c ->
Scanning.store_char width ib (char_for_backslash c)
| '0' .. '9' as c ->
let get_digit () =
let c = Scanning.next_char ib in
match c with
| '0' .. '9' as c -> c
| c -> bad_input_escape c in
let c0 = c in
let c1 = get_digit () in
let c2 = get_digit () in
Scanning.store_char (width - 2) ib (char_for_decimal_code c0 c1 c2)
| 'x' ->
let get_digit () =
let c = Scanning.next_char ib in
match c with
| '0' .. '9' | 'A' .. 'F' | 'a' .. 'f' as c -> c
| c -> bad_input_escape c in
let c1 = get_digit () in
let c2 = get_digit () in
Scanning.store_char (width - 2) ib (char_for_hexadecimal_code c1 c2)
| c ->
bad_input_escape c
(* Scan a character (an OCaml token). *)
let scan_caml_char width ib =
let rec find_start width =
match Scanning.checked_peek_char ib with
| '\'' -> find_char (Scanning.ignore_char width ib)
| c -> character_mismatch '\'' c
and find_char width =
match check_next_char_for_char width ib with
| '\\' ->
find_stop (scan_backslash_char (Scanning.ignore_char width ib) ib)
| c ->
find_stop (Scanning.store_char width ib c)
and find_stop width =
match check_next_char_for_char width ib with
| '\'' -> Scanning.ignore_char width ib
| c -> character_mismatch '\'' c in
find_start width
(* Scan a delimited string (an OCaml token). *)
let scan_caml_string width ib =
let rec find_start width =
match Scanning.checked_peek_char ib with
| '\"' -> find_stop (Scanning.ignore_char width ib)
| c -> character_mismatch '\"' c
and find_stop width =
match check_next_char_for_string width ib with
| '\"' -> Scanning.ignore_char width ib
| '\\' -> scan_backslash (Scanning.ignore_char width ib)
| c -> find_stop (Scanning.store_char width ib c)
and scan_backslash width =
match check_next_char_for_string width ib with
| '\r' -> skip_newline (Scanning.ignore_char width ib)
| '\n' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop (scan_backslash_char width ib)
and skip_newline width =
match check_next_char_for_string width ib with
| '\n' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop (Scanning.store_char width ib '\r')
and skip_spaces width =
match check_next_char_for_string width ib with
| ' ' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop width in
find_start width
(* Scan a boolean (an OCaml token). *)
let scan_bool ib =
let c = Scanning.checked_peek_char ib in
let m =
match c with
| 't' -> 4
| 'f' -> 5
| c ->
bad_input
(Printf.sprintf "the character %C cannot start a boolean" c) in
scan_string None m ib
(* Scan a string containing elements in char_set and terminated by scan_indic
if provided. *)
let scan_chars_in_char_set char_set scan_indic width ib =
let rec scan_chars i stp =
let c = Scanning.peek_char ib in
if i > 0 && not (Scanning.eof ib) &&
is_in_char_set char_set c &&
int_of_char c <> stp then
let _ = Scanning.store_char max_int ib c in
scan_chars (i - 1) stp in
match scan_indic with
| None -> scan_chars width (-1);
| Some c ->
scan_chars width (int_of_char c);
if not (Scanning.eof ib) then
let ci = Scanning.peek_char ib in
if c = ci
then Scanning.invalidate_current_char ib
else character_mismatch c ci
(* The global error report function for [Scanf]. *)
let scanf_bad_input ib = function
| Scan_failure s | Failure s ->
let i = Scanning.char_count ib in
bad_input (Printf.sprintf "scanf: bad input at char number %i: %s" i s)
| x -> raise x
(* Get the content of a counter from an input buffer. *)
let get_counter ib counter =
match counter with
| Line_counter -> Scanning.line_count ib
| Char_counter -> Scanning.char_count ib
| Token_counter -> Scanning.token_count ib
Compute the width of a padding option ( see " % 42 { " and " % 123 ( " ) .
let width_of_pad_opt pad_opt = match pad_opt with
| None -> max_int
| Some width -> width
let stopper_of_formatting_lit fmting =
if fmting = Escaped_percent then '%', "" else
let str = string_of_formatting_lit fmting in
let stp = str.[1] in
let sub_str = String.sub str 2 (String.length str - 2) in
stp, sub_str
(******************************************************************************)
(* Readers managment *)
(* A call to take_format_readers on a format is evaluated into functions
taking readers as arguments and aggregate them into an heterogeneous list *)
(* When all readers are taken, finally pass the list of the readers to the
continuation k. *)
let rec take_format_readers : type a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, e, f) fmt ->
d =
fun k fmt -> match fmt with
| Reader fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_format_readers new_k fmt_rest
| Char rest -> take_format_readers k rest
| Caml_char rest -> take_format_readers k rest
| String (_, rest) -> take_format_readers k rest
| Caml_string (_, rest) -> take_format_readers k rest
| Int (_, _, _, rest) -> take_format_readers k rest
| Int32 (_, _, _, rest) -> take_format_readers k rest
| Nativeint (_, _, _, rest) -> take_format_readers k rest
| Int64 (_, _, _, rest) -> take_format_readers k rest
| Float (_, _, _, rest) -> take_format_readers k rest
| Bool rest -> take_format_readers k rest
| Alpha rest -> take_format_readers k rest
| Theta rest -> take_format_readers k rest
| Flush rest -> take_format_readers k rest
| String_literal (_, rest) -> take_format_readers k rest
| Char_literal (_, rest) -> take_format_readers k rest
| Custom (_, _, rest) -> take_format_readers k rest
| Scan_char_set (_, _, rest) -> take_format_readers k rest
| Scan_get_counter (_, rest) -> take_format_readers k rest
| Scan_next_char rest -> take_format_readers k rest
| Formatting_lit (_, rest) -> take_format_readers k rest
| Formatting_gen (Open_tag (Format (fmt, _)), rest) ->
take_format_readers k (concat_fmt fmt rest)
| Formatting_gen (Open_box (Format (fmt, _)), rest) ->
take_format_readers k (concat_fmt fmt rest)
| Format_arg (_, _, rest) -> take_format_readers k rest
| Format_subst (_, fmtty, rest) ->
take_fmtty_format_readers k (erase_rel (symm fmtty)) rest
| Ignored_param (ign, rest) -> take_ignored_format_readers k ign rest
| End_of_format -> k Nil
(* Take readers associated to an fmtty coming from a Format_subst "%(...%)". *)
and take_fmtty_format_readers : type x y a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) fmtty ->
(y, Scanning.in_channel, c, x, e, f) fmt -> d =
fun k fmtty fmt -> match fmtty with
| Reader_ty fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_fmtty_format_readers new_k fmt_rest fmt
| Ignored_reader_ty fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_fmtty_format_readers new_k fmt_rest fmt
| Char_ty rest -> take_fmtty_format_readers k rest fmt
| String_ty rest -> take_fmtty_format_readers k rest fmt
| Int_ty rest -> take_fmtty_format_readers k rest fmt
| Int32_ty rest -> take_fmtty_format_readers k rest fmt
| Nativeint_ty rest -> take_fmtty_format_readers k rest fmt
| Int64_ty rest -> take_fmtty_format_readers k rest fmt
| Float_ty rest -> take_fmtty_format_readers k rest fmt
| Bool_ty rest -> take_fmtty_format_readers k rest fmt
| Alpha_ty rest -> take_fmtty_format_readers k rest fmt
| Theta_ty rest -> take_fmtty_format_readers k rest fmt
| Any_ty rest -> take_fmtty_format_readers k rest fmt
| Format_arg_ty (_, rest) -> take_fmtty_format_readers k rest fmt
| End_of_fmtty -> take_format_readers k fmt
| Format_subst_ty (ty1, ty2, rest) ->
let ty = trans (symm ty1) ty2 in
take_fmtty_format_readers k (concat_fmtty ty rest) fmt
(* Take readers associated to an ignored parameter. *)
and take_ignored_format_readers : type x y a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) ignored ->
(y, Scanning.in_channel, c, x, e, f) fmt -> d =
fun k ign fmt -> match ign with
| Ignored_reader ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_format_readers new_k fmt
| Ignored_char -> take_format_readers k fmt
| Ignored_caml_char -> take_format_readers k fmt
| Ignored_string _ -> take_format_readers k fmt
| Ignored_caml_string _ -> take_format_readers k fmt
| Ignored_int (_, _) -> take_format_readers k fmt
| Ignored_int32 (_, _) -> take_format_readers k fmt
| Ignored_nativeint (_, _) -> take_format_readers k fmt
| Ignored_int64 (_, _) -> take_format_readers k fmt
| Ignored_float (_, _) -> take_format_readers k fmt
| Ignored_bool -> take_format_readers k fmt
| Ignored_format_arg _ -> take_format_readers k fmt
| Ignored_format_subst (_, fmtty) -> take_fmtty_format_readers k fmtty fmt
| Ignored_scan_char_set _ -> take_format_readers k fmt
| Ignored_scan_get_counter _ -> take_format_readers k fmt
| Ignored_scan_next_char -> take_format_readers k fmt
(******************************************************************************)
Generic scanning
(* Make a generic scanning function. *)
(* Scan a stream according to a format and readers obtained by
take_format_readers, and aggegate scanned values into an
heterogeneous list. *)
(* Return the heterogeneous list of scanned values. *)
let rec make_scanf : type a c d e f.
Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
(d, e) heter_list -> (a, f) heter_list =
fun ib fmt readers -> match fmt with
| Char rest ->
let _ = scan_char 0 ib in
let c = token_char ib in
Cons (c, make_scanf ib rest readers)
| Caml_char rest ->
let _ = scan_caml_char 0 ib in
let c = token_char ib in
Cons (c, make_scanf ib rest readers)
| String (pad, Formatting_lit (fmting_lit, rest)) ->
let stp, str = stopper_of_formatting_lit fmting_lit in
let scan width _ ib = scan_string (Some stp) width ib in
let str_rest = String_literal (str, rest) in
pad_prec_scanf ib str_rest readers pad No_precision scan token_string
| String (pad, Formatting_gen (Open_tag (Format (fmt', _)), rest)) ->
let scan width _ ib = scan_string (Some '{') width ib in
pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan
token_string
| String (pad, Formatting_gen (Open_box (Format (fmt', _)), rest)) ->
let scan width _ ib = scan_string (Some '[') width ib in
pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan
token_string
| String (pad, rest) ->
let scan width _ ib = scan_string None width ib in
pad_prec_scanf ib rest readers pad No_precision scan token_string
| Caml_string (pad, rest) ->
let scan width _ ib = scan_caml_string width ib in
pad_prec_scanf ib rest readers pad No_precision scan token_string
| Int (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int c)
| Int32 (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int32 c)
| Nativeint (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_nativeint c)
| Int64 (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int64 c)
| Float (Float_F, pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_caml_float token_float
| Float ((Float_f | Float_pf | Float_sf | Float_e | Float_pe | Float_se
| Float_E | Float_pE | Float_sE | Float_g | Float_pg | Float_sg
| Float_G | Float_pG | Float_sG), pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_float token_float
| Float ((Float_h | Float_ph | Float_sh | Float_H | Float_pH | Float_sH),
pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_hex_float token_float
| Bool rest ->
let _ = scan_bool ib in
let b = token_bool ib in
Cons (b, make_scanf ib rest readers)
| Alpha _ ->
invalid_arg "scanf: bad conversion \"%a\""
| Theta _ ->
invalid_arg "scanf: bad conversion \"%t\""
| Custom _ ->
invalid_arg "scanf: bad conversion \"%?\" (custom converter)"
| Reader fmt_rest ->
begin match readers with
| Cons (reader, readers_rest) ->
let x = reader ib in
Cons (x, make_scanf ib fmt_rest readers_rest)
| Nil ->
invalid_arg "scanf: missing reader"
end
| Flush rest ->
if Scanning.end_of_input ib then make_scanf ib rest readers
else bad_input "end of input not found"
| String_literal (str, rest) ->
String.iter (check_char ib) str;
make_scanf ib rest readers
| Char_literal (chr, rest) ->
check_char ib chr;
make_scanf ib rest readers
| Format_arg (pad_opt, fmtty, rest) ->
let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
let s = token_string ib in
let fmt =
try format_of_string_fmtty s fmtty
with Failure msg -> bad_input msg
in
Cons (fmt, make_scanf ib rest readers)
| Format_subst (pad_opt, fmtty, rest) ->
let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
let s = token_string ib in
let fmt, fmt' =
try
let Fmt_EBB fmt = fmt_ebb_of_string s in
let Fmt_EBB fmt' = fmt_ebb_of_string s in
(* TODO: find a way to avoid reparsing twice *)
TODO : these type - checks below * can * fail because of type
ambiguity in presence of ignored - readers : " % _ r%d " and " % d%_r "
are typed in the same way .
# Scanf.sscanf " \"%_r%d\"3 " " % ( % d%_r% ) " ignore
( fun fmt n - > string_of_format fmt , n )
Exception : CamlinternalFormat . Type_mismatch .
We should properly catch this exception .
ambiguity in presence of ignored-readers: "%_r%d" and "%d%_r"
are typed in the same way.
# Scanf.sscanf "\"%_r%d\"3" "%(%d%_r%)" ignore
(fun fmt n -> string_of_format fmt, n)
Exception: CamlinternalFormat.Type_mismatch.
We should properly catch this exception.
*)
type_format fmt (erase_rel fmtty),
type_format fmt' (erase_rel (symm fmtty))
with Failure msg -> bad_input msg
in
Cons (Format (fmt, s),
make_scanf ib (concat_fmt fmt' rest) readers)
| Scan_char_set (width_opt, char_set, Formatting_lit (fmting_lit, rest)) ->
let stp, str = stopper_of_formatting_lit fmting_lit in
let width = width_of_pad_opt width_opt in
scan_chars_in_char_set char_set (Some stp) width ib;
let s = token_string ib in
let str_rest = String_literal (str, rest) in
Cons (s, make_scanf ib str_rest readers)
| Scan_char_set (width_opt, char_set, rest) ->
let width = width_of_pad_opt width_opt in
scan_chars_in_char_set char_set None width ib;
let s = token_string ib in
Cons (s, make_scanf ib rest readers)
| Scan_get_counter (counter, rest) ->
let count = get_counter ib counter in
Cons (count, make_scanf ib rest readers)
| Scan_next_char rest ->
let c = Scanning.checked_peek_char ib in
Cons (c, make_scanf ib rest readers)
| Formatting_lit (formatting_lit, rest) ->
String.iter (check_char ib) (string_of_formatting_lit formatting_lit);
make_scanf ib rest readers
| Formatting_gen (Open_tag (Format (fmt', _)), rest) ->
check_char ib '@'; check_char ib '{';
make_scanf ib (concat_fmt fmt' rest) readers
| Formatting_gen (Open_box (Format (fmt', _)), rest) ->
check_char ib '@'; check_char ib '[';
make_scanf ib (concat_fmt fmt' rest) readers
| Ignored_param (ign, rest) ->
let Param_format_EBB fmt' = param_format_of_ignored_format ign rest in
begin match make_scanf ib fmt' readers with
| Cons (_, arg_rest) -> arg_rest
| Nil -> assert false
end
| End_of_format ->
Nil
(* Case analysis on padding and precision. *)
Reject formats containing " % * " or " % . * " .
(* Pass padding and precision to the generic scanner `scan'. *)
and pad_prec_scanf : type a c d e f x y z t .
Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
(d, e) heter_list -> (x, y) padding -> (y, z -> a) precision ->
(int -> int -> Scanning.in_channel -> t) ->
(Scanning.in_channel -> z) ->
(x, f) heter_list =
fun ib fmt readers pad prec scan token -> match pad, prec with
| No_padding, No_precision ->
let _ = scan max_int max_int ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| No_padding, Lit_precision p ->
let _ = scan max_int p ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding ((Right | Zeros), w), No_precision ->
let _ = scan w max_int ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding ((Right | Zeros), w), Lit_precision p ->
let _ = scan w p ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding (Left, _), _ ->
invalid_arg "scanf: bad conversion \"%-\""
| Lit_padding ((Right | Zeros), _), Arg_precision ->
invalid_arg "scanf: bad conversion \"%*\""
| Arg_padding _, _ ->
invalid_arg "scanf: bad conversion \"%*\""
| No_padding, Arg_precision ->
invalid_arg "scanf: bad conversion \"%*\""
(******************************************************************************)
(* Defining [scanf] and various flavors of [scanf] *)
type 'a kscanf_result = Args of 'a | Exc of exn
let kscanf ib ef (Format (fmt, str)) =
let rec apply : type a b . a -> (a, b) heter_list -> b =
fun f args -> match args with
| Cons (x, r) -> apply (f x) r
| Nil -> f
in
let k readers f =
Scanning.reset_token ib;
match try Args (make_scanf ib fmt readers) with
| (Scan_failure _ | Failure _ | End_of_file) as exc -> Exc exc
| Invalid_argument msg ->
invalid_arg (msg ^ " in format \"" ^ String.escaped str ^ "\"")
with
| Args args -> apply f args
| Exc exc -> ef ib exc
in
take_format_readers k fmt
(***)
let kbscanf = kscanf
let bscanf ib fmt = kbscanf ib scanf_bad_input fmt
let ksscanf s ef fmt = kbscanf (Scanning.from_string s) ef fmt
let sscanf s fmt = kbscanf (Scanning.from_string s) scanf_bad_input fmt
let scanf fmt = kscanf Scanning.stdib scanf_bad_input fmt
(***)
(* Scanning format strings. *)
let bscanf_format :
Scanning.in_channel -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
(('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
fun ib format f ->
let _ = scan_caml_string max_int ib in
let str = token_string ib in
let fmt' =
try format_of_string_format str format
with Failure msg -> bad_input msg in
f fmt'
let sscanf_format :
string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
(('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
fun s format f -> bscanf_format (Scanning.from_string s) format f
let string_to_String s =
let l = String.length s in
let b = Buffer.create (l + 2) in
Buffer.add_char b '\"';
for i = 0 to l - 1 do
let c = s.[i] in
if c = '\"' then Buffer.add_char b '\\';
Buffer.add_char b c;
done;
Buffer.add_char b '\"';
Buffer.contents b
let format_from_string s fmt =
sscanf_format (string_to_String s) fmt (fun x -> x)
let unescaped s =
sscanf ("\"" ^ s ^ "\"") "%S%!" (fun x -> x)
(* Deprecated *)
let kfscanf ic ef fmt = kbscanf (Scanning.memo_from_channel ic) ef fmt
let fscanf ic fmt = kscanf (Scanning.memo_from_channel ic) scanf_bad_input fmt
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/stdlib/scanf.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
alias to avoid warning for ambiguity between
Pervasives.format6
and CamlinternalFormatBasics.format6
(the former is in fact an alias for the latter,
but the ambiguity warning doesn't care)
The run-time library for scanners.
Scanning buffers.
The scanning buffer reading from [Pervasives.stdin].
[stdib] is equivalent to [Scanning.from_channel Pervasives.stdin].
An alias for [Scanf.stdin], the scanning buffer reading from
[Pervasives.stdin].
[Scanning.invalidate_current_char ib] mark the current_char as already
scanned.
Same as [Scanning.peek_char] above but always returns a valid char or
fails: instead of returning a null char when the reading method of the
input buffer has reached an end of file, the function raises exception
[End_of_file].
[Scanning.ignore_char ib lim] ignores the current character and
decrements the limit.
[Scanning.token ib] returns the string stored into the token
buffer of the scanning buffer: it returns the token matched by the
format.
[Scanning.token_count ib] returns the number of tokens read
so far from [ib].
[Scanning.end_of_input ib] tests the end of input condition
of the given buffer (if no char has ever been read, an attempt to
read one is performed).
[Scanning.beginning_of_input ib] tests the beginning of input
condition of the given buffer.
[Scanning.name_of_input ib] returns the name of the character
source for input buffer [ib].
Obsolete.
The run-time library for scanf.
Reads a new character from input buffer.
Next_char never fails, even in case of end of input:
it then simply sets the end of file condition.
Returns a valid current char for the input buffer. In particular
no irrelevant null character (as set by [next_char] in case of end
of input) is returned, since [End_of_file] is raised when
[next_char] sets the end of file condition while trying to read a
new character.
Scanning from an input channel.
Perform bufferized input to improve efficiency.
The scanner closes the input channel at end of input.
The scanner does not close the input channel at end of input:
it just raises [End_of_file].
Obsolete: a memo [from_channel] version to build a [Scanning.in_channel]
scanning buffer out of a [Pervasives.in_channel].
This function was used to try to preserve the scanning
semantics for the (now obsolete) function [fscanf].
Given that all scanner must read from a [Scanning.in_channel] scanning
buffer, [fscanf] must read from one!
More precisely, given [ic], all successive calls [fscanf ic] must read
from the same scanning buffer.
This obliged this library to allocated scanning buffers that were
not properly garbbage collectable, hence leading to memory leaks.
If you need to read from a [Pervasives.in_channel] input channel
[ic], simply define a [Scanning.in_channel] formatted input channel as in
[let ib = Scanning.from_channel ic], then use [Scanf.bscanf ib] as usual.
Obsolete: see {!memo_from_ic} above.
Formatted input functions.
Reporting errors.
Checking that [c] is indeed in the input, then skips it.
In this case, the character [c] has been explicitly specified in the
format as being mandatory in the input; hence we should fail with
[End_of_file] in case of end_of_input.
(Remember that [Scan_failure] is raised only when (we can prove by
evidence) that the input does not match the format string given. We must
thus differentiate [End_of_file] as an error due to lack of input, and
[Scan_failure] which is due to provably wrong input. I am not sure this is
worth the burden: it is complex and somehow subliminal; should be clearer
to fail with Scan_failure "Not enough input to complete scanning"!)
That's why, waiting for a better solution, we use checked_peek_char here.
We are also careful to treat "\r\n" in the input as an end of line marker:
it always matches a '\n' specification in the input format string.
Extracting tokens from the output token buffer.
The type of integer conversions.
Unsigned binary conversion
Signed decimal conversion
Signed integer conversion
Unsigned octal conversion
Unsigned decimal conversion
Unsigned hexadecimal conversion
Scanning numbers.
The decimal case is treated especially for optimization purposes.
To scan numbers from other bases, we use a predicate argument to
scan digits.
Scan a decimal integer.
Scanning floating point numbers.
Fractional part is optional and can be reduced to 0 digits.
Exp part is optional and can be reduced to 0 digits.
The effective width available for scanning the fractional part is
the minimum of declared precision and width left.
After scanning the fractional part with [precision] provisional width,
[width_precision] is left.
Hence, scanning the fractional part took exactly
[precision - width_precision] chars.
And new provisional width is [width - width_precision.
Scan a regular string:
stops when encountering a space, if no scanning indication has been given;
otherwise, stops when encountering the characters in the scanning
indication [stp].
It also stops at end of file or when the maximum number of characters has
been read.
The case width = 0 could not happen here, since it is tested before
calling scan_char, in the main scanning function.
if width = 0 then bad_token_length "a character" else
The integer value corresponding to the facial value of a valid
decimal digit character.
The integer value corresponding to the facial value of a valid
hexadecimal digit character.
Could also be:
if d <= int_of_char '9' then d - int_of_char '0' else
if d <= int_of_char 'F' then 10 + d - int_of_char 'A' else
if d <= int_of_char 'f' then 10 + d - int_of_char 'a' else assert false
10 + int_of_char c - int_of_char 'a'
10 + int_of_char c - int_of_char 'A'
Called in particular when encountering '\\' as starter of a char.
Stops before the corresponding '\''.
Scan a character (an OCaml token).
Scan a delimited string (an OCaml token).
Scan a boolean (an OCaml token).
Scan a string containing elements in char_set and terminated by scan_indic
if provided.
The global error report function for [Scanf].
Get the content of a counter from an input buffer.
****************************************************************************
Readers managment
A call to take_format_readers on a format is evaluated into functions
taking readers as arguments and aggregate them into an heterogeneous list
When all readers are taken, finally pass the list of the readers to the
continuation k.
Take readers associated to an fmtty coming from a Format_subst "%(...%)".
Take readers associated to an ignored parameter.
****************************************************************************
Make a generic scanning function.
Scan a stream according to a format and readers obtained by
take_format_readers, and aggegate scanned values into an
heterogeneous list.
Return the heterogeneous list of scanned values.
TODO: find a way to avoid reparsing twice
Case analysis on padding and precision.
Pass padding and precision to the generic scanner `scan'.
****************************************************************************
Defining [scanf] and various flavors of [scanf]
*
*
Scanning format strings.
Deprecated | , projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open CamlinternalFormatBasics
open CamlinternalFormat
type ('a, 'b, 'c, 'd, 'e, 'f) format6 =
('a, 'b, 'c, 'd, 'e, 'f) Pervasives.format6
module type SCANNING = sig
type in_channel
type scanbuf = in_channel
type file_name = string
val stdin : in_channel
val stdib : in_channel
val next_char : scanbuf -> char
[ ib ] advance the scanning buffer for
one character .
If no more character can be read , sets a end of file condition and
returns ' \000 ' .
one character.
If no more character can be read, sets a end of file condition and
returns '\000'. *)
val invalidate_current_char : scanbuf -> unit
val peek_char : scanbuf -> char
[ Scanning.peek_char ib ] returns the current char available in
the buffer or reads one if necessary ( when the current character is
already scanned ) .
If no character can be read , sets an end of file condition and
returns ' \000 ' .
the buffer or reads one if necessary (when the current character is
already scanned).
If no character can be read, sets an end of file condition and
returns '\000'. *)
val checked_peek_char : scanbuf -> char
val store_char : int -> scanbuf -> char -> int
[ Scanning.store_char ] adds [ c ] to the token buffer
of the scanning buffer [ ib ] . It also advances the scanning buffer for
one character and returns [ lim - 1 ] , indicating the new limit for the
length of the current token .
of the scanning buffer [ib]. It also advances the scanning buffer for
one character and returns [lim - 1], indicating the new limit for the
length of the current token. *)
val skip_char : int -> scanbuf -> int
[ ignores the current character .
val ignore_char : int -> scanbuf -> int
val token : scanbuf -> string
val reset_token : scanbuf -> unit
[ ib ] resets the token buffer of
the given scanning buffer .
the given scanning buffer. *)
val char_count : scanbuf -> int
[ Scanning.char_count ib ] returns the number of characters
read so far from the given buffer .
read so far from the given buffer. *)
val line_count : scanbuf -> int
[ Scanning.line_count ib ] returns the number of new line
characters read so far from the given buffer .
characters read so far from the given buffer. *)
val token_count : scanbuf -> int
val eof : scanbuf -> bool
[ Scanning.eof ib ] returns the end of input condition
of the given buffer .
of the given buffer. *)
val end_of_input : scanbuf -> bool
val beginning_of_input : scanbuf -> bool
val name_of_input : scanbuf -> string
val open_in : file_name -> in_channel
val open_in_bin : file_name -> in_channel
val from_file : file_name -> in_channel
val from_file_bin : file_name -> in_channel
val from_string : string -> in_channel
val from_function : (unit -> char) -> in_channel
val from_channel : Pervasives.in_channel -> in_channel
val close_in : in_channel -> unit
val memo_from_channel : Pervasives.in_channel -> in_channel
end
module Scanning : SCANNING = struct
type file_name = string
type in_channel_name =
| From_channel of Pervasives.in_channel
| From_file of file_name * Pervasives.in_channel
| From_function
| From_string
type in_channel = {
mutable ic_eof : bool;
mutable ic_current_char : char;
mutable ic_current_char_is_valid : bool;
mutable ic_char_count : int;
mutable ic_line_count : int;
mutable ic_token_count : int;
mutable ic_get_next_char : unit -> char;
ic_token_buffer : Buffer.t;
ic_input_name : in_channel_name;
}
type scanbuf = in_channel
let null_char = '\000'
let next_char ib =
try
let c = ib.ic_get_next_char () in
ib.ic_current_char <- c;
ib.ic_current_char_is_valid <- true;
ib.ic_char_count <- succ ib.ic_char_count;
if c = '\n' then ib.ic_line_count <- succ ib.ic_line_count;
c with
| End_of_file ->
let c = null_char in
ib.ic_current_char <- c;
ib.ic_current_char_is_valid <- false;
ib.ic_eof <- true;
c
let peek_char ib =
if ib.ic_current_char_is_valid
then ib.ic_current_char
else next_char ib
let checked_peek_char ib =
let c = peek_char ib in
if ib.ic_eof then raise End_of_file;
c
let end_of_input ib =
ignore (peek_char ib);
ib.ic_eof
let eof ib = ib.ic_eof
let beginning_of_input ib = ib.ic_char_count = 0
let name_of_input ib =
match ib.ic_input_name with
| From_channel _ic -> "unnamed Pervasives input channel"
| From_file (fname, _ic) -> fname
| From_function -> "unnamed function"
| From_string -> "unnamed character string"
let char_count ib =
if ib.ic_current_char_is_valid
then ib.ic_char_count - 1
else ib.ic_char_count
let line_count ib = ib.ic_line_count
let reset_token ib = Buffer.reset ib.ic_token_buffer
let invalidate_current_char ib = ib.ic_current_char_is_valid <- false
let token ib =
let token_buffer = ib.ic_token_buffer in
let tok = Buffer.contents token_buffer in
Buffer.clear token_buffer;
ib.ic_token_count <- succ ib.ic_token_count;
tok
let token_count ib = ib.ic_token_count
let skip_char width ib =
invalidate_current_char ib;
width
let ignore_char width ib = skip_char (width - 1) ib
let store_char width ib c =
Buffer.add_char ib.ic_token_buffer c;
ignore_char width ib
let default_token_buffer_size = 1024
let create iname next = {
ic_eof = false;
ic_current_char = null_char;
ic_current_char_is_valid = false;
ic_char_count = 0;
ic_line_count = 0;
ic_token_count = 0;
ic_get_next_char = next;
ic_token_buffer = Buffer.create default_token_buffer_size;
ic_input_name = iname;
}
let from_string s =
let i = ref 0 in
let len = String.length s in
let next () =
if !i >= len then raise End_of_file else
let c = s.[!i] in
incr i;
c in
create From_string next
let from_function = create From_function
Position of the problem :
We can not prevent the scanning mechanism to use one lookahead character ,
if needed by the semantics of the format string specifications ( e.g. a
trailing ' skip space ' specification in the format string ) ; in this case ,
the mandatory lookahead character is indeed read from the input and not
used to return the token read . It is thus mandatory to be able to store
an unused lookahead character somewhere to get it as the first character
of the next scan .
To circumvent this problem , all the scanning functions get a low level
input buffer argument where they store the lookahead character when
needed ; additionally , the input buffer is the only source of character of
a scanner . The [ scanbuf ] input buffers are defined in module { ! Scanning } .
Now we understand that it is extremely important that related and
successive calls to scanners indeed read from the same input buffer .
In effect , if a scanner [ scan1 ] is reading from [ ib1 ] and stores an
unused lookahead character [ c1 ] into its input buffer [ ib1 ] , then
another scanner [ scan2 ] not reading from the same buffer [ ib1 ] will miss
the character [ c1 ] , seemingly vanished in the air from the point of view
of [ scan2 ] .
This mechanism works perfectly to read from strings , from files , and from
functions , since in those cases , allocating two buffers reading from the
same source is unnatural .
Still , there is a difficulty in the case of scanning from an input
channel . In effect , when scanning from an input channel [ ic ] , this channel
may not have been allocated from within this library . Hence , it may be
shared ( two functions of the user 's program may successively read from
[ ic ] ) . This is highly error prone since , one of the function may seek the
input channel , while the other function has still an unused lookahead
character in its input buffer . In conclusion , you should never mix direct
low level reading and high level scanning from the same input channel .
We cannot prevent the scanning mechanism to use one lookahead character,
if needed by the semantics of the format string specifications (e.g. a
trailing 'skip space' specification in the format string); in this case,
the mandatory lookahead character is indeed read from the input and not
used to return the token read. It is thus mandatory to be able to store
an unused lookahead character somewhere to get it as the first character
of the next scan.
To circumvent this problem, all the scanning functions get a low level
input buffer argument where they store the lookahead character when
needed; additionally, the input buffer is the only source of character of
a scanner. The [scanbuf] input buffers are defined in module {!Scanning}.
Now we understand that it is extremely important that related and
successive calls to scanners indeed read from the same input buffer.
In effect, if a scanner [scan1] is reading from [ib1] and stores an
unused lookahead character [c1] into its input buffer [ib1], then
another scanner [scan2] not reading from the same buffer [ib1] will miss
the character [c1], seemingly vanished in the air from the point of view
of [scan2].
This mechanism works perfectly to read from strings, from files, and from
functions, since in those cases, allocating two buffers reading from the
same source is unnatural.
Still, there is a difficulty in the case of scanning from an input
channel. In effect, when scanning from an input channel [ic], this channel
may not have been allocated from within this library. Hence, it may be
shared (two functions of the user's program may successively read from
[ic]). This is highly error prone since, one of the function may seek the
input channel, while the other function has still an unused lookahead
character in its input buffer. In conclusion, you should never mix direct
low level reading and high level scanning from the same input channel.
*)
let file_buffer_size = ref 1024
let scan_close_at_end ic = Pervasives.close_in ic; raise End_of_file
let scan_raise_at_end _ic = raise End_of_file
let from_ic scan_close_ic iname ic =
let len = !file_buffer_size in
let buf = Bytes.create len in
let i = ref 0 in
let lim = ref 0 in
let eof = ref false in
let next () =
if !i < !lim then begin let c = Bytes.get buf !i in incr i; c end else
if !eof then raise End_of_file else begin
lim := input ic buf 0 len;
if !lim = 0 then begin eof := true; scan_close_ic ic end else begin
i := 1;
Bytes.get buf 0
end
end in
create iname next
let from_ic_close_at_end = from_ic scan_close_at_end
let from_ic_raise_at_end = from_ic scan_raise_at_end
The scanning buffer reading from [ Pervasives.stdin ] .
One could try to define [ stdib ] as a scanning buffer reading a character
at a time ( no bufferization at all ) , but unfortunately the top - level
interaction would be wrong . This is due to some kind of
' race condition ' when reading from [ Pervasives.stdin ] ,
since the interactive compiler and [ Scanf.scanf ] will simultaneously
read the material they need from [ Pervasives.stdin ] ; then , confusion
will result from what should be read by the top - level and what should be
read by [ Scanf.scanf ] .
This is even more complicated by the one character lookahead that
[ Scanf.scanf ] is sometimes obliged to maintain : the lookahead character
will be available for the next [ Scanf.scanf ] entry , seemingly coming from
nowhere .
Also no [ End_of_file ] is raised when reading from stdin : if not enough
characters have been read , we simply ask to read more .
One could try to define [stdib] as a scanning buffer reading a character
at a time (no bufferization at all), but unfortunately the top-level
interaction would be wrong. This is due to some kind of
'race condition' when reading from [Pervasives.stdin],
since the interactive compiler and [Scanf.scanf] will simultaneously
read the material they need from [Pervasives.stdin]; then, confusion
will result from what should be read by the top-level and what should be
read by [Scanf.scanf].
This is even more complicated by the one character lookahead that
[Scanf.scanf] is sometimes obliged to maintain: the lookahead character
will be available for the next [Scanf.scanf] entry, seemingly coming from
nowhere.
Also no [End_of_file] is raised when reading from stdin: if not enough
characters have been read, we simply ask to read more. *)
let stdin =
from_ic scan_raise_at_end
(From_file ("-", Pervasives.stdin)) Pervasives.stdin
let stdib = stdin
let open_in_file open_in fname =
match fname with
| "-" -> stdin
| fname ->
let ic = open_in fname in
from_ic_close_at_end (From_file (fname, ic)) ic
let open_in = open_in_file Pervasives.open_in
let open_in_bin = open_in_file Pervasives.open_in_bin
let from_file = open_in
let from_file_bin = open_in_bin
let from_channel ic =
from_ic_raise_at_end (From_channel ic) ic
let close_in ib =
match ib.ic_input_name with
| From_channel ic ->
Pervasives.close_in ic
| From_file (_fname, ic) -> Pervasives.close_in ic
| From_function | From_string -> ()
let memo_from_ic =
let memo = ref [] in
(fun scan_close_ic ic ->
try List.assq ic !memo with
| Not_found ->
let ib =
from_ic scan_close_ic (From_channel ic) ic in
memo := (ic, ib) :: !memo;
ib)
let memo_from_channel = memo_from_ic scan_raise_at_end
end
type ('a, 'b, 'c, 'd) scanner =
('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c
exception Scan_failure of string
let bad_input s = raise (Scan_failure s)
let bad_input_escape c =
bad_input (Printf.sprintf "illegal escape character %C" c)
let bad_token_length message =
bad_input
(Printf.sprintf
"scanning of %s failed: \
the specified length was too short for token"
message)
let bad_end_of_input message =
bad_input
(Printf.sprintf
"scanning of %s failed: \
premature end of file occurred before end of token"
message)
let bad_float () =
bad_input "no dot or exponent part found in float token"
let bad_hex_float () =
bad_input "not a valid float in hexadecimal notation"
let character_mismatch_err c ci =
Printf.sprintf "looking for %C, found %C" c ci
let character_mismatch c ci =
bad_input (character_mismatch_err c ci)
let rec skip_whites ib =
let c = Scanning.peek_char ib in
if not (Scanning.eof ib) then begin
match c with
| ' ' | '\t' | '\n' | '\r' ->
Scanning.invalidate_current_char ib; skip_whites ib
| _ -> ()
end
let rec check_char ib c =
match c with
| ' ' -> skip_whites ib
| '\n' -> check_newline ib
| c -> check_this_char ib c
and check_this_char ib c =
let ci = Scanning.checked_peek_char ib in
if ci = c then Scanning.invalidate_current_char ib else
character_mismatch c ci
and check_newline ib =
let ci = Scanning.checked_peek_char ib in
match ci with
| '\n' -> Scanning.invalidate_current_char ib
| '\r' -> Scanning.invalidate_current_char ib; check_this_char ib '\n'
| _ -> character_mismatch '\n' ci
let token_char ib = (Scanning.token ib).[0]
let token_string = Scanning.token
let token_bool ib =
match Scanning.token ib with
| "true" -> true
| "false" -> false
| s -> bad_input (Printf.sprintf "invalid boolean '%s'" s)
type integer_conversion =
let integer_conversion_of_char = function
| 'b' -> B_conversion
| 'd' -> D_conversion
| 'i' -> I_conversion
| 'o' -> O_conversion
| 'u' -> U_conversion
| 'x' | 'X' -> X_conversion
| _ -> assert false
Extract an integer literal token .
Since the functions Pervasives.*int*_of_string do not accept a leading + ,
we skip it if necessary .
Since the functions Pervasives.*int*_of_string do not accept a leading +,
we skip it if necessary. *)
let token_int_literal conv ib =
let tok =
match conv with
| D_conversion | I_conversion -> Scanning.token ib
| U_conversion -> "0u" ^ Scanning.token ib
| O_conversion -> "0o" ^ Scanning.token ib
| X_conversion -> "0x" ^ Scanning.token ib
| B_conversion -> "0b" ^ Scanning.token ib in
let l = String.length tok in
if l = 0 || tok.[0] <> '+' then tok else String.sub tok 1 (l - 1)
All the functions that convert a string to a number raise the exception
Failure when the conversion is not possible .
This exception is then trapped in [ kscanf ] .
Failure when the conversion is not possible.
This exception is then trapped in [kscanf]. *)
let token_int conv ib = int_of_string (token_int_literal conv ib)
let token_float ib = float_of_string (Scanning.token ib)
To scan native ints , int32 and int64 integers .
We can not access to conversions to / from strings for those types ,
Nativeint.of_string , Int32.of_string , and Int64.of_string ,
since those modules are not available to [ Scanf ] .
However , we can bind and use the corresponding primitives that are
available in the runtime .
We cannot access to conversions to/from strings for those types,
Nativeint.of_string, Int32.of_string, and Int64.of_string,
since those modules are not available to [Scanf].
However, we can bind and use the corresponding primitives that are
available in the runtime. *)
external nativeint_of_string : string -> nativeint
= "caml_nativeint_of_string"
external int32_of_string : string -> int32
= "caml_int32_of_string"
external int64_of_string : string -> int64
= "caml_int64_of_string"
let token_nativeint conv ib = nativeint_of_string (token_int_literal conv ib)
let token_int32 conv ib = int32_of_string (token_int_literal conv ib)
let token_int64 conv ib = int64_of_string (token_int_literal conv ib)
Digits scanning functions suppose that one character has been checked and
is available , since they return at end of file with the currently found
token selected .
Put it in another way , the digits scanning functions scan for a possibly
empty sequence of digits , ( hence , a successful scanning from one of those
functions does not imply that the token is a well - formed number : to get a
true number , it is mandatory to check that at least one valid digit is
available before calling one of the digit scanning functions ) .
is available, since they return at end of file with the currently found
token selected.
Put it in another way, the digits scanning functions scan for a possibly
empty sequence of digits, (hence, a successful scanning from one of those
functions does not imply that the token is a well-formed number: to get a
true number, it is mandatory to check that at least one valid digit is
available before calling one of the digit scanning functions). *)
let rec scan_decimal_digit_star width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| '0' .. '9' as c ->
let width = Scanning.store_char width ib c in
scan_decimal_digit_star width ib
| '_' ->
let width = Scanning.ignore_char width ib in
scan_decimal_digit_star width ib
| _ -> width
let scan_decimal_digit_plus width ib =
if width = 0 then bad_token_length "decimal digits" else
let c = Scanning.checked_peek_char ib in
match c with
| '0' .. '9' ->
let width = Scanning.store_char width ib c in
scan_decimal_digit_star width ib
| c ->
bad_input (Printf.sprintf "character %C is not a decimal digit" c)
let scan_digit_star digitp width ib =
let rec scan_digits width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| c when digitp c ->
let width = Scanning.store_char width ib c in
scan_digits width ib
| '_' ->
let width = Scanning.ignore_char width ib in
scan_digits width ib
| _ -> width in
scan_digits width ib
let scan_digit_plus basis digitp width ib =
Ensure we have got enough width left ,
and read at list one digit .
and read at list one digit. *)
if width = 0 then bad_token_length "digits" else
let c = Scanning.checked_peek_char ib in
if digitp c then
let width = Scanning.store_char width ib c in
scan_digit_star digitp width ib
else
bad_input (Printf.sprintf "character %C is not a valid %s digit" c basis)
let is_binary_digit = function
| '0' .. '1' -> true
| _ -> false
let scan_binary_int = scan_digit_plus "binary" is_binary_digit
let is_octal_digit = function
| '0' .. '7' -> true
| _ -> false
let scan_octal_int = scan_digit_plus "octal" is_octal_digit
let is_hexa_digit = function
| '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' -> true
| _ -> false
let scan_hexadecimal_int = scan_digit_plus "hexadecimal" is_hexa_digit
let scan_unsigned_decimal_int = scan_decimal_digit_plus
let scan_sign width ib =
let c = Scanning.checked_peek_char ib in
match c with
| '+' -> Scanning.store_char width ib c
| '-' -> Scanning.store_char width ib c
| _ -> width
let scan_optionally_signed_decimal_int width ib =
let width = scan_sign width ib in
scan_unsigned_decimal_int width ib
Scan an unsigned integer that could be given in any ( common ) basis .
If digits are prefixed by one of 0x , 0X , 0o , or 0b , the number is
assumed to be written respectively in hexadecimal , hexadecimal ,
octal , or binary .
If digits are prefixed by one of 0x, 0X, 0o, or 0b, the number is
assumed to be written respectively in hexadecimal, hexadecimal,
octal, or binary. *)
let scan_unsigned_int width ib =
match Scanning.checked_peek_char ib with
| '0' as c ->
let width = Scanning.store_char width ib c in
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
begin match c with
| 'x' | 'X' -> scan_hexadecimal_int (Scanning.store_char width ib c) ib
| 'o' -> scan_octal_int (Scanning.store_char width ib c) ib
| 'b' -> scan_binary_int (Scanning.store_char width ib c) ib
| _ -> scan_decimal_digit_star width ib end
| _ -> scan_unsigned_decimal_int width ib
let scan_optionally_signed_int width ib =
let width = scan_sign width ib in
scan_unsigned_int width ib
let scan_int_conversion conv width ib =
match conv with
| B_conversion -> scan_binary_int width ib
| D_conversion -> scan_optionally_signed_decimal_int width ib
| I_conversion -> scan_optionally_signed_int width ib
| O_conversion -> scan_octal_int width ib
| U_conversion -> scan_unsigned_decimal_int width ib
| X_conversion -> scan_hexadecimal_int width ib
let scan_fractional_part width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| '0' .. '9' as c ->
scan_decimal_digit_star (Scanning.store_char width ib c) ib
| _ -> width
let scan_exponent_part width ib =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match c with
| 'e' | 'E' as c ->
scan_optionally_signed_decimal_int (Scanning.store_char width ib c) ib
| _ -> width
Scan the integer part of a floating point number , ( not using the
OCaml lexical convention since the integer part can be empty ):
an optional sign , followed by a possibly empty sequence of decimal
digits ( e.g. -.1 ) .
OCaml lexical convention since the integer part can be empty):
an optional sign, followed by a possibly empty sequence of decimal
digits (e.g. -.1). *)
let scan_integer_part width ib =
let width = scan_sign width ib in
scan_decimal_digit_star width ib
For the time being we have ( as found in scanf.mli ):
the field width is composed of an optional integer literal
indicating the maximal width of the token to read .
Unfortunately , the type - checker let the user write an optional precision ,
since this is valid for printf format strings .
Thus , the next step for is to support a full width and precision
indication , more or less similar to the one for printf , possibly extended
to the specification of a [ max , min ] range for the width of the token read
for strings . Something like the following spec for scanf.mli :
The optional [ width ] is an integer indicating the maximal
width of the token read . For instance , [ % 6d ] reads an integer ,
having at most 6 characters .
The optional [ precision ] is a dot [ . ] followed by an integer :
- in the floating point number conversions ( [ % f ] , [ % e ] , [ % g ] , [ % F ] , [ % E ] ,
and [ % F ] conversions , the [ precision ] indicates the maximum number of
digits that may follow the decimal point . For instance , [ % .4f ] reads a
[ float ] with at most 4 fractional digits ,
- in the string conversions ( [ % s ] , [ % S ] , [ % \ [ range \ ] ] ) , and in the
integer number conversions ( [ % i ] , [ % d ] , [ % u ] , [ % x ] , [ % o ] , and their
[ int32 ] , [ int64 ] , and [ native_int ] correspondent ) , the [ precision ]
indicates the required minimum width of the token read ,
- on all other conversions , the width and precision specify the [ max , min ]
range for the width of the token read .
For the time being we have (as found in scanf.mli):
the field width is composed of an optional integer literal
indicating the maximal width of the token to read.
Unfortunately, the type-checker let the user write an optional precision,
since this is valid for printf format strings.
Thus, the next step for Scanf is to support a full width and precision
indication, more or less similar to the one for printf, possibly extended
to the specification of a [max, min] range for the width of the token read
for strings. Something like the following spec for scanf.mli:
The optional [width] is an integer indicating the maximal
width of the token read. For instance, [%6d] reads an integer,
having at most 6 characters.
The optional [precision] is a dot [.] followed by an integer:
- in the floating point number conversions ([%f], [%e], [%g], [%F], [%E],
and [%F] conversions, the [precision] indicates the maximum number of
digits that may follow the decimal point. For instance, [%.4f] reads a
[float] with at most 4 fractional digits,
- in the string conversions ([%s], [%S], [%\[ range \]]), and in the
integer number conversions ([%i], [%d], [%u], [%x], [%o], and their
[int32], [int64], and [native_int] correspondent), the [precision]
indicates the required minimum width of the token read,
- on all other conversions, the width and precision specify the [max, min]
range for the width of the token read.
*)
let scan_float width precision ib =
let width = scan_integer_part width ib in
if width = 0 then width, precision else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width, precision else
match c with
| '.' ->
let width = Scanning.store_char width ib c in
let precision = min width precision in
let width = width - (precision - scan_fractional_part precision ib) in
scan_exponent_part width ib, precision
| _ ->
scan_exponent_part width ib, precision
let check_case_insensitive_string width ib error str =
let lowercase c =
match c with
| 'A' .. 'Z' ->
char_of_int (int_of_char c - int_of_char 'A' + int_of_char 'a')
| _ -> c in
let len = String.length str in
let width = ref width in
for i = 0 to len - 1 do
let c = Scanning.peek_char ib in
if lowercase c <> lowercase str.[i] then error ();
if !width = 0 then error ();
width := Scanning.store_char !width ib c;
done;
!width
let scan_hex_float width precision ib =
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
let width = scan_sign width ib in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
match Scanning.peek_char ib with
| '0' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
let width = check_case_insensitive_string width ib bad_hex_float "x" in
if width = 0 || Scanning.end_of_input ib then width else
let width = match Scanning.peek_char ib with
| '.' | 'p' | 'P' -> width
| _ -> scan_hexadecimal_int width ib in
if width = 0 || Scanning.end_of_input ib then width else
let width = match Scanning.peek_char ib with
| '.' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' -> width
| _ ->
let precision = min width precision in
width - (precision - scan_hexadecimal_int precision ib)
)
| _ -> width in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
scan_optionally_signed_decimal_int width ib
| _ -> width
)
| 'n' | 'N' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
check_case_insensitive_string width ib bad_hex_float "an"
| 'i' | 'I' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
check_case_insensitive_string width ib bad_hex_float "nfinity"
| _ -> bad_hex_float ()
let scan_caml_float_rest width precision ib =
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = scan_decimal_digit_star width ib in
if width = 0 || Scanning.end_of_input ib then bad_float ();
let c = Scanning.peek_char ib in
match c with
| '.' ->
let width = Scanning.store_char width ib c in
let precision = min width precision in
let width_precision = scan_fractional_part precision ib in
let frac_width = precision - width_precision in
let width = width - frac_width in
scan_exponent_part width ib
| 'e' | 'E' ->
scan_exponent_part width ib
| _ -> bad_float ()
let scan_caml_float width precision ib =
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = scan_sign width ib in
if width = 0 || Scanning.end_of_input ib then bad_float ();
match Scanning.peek_char ib with
| '0' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_float ();
match Scanning.peek_char ib with
| 'x' | 'X' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = scan_hexadecimal_int width ib in
if width = 0 || Scanning.end_of_input ib then bad_float ();
let width = match Scanning.peek_char ib with
| '.' as c -> (
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' -> width
| _ ->
let precision = min width precision in
width - (precision - scan_hexadecimal_int precision ib)
)
| 'p' | 'P' -> width
| _ -> bad_float () in
if width = 0 || Scanning.end_of_input ib then width else
match Scanning.peek_char ib with
| 'p' | 'P' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_hex_float ();
scan_optionally_signed_decimal_int width ib
| _ -> width
)
| _ ->
scan_caml_float_rest width precision ib
)
| '1' .. '9' as c ->
let width = Scanning.store_char width ib c in
if width = 0 || Scanning.end_of_input ib then bad_float ();
scan_caml_float_rest width precision ib
Special case of and infinity :
| ' i ' - >
| ' n ' - >
| 'i' ->
| 'n' ->
*)
| _ -> bad_float ()
let scan_string stp width ib =
let rec loop width =
if width = 0 then width else
let c = Scanning.peek_char ib in
if Scanning.eof ib then width else
match stp with
| Some c' when c = c' -> Scanning.skip_char width ib
| Some _ -> loop (Scanning.store_char width ib c)
| None ->
match c with
| ' ' | '\t' | '\n' | '\r' -> width
| _ -> loop (Scanning.store_char width ib c) in
loop width
Scan a char : peek strictly one character in the input , whatsoever .
let scan_char width ib =
Scanning.store_char width ib (Scanning.checked_peek_char ib)
let char_for_backslash = function
| 'n' -> '\010'
| 'r' -> '\013'
| 'b' -> '\008'
| 't' -> '\009'
| c -> c
let decimal_value_of_char c = int_of_char c - int_of_char '0'
let char_for_decimal_code c0 c1 c2 =
let c =
100 * decimal_value_of_char c0 +
10 * decimal_value_of_char c1 +
decimal_value_of_char c2 in
if c < 0 || c > 255 then
bad_input
(Printf.sprintf
"bad character decimal encoding \\%c%c%c" c0 c1 c2) else
char_of_int c
let hexadecimal_value_of_char c =
let d = int_of_char c in
if d >= int_of_char 'a' then
if d >= int_of_char 'A' then
d - int_of_char '0'
let char_for_hexadecimal_code c1 c2 =
let c =
16 * hexadecimal_value_of_char c1 +
hexadecimal_value_of_char c2 in
if c < 0 || c > 255 then
bad_input
(Printf.sprintf "bad character hexadecimal encoding \\%c%c" c1 c2) else
char_of_int c
let check_next_char message width ib =
if width = 0 then bad_token_length message else
let c = Scanning.peek_char ib in
if Scanning.eof ib then bad_end_of_input message else
c
let check_next_char_for_char = check_next_char "a Char"
let check_next_char_for_string = check_next_char "a String"
let scan_backslash_char width ib =
match check_next_char_for_char width ib with
| '\\' | '\'' | '\"' | 'n' | 't' | 'b' | 'r' as c ->
Scanning.store_char width ib (char_for_backslash c)
| '0' .. '9' as c ->
let get_digit () =
let c = Scanning.next_char ib in
match c with
| '0' .. '9' as c -> c
| c -> bad_input_escape c in
let c0 = c in
let c1 = get_digit () in
let c2 = get_digit () in
Scanning.store_char (width - 2) ib (char_for_decimal_code c0 c1 c2)
| 'x' ->
let get_digit () =
let c = Scanning.next_char ib in
match c with
| '0' .. '9' | 'A' .. 'F' | 'a' .. 'f' as c -> c
| c -> bad_input_escape c in
let c1 = get_digit () in
let c2 = get_digit () in
Scanning.store_char (width - 2) ib (char_for_hexadecimal_code c1 c2)
| c ->
bad_input_escape c
let scan_caml_char width ib =
let rec find_start width =
match Scanning.checked_peek_char ib with
| '\'' -> find_char (Scanning.ignore_char width ib)
| c -> character_mismatch '\'' c
and find_char width =
match check_next_char_for_char width ib with
| '\\' ->
find_stop (scan_backslash_char (Scanning.ignore_char width ib) ib)
| c ->
find_stop (Scanning.store_char width ib c)
and find_stop width =
match check_next_char_for_char width ib with
| '\'' -> Scanning.ignore_char width ib
| c -> character_mismatch '\'' c in
find_start width
let scan_caml_string width ib =
let rec find_start width =
match Scanning.checked_peek_char ib with
| '\"' -> find_stop (Scanning.ignore_char width ib)
| c -> character_mismatch '\"' c
and find_stop width =
match check_next_char_for_string width ib with
| '\"' -> Scanning.ignore_char width ib
| '\\' -> scan_backslash (Scanning.ignore_char width ib)
| c -> find_stop (Scanning.store_char width ib c)
and scan_backslash width =
match check_next_char_for_string width ib with
| '\r' -> skip_newline (Scanning.ignore_char width ib)
| '\n' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop (scan_backslash_char width ib)
and skip_newline width =
match check_next_char_for_string width ib with
| '\n' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop (Scanning.store_char width ib '\r')
and skip_spaces width =
match check_next_char_for_string width ib with
| ' ' -> skip_spaces (Scanning.ignore_char width ib)
| _ -> find_stop width in
find_start width
let scan_bool ib =
let c = Scanning.checked_peek_char ib in
let m =
match c with
| 't' -> 4
| 'f' -> 5
| c ->
bad_input
(Printf.sprintf "the character %C cannot start a boolean" c) in
scan_string None m ib
let scan_chars_in_char_set char_set scan_indic width ib =
let rec scan_chars i stp =
let c = Scanning.peek_char ib in
if i > 0 && not (Scanning.eof ib) &&
is_in_char_set char_set c &&
int_of_char c <> stp then
let _ = Scanning.store_char max_int ib c in
scan_chars (i - 1) stp in
match scan_indic with
| None -> scan_chars width (-1);
| Some c ->
scan_chars width (int_of_char c);
if not (Scanning.eof ib) then
let ci = Scanning.peek_char ib in
if c = ci
then Scanning.invalidate_current_char ib
else character_mismatch c ci
let scanf_bad_input ib = function
| Scan_failure s | Failure s ->
let i = Scanning.char_count ib in
bad_input (Printf.sprintf "scanf: bad input at char number %i: %s" i s)
| x -> raise x
let get_counter ib counter =
match counter with
| Line_counter -> Scanning.line_count ib
| Char_counter -> Scanning.char_count ib
| Token_counter -> Scanning.token_count ib
Compute the width of a padding option ( see " % 42 { " and " % 123 ( " ) .
let width_of_pad_opt pad_opt = match pad_opt with
| None -> max_int
| Some width -> width
let stopper_of_formatting_lit fmting =
if fmting = Escaped_percent then '%', "" else
let str = string_of_formatting_lit fmting in
let stp = str.[1] in
let sub_str = String.sub str 2 (String.length str - 2) in
stp, sub_str
let rec take_format_readers : type a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, e, f) fmt ->
d =
fun k fmt -> match fmt with
| Reader fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_format_readers new_k fmt_rest
| Char rest -> take_format_readers k rest
| Caml_char rest -> take_format_readers k rest
| String (_, rest) -> take_format_readers k rest
| Caml_string (_, rest) -> take_format_readers k rest
| Int (_, _, _, rest) -> take_format_readers k rest
| Int32 (_, _, _, rest) -> take_format_readers k rest
| Nativeint (_, _, _, rest) -> take_format_readers k rest
| Int64 (_, _, _, rest) -> take_format_readers k rest
| Float (_, _, _, rest) -> take_format_readers k rest
| Bool rest -> take_format_readers k rest
| Alpha rest -> take_format_readers k rest
| Theta rest -> take_format_readers k rest
| Flush rest -> take_format_readers k rest
| String_literal (_, rest) -> take_format_readers k rest
| Char_literal (_, rest) -> take_format_readers k rest
| Custom (_, _, rest) -> take_format_readers k rest
| Scan_char_set (_, _, rest) -> take_format_readers k rest
| Scan_get_counter (_, rest) -> take_format_readers k rest
| Scan_next_char rest -> take_format_readers k rest
| Formatting_lit (_, rest) -> take_format_readers k rest
| Formatting_gen (Open_tag (Format (fmt, _)), rest) ->
take_format_readers k (concat_fmt fmt rest)
| Formatting_gen (Open_box (Format (fmt, _)), rest) ->
take_format_readers k (concat_fmt fmt rest)
| Format_arg (_, _, rest) -> take_format_readers k rest
| Format_subst (_, fmtty, rest) ->
take_fmtty_format_readers k (erase_rel (symm fmtty)) rest
| Ignored_param (ign, rest) -> take_ignored_format_readers k ign rest
| End_of_format -> k Nil
and take_fmtty_format_readers : type x y a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) fmtty ->
(y, Scanning.in_channel, c, x, e, f) fmt -> d =
fun k fmtty fmt -> match fmtty with
| Reader_ty fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_fmtty_format_readers new_k fmt_rest fmt
| Ignored_reader_ty fmt_rest ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_fmtty_format_readers new_k fmt_rest fmt
| Char_ty rest -> take_fmtty_format_readers k rest fmt
| String_ty rest -> take_fmtty_format_readers k rest fmt
| Int_ty rest -> take_fmtty_format_readers k rest fmt
| Int32_ty rest -> take_fmtty_format_readers k rest fmt
| Nativeint_ty rest -> take_fmtty_format_readers k rest fmt
| Int64_ty rest -> take_fmtty_format_readers k rest fmt
| Float_ty rest -> take_fmtty_format_readers k rest fmt
| Bool_ty rest -> take_fmtty_format_readers k rest fmt
| Alpha_ty rest -> take_fmtty_format_readers k rest fmt
| Theta_ty rest -> take_fmtty_format_readers k rest fmt
| Any_ty rest -> take_fmtty_format_readers k rest fmt
| Format_arg_ty (_, rest) -> take_fmtty_format_readers k rest fmt
| End_of_fmtty -> take_format_readers k fmt
| Format_subst_ty (ty1, ty2, rest) ->
let ty = trans (symm ty1) ty2 in
take_fmtty_format_readers k (concat_fmtty ty rest) fmt
and take_ignored_format_readers : type x y a c d e f .
((d, e) heter_list -> e) -> (a, Scanning.in_channel, c, d, x, y) ignored ->
(y, Scanning.in_channel, c, x, e, f) fmt -> d =
fun k ign fmt -> match ign with
| Ignored_reader ->
fun reader ->
let new_k readers_rest = k (Cons (reader, readers_rest)) in
take_format_readers new_k fmt
| Ignored_char -> take_format_readers k fmt
| Ignored_caml_char -> take_format_readers k fmt
| Ignored_string _ -> take_format_readers k fmt
| Ignored_caml_string _ -> take_format_readers k fmt
| Ignored_int (_, _) -> take_format_readers k fmt
| Ignored_int32 (_, _) -> take_format_readers k fmt
| Ignored_nativeint (_, _) -> take_format_readers k fmt
| Ignored_int64 (_, _) -> take_format_readers k fmt
| Ignored_float (_, _) -> take_format_readers k fmt
| Ignored_bool -> take_format_readers k fmt
| Ignored_format_arg _ -> take_format_readers k fmt
| Ignored_format_subst (_, fmtty) -> take_fmtty_format_readers k fmtty fmt
| Ignored_scan_char_set _ -> take_format_readers k fmt
| Ignored_scan_get_counter _ -> take_format_readers k fmt
| Ignored_scan_next_char -> take_format_readers k fmt
Generic scanning
let rec make_scanf : type a c d e f.
Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
(d, e) heter_list -> (a, f) heter_list =
fun ib fmt readers -> match fmt with
| Char rest ->
let _ = scan_char 0 ib in
let c = token_char ib in
Cons (c, make_scanf ib rest readers)
| Caml_char rest ->
let _ = scan_caml_char 0 ib in
let c = token_char ib in
Cons (c, make_scanf ib rest readers)
| String (pad, Formatting_lit (fmting_lit, rest)) ->
let stp, str = stopper_of_formatting_lit fmting_lit in
let scan width _ ib = scan_string (Some stp) width ib in
let str_rest = String_literal (str, rest) in
pad_prec_scanf ib str_rest readers pad No_precision scan token_string
| String (pad, Formatting_gen (Open_tag (Format (fmt', _)), rest)) ->
let scan width _ ib = scan_string (Some '{') width ib in
pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan
token_string
| String (pad, Formatting_gen (Open_box (Format (fmt', _)), rest)) ->
let scan width _ ib = scan_string (Some '[') width ib in
pad_prec_scanf ib (concat_fmt fmt' rest) readers pad No_precision scan
token_string
| String (pad, rest) ->
let scan width _ ib = scan_string None width ib in
pad_prec_scanf ib rest readers pad No_precision scan token_string
| Caml_string (pad, rest) ->
let scan width _ ib = scan_caml_string width ib in
pad_prec_scanf ib rest readers pad No_precision scan token_string
| Int (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int c)
| Int32 (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int32 c)
| Nativeint (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_nativeint c)
| Int64 (iconv, pad, prec, rest) ->
let c = integer_conversion_of_char (char_of_iconv iconv) in
let scan width _ ib = scan_int_conversion c width ib in
pad_prec_scanf ib rest readers pad prec scan (token_int64 c)
| Float (Float_F, pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_caml_float token_float
| Float ((Float_f | Float_pf | Float_sf | Float_e | Float_pe | Float_se
| Float_E | Float_pE | Float_sE | Float_g | Float_pg | Float_sg
| Float_G | Float_pG | Float_sG), pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_float token_float
| Float ((Float_h | Float_ph | Float_sh | Float_H | Float_pH | Float_sH),
pad, prec, rest) ->
pad_prec_scanf ib rest readers pad prec scan_hex_float token_float
| Bool rest ->
let _ = scan_bool ib in
let b = token_bool ib in
Cons (b, make_scanf ib rest readers)
| Alpha _ ->
invalid_arg "scanf: bad conversion \"%a\""
| Theta _ ->
invalid_arg "scanf: bad conversion \"%t\""
| Custom _ ->
invalid_arg "scanf: bad conversion \"%?\" (custom converter)"
| Reader fmt_rest ->
begin match readers with
| Cons (reader, readers_rest) ->
let x = reader ib in
Cons (x, make_scanf ib fmt_rest readers_rest)
| Nil ->
invalid_arg "scanf: missing reader"
end
| Flush rest ->
if Scanning.end_of_input ib then make_scanf ib rest readers
else bad_input "end of input not found"
| String_literal (str, rest) ->
String.iter (check_char ib) str;
make_scanf ib rest readers
| Char_literal (chr, rest) ->
check_char ib chr;
make_scanf ib rest readers
| Format_arg (pad_opt, fmtty, rest) ->
let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
let s = token_string ib in
let fmt =
try format_of_string_fmtty s fmtty
with Failure msg -> bad_input msg
in
Cons (fmt, make_scanf ib rest readers)
| Format_subst (pad_opt, fmtty, rest) ->
let _ = scan_caml_string (width_of_pad_opt pad_opt) ib in
let s = token_string ib in
let fmt, fmt' =
try
let Fmt_EBB fmt = fmt_ebb_of_string s in
let Fmt_EBB fmt' = fmt_ebb_of_string s in
TODO : these type - checks below * can * fail because of type
ambiguity in presence of ignored - readers : " % _ r%d " and " % d%_r "
are typed in the same way .
# Scanf.sscanf " \"%_r%d\"3 " " % ( % d%_r% ) " ignore
( fun fmt n - > string_of_format fmt , n )
Exception : CamlinternalFormat . Type_mismatch .
We should properly catch this exception .
ambiguity in presence of ignored-readers: "%_r%d" and "%d%_r"
are typed in the same way.
# Scanf.sscanf "\"%_r%d\"3" "%(%d%_r%)" ignore
(fun fmt n -> string_of_format fmt, n)
Exception: CamlinternalFormat.Type_mismatch.
We should properly catch this exception.
*)
type_format fmt (erase_rel fmtty),
type_format fmt' (erase_rel (symm fmtty))
with Failure msg -> bad_input msg
in
Cons (Format (fmt, s),
make_scanf ib (concat_fmt fmt' rest) readers)
| Scan_char_set (width_opt, char_set, Formatting_lit (fmting_lit, rest)) ->
let stp, str = stopper_of_formatting_lit fmting_lit in
let width = width_of_pad_opt width_opt in
scan_chars_in_char_set char_set (Some stp) width ib;
let s = token_string ib in
let str_rest = String_literal (str, rest) in
Cons (s, make_scanf ib str_rest readers)
| Scan_char_set (width_opt, char_set, rest) ->
let width = width_of_pad_opt width_opt in
scan_chars_in_char_set char_set None width ib;
let s = token_string ib in
Cons (s, make_scanf ib rest readers)
| Scan_get_counter (counter, rest) ->
let count = get_counter ib counter in
Cons (count, make_scanf ib rest readers)
| Scan_next_char rest ->
let c = Scanning.checked_peek_char ib in
Cons (c, make_scanf ib rest readers)
| Formatting_lit (formatting_lit, rest) ->
String.iter (check_char ib) (string_of_formatting_lit formatting_lit);
make_scanf ib rest readers
| Formatting_gen (Open_tag (Format (fmt', _)), rest) ->
check_char ib '@'; check_char ib '{';
make_scanf ib (concat_fmt fmt' rest) readers
| Formatting_gen (Open_box (Format (fmt', _)), rest) ->
check_char ib '@'; check_char ib '[';
make_scanf ib (concat_fmt fmt' rest) readers
| Ignored_param (ign, rest) ->
let Param_format_EBB fmt' = param_format_of_ignored_format ign rest in
begin match make_scanf ib fmt' readers with
| Cons (_, arg_rest) -> arg_rest
| Nil -> assert false
end
| End_of_format ->
Nil
Reject formats containing " % * " or " % . * " .
and pad_prec_scanf : type a c d e f x y z t .
Scanning.in_channel -> (a, Scanning.in_channel, c, d, e, f) fmt ->
(d, e) heter_list -> (x, y) padding -> (y, z -> a) precision ->
(int -> int -> Scanning.in_channel -> t) ->
(Scanning.in_channel -> z) ->
(x, f) heter_list =
fun ib fmt readers pad prec scan token -> match pad, prec with
| No_padding, No_precision ->
let _ = scan max_int max_int ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| No_padding, Lit_precision p ->
let _ = scan max_int p ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding ((Right | Zeros), w), No_precision ->
let _ = scan w max_int ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding ((Right | Zeros), w), Lit_precision p ->
let _ = scan w p ib in
let x = token ib in
Cons (x, make_scanf ib fmt readers)
| Lit_padding (Left, _), _ ->
invalid_arg "scanf: bad conversion \"%-\""
| Lit_padding ((Right | Zeros), _), Arg_precision ->
invalid_arg "scanf: bad conversion \"%*\""
| Arg_padding _, _ ->
invalid_arg "scanf: bad conversion \"%*\""
| No_padding, Arg_precision ->
invalid_arg "scanf: bad conversion \"%*\""
type 'a kscanf_result = Args of 'a | Exc of exn
let kscanf ib ef (Format (fmt, str)) =
let rec apply : type a b . a -> (a, b) heter_list -> b =
fun f args -> match args with
| Cons (x, r) -> apply (f x) r
| Nil -> f
in
let k readers f =
Scanning.reset_token ib;
match try Args (make_scanf ib fmt readers) with
| (Scan_failure _ | Failure _ | End_of_file) as exc -> Exc exc
| Invalid_argument msg ->
invalid_arg (msg ^ " in format \"" ^ String.escaped str ^ "\"")
with
| Args args -> apply f args
| Exc exc -> ef ib exc
in
take_format_readers k fmt
let kbscanf = kscanf
let bscanf ib fmt = kbscanf ib scanf_bad_input fmt
let ksscanf s ef fmt = kbscanf (Scanning.from_string s) ef fmt
let sscanf s fmt = kbscanf (Scanning.from_string s) scanf_bad_input fmt
let scanf fmt = kscanf Scanning.stdib scanf_bad_input fmt
let bscanf_format :
Scanning.in_channel -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
(('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
fun ib format f ->
let _ = scan_caml_string max_int ib in
let str = token_string ib in
let fmt' =
try format_of_string_format str format
with Failure msg -> bad_input msg in
f fmt'
let sscanf_format :
string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
(('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g =
fun s format f -> bscanf_format (Scanning.from_string s) format f
let string_to_String s =
let l = String.length s in
let b = Buffer.create (l + 2) in
Buffer.add_char b '\"';
for i = 0 to l - 1 do
let c = s.[i] in
if c = '\"' then Buffer.add_char b '\\';
Buffer.add_char b c;
done;
Buffer.add_char b '\"';
Buffer.contents b
let format_from_string s fmt =
sscanf_format (string_to_String s) fmt (fun x -> x)
let unescaped s =
sscanf ("\"" ^ s ^ "\"") "%S%!" (fun x -> x)
let kfscanf ic ef fmt = kbscanf (Scanning.memo_from_channel ic) ef fmt
let fscanf ic fmt = kscanf (Scanning.memo_from_channel ic) scanf_bad_input fmt
|
26f7fdf00bf48dee132c9b0eef59e4cb7114cb671f81c406e797ffc15aeaf546 | jbrisbin/amqp_client | amqp_rpc_client.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License at
%% /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%% License for the specific language governing rights and limitations
%% under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2016 Pivotal Software , Inc. All rights reserved .
%%
%% @doc This module allows the simple execution of an asynchronous RPC over
AMQP . It frees a client programmer of the necessary having to
%% plumbing. Note that the this module does not handle any data encoding,
so it is up to the caller to and unmarshall message payloads
%% accordingly.
-module(amqp_rpc_client).
-include("amqp_client.hrl").
-behaviour(gen_server).
-export([start/2, start_link/2, stop/1]).
-export([call/2]).
-export([init/1, terminate/2, code_change/3, handle_call/3,
handle_cast/2, handle_info/2]).
-record(state, {channel,
reply_queue,
exchange,
routing_key,
continuations = dict:new(),
correlation_id = 0}).
%%--------------------------------------------------------------------------
%% API
%%--------------------------------------------------------------------------
%% @spec (Connection, Queue) -> RpcClient
%% where
%% Connection = pid()
%% Queue = binary()
%% RpcClient = pid()
@doc Starts a new RPC client instance that sends requests to a
specified queue . This function returns the pid of the RPC client process
%% that can be used to invoke RPCs and stop the client.
start(Connection, Queue) ->
{ok, Pid} = gen_server:start(?MODULE, [Connection, Queue], []),
Pid.
%% @spec (Connection, Queue) -> RpcClient
%% where
%% Connection = pid()
%% Queue = binary()
%% RpcClient = pid()
@doc Starts , and links to , a new RPC client instance that sends requests
to a specified queue . This function returns the pid of the RPC client
%% process that can be used to invoke RPCs and stop the client.
start_link(Connection, Queue) ->
{ok, Pid} = gen_server:start_link(?MODULE, [Connection, Queue], []),
Pid.
%% @spec (RpcClient) -> ok
%% where
%% RpcClient = pid()
@doc Stops an exisiting RPC client .
stop(Pid) ->
gen_server:call(Pid, stop, infinity).
@spec ( RpcClient , Payload ) - > ok
%% where
%% RpcClient = pid()
%% Payload = binary()
@doc Invokes an RPC . Note the caller of this function is responsible for
%% encoding the request and decoding the response.
call(RpcClient, Payload) ->
gen_server:call(RpcClient, {call, Payload}, infinity).
%%--------------------------------------------------------------------------
%% Plumbing
%%--------------------------------------------------------------------------
%% Sets up a reply queue for this client to listen on
setup_reply_queue(State = #state{channel = Channel}) ->
#'queue.declare_ok'{queue = Q} =
amqp_channel:call(Channel, #'queue.declare'{exclusive = true,
auto_delete = true}),
State#state{reply_queue = Q}.
Registers this RPC client instance as a consumer to handle rpc responses
setup_consumer(#state{channel = Channel, reply_queue = Q}) ->
amqp_channel:call(Channel, #'basic.consume'{queue = Q}).
%% Publishes to the broker, stores the From address against
%% the correlation id and increments the correlationid for
%% the next request
publish(Payload, From,
State = #state{channel = Channel,
reply_queue = Q,
exchange = X,
routing_key = RoutingKey,
correlation_id = CorrelationId,
continuations = Continuations}) ->
EncodedCorrelationId = base64:encode(<<CorrelationId:64>>),
Props = #'P_basic'{correlation_id = EncodedCorrelationId,
content_type = <<"application/octet-stream">>,
reply_to = Q},
Publish = #'basic.publish'{exchange = X,
routing_key = RoutingKey,
mandatory = true},
amqp_channel:call(Channel, Publish, #amqp_msg{props = Props,
payload = Payload}),
State#state{correlation_id = CorrelationId + 1,
continuations = dict:store(EncodedCorrelationId, From, Continuations)}.
%%--------------------------------------------------------------------------
%% gen_server callbacks
%%--------------------------------------------------------------------------
%% Sets up a reply queue and consumer within an existing channel
@private
init([Connection, RoutingKey]) ->
{ok, Channel} = amqp_connection:open_channel(
Connection, {amqp_direct_consumer, [self()]}),
InitialState = #state{channel = Channel,
exchange = <<>>,
routing_key = RoutingKey},
State = setup_reply_queue(InitialState),
setup_consumer(State),
{ok, State}.
%% Closes the channel this gen_server instance started
@private
terminate(_Reason, #state{channel = Channel}) ->
amqp_channel:close(Channel),
ok.
%% Handle the application initiated stop by just stopping this gen server
@private
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
@private
handle_call({call, Payload}, From, State) ->
NewState = publish(Payload, From, State),
{noreply, NewState}.
@private
handle_cast(_Msg, State) ->
{noreply, State}.
@private
handle_info({#'basic.consume'{}, _Pid}, State) ->
{noreply, State};
@private
handle_info(#'basic.consume_ok'{}, State) ->
{noreply, State};
@private
handle_info(#'basic.cancel'{}, State) ->
{noreply, State};
@private
handle_info(#'basic.cancel_ok'{}, State) ->
{stop, normal, State};
@private
handle_info({#'basic.deliver'{delivery_tag = DeliveryTag},
#amqp_msg{props = #'P_basic'{correlation_id = Id},
payload = Payload}},
State = #state{continuations = Conts, channel = Channel}) ->
From = dict:fetch(Id, Conts),
gen_server:reply(From, Payload),
amqp_channel:call(Channel, #'basic.ack'{delivery_tag = DeliveryTag}),
{noreply, State#state{continuations = dict:erase(Id, Conts) }}.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/jbrisbin/amqp_client/d50aec00b94f0766a048b4eceaf25ddfdeeb1d86/src/amqp_rpc_client.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
@doc This module allows the simple execution of an asynchronous RPC over
plumbing. Note that the this module does not handle any data encoding,
accordingly.
--------------------------------------------------------------------------
API
--------------------------------------------------------------------------
@spec (Connection, Queue) -> RpcClient
where
Connection = pid()
Queue = binary()
RpcClient = pid()
that can be used to invoke RPCs and stop the client.
@spec (Connection, Queue) -> RpcClient
where
Connection = pid()
Queue = binary()
RpcClient = pid()
process that can be used to invoke RPCs and stop the client.
@spec (RpcClient) -> ok
where
RpcClient = pid()
where
RpcClient = pid()
Payload = binary()
encoding the request and decoding the response.
--------------------------------------------------------------------------
Plumbing
--------------------------------------------------------------------------
Sets up a reply queue for this client to listen on
Publishes to the broker, stores the From address against
the correlation id and increments the correlationid for
the next request
--------------------------------------------------------------------------
gen_server callbacks
--------------------------------------------------------------------------
Sets up a reply queue and consumer within an existing channel
Closes the channel this gen_server instance started
Handle the application initiated stop by just stopping this gen server | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2016 Pivotal Software , Inc. All rights reserved .
AMQP . It frees a client programmer of the necessary having to
so it is up to the caller to and unmarshall message payloads
-module(amqp_rpc_client).
-include("amqp_client.hrl").
-behaviour(gen_server).
-export([start/2, start_link/2, stop/1]).
-export([call/2]).
-export([init/1, terminate/2, code_change/3, handle_call/3,
handle_cast/2, handle_info/2]).
-record(state, {channel,
reply_queue,
exchange,
routing_key,
continuations = dict:new(),
correlation_id = 0}).
@doc Starts a new RPC client instance that sends requests to a
specified queue . This function returns the pid of the RPC client process
start(Connection, Queue) ->
{ok, Pid} = gen_server:start(?MODULE, [Connection, Queue], []),
Pid.
@doc Starts , and links to , a new RPC client instance that sends requests
to a specified queue . This function returns the pid of the RPC client
start_link(Connection, Queue) ->
{ok, Pid} = gen_server:start_link(?MODULE, [Connection, Queue], []),
Pid.
@doc Stops an exisiting RPC client .
stop(Pid) ->
gen_server:call(Pid, stop, infinity).
@spec ( RpcClient , Payload ) - > ok
@doc Invokes an RPC . Note the caller of this function is responsible for
call(RpcClient, Payload) ->
gen_server:call(RpcClient, {call, Payload}, infinity).
setup_reply_queue(State = #state{channel = Channel}) ->
#'queue.declare_ok'{queue = Q} =
amqp_channel:call(Channel, #'queue.declare'{exclusive = true,
auto_delete = true}),
State#state{reply_queue = Q}.
Registers this RPC client instance as a consumer to handle rpc responses
setup_consumer(#state{channel = Channel, reply_queue = Q}) ->
amqp_channel:call(Channel, #'basic.consume'{queue = Q}).
publish(Payload, From,
State = #state{channel = Channel,
reply_queue = Q,
exchange = X,
routing_key = RoutingKey,
correlation_id = CorrelationId,
continuations = Continuations}) ->
EncodedCorrelationId = base64:encode(<<CorrelationId:64>>),
Props = #'P_basic'{correlation_id = EncodedCorrelationId,
content_type = <<"application/octet-stream">>,
reply_to = Q},
Publish = #'basic.publish'{exchange = X,
routing_key = RoutingKey,
mandatory = true},
amqp_channel:call(Channel, Publish, #amqp_msg{props = Props,
payload = Payload}),
State#state{correlation_id = CorrelationId + 1,
continuations = dict:store(EncodedCorrelationId, From, Continuations)}.
@private
init([Connection, RoutingKey]) ->
{ok, Channel} = amqp_connection:open_channel(
Connection, {amqp_direct_consumer, [self()]}),
InitialState = #state{channel = Channel,
exchange = <<>>,
routing_key = RoutingKey},
State = setup_reply_queue(InitialState),
setup_consumer(State),
{ok, State}.
@private
terminate(_Reason, #state{channel = Channel}) ->
amqp_channel:close(Channel),
ok.
@private
handle_call(stop, _From, State) ->
{stop, normal, ok, State};
@private
handle_call({call, Payload}, From, State) ->
NewState = publish(Payload, From, State),
{noreply, NewState}.
@private
handle_cast(_Msg, State) ->
{noreply, State}.
@private
handle_info({#'basic.consume'{}, _Pid}, State) ->
{noreply, State};
@private
handle_info(#'basic.consume_ok'{}, State) ->
{noreply, State};
@private
handle_info(#'basic.cancel'{}, State) ->
{noreply, State};
@private
handle_info(#'basic.cancel_ok'{}, State) ->
{stop, normal, State};
@private
handle_info({#'basic.deliver'{delivery_tag = DeliveryTag},
#amqp_msg{props = #'P_basic'{correlation_id = Id},
payload = Payload}},
State = #state{continuations = Conts, channel = Channel}) ->
From = dict:fetch(Id, Conts),
gen_server:reply(From, Payload),
amqp_channel:call(Channel, #'basic.ack'{delivery_tag = DeliveryTag}),
{noreply, State#state{continuations = dict:erase(Id, Conts) }}.
@private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
6bcfe32f30d2883094d877110f40e8785c547c80ebd8d4aae16cc0f0ca1dd418 | haskell-opengl/OpenGLRaw | FragmentCoverageToColor.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.NV.FragmentCoverageToColor
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.NV.FragmentCoverageToColor (
-- * Extension Support
glGetNVFragmentCoverageToColor,
gl_NV_fragment_coverage_to_color,
-- * Enums
pattern GL_FRAGMENT_COVERAGE_COLOR_NV,
pattern GL_FRAGMENT_COVERAGE_TO_COLOR_NV,
-- * Functions
glFragmentCoverageColorNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/NV/FragmentCoverageToColor.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.NV.FragmentCoverageToColor
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions | # LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.NV.FragmentCoverageToColor (
glGetNVFragmentCoverageToColor,
gl_NV_fragment_coverage_to_color,
pattern GL_FRAGMENT_COVERAGE_COLOR_NV,
pattern GL_FRAGMENT_COVERAGE_TO_COLOR_NV,
glFragmentCoverageColorNV
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
655a5ff10719f3a1b822afe64fa889229bbb9e4677da13e477d4f296062a8d66 | statebox/cql | CQL.hs |
SPDX - License - Identifier : AGPL-3.0 - only
This file is part of ` statebox / cql ` , the categorical query language .
Copyright ( C ) 2019 <
This program is free software : you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
along with this program . If not , see < / > .
SPDX-License-Identifier: AGPL-3.0-only
This file is part of `statebox/cql`, the categorical query language.
Copyright (C) 2019 Stichting Statebox <>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see </>.
-}
# LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE DataKinds #-}
# LANGUAGE DuplicateRecordFields #
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE ImpredicativeTypes #
# LANGUAGE InstanceSigs #
{-# LANGUAGE LiberalTypeSynonyms #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE UndecidableInstances #
module Language.CQL where
import Control.Concurrent
import Control.DeepSeq
import Control.Exception
import Data.List (nub)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Typeable
import Language.CQL.Common as C
import Language.CQL.Graph
import Language.CQL.Instance as I
import qualified Language.CQL.Instance.Presentation as IP
import Language.CQL.Mapping as M
import Language.CQL.Options
import Language.CQL.Parser.Program (parseProgram)
import Language.CQL.Program as P
import Language.CQL.Query as Q
import Language.CQL.Schema as S
import Language.CQL.Term as Term
import Language.CQL.Transform as Tr
import Language.CQL.Typeside as T
import Prelude hiding (EQ, exp)
import System.IO.Unsafe
| Times out a computation after @i@ microseconds .
timeout' :: NFData x => Integer -> Err x -> Err x
timeout' i p = unsafePerformIO $ do
m <- newEmptyMVar
computer <- forkIO $ f m p
_ <- forkIO $ s m computer
takeMVar m
where
secs = (fromIntegral i) * 1000000
f m p0 = do
x <- evaluate $ force p0
putMVar m x
s m c = do
threadDelay secs
x <- tryTakeMVar m
case x of
Just y -> putMVar m y
Nothing -> do
putMVar m $ Left $ "Timeout after " ++ show i ++ " seconds."
killThread c
-----------------------------------------------------------------------------------------------------------------
-- Type checking
class Typecheck e e' where
typecheck :: Types -> e -> Err e'
| Checks that e.g. in @sigma F I@ that @F : S - > T@ and @I : S - Inst@.
-- Checking that @S@ is well-formed is done by 'validate'.
typecheckCqlProgram :: [(String,Kind)] -> Prog -> Types -> Err Types
typecheckCqlProgram [] _ x = pure x
typecheckCqlProgram ((v, k):l) prog ts = do
m <- getKindCtx prog v k
t <- wrapError ("Type Error in " ++ v ++ ": ") $ typecheck' v ts m
typecheckCqlProgram l prog t
typecheck' :: String -> Types -> Exp -> Err Types
typecheck' v ts e = case e of
ExpTy e' -> do { t <- typecheck ts e'; return $ ts { typesides = Map.insert v t $ typesides ts } }
ExpS e' -> do { t <- typecheck ts e'; return $ ts { schemas = Map.insert v t $ schemas ts } }
ExpI e' -> do { t <- typecheck ts e'; return $ ts { instances = Map.insert v t $ instances ts } }
ExpM e' -> do { t <- typecheck ts e'; return $ ts { mappings = Map.insert v t $ mappings ts } }
ExpT e' -> do { t <- typecheck ts e'; return $ ts { transforms = Map.insert v t $ transforms ts } }
ExpQ e' -> do { t <- typecheck ts e'; return $ ts { queries = Map.insert v t $ queries ts } }
instance Typecheck TypesideExp TypesideExp where
typecheck = typecheckTypesideExp
instance Typecheck SchemaExp TypesideExp where
typecheck = typecheckSchemaExp
instance Typecheck InstanceExp SchemaExp where
typecheck = typecheckInstExp
instance Typecheck MappingExp (SchemaExp, SchemaExp) where
typecheck = typecheckMapExp
instance Typecheck TransformExp (InstanceExp, InstanceExp) where
typecheck = typecheckTransExp
instance Typecheck QueryExp (SchemaExp, SchemaExp) where
typecheck = error "todo typecheck query exp"
typecheckTransExp :: Types -> TransformExp -> Err (InstanceExp, InstanceExp)
typecheckTransExp p (TransformVar v) = note ("Undefined transform: " ++ show v) $ Map.lookup v $ transforms p
typecheckTransExp _ (TransformId s) = pure (s, s)
typecheckTransExp p (TransformComp f g) = do
(a, b) <- typecheckTransExp p f
(c, d) <- typecheckTransExp p g
if b == c
then pure (a, d)
else Left "Transform composition has non equal intermediate transforms"
typecheckTransExp p (TransformSigma f' h o) = do
(s, _) <- typecheckMapExp p f'
(i, j) <- typecheckTransExp p h
s' <- typecheckInstExp p i
if s == s'
then pure (InstanceSigma f' i o, InstanceSigma f' j o)
else Left "Source of mapping does not match instance schema"
typecheckTransExp p (TransformSigmaDeltaUnit f' i o) = do
(s, _) <- typecheckMapExp p f'
x <- typecheckInstExp p i
if s == x
then pure (i, InstanceDelta f' (InstanceSigma f' i o) o)
else Left "Source of mapping does not match instance schema"
typecheckTransExp p (TransformSigmaDeltaCoUnit f' i o) = do
(_, t) <- typecheckMapExp p f'
x <- typecheckInstExp p i
if t == x
then pure (i, InstanceSigma f' (InstanceDelta f' i o) o)
else Left "Target of mapping does not match instance schema"
typecheckTransExp p (TransformDelta f' h o) = do
(_, t) <- typecheckMapExp p f'
(i, j) <- typecheckTransExp p h
t' <- typecheckInstExp p i
if t == t'
then pure (InstanceDelta f' i o, InstanceDelta f' j o)
else Left "Target of mapping does not match instance schema"
typecheckTransExp p (TransformRaw r) = do
l' <- typecheckInstExp p $ transraw_src r
r' <- typecheckInstExp p $ transraw_dst r
if l' == r'
then pure (transraw_src r, transraw_src r)
else Left "Mapping has non equal schemas"
typecheckTransExp _ _ = error "todo"
typecheckMapExp :: Types -> MappingExp -> Err (SchemaExp, SchemaExp)
typecheckMapExp p (MappingVar v) = note ("Undefined mapping: " ++ show v) $ Map.lookup v $ mappings p
typecheckMapExp p (MappingComp f g) = do
(a, b) <- typecheckMapExp p f
(c, d) <- typecheckMapExp p g
if b == c
then pure (a, d)
else Left "Mapping composition has non equal intermediate schemas"
typecheckMapExp p (MappingId s) = do
_ <- typecheckSchemaExp p s
pure (s, s)
typecheckMapExp p (MappingRaw r) = do
l' <- typecheckSchemaExp p $ mapraw_src r
r' <- typecheckSchemaExp p $ mapraw_dst r
if l' == r'
then pure (mapraw_src r, mapraw_dst r)
else Left "Mapping has non equal typesides"
typecheckInstExp :: Types -> InstanceExp -> Err SchemaExp
typecheckInstExp p (InstanceVar v) = note ("Undefined instance: " ++ show v) $ Map.lookup v $ instances p
typecheckInstExp _ (InstanceInitial s) = pure s
typecheckInstExp _ (InstanceRaw r) = pure $ instraw_schema r
typecheckInstExp p (InstanceSigma f' i _) = do
(s, t) <- typecheckMapExp p f'
s' <- typecheckInstExp p i
if s == s'
then pure t
else Left "(Sigma): Instance not on mapping source."
typecheckInstExp p (InstanceDelta f' i _) = do
(s, t) <- typecheckMapExp p f'
t' <- typecheckInstExp p i
if t == t'
then pure s
else Left "(Delta): Instance not on mapping target."
typecheckInstExp _ (InstancePivot _) = undefined --todo: requires breaking import cycle
typecheckInstExp _ _ = error "todo"
typecheckTypesideExp :: Types -> TypesideExp -> Err TypesideExp
typecheckTypesideExp p x = case x of
TypesideSql -> pure TypesideSql
TypesideInitial -> pure TypesideInitial
TypesideRaw r -> pure $ TypesideRaw r
TypesideVar v -> note ("Undefined typeside: " ++ show v) $ Map.lookup v $ typesides p
typecheckSchemaExp
:: Types -> SchemaExp -> Either String TypesideExp
typecheckSchemaExp p x = case x of
SchemaRaw r -> pure $ schraw_ts r
SchemaVar v -> note ("Undefined schema: " ++ show v) $ Map.lookup v $ schemas p
SchemaInitial t -> do { _ <- typecheckTypesideExp p t ; return t }
SchemaCoProd l r -> do
l' <- typecheckSchemaExp p l
r' <- typecheckSchemaExp p r
if l' == r'
then return l'
else Left "Coproduct has non equal typesides"
------------------------------------------------------------------------------------------------------------
-- evaluation
| The result of evaluating an CQL program .
type Env = KindCtx TypesideEx SchemaEx InstanceEx MappingEx QueryEx TransformEx Options
| Parse , , and evaluate the CQL program .
runProg :: String -> Err (Prog, Types, Env)
runProg srcText = do
progE <- parseProgram srcText
opts <- toOptions defaultOptions $ other progE
o <- findOrder progE
typesE <- typecheckCqlProgram o progE newTypes
envE <- evalCqlProgram o progE $ newEnv opts
return (progE, typesE, envE)
evalCqlProgram :: [(String,Kind)] -> Prog -> Env -> Err Env
evalCqlProgram [] _ env = pure env
evalCqlProgram ((v,k):l) prog env = do
e <- getKindCtx prog v k
ops <- toOptions (other env) $ getOptions' e
t <- wrapError ("Eval Error in " ++ v) $ timeout' (iOps ops Timeout) $ eval' prog env e
evalCqlProgram l prog $ setEnv env v t
findOrder :: Prog -> Err [(String, Kind)]
findOrder p@(KindCtx t s i m q tr _) = do
ret <- tsort g
pure $ reverse ret
where
g = Graph (allVars p) $ nub $ f0 t TYPESIDE ++ f0 s SCHEMA ++ f0 i INSTANCE ++ f0 m MAPPING ++ f0 q QUERY ++ f0 tr TRANSFORM
f0 m0 k = concatMap (\(v,e) -> [ ((v,k),x) | x <- deps e ]) $ Map.toList m0
class Evalable e e' | e' -> e, e -> e' where
validate :: e' -> Err ()
eval :: Prog -> Env -> e -> Err e'
getOptions :: e -> [(String, String)]
eval' :: Prog -> Env -> Exp -> Err Val
eval' p env e = case e of
ExpTy e' -> do { x <- eval p env e'; maybeValidate x; return $ ValTy x }
ExpS e' -> do { x <- eval p env e'; maybeValidate x; return $ ValS x }
ExpI e' -> do { x <- eval p env e'; maybeValidate x; return $ ValI x }
ExpM e' -> do { x <- eval p env e'; maybeValidate x; return $ ValM x }
ExpT e' -> do { x <- eval p env e'; maybeValidate x; return $ ValT x }
ExpQ e' -> do { x <- eval p env e'; maybeValidate x; return $ ValQ x }
where
maybeValidate :: Evalable exp val => val -> Err ()
maybeValidate val = do
ops <- toOptions (other env) $ getOptions' e
if bOps ops Dont_Validate_Unsafe then return () else validate val
getKindCtx :: Prog -> String -> Kind -> Err Exp
getKindCtx g v k = case k of
TYPESIDE -> fmap ExpTy $ n $ Map.lookup v $ typesides g
SCHEMA -> fmap ExpS $ n $ Map.lookup v $ schemas g
INSTANCE -> fmap ExpI $ n $ Map.lookup v $ instances g
MAPPING -> fmap ExpM $ n $ Map.lookup v $ mappings g
TRANSFORM -> fmap ExpT $ n $ Map.lookup v $ transforms g
QUERY -> fmap ExpQ $ n $ Map.lookup v $ queries g
_ -> error "todo"
where
n :: forall x. Maybe x -> Err x
n = note ("Undefined " ++ show k ++ ": " ++ v)
setEnv :: Env -> String -> Val -> Env
setEnv env v val = case val of
ValTy t -> env { typesides = Map.insert v t $ typesides env }
ValS t -> env { schemas = Map.insert v t $ schemas env }
ValI t -> env { instances = Map.insert v t $ instances env }
ValM t -> env { mappings = Map.insert v t $ mappings env }
ValT t -> env { transforms = Map.insert v t $ transforms env }
ValQ t -> env { queries = Map.insert v t $ queries env }
instance Evalable TypesideExp TypesideEx where
validate (TypesideEx x) = typecheckTypeside x
eval = evalTypeside
getOptions = getOptionsTypeside
instance Evalable SchemaExp SchemaEx where
validate (SchemaEx x) = typecheckSchema x
eval = evalSchema
getOptions = getOptionsSchema
instance Evalable InstanceExp InstanceEx where
validate (InstanceEx x) = do
IP.typecheck (schema x) (pres x)
I.satisfiesSchema x
eval prog env exp = do
i <- evalInstance prog env exp
o' <- toOptions (other env) $ getOptions exp
_ <- checkCons i $ bOps o' Require_Consistency
pure i
where
checkCons (InstanceEx i) True = if freeTalg i
then pure ()
else Left "Warning: type algebra not free. Set require_consistency = false to continue."
checkCons _ False = pure ()
getOptions = getOptionsInstance
instance Evalable MappingExp MappingEx where
validate (MappingEx x) = typecheckMapping x
eval = evalMapping
getOptions = getOptionsMapping
instance Evalable TransformExp TransformEx where
validate (TransformEx x) = typecheckTransform x
eval = evalTransform
getOptions = getOptionsTransform
instance Evalable QueryExp QueryEx where
validate (QueryEx x) = typecheckQuery x
eval = evalQuery
getOptions = getOptionsQuery
getOptions' :: Exp -> [(String, String)]
getOptions' e = case e of
ExpTy e' -> getOptions e'
ExpS e' -> getOptions e'
ExpI e' -> getOptions e'
ExpM e' -> getOptions e'
ExpT e' -> getOptions e'
ExpQ e' -> getOptions e'
------------------------------------------------------------------------------------------------------------
evalTypeside :: Prog -> Env -> TypesideExp -> Err TypesideEx
evalTypeside _ _ TypesideInitial = pure $ TypesideEx initialTypeside
evalTypeside p e (TypesideRaw r) = do
x <- mapM (evalTypeside p e) $ tsraw_imports r
evalTypesideRaw (other e) r x
evalTypeside _ env (TypesideVar v) = case Map.lookup v $ typesides env of
Nothing -> Left $ "Undefined typeside: " ++ show v
Just (TypesideEx e) -> Right $ TypesideEx e
evalTypeside _ _ TypesideSql = pure $ TypesideEx $ sqlTypeside
evalTransform :: Prog -> Env -> TransformExp -> Err TransformEx
evalTransform _ env (TransformVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ transforms env
evalTransform p env (TransformId s) = do
(InstanceEx i) <- evalInstance p env s
pure $ TransformEx $ Transform i i (h i) (g i)
where
h i = foldr (\(gen,_) m -> Map.insert gen (Gen gen) m) Map.empty $ Map.toList $ IP.gens $ pres i
g i = foldr (\(sk ,_) m -> Map.insert sk (Sk sk) m) Map.empty $ Map.toList $ IP.sks $ pres i
evalTransform p env (TransformComp f g) = do
(TransformEx (f' :: Transform var ty sym en fk att gen sk x y gen' sk' x' y' )) <- evalTransform p env f
(TransformEx (g' :: Transform var2 ty2 sym2 en2 fk2 att2 gen2 sk2 x2 y2 gen'2 sk'2 x'2 y'2)) <- evalTransform p env g
z <- composeTransform f' (fromJust (cast g' :: Maybe (Transform var ty sym en fk att gen' sk' x' y' gen'2 sk'2 x'2 y'2)))
pure $ TransformEx z
evalTransform p env (TransformRaw r) = do
InstanceEx s <- evalInstance p env $ transraw_src r
InstanceEx (t :: Instance var ty sym en fk att gen sk x y) <- evalInstance p env $ transraw_dst r
is <- mapM (evalTransform p env) $ transraw_imports r
evalTransformRaw (fromJust (cast s)::Instance var ty sym en fk att gen sk x y) t r is
evalTransform prog env (TransformSigma f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(TransformEx (i' :: Transform var'' ty'' sym'' en'' fk'' att'' gen sk x y gen' sk' x' y')) <- evalTransform prog env i
o' <- toOptions (other env) o
r <- evalSigmaTrans f'' (fromJust (cast i' :: Maybe (Transform var ty sym en fk att gen sk x y gen' sk' x' y'))) o'
pure $ TransformEx r
evalTransform prog env (TransformDelta f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en' fk' att' en fk att)) <- evalMapping prog env f'
(TransformEx (i' :: Transform var'' ty'' sym'' en'' fk'' att'' gen sk x y gen' sk' x' y')) <- evalTransform prog env i
o' <- toOptions (other env) o
r <- evalDeltaTrans f'' (fromJust (cast i' :: Maybe (Transform var ty sym en fk att gen sk x y gen' sk' x' y'))) o'
pure $ TransformEx r
evalTransform prog env (TransformSigmaDeltaUnit f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y )) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalDeltaSigmaUnit f'' (fromJust (cast i' :: Maybe (Instance var ty sym en fk att gen sk x y))) o'
pure $ TransformEx r
evalTransform prog env (TransformSigmaDeltaCoUnit f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y )) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalDeltaSigmaCoUnit f'' (fromJust (cast i' :: Maybe (Instance var ty sym en' fk' att' gen sk x y))) o'
pure $ TransformEx r
evalTransform _ _ _ = error "todo"
evalMapping :: Prog -> Env -> MappingExp -> Err MappingEx
evalMapping _ env (MappingVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ mappings env
evalMapping p env (MappingComp f g) = do
(MappingEx (f' :: Mapping var ty sym en fk att en' fk' att' )) <- evalMapping p env f
(MappingEx (g' :: Mapping var2 ty2 sym2 en2 fk2 att2 en'2 fk'2 att'2)) <- evalMapping p env g
z <- composeMapping f' $ (fromJust (cast g' :: Maybe (Mapping var ty sym en' fk' att' en'2 fk'2 att'2)))
pure $ MappingEx z
evalMapping p env (MappingId s) = do
(SchemaEx s') <- evalSchema p env s
pure $ MappingEx $ foldr
(\en' (Mapping s'' t e f' a) -> Mapping s'' t (Map.insert en' en' e) (f'' en' s' f') (g' en' s' a))
(Mapping s' s' Map.empty Map.empty Map.empty) (S.ens s')
where
f'' en' s' f''' = foldr (\(fk, _) m -> Map.insert fk (Fk fk $ Var ()) m) f''' $ fksFrom' s' en'
g' en' s' f''' = foldr (\(fk, _) m -> Map.insert fk (Att fk $ Var ()) m) f''' $ attsFrom' s' en'
evalMapping p env (MappingRaw r) = do
SchemaEx s <- evalSchema p env $ mapraw_src r
SchemaEx (t::Schema var ty sym en fk att) <- evalSchema p env $ mapraw_dst r
ix <- mapM (evalMapping p env) $ mapraw_imports r
evalMappingRaw (fromJust (cast s) :: Schema var ty sym en fk att) t r ix
evalQuery :: Prog -> Env -> QueryExp -> Err QueryEx
evalQuery _ env (QueryVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ queries env
evalQuery _ _ _ = error "todo"
evalSchema :: Prog -> Env -> SchemaExp -> Err SchemaEx
evalSchema _ env (SchemaVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ schemas env
evalSchema prog env (SchemaInitial ts) = do
TypesideEx ts'' <- evalTypeside prog env ts
pure $ SchemaEx $ typesideToSchema ts''
evalSchema prog env (SchemaRaw r) = do
TypesideEx t' <- evalTypeside prog env $ schraw_ts r
x <- mapM (evalSchema prog env) $ schraw_imports r
evalSchemaRaw (other env) t' r x
evalSchema _ _ _ = undefined
evalInstance :: Prog -> Env -> InstanceExp -> Either String InstanceEx
evalInstance _ env (InstanceVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ instances env
evalInstance prog env (InstancePivot i) = do
InstanceEx i' <- evalInstance prog env i
let (_, i'', _) = pivot i'
return $ InstanceEx i''
evalInstance prog env (InstanceInitial s) = do
SchemaEx ts'' <- evalSchema prog env s
pure $ InstanceEx $ emptyInstance ts''
evalInstance prog env (InstanceRaw r) = do
SchemaEx t' <- evalSchema prog env $ instraw_schema r
i <- mapM (evalInstance prog env) (instraw_imports r)
evalInstanceRaw (other env) t' r i
evalInstance prog env (InstanceSigma f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y)) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalSigmaInst f'' (fromJust (cast i' :: Maybe (Instance var ty sym en fk att gen sk x y))) o'
return $ InstanceEx r
evalInstance prog env (InstanceDelta f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y)) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalDeltaInst f'' (fromJust (cast i' :: Maybe (Instance var ty sym en' fk' att' gen sk x y))) o'
return $ InstanceEx r
evalInstance _ _ _ = error "todo"
| null | https://raw.githubusercontent.com/statebox/cql/b155e737ef4977ec753e44790f236686ff6a4558/src/Language/CQL.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE ExplicitForAll #
# LANGUAGE FlexibleContexts #
# LANGUAGE GADTs #
# LANGUAGE LiberalTypeSynonyms #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
# LANGUAGE TypeSynonymInstances #
---------------------------------------------------------------------------------------------------------------
Type checking
Checking that @S@ is well-formed is done by 'validate'.
todo: requires breaking import cycle
----------------------------------------------------------------------------------------------------------
evaluation
---------------------------------------------------------------------------------------------------------- |
SPDX - License - Identifier : AGPL-3.0 - only
This file is part of ` statebox / cql ` , the categorical query language .
Copyright ( C ) 2019 <
This program is free software : you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
along with this program . If not , see < / > .
SPDX-License-Identifier: AGPL-3.0-only
This file is part of `statebox/cql`, the categorical query language.
Copyright (C) 2019 Stichting Statebox <>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see </>.
-}
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE ImpredicativeTypes #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
module Language.CQL where
import Control.Concurrent
import Control.DeepSeq
import Control.Exception
import Data.List (nub)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Typeable
import Language.CQL.Common as C
import Language.CQL.Graph
import Language.CQL.Instance as I
import qualified Language.CQL.Instance.Presentation as IP
import Language.CQL.Mapping as M
import Language.CQL.Options
import Language.CQL.Parser.Program (parseProgram)
import Language.CQL.Program as P
import Language.CQL.Query as Q
import Language.CQL.Schema as S
import Language.CQL.Term as Term
import Language.CQL.Transform as Tr
import Language.CQL.Typeside as T
import Prelude hiding (EQ, exp)
import System.IO.Unsafe
| Times out a computation after @i@ microseconds .
timeout' :: NFData x => Integer -> Err x -> Err x
timeout' i p = unsafePerformIO $ do
m <- newEmptyMVar
computer <- forkIO $ f m p
_ <- forkIO $ s m computer
takeMVar m
where
secs = (fromIntegral i) * 1000000
f m p0 = do
x <- evaluate $ force p0
putMVar m x
s m c = do
threadDelay secs
x <- tryTakeMVar m
case x of
Just y -> putMVar m y
Nothing -> do
putMVar m $ Left $ "Timeout after " ++ show i ++ " seconds."
killThread c
class Typecheck e e' where
typecheck :: Types -> e -> Err e'
| Checks that e.g. in @sigma F I@ that @F : S - > T@ and @I : S - Inst@.
typecheckCqlProgram :: [(String,Kind)] -> Prog -> Types -> Err Types
typecheckCqlProgram [] _ x = pure x
typecheckCqlProgram ((v, k):l) prog ts = do
m <- getKindCtx prog v k
t <- wrapError ("Type Error in " ++ v ++ ": ") $ typecheck' v ts m
typecheckCqlProgram l prog t
typecheck' :: String -> Types -> Exp -> Err Types
typecheck' v ts e = case e of
ExpTy e' -> do { t <- typecheck ts e'; return $ ts { typesides = Map.insert v t $ typesides ts } }
ExpS e' -> do { t <- typecheck ts e'; return $ ts { schemas = Map.insert v t $ schemas ts } }
ExpI e' -> do { t <- typecheck ts e'; return $ ts { instances = Map.insert v t $ instances ts } }
ExpM e' -> do { t <- typecheck ts e'; return $ ts { mappings = Map.insert v t $ mappings ts } }
ExpT e' -> do { t <- typecheck ts e'; return $ ts { transforms = Map.insert v t $ transforms ts } }
ExpQ e' -> do { t <- typecheck ts e'; return $ ts { queries = Map.insert v t $ queries ts } }
instance Typecheck TypesideExp TypesideExp where
typecheck = typecheckTypesideExp
instance Typecheck SchemaExp TypesideExp where
typecheck = typecheckSchemaExp
instance Typecheck InstanceExp SchemaExp where
typecheck = typecheckInstExp
instance Typecheck MappingExp (SchemaExp, SchemaExp) where
typecheck = typecheckMapExp
instance Typecheck TransformExp (InstanceExp, InstanceExp) where
typecheck = typecheckTransExp
instance Typecheck QueryExp (SchemaExp, SchemaExp) where
typecheck = error "todo typecheck query exp"
typecheckTransExp :: Types -> TransformExp -> Err (InstanceExp, InstanceExp)
typecheckTransExp p (TransformVar v) = note ("Undefined transform: " ++ show v) $ Map.lookup v $ transforms p
typecheckTransExp _ (TransformId s) = pure (s, s)
typecheckTransExp p (TransformComp f g) = do
(a, b) <- typecheckTransExp p f
(c, d) <- typecheckTransExp p g
if b == c
then pure (a, d)
else Left "Transform composition has non equal intermediate transforms"
typecheckTransExp p (TransformSigma f' h o) = do
(s, _) <- typecheckMapExp p f'
(i, j) <- typecheckTransExp p h
s' <- typecheckInstExp p i
if s == s'
then pure (InstanceSigma f' i o, InstanceSigma f' j o)
else Left "Source of mapping does not match instance schema"
typecheckTransExp p (TransformSigmaDeltaUnit f' i o) = do
(s, _) <- typecheckMapExp p f'
x <- typecheckInstExp p i
if s == x
then pure (i, InstanceDelta f' (InstanceSigma f' i o) o)
else Left "Source of mapping does not match instance schema"
typecheckTransExp p (TransformSigmaDeltaCoUnit f' i o) = do
(_, t) <- typecheckMapExp p f'
x <- typecheckInstExp p i
if t == x
then pure (i, InstanceSigma f' (InstanceDelta f' i o) o)
else Left "Target of mapping does not match instance schema"
typecheckTransExp p (TransformDelta f' h o) = do
(_, t) <- typecheckMapExp p f'
(i, j) <- typecheckTransExp p h
t' <- typecheckInstExp p i
if t == t'
then pure (InstanceDelta f' i o, InstanceDelta f' j o)
else Left "Target of mapping does not match instance schema"
typecheckTransExp p (TransformRaw r) = do
l' <- typecheckInstExp p $ transraw_src r
r' <- typecheckInstExp p $ transraw_dst r
if l' == r'
then pure (transraw_src r, transraw_src r)
else Left "Mapping has non equal schemas"
typecheckTransExp _ _ = error "todo"
typecheckMapExp :: Types -> MappingExp -> Err (SchemaExp, SchemaExp)
typecheckMapExp p (MappingVar v) = note ("Undefined mapping: " ++ show v) $ Map.lookup v $ mappings p
typecheckMapExp p (MappingComp f g) = do
(a, b) <- typecheckMapExp p f
(c, d) <- typecheckMapExp p g
if b == c
then pure (a, d)
else Left "Mapping composition has non equal intermediate schemas"
typecheckMapExp p (MappingId s) = do
_ <- typecheckSchemaExp p s
pure (s, s)
typecheckMapExp p (MappingRaw r) = do
l' <- typecheckSchemaExp p $ mapraw_src r
r' <- typecheckSchemaExp p $ mapraw_dst r
if l' == r'
then pure (mapraw_src r, mapraw_dst r)
else Left "Mapping has non equal typesides"
typecheckInstExp :: Types -> InstanceExp -> Err SchemaExp
typecheckInstExp p (InstanceVar v) = note ("Undefined instance: " ++ show v) $ Map.lookup v $ instances p
typecheckInstExp _ (InstanceInitial s) = pure s
typecheckInstExp _ (InstanceRaw r) = pure $ instraw_schema r
typecheckInstExp p (InstanceSigma f' i _) = do
(s, t) <- typecheckMapExp p f'
s' <- typecheckInstExp p i
if s == s'
then pure t
else Left "(Sigma): Instance not on mapping source."
typecheckInstExp p (InstanceDelta f' i _) = do
(s, t) <- typecheckMapExp p f'
t' <- typecheckInstExp p i
if t == t'
then pure s
else Left "(Delta): Instance not on mapping target."
typecheckInstExp _ _ = error "todo"
typecheckTypesideExp :: Types -> TypesideExp -> Err TypesideExp
typecheckTypesideExp p x = case x of
TypesideSql -> pure TypesideSql
TypesideInitial -> pure TypesideInitial
TypesideRaw r -> pure $ TypesideRaw r
TypesideVar v -> note ("Undefined typeside: " ++ show v) $ Map.lookup v $ typesides p
typecheckSchemaExp
:: Types -> SchemaExp -> Either String TypesideExp
typecheckSchemaExp p x = case x of
SchemaRaw r -> pure $ schraw_ts r
SchemaVar v -> note ("Undefined schema: " ++ show v) $ Map.lookup v $ schemas p
SchemaInitial t -> do { _ <- typecheckTypesideExp p t ; return t }
SchemaCoProd l r -> do
l' <- typecheckSchemaExp p l
r' <- typecheckSchemaExp p r
if l' == r'
then return l'
else Left "Coproduct has non equal typesides"
| The result of evaluating an CQL program .
type Env = KindCtx TypesideEx SchemaEx InstanceEx MappingEx QueryEx TransformEx Options
| Parse , , and evaluate the CQL program .
runProg :: String -> Err (Prog, Types, Env)
runProg srcText = do
progE <- parseProgram srcText
opts <- toOptions defaultOptions $ other progE
o <- findOrder progE
typesE <- typecheckCqlProgram o progE newTypes
envE <- evalCqlProgram o progE $ newEnv opts
return (progE, typesE, envE)
evalCqlProgram :: [(String,Kind)] -> Prog -> Env -> Err Env
evalCqlProgram [] _ env = pure env
evalCqlProgram ((v,k):l) prog env = do
e <- getKindCtx prog v k
ops <- toOptions (other env) $ getOptions' e
t <- wrapError ("Eval Error in " ++ v) $ timeout' (iOps ops Timeout) $ eval' prog env e
evalCqlProgram l prog $ setEnv env v t
findOrder :: Prog -> Err [(String, Kind)]
findOrder p@(KindCtx t s i m q tr _) = do
ret <- tsort g
pure $ reverse ret
where
g = Graph (allVars p) $ nub $ f0 t TYPESIDE ++ f0 s SCHEMA ++ f0 i INSTANCE ++ f0 m MAPPING ++ f0 q QUERY ++ f0 tr TRANSFORM
f0 m0 k = concatMap (\(v,e) -> [ ((v,k),x) | x <- deps e ]) $ Map.toList m0
class Evalable e e' | e' -> e, e -> e' where
validate :: e' -> Err ()
eval :: Prog -> Env -> e -> Err e'
getOptions :: e -> [(String, String)]
eval' :: Prog -> Env -> Exp -> Err Val
eval' p env e = case e of
ExpTy e' -> do { x <- eval p env e'; maybeValidate x; return $ ValTy x }
ExpS e' -> do { x <- eval p env e'; maybeValidate x; return $ ValS x }
ExpI e' -> do { x <- eval p env e'; maybeValidate x; return $ ValI x }
ExpM e' -> do { x <- eval p env e'; maybeValidate x; return $ ValM x }
ExpT e' -> do { x <- eval p env e'; maybeValidate x; return $ ValT x }
ExpQ e' -> do { x <- eval p env e'; maybeValidate x; return $ ValQ x }
where
maybeValidate :: Evalable exp val => val -> Err ()
maybeValidate val = do
ops <- toOptions (other env) $ getOptions' e
if bOps ops Dont_Validate_Unsafe then return () else validate val
getKindCtx :: Prog -> String -> Kind -> Err Exp
getKindCtx g v k = case k of
TYPESIDE -> fmap ExpTy $ n $ Map.lookup v $ typesides g
SCHEMA -> fmap ExpS $ n $ Map.lookup v $ schemas g
INSTANCE -> fmap ExpI $ n $ Map.lookup v $ instances g
MAPPING -> fmap ExpM $ n $ Map.lookup v $ mappings g
TRANSFORM -> fmap ExpT $ n $ Map.lookup v $ transforms g
QUERY -> fmap ExpQ $ n $ Map.lookup v $ queries g
_ -> error "todo"
where
n :: forall x. Maybe x -> Err x
n = note ("Undefined " ++ show k ++ ": " ++ v)
setEnv :: Env -> String -> Val -> Env
setEnv env v val = case val of
ValTy t -> env { typesides = Map.insert v t $ typesides env }
ValS t -> env { schemas = Map.insert v t $ schemas env }
ValI t -> env { instances = Map.insert v t $ instances env }
ValM t -> env { mappings = Map.insert v t $ mappings env }
ValT t -> env { transforms = Map.insert v t $ transforms env }
ValQ t -> env { queries = Map.insert v t $ queries env }
instance Evalable TypesideExp TypesideEx where
validate (TypesideEx x) = typecheckTypeside x
eval = evalTypeside
getOptions = getOptionsTypeside
instance Evalable SchemaExp SchemaEx where
validate (SchemaEx x) = typecheckSchema x
eval = evalSchema
getOptions = getOptionsSchema
instance Evalable InstanceExp InstanceEx where
validate (InstanceEx x) = do
IP.typecheck (schema x) (pres x)
I.satisfiesSchema x
eval prog env exp = do
i <- evalInstance prog env exp
o' <- toOptions (other env) $ getOptions exp
_ <- checkCons i $ bOps o' Require_Consistency
pure i
where
checkCons (InstanceEx i) True = if freeTalg i
then pure ()
else Left "Warning: type algebra not free. Set require_consistency = false to continue."
checkCons _ False = pure ()
getOptions = getOptionsInstance
instance Evalable MappingExp MappingEx where
validate (MappingEx x) = typecheckMapping x
eval = evalMapping
getOptions = getOptionsMapping
instance Evalable TransformExp TransformEx where
validate (TransformEx x) = typecheckTransform x
eval = evalTransform
getOptions = getOptionsTransform
instance Evalable QueryExp QueryEx where
validate (QueryEx x) = typecheckQuery x
eval = evalQuery
getOptions = getOptionsQuery
getOptions' :: Exp -> [(String, String)]
getOptions' e = case e of
ExpTy e' -> getOptions e'
ExpS e' -> getOptions e'
ExpI e' -> getOptions e'
ExpM e' -> getOptions e'
ExpT e' -> getOptions e'
ExpQ e' -> getOptions e'
evalTypeside :: Prog -> Env -> TypesideExp -> Err TypesideEx
evalTypeside _ _ TypesideInitial = pure $ TypesideEx initialTypeside
evalTypeside p e (TypesideRaw r) = do
x <- mapM (evalTypeside p e) $ tsraw_imports r
evalTypesideRaw (other e) r x
evalTypeside _ env (TypesideVar v) = case Map.lookup v $ typesides env of
Nothing -> Left $ "Undefined typeside: " ++ show v
Just (TypesideEx e) -> Right $ TypesideEx e
evalTypeside _ _ TypesideSql = pure $ TypesideEx $ sqlTypeside
evalTransform :: Prog -> Env -> TransformExp -> Err TransformEx
evalTransform _ env (TransformVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ transforms env
evalTransform p env (TransformId s) = do
(InstanceEx i) <- evalInstance p env s
pure $ TransformEx $ Transform i i (h i) (g i)
where
h i = foldr (\(gen,_) m -> Map.insert gen (Gen gen) m) Map.empty $ Map.toList $ IP.gens $ pres i
g i = foldr (\(sk ,_) m -> Map.insert sk (Sk sk) m) Map.empty $ Map.toList $ IP.sks $ pres i
evalTransform p env (TransformComp f g) = do
(TransformEx (f' :: Transform var ty sym en fk att gen sk x y gen' sk' x' y' )) <- evalTransform p env f
(TransformEx (g' :: Transform var2 ty2 sym2 en2 fk2 att2 gen2 sk2 x2 y2 gen'2 sk'2 x'2 y'2)) <- evalTransform p env g
z <- composeTransform f' (fromJust (cast g' :: Maybe (Transform var ty sym en fk att gen' sk' x' y' gen'2 sk'2 x'2 y'2)))
pure $ TransformEx z
evalTransform p env (TransformRaw r) = do
InstanceEx s <- evalInstance p env $ transraw_src r
InstanceEx (t :: Instance var ty sym en fk att gen sk x y) <- evalInstance p env $ transraw_dst r
is <- mapM (evalTransform p env) $ transraw_imports r
evalTransformRaw (fromJust (cast s)::Instance var ty sym en fk att gen sk x y) t r is
evalTransform prog env (TransformSigma f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(TransformEx (i' :: Transform var'' ty'' sym'' en'' fk'' att'' gen sk x y gen' sk' x' y')) <- evalTransform prog env i
o' <- toOptions (other env) o
r <- evalSigmaTrans f'' (fromJust (cast i' :: Maybe (Transform var ty sym en fk att gen sk x y gen' sk' x' y'))) o'
pure $ TransformEx r
evalTransform prog env (TransformDelta f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en' fk' att' en fk att)) <- evalMapping prog env f'
(TransformEx (i' :: Transform var'' ty'' sym'' en'' fk'' att'' gen sk x y gen' sk' x' y')) <- evalTransform prog env i
o' <- toOptions (other env) o
r <- evalDeltaTrans f'' (fromJust (cast i' :: Maybe (Transform var ty sym en fk att gen sk x y gen' sk' x' y'))) o'
pure $ TransformEx r
evalTransform prog env (TransformSigmaDeltaUnit f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y )) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalDeltaSigmaUnit f'' (fromJust (cast i' :: Maybe (Instance var ty sym en fk att gen sk x y))) o'
pure $ TransformEx r
evalTransform prog env (TransformSigmaDeltaCoUnit f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y )) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalDeltaSigmaCoUnit f'' (fromJust (cast i' :: Maybe (Instance var ty sym en' fk' att' gen sk x y))) o'
pure $ TransformEx r
evalTransform _ _ _ = error "todo"
evalMapping :: Prog -> Env -> MappingExp -> Err MappingEx
evalMapping _ env (MappingVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ mappings env
evalMapping p env (MappingComp f g) = do
(MappingEx (f' :: Mapping var ty sym en fk att en' fk' att' )) <- evalMapping p env f
(MappingEx (g' :: Mapping var2 ty2 sym2 en2 fk2 att2 en'2 fk'2 att'2)) <- evalMapping p env g
z <- composeMapping f' $ (fromJust (cast g' :: Maybe (Mapping var ty sym en' fk' att' en'2 fk'2 att'2)))
pure $ MappingEx z
evalMapping p env (MappingId s) = do
(SchemaEx s') <- evalSchema p env s
pure $ MappingEx $ foldr
(\en' (Mapping s'' t e f' a) -> Mapping s'' t (Map.insert en' en' e) (f'' en' s' f') (g' en' s' a))
(Mapping s' s' Map.empty Map.empty Map.empty) (S.ens s')
where
f'' en' s' f''' = foldr (\(fk, _) m -> Map.insert fk (Fk fk $ Var ()) m) f''' $ fksFrom' s' en'
g' en' s' f''' = foldr (\(fk, _) m -> Map.insert fk (Att fk $ Var ()) m) f''' $ attsFrom' s' en'
evalMapping p env (MappingRaw r) = do
SchemaEx s <- evalSchema p env $ mapraw_src r
SchemaEx (t::Schema var ty sym en fk att) <- evalSchema p env $ mapraw_dst r
ix <- mapM (evalMapping p env) $ mapraw_imports r
evalMappingRaw (fromJust (cast s) :: Schema var ty sym en fk att) t r ix
evalQuery :: Prog -> Env -> QueryExp -> Err QueryEx
evalQuery _ env (QueryVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ queries env
evalQuery _ _ _ = error "todo"
evalSchema :: Prog -> Env -> SchemaExp -> Err SchemaEx
evalSchema _ env (SchemaVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ schemas env
evalSchema prog env (SchemaInitial ts) = do
TypesideEx ts'' <- evalTypeside prog env ts
pure $ SchemaEx $ typesideToSchema ts''
evalSchema prog env (SchemaRaw r) = do
TypesideEx t' <- evalTypeside prog env $ schraw_ts r
x <- mapM (evalSchema prog env) $ schraw_imports r
evalSchemaRaw (other env) t' r x
evalSchema _ _ _ = undefined
evalInstance :: Prog -> Env -> InstanceExp -> Either String InstanceEx
evalInstance _ env (InstanceVar v) = note ("Could not find " ++ show v ++ " in ctx") $ Map.lookup v $ instances env
evalInstance prog env (InstancePivot i) = do
InstanceEx i' <- evalInstance prog env i
let (_, i'', _) = pivot i'
return $ InstanceEx i''
evalInstance prog env (InstanceInitial s) = do
SchemaEx ts'' <- evalSchema prog env s
pure $ InstanceEx $ emptyInstance ts''
evalInstance prog env (InstanceRaw r) = do
SchemaEx t' <- evalSchema prog env $ instraw_schema r
i <- mapM (evalInstance prog env) (instraw_imports r)
evalInstanceRaw (other env) t' r i
evalInstance prog env (InstanceSigma f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y)) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalSigmaInst f'' (fromJust (cast i' :: Maybe (Instance var ty sym en fk att gen sk x y))) o'
return $ InstanceEx r
evalInstance prog env (InstanceDelta f' i o) = do
(MappingEx (f'' :: Mapping var ty sym en fk att en' fk' att')) <- evalMapping prog env f'
(InstanceEx (i' :: Instance var'' ty'' sym'' en'' fk'' att'' gen sk x y)) <- evalInstance prog env i
o' <- toOptions (other env) o
r <- evalDeltaInst f'' (fromJust (cast i' :: Maybe (Instance var ty sym en' fk' att' gen sk x y))) o'
return $ InstanceEx r
evalInstance _ _ _ = error "todo"
|
50a56d487e5d0761c3db05769f6b5ecb3097f81679bcc8b5c15ef5b13219b656 | corecursive/sicp-study-group | exercise-1.3.scm | Exercise 1.3 .
;;
Define a procedure that takes three numbers as arguments and
returns the sum of the squares of the two larger numbers .
(define (square x) (* x x))
(define (sum-of-squares x y)
(+ (square x) (square y)))
(define (max x y)
(if (> x y) x y))
(define (min x y)
(if (< x y) x y))
(define (ex13 x y z)
(sum-of-squares (max x y)
(max z (min x y))))
(= (ex13 1 2 3) 13)
(= (ex13 1 3 2) 13)
(= (ex13 2 1 3) 13)
(= (ex13 2 3 1) 13)
(= (ex13 3 1 2) 13)
(= (ex13 3 2 1) 13)
(= (ex13 1 1 1) 2)
(= (ex13 1 1 2) 5)
(= (ex13 1 2 2) 8)
| null | https://raw.githubusercontent.com/corecursive/sicp-study-group/145b2d48ce0fd6108c4568b0c3d206fbea7a3fcf/wulab/exercises/exercise-1.3.scm | scheme | Exercise 1.3 .
Define a procedure that takes three numbers as arguments and
returns the sum of the squares of the two larger numbers .
(define (square x) (* x x))
(define (sum-of-squares x y)
(+ (square x) (square y)))
(define (max x y)
(if (> x y) x y))
(define (min x y)
(if (< x y) x y))
(define (ex13 x y z)
(sum-of-squares (max x y)
(max z (min x y))))
(= (ex13 1 2 3) 13)
(= (ex13 1 3 2) 13)
(= (ex13 2 1 3) 13)
(= (ex13 2 3 1) 13)
(= (ex13 3 1 2) 13)
(= (ex13 3 2 1) 13)
(= (ex13 1 1 1) 2)
(= (ex13 1 1 2) 5)
(= (ex13 1 2 2) 8)
|
|
603ee1f7aca517df45140eef30adead873ef08622fcb157da92558c1256a3dee | lambe-lang/nethra | t10_infer_function.ml | open Common
open Preface.Option.Functor
open Nethra.Lang.Ast.Term.Construct
open Nethra.Lang.Ast.Proof
open Nethra.Lang.Ast.Proof.Destruct
open Nethra.Lang.Ast.Hypothesis.Construct
open Nethra.Lang.Ast.Hypothesis.Access
open Nethra.Lang.System.Type
module Theory = struct
let type_in_type = true
end
module rec TypeInfer : Specs.Infer =
Infer.Impl (Theory) (Checker.Impl (Theory) (TypeInfer))
let infer_pi () =
let hypothesis = create
and term = pi "x" (kind 0) (id "x")
and expect = kind 0 in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"pi"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_explicit () =
let hypothesis = add_signature create ("plus", arrow (id "int") (id "int"))
and term = lambda "x" (apply (id "plus") (id "x"))
and expect = pi "x" (id "int") (id "int") in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_general_explicit () =
let hypothesis = create
and term = lambda "x" (id "x")
and expect = pi ~implicit:true "x" (kind 0) (pi "x" (id "x") (id "x")) in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda general explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_implicit () =
let hypothesis = add_signature create ("plus", arrow (id "int") (id "int"))
and term = lambda ~implicit:true "x" (apply (id "plus") (id "x"))
and expect = pi ~implicit:true "x" (id "int") (id "int") in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda implicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_general_implicit () =
let hypothesis = create
and term = lambda ~implicit:true "x" (id "x")
and expect =
pi ~implicit:true "x" (kind 0) (pi ~implicit:true "x" (id "x") (id "x"))
in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda general explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_apply_explicit () =
let hypothesis = add_signature create ("plus", arrow (id "int") (id "int"))
and term = apply (id "plus") (int 1)
and expect = id "int" in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"apply explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_apply_implicit () =
let hypothesis =
add_signature create ("plus", pi ~implicit:true "_" (id "int") (id "int"))
and term = apply ~implicit:true (id "plus") (int 1)
and expect = id "int" in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"apply implicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let cases =
let open Alcotest in
( "Infer function terms"
, [
test_case "Γ ⊢ (x:M) -> N : Type_0" `Quick infer_pi
; test_case "Γ ⊢ (x).(plus x) : (x:int) -> int" `Quick infer_lambda_explicit
; test_case "Γ ⊢ (x).x : {x:Type_0} -> (x:int) -> int" `Quick
infer_lambda_general_explicit
; test_case "Γ ⊢ {x}.(plus x) : {x:int} -> int" `Quick infer_lambda_implicit
; test_case "Γ ⊢ {x}.x :{x:Type_0} -> {x:int} -> int" `Quick
infer_lambda_general_implicit
; test_case "Γ ⊢ plus 1 : int" `Quick infer_apply_explicit
; test_case "Γ ⊢ plus {1} : int" `Quick infer_apply_implicit
] )
| null | https://raw.githubusercontent.com/lambe-lang/nethra/892b84deb9475021b95bfa6274dc8b70cb3e44ea/test/nethra/lang/system/s03_typer/t10_infer_function.ml | ocaml | open Common
open Preface.Option.Functor
open Nethra.Lang.Ast.Term.Construct
open Nethra.Lang.Ast.Proof
open Nethra.Lang.Ast.Proof.Destruct
open Nethra.Lang.Ast.Hypothesis.Construct
open Nethra.Lang.Ast.Hypothesis.Access
open Nethra.Lang.System.Type
module Theory = struct
let type_in_type = true
end
module rec TypeInfer : Specs.Infer =
Infer.Impl (Theory) (Checker.Impl (Theory) (TypeInfer))
let infer_pi () =
let hypothesis = create
and term = pi "x" (kind 0) (id "x")
and expect = kind 0 in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"pi"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_explicit () =
let hypothesis = add_signature create ("plus", arrow (id "int") (id "int"))
and term = lambda "x" (apply (id "plus") (id "x"))
and expect = pi "x" (id "int") (id "int") in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_general_explicit () =
let hypothesis = create
and term = lambda "x" (id "x")
and expect = pi ~implicit:true "x" (kind 0) (pi "x" (id "x") (id "x")) in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda general explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_implicit () =
let hypothesis = add_signature create ("plus", arrow (id "int") (id "int"))
and term = lambda ~implicit:true "x" (apply (id "plus") (id "x"))
and expect = pi ~implicit:true "x" (id "int") (id "int") in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda implicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_lambda_general_implicit () =
let hypothesis = create
and term = lambda ~implicit:true "x" (id "x")
and expect =
pi ~implicit:true "x" (kind 0) (pi ~implicit:true "x" (id "x") (id "x"))
in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"lambda general explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_apply_explicit () =
let hypothesis = add_signature create ("plus", arrow (id "int") (id "int"))
and term = apply (id "plus") (int 1)
and expect = id "int" in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"apply explicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let infer_apply_implicit () =
let hypothesis =
add_signature create ("plus", pi ~implicit:true "_" (id "int") (id "int"))
and term = apply ~implicit:true (id "plus") (int 1)
and expect = id "int" in
let proof = TypeInfer.(hypothesis |- term => ()) in
let term' = get_type proof in
Alcotest.(check (pair (option string) bool))
"apply implicit"
(Some (render expect), true)
(term' <&> render, is_success proof)
let cases =
let open Alcotest in
( "Infer function terms"
, [
test_case "Γ ⊢ (x:M) -> N : Type_0" `Quick infer_pi
; test_case "Γ ⊢ (x).(plus x) : (x:int) -> int" `Quick infer_lambda_explicit
; test_case "Γ ⊢ (x).x : {x:Type_0} -> (x:int) -> int" `Quick
infer_lambda_general_explicit
; test_case "Γ ⊢ {x}.(plus x) : {x:int} -> int" `Quick infer_lambda_implicit
; test_case "Γ ⊢ {x}.x :{x:Type_0} -> {x:int} -> int" `Quick
infer_lambda_general_implicit
; test_case "Γ ⊢ plus 1 : int" `Quick infer_apply_explicit
; test_case "Γ ⊢ plus {1} : int" `Quick infer_apply_implicit
] )
|
|
c57232ee33d1b656fb4b8595634b340dd2acb8896c7c8a57c3ac40690d4fbef3 | OCamlPro/operf-micro | option_array.mli |
include module type of Nullable_array_interface
| null | https://raw.githubusercontent.com/OCamlPro/operf-micro/d5d2bf2068204b889321b0c5a7bc0d079c0fca80/share/operf-micro/benchmarks/nullable_array/option_array.mli | ocaml |
include module type of Nullable_array_interface
|
|
6adb288579e3947436152f231c0a9a9d065b0e8408b762a49b3322dc3ffd69e7 | serokell/servant-util | Base.hs | module Servant.Util.Combinators.Sorting.Base
( SortingParams
, SortParamsExpanded
, SortingSpec (..)
, ssBase
, ssAll
, SortingOrder (..)
, NullsSortingOrder (..)
, SortingItemTagged (..)
, SortingItem (..)
, TaggedSortingItemsList
, SortingOrderType (..)
, ReifySortingItems (..)
, BaseSortingToParam
, AllSortingParams
, SortingParamProvidedOf
, SortingParamBaseOf
, SortingParamsOf
, SortingSpecOf
) where
import Universum
import Data.List (nubBy)
import Fmt (Buildable (..))
import GHC.TypeLits (KnownSymbol)
import Servant (QueryParam, (:>))
import Servant.API (NoContent)
import Servant.Server (Tagged (..))
import Servant.Util.Common
import qualified Text.Show
| Servant API combinator which allows to accept sorting parameters as a query parameter .
Example : with the following combinator
@
SortingParams [ " time " ? : Timestamp , " name " ? : Text ] ' [ ]
@
the endpoint can parse " sortBy=-time,+name " or " = desc(time),asc(name ) " formats ,
which would mean sorting by mentioned fields lexicographically . All sorting
subparameters are optional , as well as entire " sortBy " parameter .
The second type - level list stands for the base sorting order , it will be applied
in the end disregard the user 's input .
It is highly recommended to specify the base sorting that unambigously orders the
result(for example - by the primary key of the database ) , otherwise pagination
may behave unexpectedly for the client when it specifies no sorting .
If you want the base sorting order to be overridable by the user , you can
put the respective fields in both lists . For example , this combinator :
@
SortingParams
' [ " time " ? : Timestamp ]
[ " i d " ? : ' ( I d , ' Descendant ) , " time " ? : ' ( Timestamp , ' Ascendant ) ]
@
will sort results lexicographically by @(Down i d , time)@ , but if the client
specifies sorting by time , you will get sorting by @(time , Down id)@ as the
trailing @"time"@ will not affect anything .
It is preferred to put a base sorting at least by @ID@ , this way results will be
more deterministic .
Your handler will be provided with ' SortingSpec ' argument which can later be passed
in an appropriate function to perform sorting .
Example: with the following combinator
@
SortingParams ["time" ?: Timestamp, "name" ?: Text] '[]
@
the endpoint can parse "sortBy=-time,+name" or "sortBy=desc(time),asc(name)" formats,
which would mean sorting by mentioned fields lexicographically. All sorting
subparameters are optional, as well as entire "sortBy" parameter.
The second type-level list stands for the base sorting order, it will be applied
in the end disregard the user's input.
It is highly recommended to specify the base sorting that unambigously orders the
result(for example - by the primary key of the database), otherwise pagination
may behave unexpectedly for the client when it specifies no sorting.
If you want the base sorting order to be overridable by the user, you can
put the respective fields in both lists. For example, this combinator:
@
SortingParams
'["time" ?: Timestamp]
["id" ?: '(Id, 'Descendant), "time" ?: '(Timestamp, 'Ascendant)]
@
will sort results lexicographically by @(Down id, time)@, but if the client
specifies sorting by time, you will get sorting by @(time, Down id)@ as the
trailing @"time"@ will not affect anything.
It is preferred to put a base sorting at least by @ID@, this way results will be
more deterministic.
Your handler will be provided with 'SortingSpec' argument which can later be passed
in an appropriate function to perform sorting.
-}
data SortingParams
(provided :: [TyNamedParam *])
(base :: [TyNamedParam (SortingOrderType *)])
| How servant sees ' SortParams ' under the hood .
type SortParamsExpanded allowed subApi =
QueryParam "sortBy" (TaggedSortingItemsList allowed) :> subApi
-- | Order of sorting.
data SortingOrder
= Descendant
| Ascendant
deriving (Show, Eq, Enum)
-- | Where to place null fields.
data NullsSortingOrder
= NullsFirst
| NullsLast
deriving (Show, Eq, Enum)
-- | For a given field, user-supplied order of sorting.
-- This type is primarly for internal use, see also 'SortingItemTagged'.
data SortingItem = SortingItem
{ siName :: Text
-- ^ Name of parameter.
Always matches one in @param@ , but we keep it at term - level as well for convenience .
, siOrder :: SortingOrder
-- ^ Sorting order on the given parameter.
-- , siNullsOrder :: Maybe NullsSortingOrder
---- ^ Order of null fields.
-- Present only when the second element in @param@ tuple is ' Maybe ' .
-- TODO [ ] add support for this
} deriving (Show)
| Version ' SortingItem ' which remembers its name and parameter type at type level .
-- In functions which belong to public API you will most probably want to use this datatype
-- as a safer variant of 'SortingItem'.
newtype SortingItemTagged (provided :: TyNamedParam *) = SortingItemTagged
{ untagSortingItem :: SortingItem
} deriving (Show)
instance Buildable SortingItem where
build SortingItem{..} =
let order = case siOrder of { Ascendant -> "⯅ "; Descendant -> "⯆ " }
in order <> build siName
deriving instance Buildable (SortingItemTagged param)
-- | Tagged, because we want to retain list of allowed fields for parsing
-- (in @instance FromHttpApiData@).
type TaggedSortingItemsList provided = Tagged (provided :: [TyNamedParam *]) [SortingItem]
-- | Order of sorting for type-level.
--
Its constructors accept the type of thing we order by , e.g. @Asc Id@.
data SortingOrderType k
= Desc k
| Asc k
-- | What is passed to an endpoint, contains all sorting parameters provided by a user.
Following properties hold :
1 . Each entry in the underlying list has a unique name ( ' siName ' field ) .
2 . Entries correspond to @params@ type , i.e. any ' SortingItem ' entry of the underlying
list with name " N " will be present in @params@.
Not all parameters specified by @params@ phantom type can be present , e.g. the underlying
list will be empty if user did n't pass " sortBy " query parameter at all . However ,
entries from the base sorting are always present .
1. Each entry in the underlying list has a unique name ('siName' field).
2. Entries correspond to @params@ type, i.e. any 'SortingItem' entry of the underlying
list with name "N" will be present in @params@.
Not all parameters specified by @params@ phantom type can be present, e.g. the underlying
list will be empty if user didn't pass "sortBy" query parameter at all. However,
entries from the base sorting are always present.
-}
data SortingSpec
(provided :: [TyNamedParam *])
(base :: [TyNamedParam (SortingOrderType *)]) =
ReifySortingItems base =>
SortingSpec
{ ssProvided :: [SortingItem]
-- ^ Sorting items provided by the user (lexicographical order).
}
instance Show (SortingSpec provided base) where
show s =
"SortingSpec {ssProvided = " <> show (ssProvided s) <>
", ssBase = " <> show (ssBase s) <> "}"
-- | Base sorting items, that are present disregard the client's input
-- (lexicographical order).
--
-- This is a sort of virtual field, so such naming.
ssBase :: forall base provided. SortingSpec provided base -> [SortingItem]
ssBase SortingSpec{} = reifySortingItems @base
-- | Requires given type-level items to be valid specification of sorting.
class ReifySortingItems (items :: [TyNamedParam (SortingOrderType *)]) where
reifySortingItems :: [SortingItem]
instance ReifySortingItems '[] where
reifySortingItems = []
instance ( ReifySortingOrder order, KnownSymbol name
, ReifySortingItems items
) => ReifySortingItems ('TyNamedParam name (order field) ': items) where
reifySortingItems =
SortingItem
{ siName = symbolValT @name
, siOrder = reifySortingOrder @order
} : reifySortingItems @items
class ReifySortingOrder (order :: * -> SortingOrderType *) where
reifySortingOrder :: SortingOrder
instance ReifySortingOrder 'Asc where
reifySortingOrder = Ascendant
instance ReifySortingOrder 'Desc where
reifySortingOrder = Descendant
-- | All sorting items with duplicates removed (lexicographical order).
ssAll :: SortingSpec provided base -> [SortingItem]
ssAll s = nubBy ((==) `on` siName) (ssProvided s <> ssBase s)
| Maps @base@ params to the form common for @provided@ and
type family BaseSortingToParam (base :: [TyNamedParam (SortingOrderType *)])
:: [TyNamedParam *] where
BaseSortingToParam '[] = '[]
BaseSortingToParam ('TyNamedParam name (order field) ': xs) =
'TyNamedParam name field ': BaseSortingToParam xs
-- | All sorting params, provided + base.
--
-- This does not yet remove duplicates from @provided@ and @base@ sets,
-- we wait for specific use cases to decide how to handle this better.
type family AllSortingParams
(provided :: [TyNamedParam *])
(base :: [TyNamedParam (SortingOrderType *)])
:: [TyNamedParam *] where
AllSortingParams provided base = provided ++ BaseSortingToParam base
-- | For a given return type of an endpoint get corresponding sorting params
-- that can be specified by user.
-- This mapping is sensible, since we usually allow to sort only on fields appearing in
-- endpoint's response.
type family SortingParamProvidedOf a :: [TyNamedParam *]
-- | For a given return type of an endpoint get corresponding base sorting params.
type family SortingParamBaseOf a :: [TyNamedParam (SortingOrderType *)]
-- | This you will most probably want to specify in API.
type SortingParamsOf a = SortingParams (SortingParamProvidedOf a) (SortingParamBaseOf a)
-- | This you will most probably want to specify in an endpoint implementation.
type SortingSpecOf a = SortingSpec (SortingParamProvidedOf a) (SortingParamBaseOf a)
type instance SortingParamBaseOf NoContent = '[]
type instance SortingParamProvidedOf NoContent = '[]
| null | https://raw.githubusercontent.com/serokell/servant-util/290f0e6db5204ca64f54374a06bdc98cfbf4cda2/servant-util/src/Servant/Util/Combinators/Sorting/Base.hs | haskell | | Order of sorting.
| Where to place null fields.
| For a given field, user-supplied order of sorting.
This type is primarly for internal use, see also 'SortingItemTagged'.
^ Name of parameter.
^ Sorting order on the given parameter.
, siNullsOrder :: Maybe NullsSortingOrder
-- ^ Order of null fields.
Present only when the second element in @param@ tuple is ' Maybe ' .
TODO [ ] add support for this
In functions which belong to public API you will most probably want to use this datatype
as a safer variant of 'SortingItem'.
| Tagged, because we want to retain list of allowed fields for parsing
(in @instance FromHttpApiData@).
| Order of sorting for type-level.
| What is passed to an endpoint, contains all sorting parameters provided by a user.
^ Sorting items provided by the user (lexicographical order).
| Base sorting items, that are present disregard the client's input
(lexicographical order).
This is a sort of virtual field, so such naming.
| Requires given type-level items to be valid specification of sorting.
| All sorting items with duplicates removed (lexicographical order).
| All sorting params, provided + base.
This does not yet remove duplicates from @provided@ and @base@ sets,
we wait for specific use cases to decide how to handle this better.
| For a given return type of an endpoint get corresponding sorting params
that can be specified by user.
This mapping is sensible, since we usually allow to sort only on fields appearing in
endpoint's response.
| For a given return type of an endpoint get corresponding base sorting params.
| This you will most probably want to specify in API.
| This you will most probably want to specify in an endpoint implementation. | module Servant.Util.Combinators.Sorting.Base
( SortingParams
, SortParamsExpanded
, SortingSpec (..)
, ssBase
, ssAll
, SortingOrder (..)
, NullsSortingOrder (..)
, SortingItemTagged (..)
, SortingItem (..)
, TaggedSortingItemsList
, SortingOrderType (..)
, ReifySortingItems (..)
, BaseSortingToParam
, AllSortingParams
, SortingParamProvidedOf
, SortingParamBaseOf
, SortingParamsOf
, SortingSpecOf
) where
import Universum
import Data.List (nubBy)
import Fmt (Buildable (..))
import GHC.TypeLits (KnownSymbol)
import Servant (QueryParam, (:>))
import Servant.API (NoContent)
import Servant.Server (Tagged (..))
import Servant.Util.Common
import qualified Text.Show
| Servant API combinator which allows to accept sorting parameters as a query parameter .
Example : with the following combinator
@
SortingParams [ " time " ? : Timestamp , " name " ? : Text ] ' [ ]
@
the endpoint can parse " sortBy=-time,+name " or " = desc(time),asc(name ) " formats ,
which would mean sorting by mentioned fields lexicographically . All sorting
subparameters are optional , as well as entire " sortBy " parameter .
The second type - level list stands for the base sorting order , it will be applied
in the end disregard the user 's input .
It is highly recommended to specify the base sorting that unambigously orders the
result(for example - by the primary key of the database ) , otherwise pagination
may behave unexpectedly for the client when it specifies no sorting .
If you want the base sorting order to be overridable by the user , you can
put the respective fields in both lists . For example , this combinator :
@
SortingParams
' [ " time " ? : Timestamp ]
[ " i d " ? : ' ( I d , ' Descendant ) , " time " ? : ' ( Timestamp , ' Ascendant ) ]
@
will sort results lexicographically by @(Down i d , time)@ , but if the client
specifies sorting by time , you will get sorting by @(time , Down id)@ as the
trailing @"time"@ will not affect anything .
It is preferred to put a base sorting at least by @ID@ , this way results will be
more deterministic .
Your handler will be provided with ' SortingSpec ' argument which can later be passed
in an appropriate function to perform sorting .
Example: with the following combinator
@
SortingParams ["time" ?: Timestamp, "name" ?: Text] '[]
@
the endpoint can parse "sortBy=-time,+name" or "sortBy=desc(time),asc(name)" formats,
which would mean sorting by mentioned fields lexicographically. All sorting
subparameters are optional, as well as entire "sortBy" parameter.
The second type-level list stands for the base sorting order, it will be applied
in the end disregard the user's input.
It is highly recommended to specify the base sorting that unambigously orders the
result(for example - by the primary key of the database), otherwise pagination
may behave unexpectedly for the client when it specifies no sorting.
If you want the base sorting order to be overridable by the user, you can
put the respective fields in both lists. For example, this combinator:
@
SortingParams
'["time" ?: Timestamp]
["id" ?: '(Id, 'Descendant), "time" ?: '(Timestamp, 'Ascendant)]
@
will sort results lexicographically by @(Down id, time)@, but if the client
specifies sorting by time, you will get sorting by @(time, Down id)@ as the
trailing @"time"@ will not affect anything.
It is preferred to put a base sorting at least by @ID@, this way results will be
more deterministic.
Your handler will be provided with 'SortingSpec' argument which can later be passed
in an appropriate function to perform sorting.
-}
data SortingParams
(provided :: [TyNamedParam *])
(base :: [TyNamedParam (SortingOrderType *)])
| How servant sees ' SortParams ' under the hood .
type SortParamsExpanded allowed subApi =
QueryParam "sortBy" (TaggedSortingItemsList allowed) :> subApi
data SortingOrder
= Descendant
| Ascendant
deriving (Show, Eq, Enum)
data NullsSortingOrder
= NullsFirst
| NullsLast
deriving (Show, Eq, Enum)
data SortingItem = SortingItem
{ siName :: Text
Always matches one in @param@ , but we keep it at term - level as well for convenience .
, siOrder :: SortingOrder
} deriving (Show)
| Version ' SortingItem ' which remembers its name and parameter type at type level .
newtype SortingItemTagged (provided :: TyNamedParam *) = SortingItemTagged
{ untagSortingItem :: SortingItem
} deriving (Show)
instance Buildable SortingItem where
build SortingItem{..} =
let order = case siOrder of { Ascendant -> "⯅ "; Descendant -> "⯆ " }
in order <> build siName
deriving instance Buildable (SortingItemTagged param)
type TaggedSortingItemsList provided = Tagged (provided :: [TyNamedParam *]) [SortingItem]
Its constructors accept the type of thing we order by , e.g. @Asc Id@.
data SortingOrderType k
= Desc k
| Asc k
Following properties hold :
1 . Each entry in the underlying list has a unique name ( ' siName ' field ) .
2 . Entries correspond to @params@ type , i.e. any ' SortingItem ' entry of the underlying
list with name " N " will be present in @params@.
Not all parameters specified by @params@ phantom type can be present , e.g. the underlying
list will be empty if user did n't pass " sortBy " query parameter at all . However ,
entries from the base sorting are always present .
1. Each entry in the underlying list has a unique name ('siName' field).
2. Entries correspond to @params@ type, i.e. any 'SortingItem' entry of the underlying
list with name "N" will be present in @params@.
Not all parameters specified by @params@ phantom type can be present, e.g. the underlying
list will be empty if user didn't pass "sortBy" query parameter at all. However,
entries from the base sorting are always present.
-}
data SortingSpec
(provided :: [TyNamedParam *])
(base :: [TyNamedParam (SortingOrderType *)]) =
ReifySortingItems base =>
SortingSpec
{ ssProvided :: [SortingItem]
}
instance Show (SortingSpec provided base) where
show s =
"SortingSpec {ssProvided = " <> show (ssProvided s) <>
", ssBase = " <> show (ssBase s) <> "}"
ssBase :: forall base provided. SortingSpec provided base -> [SortingItem]
ssBase SortingSpec{} = reifySortingItems @base
class ReifySortingItems (items :: [TyNamedParam (SortingOrderType *)]) where
reifySortingItems :: [SortingItem]
instance ReifySortingItems '[] where
reifySortingItems = []
instance ( ReifySortingOrder order, KnownSymbol name
, ReifySortingItems items
) => ReifySortingItems ('TyNamedParam name (order field) ': items) where
reifySortingItems =
SortingItem
{ siName = symbolValT @name
, siOrder = reifySortingOrder @order
} : reifySortingItems @items
class ReifySortingOrder (order :: * -> SortingOrderType *) where
reifySortingOrder :: SortingOrder
instance ReifySortingOrder 'Asc where
reifySortingOrder = Ascendant
instance ReifySortingOrder 'Desc where
reifySortingOrder = Descendant
ssAll :: SortingSpec provided base -> [SortingItem]
ssAll s = nubBy ((==) `on` siName) (ssProvided s <> ssBase s)
| Maps @base@ params to the form common for @provided@ and
type family BaseSortingToParam (base :: [TyNamedParam (SortingOrderType *)])
:: [TyNamedParam *] where
BaseSortingToParam '[] = '[]
BaseSortingToParam ('TyNamedParam name (order field) ': xs) =
'TyNamedParam name field ': BaseSortingToParam xs
type family AllSortingParams
(provided :: [TyNamedParam *])
(base :: [TyNamedParam (SortingOrderType *)])
:: [TyNamedParam *] where
AllSortingParams provided base = provided ++ BaseSortingToParam base
type family SortingParamProvidedOf a :: [TyNamedParam *]
type family SortingParamBaseOf a :: [TyNamedParam (SortingOrderType *)]
type SortingParamsOf a = SortingParams (SortingParamProvidedOf a) (SortingParamBaseOf a)
type SortingSpecOf a = SortingSpec (SortingParamProvidedOf a) (SortingParamBaseOf a)
type instance SortingParamBaseOf NoContent = '[]
type instance SortingParamProvidedOf NoContent = '[]
|
8267b2ca3e87a89e097d9fe89e2204772fe6bb92d27e26f98b0eae035a380683 | brendanhay/terrafomo | Provider.hs | -- This module is auto-generated.
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# OPTIONS_GHC -fno - warn - unused - imports #
-- |
Module : . OVH.Provider
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
module Terrafomo.OVH.Provider
(
-- * OVH Specific Aliases
Provider
, DataSource
, Resource
-- * OVH Configuration
, currentVersion
, newProvider
, OVH (..)
, OVH_Required (..)
) where
import Data.Function ((&))
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import Data.Version (Version, makeVersion, showVersion)
import GHC.Base (($))
import Terrafomo.OVH.Settings
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.OVH.Types as P
import qualified Terrafomo.Schema as TF
type Provider = TF.Provider OVH
type DataSource = TF.Resource OVH TF.Ignored
type Resource = TF.Resource OVH TF.Meta
type instance TF.ProviderName OVH = "ovh"
currentVersion :: Version
currentVersion = makeVersion [0, 3, 0]
| The @ovh@ Terraform provider configuration .
data OVH = OVH_Internal
{ application_key :: P.Maybe P.Text
-- ^ @application_key@
-- - (Optional)
The OVH API Application Key .
, application_secret :: P.Maybe P.Text
-- ^ @application_secret@
-- - (Optional)
The OVH API Application Secret .
, consumer_key :: P.Maybe P.Text
-- ^ @consumer_key@
-- - (Optional)
The OVH API Consumer key .
, endpoint :: P.Text
^ @endpoint@
-- - (Required)
The OVH API endpoint to target ( ex : " ovh - eu " ) .
} deriving (P.Show)
| Specify a new OVH provider configuration .
See the < terraform documentation > for more information .
See the < terraform documentation> for more information.
-}
newProvider
:: OVH_Required -- ^ The minimal/required arguments.
-> Provider
newProvider x =
TF.Provider
{ TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion)
, TF.providerConfig =
(let OVH{..} = x in OVH_Internal
{ application_key = P.Nothing
, application_secret = P.Nothing
, consumer_key = P.Nothing
, endpoint = endpoint
})
, TF.providerEncoder =
(\OVH_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "application_key") application_key
<> P.maybe P.mempty (TF.pair "application_secret") application_secret
<> P.maybe P.mempty (TF.pair "consumer_key") consumer_key
<> TF.pair "endpoint" endpoint
)
}
-- | The required arguments for 'newProvider'.
data OVH_Required = OVH
{ endpoint :: P.Text
-- ^ (Required)
The OVH API endpoint to target ( ex : " ovh - eu " ) .
} deriving (P.Show)
instance Lens.HasField "application_key" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(application_key :: OVH -> P.Maybe P.Text)
(\s a -> s { application_key = a } :: OVH)
instance Lens.HasField "application_secret" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(application_secret :: OVH -> P.Maybe P.Text)
(\s a -> s { application_secret = a } :: OVH)
instance Lens.HasField "consumer_key" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(consumer_key :: OVH -> P.Maybe P.Text)
(\s a -> s { consumer_key = a } :: OVH)
instance Lens.HasField "endpoint" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(endpoint :: OVH -> P.Text)
(\s a -> s { endpoint = a } :: OVH)
| null | https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-ovh/gen/Terrafomo/OVH/Provider.hs | haskell | This module is auto-generated.
|
Stability : auto-generated
* OVH Specific Aliases
* OVH Configuration
^ @application_key@
- (Optional)
^ @application_secret@
- (Optional)
^ @consumer_key@
- (Optional)
- (Required)
^ The minimal/required arguments.
| The required arguments for 'newProvider'.
^ (Required) |
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# OPTIONS_GHC -fno - warn - unused - imports #
Module : . OVH.Provider
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Terrafomo.OVH.Provider
(
Provider
, DataSource
, Resource
, currentVersion
, newProvider
, OVH (..)
, OVH_Required (..)
) where
import Data.Function ((&))
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import Data.Version (Version, makeVersion, showVersion)
import GHC.Base (($))
import Terrafomo.OVH.Settings
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.OVH.Types as P
import qualified Terrafomo.Schema as TF
type Provider = TF.Provider OVH
type DataSource = TF.Resource OVH TF.Ignored
type Resource = TF.Resource OVH TF.Meta
type instance TF.ProviderName OVH = "ovh"
currentVersion :: Version
currentVersion = makeVersion [0, 3, 0]
| The @ovh@ Terraform provider configuration .
data OVH = OVH_Internal
{ application_key :: P.Maybe P.Text
The OVH API Application Key .
, application_secret :: P.Maybe P.Text
The OVH API Application Secret .
, consumer_key :: P.Maybe P.Text
The OVH API Consumer key .
, endpoint :: P.Text
^ @endpoint@
The OVH API endpoint to target ( ex : " ovh - eu " ) .
} deriving (P.Show)
| Specify a new OVH provider configuration .
See the < terraform documentation > for more information .
See the < terraform documentation> for more information.
-}
newProvider
-> Provider
newProvider x =
TF.Provider
{ TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion)
, TF.providerConfig =
(let OVH{..} = x in OVH_Internal
{ application_key = P.Nothing
, application_secret = P.Nothing
, consumer_key = P.Nothing
, endpoint = endpoint
})
, TF.providerEncoder =
(\OVH_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "application_key") application_key
<> P.maybe P.mempty (TF.pair "application_secret") application_secret
<> P.maybe P.mempty (TF.pair "consumer_key") consumer_key
<> TF.pair "endpoint" endpoint
)
}
data OVH_Required = OVH
{ endpoint :: P.Text
The OVH API endpoint to target ( ex : " ovh - eu " ) .
} deriving (P.Show)
instance Lens.HasField "application_key" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(application_key :: OVH -> P.Maybe P.Text)
(\s a -> s { application_key = a } :: OVH)
instance Lens.HasField "application_secret" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(application_secret :: OVH -> P.Maybe P.Text)
(\s a -> s { application_secret = a } :: OVH)
instance Lens.HasField "consumer_key" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(consumer_key :: OVH -> P.Maybe P.Text)
(\s a -> s { consumer_key = a } :: OVH)
instance Lens.HasField "endpoint" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(endpoint :: OVH -> P.Text)
(\s a -> s { endpoint = a } :: OVH)
|
f2598ec9647559345923cb2a2869cbefc4c52d63b3a32257559525c73d29c949 | xmonad/xmonad-contrib | Place.hs | # LANGUAGE TupleSections #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.Place
-- Description : Automatic placement of floating windows.
Copyright : < >
-- License : BSD-style (see LICENSE)
--
-- Maintainer : orphaned
-- Stability : unstable
-- Portability : unportable
--
-- Automatic placement of floating windows.
--
-----------------------------------------------------------------------------
module XMonad.Hooks.Place ( -- * Usage
-- $usage
-- * Placement actions
placeFocused
, placeHook
-- * Placement policies
-- $placements
, Placement
, smart
, simpleSmart
, fixed
, underMouse
, inBounds
, withGaps
-- * Others
, purePlaceWindow ) where
import XMonad
import XMonad.Prelude
import qualified XMonad.StackSet as S
import XMonad.Layout.WindowArranger
import XMonad.Actions.FloatKeys
import qualified Data.Map as M
import Data.Ratio ((%))
import Control.Monad.Trans (lift)
-- $usage
This module provides a ' ManageHook ' that automatically places
-- floating windows at appropriate positions on the screen, as well
-- as an 'X' action to manually trigger repositioning.
--
-- You can use this module by including the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Hooks.Place
--
-- and adding 'placeHook' to your 'manageHook', for example:
--
> main = xmonad $ def { manageHook = placeHook simpleSmart
-- > <> manageHook def }
--
-- Note that 'placeHook' should be applied after most other hooks, especially hooks
-- such as 'doFloat' and 'doShift'. Since hooks combined with '<>' are applied from
-- right to left, this means that 'placeHook' should be the /first/ hook in your chain.
--
-- You can also define a key to manually trigger repositioning with 'placeFocused' by
-- adding the following to your keys definition:
--
> , ( ( modm , xK_w ) , )
--
-- Both 'placeHook' and 'placeFocused' take a 'Placement' parameter, which specifies
-- the placement policy to use (smart, under the mouse, fixed position, etc.). See
-- 'Placement' for a list of available policies.
{- Placement policies -}
-- $placements
-- Placement policies determine how windows will be placed by 'placeFocused' and 'placeHook'.
--
-- A few examples:
--
-- * Basic smart placement
--
-- > myPlacement = simpleSmart
--
-- * Under the mouse (pointer at the top-left corner), but constrained
-- inside of the screen area
--
-- > myPlacement = inBounds (underMouse (0, 0))
--
-- * Smart placement with a preference for putting windows near
-- the center of the screen, and with 16px gaps at the top and bottom
-- of the screen where no window will be placed
--
> myPlacement = withGaps ( 16,0,16,0 ) ( smart ( 0.5,0.5 ) )
-- | The type of placement policies
data Placement = Smart (Rational, Rational)
| Fixed (Rational, Rational)
| UnderMouse (Rational, Rational)
| Bounds (Dimension, Dimension, Dimension, Dimension) Placement
deriving (Show, Read, Eq)
-- | Try to place windows with as little overlap as possible
smart :: (Rational, Rational) -- ^ Where the window should be placed inside
-- the available area. See 'fixed'.
-> Placement
smart = Smart
simpleSmart :: Placement
simpleSmart = inBounds $ smart (0,0)
-- | Place windows at a fixed position
fixed :: (Rational, Rational) -- ^ Where windows should go.
--
* ( 0,0 ) - > top left of the screen
--
* ( 1,0 ) - > top right of the screen
--
-- * etc
-> Placement
fixed = Fixed
-- | Place windows under the mouse
underMouse :: (Rational, Rational) -- ^ Where the pointer should be relative to
-- the window's frame; see 'fixed'.
-> Placement
underMouse = UnderMouse
-- | Apply the given placement policy, constraining the
-- placed windows inside the screen boundaries.
inBounds :: Placement -> Placement
inBounds = Bounds (0,0,0,0)
-- | Same as 'inBounds', but allows specifying gaps along the screen's edges
withGaps :: (Dimension, Dimension, Dimension, Dimension)
-- ^ top, right, bottom and left gaps
-> Placement -> Placement
withGaps = Bounds
{- Placement functions -}
-- | Repositions the focused window according to a placement policy. Works for
both \"real\ " floating windows and windows in a '
-- layout.
placeFocused :: Placement -> X ()
placeFocused p = withFocused $ \window -> do
info <- gets $ screenInfo . S.current . windowset
floats <- gets $ M.keys . S.floating . windowset
r'@(Rectangle x' y' _ _) <- placeWindow p window info floats
use X.A.FloatKeys if the window is floating , send
-- a WindowArranger message otherwise.
if window `elem` floats
then keysMoveWindowTo (x', y') (0, 0) window
else sendMessage $ SetGeometry r'
-- | Hook to automatically place windows when they are created.
placeHook :: Placement -> ManageHook
placeHook p = do window <- ask
r <- Query $ lift $ getWindowRectangle window
allRs <- Query $ lift getAllRectangles
pointer <- Query $ lift $ getPointer window
return $ Endo $ \theWS -> fromMaybe theWS $
do let currentRect = screenRect $ S.screenDetail $ S.current theWS
floats = M.keys $ S.floating theWS
guard(window `elem` floats )
-- Look for the workspace(s) on which the window is to be
-- spawned. Each of them also needs an associated screen
-- rectangle; for hidden workspaces, we use the current
-- workspace's screen.
let infos = filter ((window `elem`) . stackContents . S.stack . fst)
$ [screenInfo $ S.current theWS]
++ map screenInfo (S.visible theWS)
++ map (, currentRect) (S.hidden theWS)
guard(not $ null infos)
let (workspace, screen) = head infos
rs = mapMaybe (`M.lookup` allRs)
$ organizeClients workspace window floats
r' = purePlaceWindow p screen rs pointer r
newRect = r2rr screen r'
newFloats = M.insert window newRect (S.floating theWS)
return $ theWS { S.floating = newFloats }
placeWindow :: Placement -> Window
-> (S.Workspace WorkspaceId (Layout Window) Window, Rectangle)
-- ^ The workspace with reference to which the window should be placed,
-- and the screen's geometry.
-> [Window]
-- ^ The list of floating windows.
-> X Rectangle
placeWindow p window (ws, s) floats
= do (r, rs, pointer) <- getNecessaryData window ws floats
return $ purePlaceWindow p s rs pointer r
-- | Compute the new position of a window according to a placement policy.
purePlaceWindow :: Placement -- ^ The placement strategy
-> Rectangle -- ^ The screen
-> [Rectangle] -- ^ The other visible windows
-> (Position, Position) -- ^ The pointer's position.
-> Rectangle -- ^ The window to be placed
-> Rectangle
purePlaceWindow (Bounds (t,r,b,l) p') (Rectangle sx sy sw sh) rs p w
= let s' = Rectangle (sx + fi l) (sy + fi t) (sw - l - r) (sh - t - b)
in checkBounds s' $ purePlaceWindow p' s' rs p w
purePlaceWindow (Fixed ratios) s _ _ w = placeRatio ratios s w
purePlaceWindow (UnderMouse (rx, ry)) _ _ (px, py) (Rectangle _ _ w h)
= Rectangle (px - truncate (rx * fi w)) (py - truncate (ry * fi h)) w h
purePlaceWindow (Smart ratios) s rs _ w
= placeSmart ratios s rs (rect_width w) (rect_height w)
| Helper : Places a Rectangle at a fixed position indicated by two Rationals
-- inside another,
placeRatio :: (Rational, Rational) -> Rectangle -> Rectangle -> Rectangle
placeRatio (rx, ry) (Rectangle x1 y1 w1 h1) (Rectangle _ _ w2 h2)
= Rectangle (scale rx x1 (x1 + fi w1 - fi w2))
(scale ry y1 (y1 + fi h1 - fi h2))
w2 h2
| Helper : Ensures its second parameter is contained inside the first
-- by possibly moving it.
checkBounds :: Rectangle -> Rectangle -> Rectangle
checkBounds (Rectangle x1 y1 w1 h1) (Rectangle x2 y2 w2 h2)
= Rectangle (max x1 (min (x1 + fi w1 - fi w2) x2))
(max y1 (min (y1 + fi h1 - fi h2) y2))
w2 h2
Utilities
scale :: (RealFrac a, Integral b) => a -> b -> b -> b
scale r n1 n2 = truncate $ r * fi n2 + (1 - r) * fi n1
r2rr :: Rectangle -> Rectangle -> S.RationalRect
r2rr (Rectangle x0 y0 w0 h0) (Rectangle x y w h)
= S.RationalRect ((fi x-fi x0) % fi w0)
((fi y-fi y0) % fi h0)
(fi w % fi w0)
(fi h % fi h0)
{- Querying stuff -}
stackContents :: Maybe (S.Stack w) -> [w]
stackContents = maybe [] S.integrate
screenInfo :: S.Screen i l a sid ScreenDetail -> (S.Workspace i l a, Rectangle)
screenInfo S.Screen{ S.workspace = ws, S.screenDetail = (SD s)} = (ws, s)
getWindowRectangle :: Window -> X Rectangle
getWindowRectangle window
= do d <- asks display
(_, x, y, w, h, _, _) <- io $ getGeometry d window
-- We can't use the border width returned by
-- getGeometry because it will be 0 if the
-- window isn't mapped yet.
b <- asks $ borderWidth . config
return $ Rectangle x y (w + 2*b) (h + 2*b)
getAllRectangles :: X (M.Map Window Rectangle)
getAllRectangles = do ws <- gets windowset
let allWindows = join $ map (stackContents . S.stack)
$ (S.workspace . S.current) ws
: (map S.workspace . S.visible) ws
++ S.hidden ws
allRects <- mapM getWindowRectangle allWindows
return $ M.fromList $ zip allWindows allRects
organizeClients :: S.Workspace a b Window -> Window -> [Window] -> [Window]
organizeClients ws w floats
= let (floatCs, layoutCs) = partition (`elem` floats) $ filter (/= w)
$ stackContents $ S.stack ws
in reverse layoutCs ++ reverse floatCs
-- About the ordering: the smart algorithm will overlap windows
-- starting ith the head of the list. So:
- we put the non - floating windows first since they 'll
-- probably be below the floating ones,
-- - we reverse the lists, since the newer/more important
-- windows are usually near the head.
getPointer :: Window -> X (Position, Position)
getPointer window = do d <- asks display
(_,_,_,x,y,_,_,_) <- io $ queryPointer d window
return (fi x,fi y)
-- | Return values are, in order: window's rectangle,
-- other windows' rectangles and pointer's coordinates.
getNecessaryData :: Window
-> S.Workspace WorkspaceId (Layout Window) Window
-> [Window]
-> X (Rectangle, [Rectangle], (Position, Position))
getNecessaryData window ws floats
= do r <- getWindowRectangle window
rs <- mapM getWindowRectangle (organizeClients ws window floats)
pointer <- getPointer window
return (r, rs, pointer)
Smart placement algorithm
-- | Alternate representation for rectangles.
data SmartRectangle a = SR
{ sr_x0, sr_y0 :: a -- ^ Top left coordinates, inclusive
, sr_x1, sr_y1 :: a -- ^ Bottom right coorsinates, exclusive
} deriving (Show, Eq)
r2sr :: Rectangle -> SmartRectangle Position
r2sr (Rectangle x y w h) = SR x y (x + fi w) (y + fi h)
sr2r :: SmartRectangle Position -> Rectangle
sr2r (SR x0 y0 x1 y1) = Rectangle x0 y0 (fi $ x1 - x0) (fi $ y1 - y0)
width :: Num a => SmartRectangle a -> a
width r = sr_x1 r - sr_x0 r
height :: Num a => SmartRectangle a -> a
height r = sr_y1 r - sr_y0 r
isEmpty :: Real a => SmartRectangle a -> Bool
isEmpty r = (width r <= 0) || (height r <= 0)
contains :: Real a => SmartRectangle a -> SmartRectangle a -> Bool
contains r1 r2 = sr_x0 r1 <= sr_x0 r2
&& sr_y0 r1 <= sr_y0 r2
&& sr_x1 r1 >= sr_x1 r2
&& sr_y1 r1 >= sr_y1 r2
-- | Main placement function
placeSmart :: (Rational, Rational) -- ^ point of the screen where windows
should be placed first , if possible .
-> Rectangle -- ^ screen
-> [Rectangle] -- ^ other clients
-> Dimension -- ^ width
-> Dimension -- ^ height
-> Rectangle
placeSmart (rx, ry) s@(Rectangle sx sy sw sh) rs w h
= let free = map sr2r $ findSpace (r2sr s) (map r2sr rs) (fi w) (fi h)
in position free (scale rx sx (sx + fi sw - fi w))
(scale ry sy (sy + fi sh - fi h))
w h
| Second part of the algorithm :
-- Chooses the best position in which to place a window,
-- according to a list of free areas and an ideal position for
-- the top-left corner.
-- We can't use semi-open surfaces for this, so we go back to
X11 Rectangles / Positions / etc instead .
position :: [Rectangle] -- ^ Free areas
-> Position -> Position -- ^ Ideal coordinates
-> Dimension -> Dimension -- ^ Width and height of the window
-> Rectangle
position rs x y w h = minimumBy distanceOrder $ map closest rs
where distanceOrder r1 r2
= compare (distance (rect_x r1,rect_y r1) (x,y) :: Dimension)
(distance (rect_x r2,rect_y r2) (x,y) :: Dimension)
distance (x1,y1) (x2,y2) = truncate $ (sqrt :: Double -> Double)
$ fi $ (x1 - x2)^(2::Int)
+ (y1 - y2)^(2::Int)
closest r = checkBounds r (Rectangle x y w h)
| First part of the algorithm :
-- Tries to find an area in which to place a new
-- rectangle so that it overlaps as little as possible with
other rectangles already present . The first rectangles in
the list will be overlapped first .
findSpace :: Real a =>
SmartRectangle a -- ^ The total available area
-> [SmartRectangle a] -- ^ The parts already in use
-> a -- ^ Width of the rectangle to place
-> a -- ^ Height of the rectangle to place
-> [SmartRectangle a]
findSpace total [] _ _ = [total]
findSpace total rs@(_:rs') w h
= case filter largeEnough $ cleanup $ subtractRects total rs of
[] -> findSpace total rs' w h
as -> as
where largeEnough r = width r >= w && height r >= h
-- | Subtracts smaller rectangles from a total rectangle
-- , returning a list of remaining rectangular areas.
subtractRects :: Real a => SmartRectangle a
-> [SmartRectangle a] -> [SmartRectangle a]
subtractRects total [] = [total]
subtractRects total (r:rs)
= do total' <- subtractRects total rs
filter (not . isEmpty)
[ total' {sr_y1 = min (sr_y1 total') (sr_y0 r)} -- Above
, total' {sr_x0 = max (sr_x0 total') (sr_x1 r)} -- Right
, total' {sr_y0 = max (sr_y0 total') (sr_y1 r)} -- Below
, total' {sr_x1 = min (sr_x1 total') (sr_x0 r)} -- Left
]
| " " a list of rectangles , dropping all those that are
-- already contained in another rectangle of the list.
cleanup :: Real a => [SmartRectangle a] -> [SmartRectangle a]
cleanup rs = foldr dropIfContained [] $ sortBy sizeOrder rs
sizeOrder :: Real a => SmartRectangle a -> SmartRectangle a -> Ordering
sizeOrder r1 r2 | w1 < w2 = LT
| w1 == w2 && h1 < h2 = LT
| w1 == w2 && h1 == h2 = EQ
| otherwise = GT
where w1 = width r1
w2 = width r2
h1 = height r1
h2 = height r2
dropIfContained :: Real a => SmartRectangle a
-> [SmartRectangle a] -> [SmartRectangle a]
dropIfContained r rs = if any (`contains` r) rs
then rs
else r:rs
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/e2ffa533da76e6375179eff942bb0647dd22fb58/XMonad/Hooks/Place.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Hooks.Place
Description : Automatic placement of floating windows.
License : BSD-style (see LICENSE)
Maintainer : orphaned
Stability : unstable
Portability : unportable
Automatic placement of floating windows.
---------------------------------------------------------------------------
* Usage
$usage
* Placement actions
* Placement policies
$placements
* Others
$usage
floating windows at appropriate positions on the screen, as well
as an 'X' action to manually trigger repositioning.
You can use this module by including the following in your @~\/.xmonad\/xmonad.hs@:
> import XMonad.Hooks.Place
and adding 'placeHook' to your 'manageHook', for example:
> <> manageHook def }
Note that 'placeHook' should be applied after most other hooks, especially hooks
such as 'doFloat' and 'doShift'. Since hooks combined with '<>' are applied from
right to left, this means that 'placeHook' should be the /first/ hook in your chain.
You can also define a key to manually trigger repositioning with 'placeFocused' by
adding the following to your keys definition:
Both 'placeHook' and 'placeFocused' take a 'Placement' parameter, which specifies
the placement policy to use (smart, under the mouse, fixed position, etc.). See
'Placement' for a list of available policies.
Placement policies
$placements
Placement policies determine how windows will be placed by 'placeFocused' and 'placeHook'.
A few examples:
* Basic smart placement
> myPlacement = simpleSmart
* Under the mouse (pointer at the top-left corner), but constrained
inside of the screen area
> myPlacement = inBounds (underMouse (0, 0))
* Smart placement with a preference for putting windows near
the center of the screen, and with 16px gaps at the top and bottom
of the screen where no window will be placed
| The type of placement policies
| Try to place windows with as little overlap as possible
^ Where the window should be placed inside
the available area. See 'fixed'.
| Place windows at a fixed position
^ Where windows should go.
* etc
| Place windows under the mouse
^ Where the pointer should be relative to
the window's frame; see 'fixed'.
| Apply the given placement policy, constraining the
placed windows inside the screen boundaries.
| Same as 'inBounds', but allows specifying gaps along the screen's edges
^ top, right, bottom and left gaps
Placement functions
| Repositions the focused window according to a placement policy. Works for
layout.
a WindowArranger message otherwise.
| Hook to automatically place windows when they are created.
Look for the workspace(s) on which the window is to be
spawned. Each of them also needs an associated screen
rectangle; for hidden workspaces, we use the current
workspace's screen.
^ The workspace with reference to which the window should be placed,
and the screen's geometry.
^ The list of floating windows.
| Compute the new position of a window according to a placement policy.
^ The placement strategy
^ The screen
^ The other visible windows
^ The pointer's position.
^ The window to be placed
inside another,
by possibly moving it.
Querying stuff
We can't use the border width returned by
getGeometry because it will be 0 if the
window isn't mapped yet.
About the ordering: the smart algorithm will overlap windows
starting ith the head of the list. So:
probably be below the floating ones,
- we reverse the lists, since the newer/more important
windows are usually near the head.
| Return values are, in order: window's rectangle,
other windows' rectangles and pointer's coordinates.
| Alternate representation for rectangles.
^ Top left coordinates, inclusive
^ Bottom right coorsinates, exclusive
| Main placement function
^ point of the screen where windows
^ screen
^ other clients
^ width
^ height
Chooses the best position in which to place a window,
according to a list of free areas and an ideal position for
the top-left corner.
We can't use semi-open surfaces for this, so we go back to
^ Free areas
^ Ideal coordinates
^ Width and height of the window
Tries to find an area in which to place a new
rectangle so that it overlaps as little as possible with
^ The total available area
^ The parts already in use
^ Width of the rectangle to place
^ Height of the rectangle to place
| Subtracts smaller rectangles from a total rectangle
, returning a list of remaining rectangular areas.
Above
Right
Below
Left
already contained in another rectangle of the list. | # LANGUAGE TupleSections #
Copyright : < >
placeFocused
, placeHook
, Placement
, smart
, simpleSmart
, fixed
, underMouse
, inBounds
, withGaps
, purePlaceWindow ) where
import XMonad
import XMonad.Prelude
import qualified XMonad.StackSet as S
import XMonad.Layout.WindowArranger
import XMonad.Actions.FloatKeys
import qualified Data.Map as M
import Data.Ratio ((%))
import Control.Monad.Trans (lift)
This module provides a ' ManageHook ' that automatically places
> main = xmonad $ def { manageHook = placeHook simpleSmart
> , ( ( modm , xK_w ) , )
> myPlacement = withGaps ( 16,0,16,0 ) ( smart ( 0.5,0.5 ) )
data Placement = Smart (Rational, Rational)
| Fixed (Rational, Rational)
| UnderMouse (Rational, Rational)
| Bounds (Dimension, Dimension, Dimension, Dimension) Placement
deriving (Show, Read, Eq)
-> Placement
smart = Smart
simpleSmart :: Placement
simpleSmart = inBounds $ smart (0,0)
* ( 0,0 ) - > top left of the screen
* ( 1,0 ) - > top right of the screen
-> Placement
fixed = Fixed
-> Placement
underMouse = UnderMouse
inBounds :: Placement -> Placement
inBounds = Bounds (0,0,0,0)
withGaps :: (Dimension, Dimension, Dimension, Dimension)
-> Placement -> Placement
withGaps = Bounds
both \"real\ " floating windows and windows in a '
placeFocused :: Placement -> X ()
placeFocused p = withFocused $ \window -> do
info <- gets $ screenInfo . S.current . windowset
floats <- gets $ M.keys . S.floating . windowset
r'@(Rectangle x' y' _ _) <- placeWindow p window info floats
use X.A.FloatKeys if the window is floating , send
if window `elem` floats
then keysMoveWindowTo (x', y') (0, 0) window
else sendMessage $ SetGeometry r'
placeHook :: Placement -> ManageHook
placeHook p = do window <- ask
r <- Query $ lift $ getWindowRectangle window
allRs <- Query $ lift getAllRectangles
pointer <- Query $ lift $ getPointer window
return $ Endo $ \theWS -> fromMaybe theWS $
do let currentRect = screenRect $ S.screenDetail $ S.current theWS
floats = M.keys $ S.floating theWS
guard(window `elem` floats )
let infos = filter ((window `elem`) . stackContents . S.stack . fst)
$ [screenInfo $ S.current theWS]
++ map screenInfo (S.visible theWS)
++ map (, currentRect) (S.hidden theWS)
guard(not $ null infos)
let (workspace, screen) = head infos
rs = mapMaybe (`M.lookup` allRs)
$ organizeClients workspace window floats
r' = purePlaceWindow p screen rs pointer r
newRect = r2rr screen r'
newFloats = M.insert window newRect (S.floating theWS)
return $ theWS { S.floating = newFloats }
placeWindow :: Placement -> Window
-> (S.Workspace WorkspaceId (Layout Window) Window, Rectangle)
-> [Window]
-> X Rectangle
placeWindow p window (ws, s) floats
= do (r, rs, pointer) <- getNecessaryData window ws floats
return $ purePlaceWindow p s rs pointer r
-> Rectangle
purePlaceWindow (Bounds (t,r,b,l) p') (Rectangle sx sy sw sh) rs p w
= let s' = Rectangle (sx + fi l) (sy + fi t) (sw - l - r) (sh - t - b)
in checkBounds s' $ purePlaceWindow p' s' rs p w
purePlaceWindow (Fixed ratios) s _ _ w = placeRatio ratios s w
purePlaceWindow (UnderMouse (rx, ry)) _ _ (px, py) (Rectangle _ _ w h)
= Rectangle (px - truncate (rx * fi w)) (py - truncate (ry * fi h)) w h
purePlaceWindow (Smart ratios) s rs _ w
= placeSmart ratios s rs (rect_width w) (rect_height w)
| Helper : Places a Rectangle at a fixed position indicated by two Rationals
placeRatio :: (Rational, Rational) -> Rectangle -> Rectangle -> Rectangle
placeRatio (rx, ry) (Rectangle x1 y1 w1 h1) (Rectangle _ _ w2 h2)
= Rectangle (scale rx x1 (x1 + fi w1 - fi w2))
(scale ry y1 (y1 + fi h1 - fi h2))
w2 h2
| Helper : Ensures its second parameter is contained inside the first
checkBounds :: Rectangle -> Rectangle -> Rectangle
checkBounds (Rectangle x1 y1 w1 h1) (Rectangle x2 y2 w2 h2)
= Rectangle (max x1 (min (x1 + fi w1 - fi w2) x2))
(max y1 (min (y1 + fi h1 - fi h2) y2))
w2 h2
Utilities
scale :: (RealFrac a, Integral b) => a -> b -> b -> b
scale r n1 n2 = truncate $ r * fi n2 + (1 - r) * fi n1
r2rr :: Rectangle -> Rectangle -> S.RationalRect
r2rr (Rectangle x0 y0 w0 h0) (Rectangle x y w h)
= S.RationalRect ((fi x-fi x0) % fi w0)
((fi y-fi y0) % fi h0)
(fi w % fi w0)
(fi h % fi h0)
stackContents :: Maybe (S.Stack w) -> [w]
stackContents = maybe [] S.integrate
screenInfo :: S.Screen i l a sid ScreenDetail -> (S.Workspace i l a, Rectangle)
screenInfo S.Screen{ S.workspace = ws, S.screenDetail = (SD s)} = (ws, s)
getWindowRectangle :: Window -> X Rectangle
getWindowRectangle window
= do d <- asks display
(_, x, y, w, h, _, _) <- io $ getGeometry d window
b <- asks $ borderWidth . config
return $ Rectangle x y (w + 2*b) (h + 2*b)
getAllRectangles :: X (M.Map Window Rectangle)
getAllRectangles = do ws <- gets windowset
let allWindows = join $ map (stackContents . S.stack)
$ (S.workspace . S.current) ws
: (map S.workspace . S.visible) ws
++ S.hidden ws
allRects <- mapM getWindowRectangle allWindows
return $ M.fromList $ zip allWindows allRects
organizeClients :: S.Workspace a b Window -> Window -> [Window] -> [Window]
organizeClients ws w floats
= let (floatCs, layoutCs) = partition (`elem` floats) $ filter (/= w)
$ stackContents $ S.stack ws
in reverse layoutCs ++ reverse floatCs
- we put the non - floating windows first since they 'll
getPointer :: Window -> X (Position, Position)
getPointer window = do d <- asks display
(_,_,_,x,y,_,_,_) <- io $ queryPointer d window
return (fi x,fi y)
getNecessaryData :: Window
-> S.Workspace WorkspaceId (Layout Window) Window
-> [Window]
-> X (Rectangle, [Rectangle], (Position, Position))
getNecessaryData window ws floats
= do r <- getWindowRectangle window
rs <- mapM getWindowRectangle (organizeClients ws window floats)
pointer <- getPointer window
return (r, rs, pointer)
Smart placement algorithm
data SmartRectangle a = SR
} deriving (Show, Eq)
r2sr :: Rectangle -> SmartRectangle Position
r2sr (Rectangle x y w h) = SR x y (x + fi w) (y + fi h)
sr2r :: SmartRectangle Position -> Rectangle
sr2r (SR x0 y0 x1 y1) = Rectangle x0 y0 (fi $ x1 - x0) (fi $ y1 - y0)
width :: Num a => SmartRectangle a -> a
width r = sr_x1 r - sr_x0 r
height :: Num a => SmartRectangle a -> a
height r = sr_y1 r - sr_y0 r
isEmpty :: Real a => SmartRectangle a -> Bool
isEmpty r = (width r <= 0) || (height r <= 0)
contains :: Real a => SmartRectangle a -> SmartRectangle a -> Bool
contains r1 r2 = sr_x0 r1 <= sr_x0 r2
&& sr_y0 r1 <= sr_y0 r2
&& sr_x1 r1 >= sr_x1 r2
&& sr_y1 r1 >= sr_y1 r2
should be placed first , if possible .
-> Rectangle
placeSmart (rx, ry) s@(Rectangle sx sy sw sh) rs w h
= let free = map sr2r $ findSpace (r2sr s) (map r2sr rs) (fi w) (fi h)
in position free (scale rx sx (sx + fi sw - fi w))
(scale ry sy (sy + fi sh - fi h))
w h
| Second part of the algorithm :
X11 Rectangles / Positions / etc instead .
-> Rectangle
position rs x y w h = minimumBy distanceOrder $ map closest rs
where distanceOrder r1 r2
= compare (distance (rect_x r1,rect_y r1) (x,y) :: Dimension)
(distance (rect_x r2,rect_y r2) (x,y) :: Dimension)
distance (x1,y1) (x2,y2) = truncate $ (sqrt :: Double -> Double)
$ fi $ (x1 - x2)^(2::Int)
+ (y1 - y2)^(2::Int)
closest r = checkBounds r (Rectangle x y w h)
| First part of the algorithm :
other rectangles already present . The first rectangles in
the list will be overlapped first .
findSpace :: Real a =>
-> [SmartRectangle a]
findSpace total [] _ _ = [total]
findSpace total rs@(_:rs') w h
= case filter largeEnough $ cleanup $ subtractRects total rs of
[] -> findSpace total rs' w h
as -> as
where largeEnough r = width r >= w && height r >= h
subtractRects :: Real a => SmartRectangle a
-> [SmartRectangle a] -> [SmartRectangle a]
subtractRects total [] = [total]
subtractRects total (r:rs)
= do total' <- subtractRects total rs
filter (not . isEmpty)
]
| " " a list of rectangles , dropping all those that are
cleanup :: Real a => [SmartRectangle a] -> [SmartRectangle a]
cleanup rs = foldr dropIfContained [] $ sortBy sizeOrder rs
sizeOrder :: Real a => SmartRectangle a -> SmartRectangle a -> Ordering
sizeOrder r1 r2 | w1 < w2 = LT
| w1 == w2 && h1 < h2 = LT
| w1 == w2 && h1 == h2 = EQ
| otherwise = GT
where w1 = width r1
w2 = width r2
h1 = height r1
h2 = height r2
dropIfContained :: Real a => SmartRectangle a
-> [SmartRectangle a] -> [SmartRectangle a]
dropIfContained r rs = if any (`contains` r) rs
then rs
else r:rs
|
7737002a2b8bfbc61faca1ba89427ad75d69c94a3690a33f485b5ab575528e4b | agda/agda | Warshall.hs | # LANGUAGE TemplateHaskell #
module Internal.Utils.Warshall ( tests ) where
import Agda.Syntax.Common ( Nat )
import Agda.Utils.Warshall
import Data.List ( sort )
import qualified Data.Map as Map
import Data.Maybe
import Internal.Helpers
-- Testing ----------------------------------------------------------------
genGraph :: Ord node => Float -> Gen edge -> [node] -> Gen (AdjList node edge)
genGraph density edge nodes = do
Map.fromList . concat <$> mapM neighbours nodes
where
k = round (100 * density)
neighbours n = do
ns <- concat <$> mapM neighbour nodes
case ns of
[] -> elements [[(n, [])], []]
_ -> return [(n, ns)]
neighbour n = frequency
[ (k, do e <- edge
ns <- neighbour n
return ((n, e):ns))
, (100 - k, return [])
]
type Distance = Weight
genGraph_ :: Nat -> Gen (AdjList Nat Distance)
genGraph_ n =
genGraph 0.2 (Finite <$> natural) [0..n - 1]
lookupEdge :: Ord n => n -> n -> AdjList n e -> Maybe e
lookupEdge i j g = lookup j =<< Map.lookup i g
edges :: AdjList n e -> [(n,n,e)]
edges g = do
(i, ns) <- Map.toList g
(j, e) <- ns
return (i, j, e)
-- | Check that no edges get longer when completing a graph.
no_tested_prop_smaller :: Nat -> Property
no_tested_prop_smaller n' =
forAll (genGraph_ n) $ \g ->
let g' = warshallG g in
and [ lookupEdge i j g' =< e
| (i, j, e) <- edges g
]
where
n = abs (div n' 2)
Nothing =< _ = False
Just x =< y = x <= y
newEdge :: Nat -> Nat -> Distance -> AdjList Nat Distance ->
AdjList Nat Distance
newEdge i j e = Map.insertWith (++) i [(j, e)]
genPath :: Nat -> Nat -> Nat -> AdjList Nat Distance ->
Gen (AdjList Nat Distance)
genPath n i j g = do
es <- listOf $ (,) <$> node <*> edge
v <- edge
return $ addPath i (es ++ [(j, v)]) g
where
edge :: Gen Distance
edge = Finite <$> natural
node :: Gen Nat
node = choose (0, n - 1)
addPath :: Nat -> [(Nat, Distance)] -> AdjList Nat Distance ->
AdjList Nat Distance
addPath _ [] g = g
addPath i ((j, v):es) g = newEdge i j v $ addPath j es g
-- | Check that all transitive edges are added.
no_tested_prop_path :: Nat -> Property
no_tested_prop_path n' =
forAll (genGraph_ n) $ \g ->
forAll (two $ choose (0, n - 1)) $ \(i, j) ->
forAll (genPath n i j g) $ \g' ->
isJust (lookupEdge i j $ warshallG g')
where
n = abs (div n' 2) + 1
mapNodes :: Ord node' => (node -> node') -> AdjList node edge -> AdjList node' edge
mapNodes f = Map.map f' . Map.mapKeys f
where
f' es = [ (f n, e) | (n,e) <- es ]
-- | Check that no edges are added between components.
no_tested_prop_disjoint :: Nat -> Property
no_tested_prop_disjoint n' =
forAll (two $ genGraph_ n) $ \(g1, g2) ->
let g = Map.union (mapNodes Left g1) (mapNodes Right g2)
g' = warshallG g
in all disjoint (Map.assocs g')
where
n = abs (div n' 3)
disjoint (Left i, es) = all (isLeft . fst) es
disjoint (Right i, es) = all (isRight . fst) es
isLeft = either (const True) (const False)
isRight = not . isLeft
no_tested_prop_stable :: Nat -> Property
no_tested_prop_stable n' =
forAll (genGraph_ n) $ \g ->
let g' = warshallG g in
g' =~= warshallG g'
where
n = abs (div n' 2)
g =~= g' = sort (edges g) == sort (edges g')
------------------------------------------------------------------------
-- * All tests
------------------------------------------------------------------------
Template Haskell hack to make the following $ allProperties work
under ghc-7.8 .
return [] -- KEEP!
| All tests as collected by ' allProperties ' .
--
Using ' allProperties ' is convenient and superior to the manual
-- enumeration of tests, since the name of the property is added
-- automatically.
tests :: TestTree
tests = testProperties "Internal.Utils.Warshall" $allProperties
| null | https://raw.githubusercontent.com/agda/agda/3543ef3df19228012a1ac5be766cc38fd2f65f6a/test/Internal/Utils/Warshall.hs | haskell | Testing ----------------------------------------------------------------
| Check that no edges get longer when completing a graph.
| Check that all transitive edges are added.
| Check that no edges are added between components.
----------------------------------------------------------------------
* All tests
----------------------------------------------------------------------
KEEP!
enumeration of tests, since the name of the property is added
automatically. | # LANGUAGE TemplateHaskell #
module Internal.Utils.Warshall ( tests ) where
import Agda.Syntax.Common ( Nat )
import Agda.Utils.Warshall
import Data.List ( sort )
import qualified Data.Map as Map
import Data.Maybe
import Internal.Helpers
genGraph :: Ord node => Float -> Gen edge -> [node] -> Gen (AdjList node edge)
genGraph density edge nodes = do
Map.fromList . concat <$> mapM neighbours nodes
where
k = round (100 * density)
neighbours n = do
ns <- concat <$> mapM neighbour nodes
case ns of
[] -> elements [[(n, [])], []]
_ -> return [(n, ns)]
neighbour n = frequency
[ (k, do e <- edge
ns <- neighbour n
return ((n, e):ns))
, (100 - k, return [])
]
type Distance = Weight
genGraph_ :: Nat -> Gen (AdjList Nat Distance)
genGraph_ n =
genGraph 0.2 (Finite <$> natural) [0..n - 1]
lookupEdge :: Ord n => n -> n -> AdjList n e -> Maybe e
lookupEdge i j g = lookup j =<< Map.lookup i g
edges :: AdjList n e -> [(n,n,e)]
edges g = do
(i, ns) <- Map.toList g
(j, e) <- ns
return (i, j, e)
no_tested_prop_smaller :: Nat -> Property
no_tested_prop_smaller n' =
forAll (genGraph_ n) $ \g ->
let g' = warshallG g in
and [ lookupEdge i j g' =< e
| (i, j, e) <- edges g
]
where
n = abs (div n' 2)
Nothing =< _ = False
Just x =< y = x <= y
newEdge :: Nat -> Nat -> Distance -> AdjList Nat Distance ->
AdjList Nat Distance
newEdge i j e = Map.insertWith (++) i [(j, e)]
genPath :: Nat -> Nat -> Nat -> AdjList Nat Distance ->
Gen (AdjList Nat Distance)
genPath n i j g = do
es <- listOf $ (,) <$> node <*> edge
v <- edge
return $ addPath i (es ++ [(j, v)]) g
where
edge :: Gen Distance
edge = Finite <$> natural
node :: Gen Nat
node = choose (0, n - 1)
addPath :: Nat -> [(Nat, Distance)] -> AdjList Nat Distance ->
AdjList Nat Distance
addPath _ [] g = g
addPath i ((j, v):es) g = newEdge i j v $ addPath j es g
no_tested_prop_path :: Nat -> Property
no_tested_prop_path n' =
forAll (genGraph_ n) $ \g ->
forAll (two $ choose (0, n - 1)) $ \(i, j) ->
forAll (genPath n i j g) $ \g' ->
isJust (lookupEdge i j $ warshallG g')
where
n = abs (div n' 2) + 1
mapNodes :: Ord node' => (node -> node') -> AdjList node edge -> AdjList node' edge
mapNodes f = Map.map f' . Map.mapKeys f
where
f' es = [ (f n, e) | (n,e) <- es ]
no_tested_prop_disjoint :: Nat -> Property
no_tested_prop_disjoint n' =
forAll (two $ genGraph_ n) $ \(g1, g2) ->
let g = Map.union (mapNodes Left g1) (mapNodes Right g2)
g' = warshallG g
in all disjoint (Map.assocs g')
where
n = abs (div n' 3)
disjoint (Left i, es) = all (isLeft . fst) es
disjoint (Right i, es) = all (isRight . fst) es
isLeft = either (const True) (const False)
isRight = not . isLeft
no_tested_prop_stable :: Nat -> Property
no_tested_prop_stable n' =
forAll (genGraph_ n) $ \g ->
let g' = warshallG g in
g' =~= warshallG g'
where
n = abs (div n' 2)
g =~= g' = sort (edges g) == sort (edges g')
Template Haskell hack to make the following $ allProperties work
under ghc-7.8 .
| All tests as collected by ' allProperties ' .
Using ' allProperties ' is convenient and superior to the manual
tests :: TestTree
tests = testProperties "Internal.Utils.Warshall" $allProperties
|
89d91dc1d7aa017b6bd9cd5118c89cc536377f04af14b282444d9af0b176f980 | johnlawrenceaspden/hobby-code | multimethods.clj | Clojure Multimethods
(defn ticket [age]
(cond (< age 16) :child
(> age 64) :ancient
:else :adult))
(defrecord person [name age])
(defmulti print-name (fn [person] (ticket (:age person))))
(defmethod print-name :child [person] (str "Young " (:name person)))
(defmethod print-name :adult [person] (str "Mr " (:name person)))
(defmethod print-name :ancient [person] (str "Old Mr " (:name person)))
(map print-name (list (person. "Fred" 23)
(person. "Jimmy" 12)
(person. "Seth" 78)))
;; And an alternative version
(defn pname [person]
(str
(case (ticket(:age person))
:child "Young "
:adult "Mr "
:ancient "Old Mr ")
(:name person)))
(map pname (list (person. "Fred" 23)
(person. "Jimmy" 12)
(person. "Seth" 78)))
| null | https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/multimethods.clj | clojure | And an alternative version | Clojure Multimethods
(defn ticket [age]
(cond (< age 16) :child
(> age 64) :ancient
:else :adult))
(defrecord person [name age])
(defmulti print-name (fn [person] (ticket (:age person))))
(defmethod print-name :child [person] (str "Young " (:name person)))
(defmethod print-name :adult [person] (str "Mr " (:name person)))
(defmethod print-name :ancient [person] (str "Old Mr " (:name person)))
(map print-name (list (person. "Fred" 23)
(person. "Jimmy" 12)
(person. "Seth" 78)))
(defn pname [person]
(str
(case (ticket(:age person))
:child "Young "
:adult "Mr "
:ancient "Old Mr ")
(:name person)))
(map pname (list (person. "Fred" 23)
(person. "Jimmy" 12)
(person. "Seth" 78)))
|
37d42f052aa5084afac667a80dcf38448d72c73030cdaa5e36c31b250209242e | sjl/scully | gdl.lisp | (in-package :scully.gdl)
(in-readtable :fare-quasiquote)
;;;; Utils --------------------------------------------------------------------
(defvar *ggp-gensym-counter* 0)
(defun gensym-ggp ()
"Return a unique symbol in the `ggp-rules` package."
(values (intern (mkstr 'rule- (incf *ggp-gensym-counter*))
(find-package :ggp-rules))))
(defun move< (a b)
(string< (structural-string a)
(structural-string b)))
(defun sort-moves (moves)
(sort (copy-seq moves) #'move<))
(defmacro time-it ((run-time-place gc-time-place) &body body)
(with-gensyms (start end result gc)
`(let* ((sb-ext:*gc-run-time* 0)
(,start (get-internal-run-time))
(,result (progn ,@body))
(,end (get-internal-run-time))
(,gc sb-ext:*gc-run-time*))
(setf ,gc-time-place (/ ,gc internal-time-units-per-second 1.0)
,run-time-place (/ (- ,end ,start ,gc 0.0)
internal-time-units-per-second))
,result)))
;;;; Files --------------------------------------------------------------------
(defun read-gdl (filename)
"Read GDL from the given file"
(let ((*package* (find-package :ggp-rules)))
(with-open-file (stream filename)
(loop
:with done = (gensym)
:for form = (read stream nil done)
:while (not (eq form done))
:collect form))))
(defun dump-gdl (rules &optional stream)
(let ((*package* (find-package :ggp-rules)))
(format stream "~(~{~S~%~}~)" rules)))
;;;; Temperance ---------------------------------------------------------------
(defun load-rules (database rules)
(push-logic-frame-with database
(mapc (lambda (rule)
(if (and (consp rule)
(eq (car rule) 'ggp-rules::<=))
(apply #'invoke-rule database (cdr rule))
(invoke-fact database rule)))
rules)))
;;;; Normalization ------------------------------------------------------------
Normalization takes a set of clauses from raw GDL format and turns them into
friendlier clauses of the form :
;;;
;;; (head . body)
;;;
;;; * (<= head . body) becomes (head . body)
;;; * (fact) becomes ((fact)), i.e. ((fact) . nil)
;;; * Nullary predicates like terminal have their parens added back.
;;;
;;; So something like (<= terminal (true foo) (not bar)) would become:
;;;
;;; ((terminal)
;;; (true foo)
;;; (not (bar)))
(defun-match normalize-term (term)
(`(ggp-rules::not ,body) `(ggp-rules::not ,(normalize-term body)))
(`(,_ ,@_) term)
(sym `(,sym)))
(defun-match normalize-rule (rule)
(`(ggp-rules::<= ,head ,@body)
`(,(normalize-term head) ,@(mapcar #'normalize-term body)))
(fact `(,(normalize-term fact))))
(defun normalize-rules (gdl-rules)
(mapcar #'normalize-rule gdl-rules))
;;;; Rule Data Access ---------------------------------------------------------
(defun-match bare-term (term)
(`(ggp-rules::not ,x) x)
(_ term))
(defun-match negationp (term)
(`(ggp-rules::not ,_) t)
(_ nil))
(defun-ematch term-predicate (term)
(`(ggp-rules::not (,predicate ,@_)) predicate)
(`(,predicate ,@_) predicate))
(defun-ematch rule-head (rule)
(`(,head ,@_) head))
(defun-ematch rule-body (rule)
(`(,_ ,@body) body))
(defun rule-predicate (rule)
(term-predicate (rule-head rule)))
(defun rule-head= (rule term &optional (predicate #'=))
(funcall predicate (rule-head rule) term))
;;;; Rule Splitting -----------------------------------------------------------
;;; Rules with many terms in their bodies are difficult to make rule trees for,
;;; because the size of the tree grows exponentially. We can fix this problem
;;; by splitting large disjunctions into separate rules.
(defparameter *max-rule-size* 8)
(defun split-rule (head bodies)
(if (<= (length bodies) *max-rule-size*)
(values (mapcar (curry #'cons head) bodies) nil)
(iterate
(for chunk :in (subdivide bodies *max-rule-size*))
(for new-head = (list (gensym-ggp)))
(collecting new-head :into new-heads)
(appending (mapcar (curry #'cons new-head) chunk)
:into new-rules)
(finally
(return (values (append new-rules
(mapcar (lambda (new-head)
(list head new-head))
new-heads))
t))))))
(defun split-rules% (normalized-rules)
(let ((rules (group-by #'rule-head normalized-rules :test #'equal)))
(iterate
(for (head instances) :in-hashtable rules)
(for bodies = (mapcar #'rule-body instances))
(for (values new-instances needed-split) = (split-rule head bodies))
(oring needed-split :into ever-needed-split)
(appending new-instances :into new-rules)
(finally (return (values new-rules ever-needed-split))))))
(defun split-rules (normalized-rules)
(iterate (for (values rules needed-split)
:first (values normalized-rules t)
:then (split-rules% rules))
(for c :from 0)
(while needed-split)
(finally (return (values rules c)))))
| null | https://raw.githubusercontent.com/sjl/scully/d4b595c38f91d6235758fa8b11f2ab64b893394b/src/gdl.lisp | lisp | Utils --------------------------------------------------------------------
Files --------------------------------------------------------------------
Temperance ---------------------------------------------------------------
Normalization ------------------------------------------------------------
(head . body)
* (<= head . body) becomes (head . body)
* (fact) becomes ((fact)), i.e. ((fact) . nil)
* Nullary predicates like terminal have their parens added back.
So something like (<= terminal (true foo) (not bar)) would become:
((terminal)
(true foo)
(not (bar)))
Rule Data Access ---------------------------------------------------------
Rule Splitting -----------------------------------------------------------
Rules with many terms in their bodies are difficult to make rule trees for,
because the size of the tree grows exponentially. We can fix this problem
by splitting large disjunctions into separate rules. | (in-package :scully.gdl)
(in-readtable :fare-quasiquote)
(defvar *ggp-gensym-counter* 0)
(defun gensym-ggp ()
"Return a unique symbol in the `ggp-rules` package."
(values (intern (mkstr 'rule- (incf *ggp-gensym-counter*))
(find-package :ggp-rules))))
(defun move< (a b)
(string< (structural-string a)
(structural-string b)))
(defun sort-moves (moves)
(sort (copy-seq moves) #'move<))
(defmacro time-it ((run-time-place gc-time-place) &body body)
(with-gensyms (start end result gc)
`(let* ((sb-ext:*gc-run-time* 0)
(,start (get-internal-run-time))
(,result (progn ,@body))
(,end (get-internal-run-time))
(,gc sb-ext:*gc-run-time*))
(setf ,gc-time-place (/ ,gc internal-time-units-per-second 1.0)
,run-time-place (/ (- ,end ,start ,gc 0.0)
internal-time-units-per-second))
,result)))
(defun read-gdl (filename)
"Read GDL from the given file"
(let ((*package* (find-package :ggp-rules)))
(with-open-file (stream filename)
(loop
:with done = (gensym)
:for form = (read stream nil done)
:while (not (eq form done))
:collect form))))
(defun dump-gdl (rules &optional stream)
(let ((*package* (find-package :ggp-rules)))
(format stream "~(~{~S~%~}~)" rules)))
(defun load-rules (database rules)
(push-logic-frame-with database
(mapc (lambda (rule)
(if (and (consp rule)
(eq (car rule) 'ggp-rules::<=))
(apply #'invoke-rule database (cdr rule))
(invoke-fact database rule)))
rules)))
Normalization takes a set of clauses from raw GDL format and turns them into
friendlier clauses of the form :
(defun-match normalize-term (term)
(`(ggp-rules::not ,body) `(ggp-rules::not ,(normalize-term body)))
(`(,_ ,@_) term)
(sym `(,sym)))
(defun-match normalize-rule (rule)
(`(ggp-rules::<= ,head ,@body)
`(,(normalize-term head) ,@(mapcar #'normalize-term body)))
(fact `(,(normalize-term fact))))
(defun normalize-rules (gdl-rules)
(mapcar #'normalize-rule gdl-rules))
(defun-match bare-term (term)
(`(ggp-rules::not ,x) x)
(_ term))
(defun-match negationp (term)
(`(ggp-rules::not ,_) t)
(_ nil))
(defun-ematch term-predicate (term)
(`(ggp-rules::not (,predicate ,@_)) predicate)
(`(,predicate ,@_) predicate))
(defun-ematch rule-head (rule)
(`(,head ,@_) head))
(defun-ematch rule-body (rule)
(`(,_ ,@body) body))
(defun rule-predicate (rule)
(term-predicate (rule-head rule)))
(defun rule-head= (rule term &optional (predicate #'=))
(funcall predicate (rule-head rule) term))
(defparameter *max-rule-size* 8)
(defun split-rule (head bodies)
(if (<= (length bodies) *max-rule-size*)
(values (mapcar (curry #'cons head) bodies) nil)
(iterate
(for chunk :in (subdivide bodies *max-rule-size*))
(for new-head = (list (gensym-ggp)))
(collecting new-head :into new-heads)
(appending (mapcar (curry #'cons new-head) chunk)
:into new-rules)
(finally
(return (values (append new-rules
(mapcar (lambda (new-head)
(list head new-head))
new-heads))
t))))))
(defun split-rules% (normalized-rules)
(let ((rules (group-by #'rule-head normalized-rules :test #'equal)))
(iterate
(for (head instances) :in-hashtable rules)
(for bodies = (mapcar #'rule-body instances))
(for (values new-instances needed-split) = (split-rule head bodies))
(oring needed-split :into ever-needed-split)
(appending new-instances :into new-rules)
(finally (return (values new-rules ever-needed-split))))))
(defun split-rules (normalized-rules)
(iterate (for (values rules needed-split)
:first (values normalized-rules t)
:then (split-rules% rules))
(for c :from 0)
(while needed-split)
(finally (return (values rules c)))))
|
3a264bf05f3f04f29779887b96ec32c1d29a08b3777d8f74807c50b106104070 | zsau/id3 | id3_test.clj | (ns id3-test
(:import [java.io ByteArrayInputStream ByteArrayOutputStream])
(:require
[clojure.spec.test.alpha :as stest]
[clojure.test :refer :all]
[id3 :refer :all]
[id3.common :refer :all]
[id3.spec]
[medley.core :as m]))
(stest/instrument)
(defn write-tag-to-bytes [tag opts]
(let [buf (ByteArrayOutputStream.)]
(m/mapply write-tag buf tag opts)
(.toByteArray buf)))
(defn encoding-short-name [enc]
(condp = enc
latin1 "latin1"
utf8 "utf8"
utf16 "utf16"
utf16be "utf16-be"))
(defn encoded-string-size [enc s]
(condp = enc
latin1 (inc (count s)) ; extra byte for the encoding marker
utf8 (inc (count s))
2 bytes per char , plus encoding marker and extra 2 bytes for the BOM
utf16be (inc (* 2 (count s)))))
(defn tag-size [enc text-frame-values]
our test files have 256 bytes of padding ,
plus 10 bytes for each frame header
(apply + 256 (map #(+ 10 (encoded-string-size enc %)) text-frame-values)))
(deftest formats
(let [[artist title] ["Nobody" "Nothing"]]
(doseq [
ver [3 4]
enc (encodings-for-version ver)
[fmt tag] {
:simple
#:id3.frame.name{:artist [artist], :title [title]}
:normal
{"TPE1" [artist], "TIT2" [title]}
:full
#:id3{:magic-number "ID3", :version ver, :revision 0, :flags #{}, :size (tag-size enc [artist title]), :frames [
#:id3.frame{:id "TIT2", :flags #{}, :encoding enc, :content [title], :size (encoded-string-size enc title)}
#:id3.frame{:id "TPE1", :flags #{}, :encoding enc, :content [artist], :size (encoded-string-size enc artist)}]}}]
(testing (format "version: %s, encoding: %s" ver enc)
(let [file (format "test/resources/basic-v2.%d-%s.mp3" ver (encoding-short-name enc))]
(is (= tag (with-mp3 [mp3 file :format fmt] (:id3/tag mp3)))))))))
(deftest non-latin
(let [tag #:id3.frame.name{:artist ["Mötley Crüe"], :title ["白い夏と緑の自転車 赤い髪と黒いギター"]}]
(doseq [ver [3 4], enc (remove #{latin1} (encodings-for-version ver))]
(let [file (format "test/resources/non-latin-v2.%s-%s.mp3" ver (encoding-short-name enc))]
(testing (str "Reading " file)
(is (= tag (with-mp3 [mp3 file] (:id3/tag mp3)))))))))
(defn normalize-full-tag [tag]
(-> tag
(dissoc :id3/size)
(update :id3/frames (fn [frames]
(mapv #(dissoc % :id3.frame/size :id3.frame/encoding) frames)))))
(deftest round-trip
(let [
full-tag #:id3{
:magic-number "ID3"
:version 4
:revision 0
:flags #{}
:size 35
:frames [
#:id3.frame{
:encoding "ISO-8859-1"
:content ["Nothing"]
:size 8
:id "TIT2"
:flags #{}}
#:id3.frame{
:encoding "ISO-8859-1"
:content ["Nobody"]
:size 7
:id "TPE1"
:flags #{}}]}
normalize (fn [tag]
(cond-> tag
(= :full (id3/tag-format tag)) normalize-full-tag))]
(doseq [ver [nil 3 4], enc [nil latin1 utf16], pad [nil 0 123], fmt [:simple :normal :full]]
(let [
tag (id3/downconvert-tag full-tag fmt)
opts (m/remove-vals nil? {:version ver, :encoding enc, :padding pad})]
(testing (format "Round-tripping with format: %s, opts: %s" fmt opts)
(is (= (normalize tag)
(-> tag
(write-tag-to-bytes opts)
ByteArrayInputStream.
(read-tag :format fmt)
normalize))))))))
| null | https://raw.githubusercontent.com/zsau/id3/94635b5fe5edc4d4b3b70469126b4d849bae5c1b/test/id3_test.clj | clojure | extra byte for the encoding marker | (ns id3-test
(:import [java.io ByteArrayInputStream ByteArrayOutputStream])
(:require
[clojure.spec.test.alpha :as stest]
[clojure.test :refer :all]
[id3 :refer :all]
[id3.common :refer :all]
[id3.spec]
[medley.core :as m]))
(stest/instrument)
(defn write-tag-to-bytes [tag opts]
(let [buf (ByteArrayOutputStream.)]
(m/mapply write-tag buf tag opts)
(.toByteArray buf)))
(defn encoding-short-name [enc]
(condp = enc
latin1 "latin1"
utf8 "utf8"
utf16 "utf16"
utf16be "utf16-be"))
(defn encoded-string-size [enc s]
(condp = enc
utf8 (inc (count s))
2 bytes per char , plus encoding marker and extra 2 bytes for the BOM
utf16be (inc (* 2 (count s)))))
(defn tag-size [enc text-frame-values]
our test files have 256 bytes of padding ,
plus 10 bytes for each frame header
(apply + 256 (map #(+ 10 (encoded-string-size enc %)) text-frame-values)))
(deftest formats
(let [[artist title] ["Nobody" "Nothing"]]
(doseq [
ver [3 4]
enc (encodings-for-version ver)
[fmt tag] {
:simple
#:id3.frame.name{:artist [artist], :title [title]}
:normal
{"TPE1" [artist], "TIT2" [title]}
:full
#:id3{:magic-number "ID3", :version ver, :revision 0, :flags #{}, :size (tag-size enc [artist title]), :frames [
#:id3.frame{:id "TIT2", :flags #{}, :encoding enc, :content [title], :size (encoded-string-size enc title)}
#:id3.frame{:id "TPE1", :flags #{}, :encoding enc, :content [artist], :size (encoded-string-size enc artist)}]}}]
(testing (format "version: %s, encoding: %s" ver enc)
(let [file (format "test/resources/basic-v2.%d-%s.mp3" ver (encoding-short-name enc))]
(is (= tag (with-mp3 [mp3 file :format fmt] (:id3/tag mp3)))))))))
(deftest non-latin
(let [tag #:id3.frame.name{:artist ["Mötley Crüe"], :title ["白い夏と緑の自転車 赤い髪と黒いギター"]}]
(doseq [ver [3 4], enc (remove #{latin1} (encodings-for-version ver))]
(let [file (format "test/resources/non-latin-v2.%s-%s.mp3" ver (encoding-short-name enc))]
(testing (str "Reading " file)
(is (= tag (with-mp3 [mp3 file] (:id3/tag mp3)))))))))
(defn normalize-full-tag [tag]
(-> tag
(dissoc :id3/size)
(update :id3/frames (fn [frames]
(mapv #(dissoc % :id3.frame/size :id3.frame/encoding) frames)))))
(deftest round-trip
(let [
full-tag #:id3{
:magic-number "ID3"
:version 4
:revision 0
:flags #{}
:size 35
:frames [
#:id3.frame{
:encoding "ISO-8859-1"
:content ["Nothing"]
:size 8
:id "TIT2"
:flags #{}}
#:id3.frame{
:encoding "ISO-8859-1"
:content ["Nobody"]
:size 7
:id "TPE1"
:flags #{}}]}
normalize (fn [tag]
(cond-> tag
(= :full (id3/tag-format tag)) normalize-full-tag))]
(doseq [ver [nil 3 4], enc [nil latin1 utf16], pad [nil 0 123], fmt [:simple :normal :full]]
(let [
tag (id3/downconvert-tag full-tag fmt)
opts (m/remove-vals nil? {:version ver, :encoding enc, :padding pad})]
(testing (format "Round-tripping with format: %s, opts: %s" fmt opts)
(is (= (normalize tag)
(-> tag
(write-tag-to-bytes opts)
ByteArrayInputStream.
(read-tag :format fmt)
normalize))))))))
|
afa0e6b93fdf38bbdda6348d6f438f2646ec7abac5d1dc98d1b0bbabbb91f322 | bcc32/projecteuler-ocaml | solutions.ml | open! Core
open! Import
(* TODO: Allow positional arg to pick just one, maybe using a regexp? *)
let list_solutions verbose =
List.iter Euler_solutions.all ~f:(fun (name, (module Sol : Solution.S)) ->
print_endline name;
if verbose then print_endline (" " ^ Sol.description))
;;
let verbose_arg =
Arg.(value & flag & info [ "v"; "verbose" ] ~doc:"Show solution descriptions")
;;
let list_command =
Cmd.v
(Cmd.info "list" ~doc:"List solution commands")
Term.(const list_solutions $ verbose_arg)
;;
let debug_arg =
Arg.(
value
& flag
& info
~env:(Cmd.Env.info "EULER_DEBUG")
[ "d"; "debug" ]
~doc:"Enable debug/progress printing")
;;
let time_arg = Arg.(value & flag & info [ "t"; "time" ] ~doc:"Measure and print runtime")
let name_arg = Arg.(required & pos 0 (some string) None & info [] ~docv:"NAME")
let run_solution name debug time =
match List.Assoc.find Euler_solutions.all name ~equal:String.equal with
| None -> error_s [%message "No such solution found" (name : string)]
| Some (module Sol) ->
(match Sol.run ~print_debug:debug ~print_elapsed_time:time () with
| () -> Ok ()
| exception e -> error_s [%message "Solution raised" (name : string) ~_:(e : exn)])
;;
let run_command =
Cmd.v
(Cmd.info "run" ~doc:"Run a solution (by name)")
Term.(term_result (const run_solution $ name_arg $ debug_arg $ time_arg))
;;
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/da90c3f3c74e7309efc6eecb6e6cff4cdc7a888b/bin/solutions.ml | ocaml | TODO: Allow positional arg to pick just one, maybe using a regexp? | open! Core
open! Import
let list_solutions verbose =
List.iter Euler_solutions.all ~f:(fun (name, (module Sol : Solution.S)) ->
print_endline name;
if verbose then print_endline (" " ^ Sol.description))
;;
let verbose_arg =
Arg.(value & flag & info [ "v"; "verbose" ] ~doc:"Show solution descriptions")
;;
let list_command =
Cmd.v
(Cmd.info "list" ~doc:"List solution commands")
Term.(const list_solutions $ verbose_arg)
;;
let debug_arg =
Arg.(
value
& flag
& info
~env:(Cmd.Env.info "EULER_DEBUG")
[ "d"; "debug" ]
~doc:"Enable debug/progress printing")
;;
let time_arg = Arg.(value & flag & info [ "t"; "time" ] ~doc:"Measure and print runtime")
let name_arg = Arg.(required & pos 0 (some string) None & info [] ~docv:"NAME")
let run_solution name debug time =
match List.Assoc.find Euler_solutions.all name ~equal:String.equal with
| None -> error_s [%message "No such solution found" (name : string)]
| Some (module Sol) ->
(match Sol.run ~print_debug:debug ~print_elapsed_time:time () with
| () -> Ok ()
| exception e -> error_s [%message "Solution raised" (name : string) ~_:(e : exn)])
;;
let run_command =
Cmd.v
(Cmd.info "run" ~doc:"Run a solution (by name)")
Term.(term_result (const run_solution $ name_arg $ debug_arg $ time_arg))
;;
|
ea2b8d6aabf44f82c7098a81b505fd79edad61ea84a60849b2157b12fcd3774f | alicemaz/digital_henge | Zodiac.hs | module Zodiac () where
import Data.List
import Types
import Util
instance CheckEvent Zodiac where
checkEvent y m d = case findIndex (== (m, d)) zodiacDates of
Just i -> Event (toEnum i :: Zodiac) (dateToTimestring y' m' d')
where (y', m', d') = (toInteger y, toInteger m, fromRational (toRational d))
Nothing -> Nil
zodiacDates :: Integral a => [(a, a)]
zodiacDates =
[
(3, 21), (4, 20), (5, 21), (6, 21), (7, 23), (8, 23),
(9, 23), (10, 23), (11, 22), (12, 22), (1, 20), (2, 19)
]
| null | https://raw.githubusercontent.com/alicemaz/digital_henge/0a1c75a5088fc6f256179024b51ebbbf4381c9e4/src/Zodiac.hs | haskell | module Zodiac () where
import Data.List
import Types
import Util
instance CheckEvent Zodiac where
checkEvent y m d = case findIndex (== (m, d)) zodiacDates of
Just i -> Event (toEnum i :: Zodiac) (dateToTimestring y' m' d')
where (y', m', d') = (toInteger y, toInteger m, fromRational (toRational d))
Nothing -> Nil
zodiacDates :: Integral a => [(a, a)]
zodiacDates =
[
(3, 21), (4, 20), (5, 21), (6, 21), (7, 23), (8, 23),
(9, 23), (10, 23), (11, 22), (12, 22), (1, 20), (2, 19)
]
|
|
669c0981deffa2609c29e9f3c7100d3e850e66ce07ae889fc22202f414414d39 | kind2-mc/kind2 | lustreGlobals.mli | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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 .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
* Global declarations for input
@author
@author Christoph Sticksel *)
(** *)
type t =
{
free_constants : (LustreIdent.t * Var.t LustreIndex.t) list;
(** Free constants *)
state_var_bounds :
(LustreExpr.expr LustreExpr.bound_or_fixed list)
StateVar.StateVarHashtbl.t;
(** Register bounds of state variables for later use *)
}
| null | https://raw.githubusercontent.com/kind2-mc/kind2/c601470eb68af9bd3b88828b04dbcdbd6bd6bbf5/src/lustre/lustreGlobals.mli | ocaml | *
* Free constants
* Register bounds of state variables for later use | This file is part of the Kind 2 model checker .
Copyright ( c ) 2015 by the Board of Trustees of the University of Iowa
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 .
Copyright (c) 2015 by the Board of Trustees of the University of Iowa
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.
*)
* Global declarations for input
@author
@author Christoph Sticksel *)
type t =
{
free_constants : (LustreIdent.t * Var.t LustreIndex.t) list;
state_var_bounds :
(LustreExpr.expr LustreExpr.bound_or_fixed list)
StateVar.StateVarHashtbl.t;
}
|
efe1fbb47b2a3f3d73e145463f72c2878468cba6dde1e9248c83e194a016e122 | sbcl/sbcl | stream.lisp | ;;;; os-independent stream functions
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-IMPL")
;;;; standard streams
;;; The initialization of these streams is performed by
;;; STREAM-COLD-INIT-OR-RESET.
(defvar *terminal-io* () "terminal I/O stream")
(defvar *standard-input* () "default input stream")
(defvar *standard-output* () "default output stream")
(defvar *error-output* () "error output stream")
(defvar *query-io* () "query I/O stream")
(defvar *trace-output* () "trace output stream")
(defvar *debug-io* () "interactive debugging stream")
(defun stream-element-type-stream-element-mode (element-type)
(cond ((or (not element-type)
(eq element-type t)
(eq element-type :default)) :bivalent)
((or (eq element-type 'character)
(eq element-type 'base-char))
'character)
((memq element-type '(signed-byte unsigned-byte))
element-type)
((and (proper-list-of-length-p element-type 2)
(memq (car element-type)
'(signed-byte unsigned-byte)))
(car element-type))
((not (ignore-errors
(setf element-type
(type-or-nil-if-unknown element-type t))))
:bivalent)
((eq element-type *empty-type*)
:bivalent)
((csubtypep element-type (specifier-type 'character))
'character)
((csubtypep element-type (specifier-type 'unsigned-byte))
'unsigned-byte)
((csubtypep element-type (specifier-type 'signed-byte))
'signed-byte)
(t
:bivalent)))
(defun ill-in (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies input-stream-p)
:format-control "~S is not a character input stream."
:format-arguments (list stream)))
(defun ill-out (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies output-stream-p)
:format-control "~S is not a character output stream."
:format-arguments (list stream)))
(defun ill-bin (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies input-stream-p)
:format-control "~S is not a binary input stream."
:format-arguments (list stream)))
(defun ill-bout (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies output-stream-p)
:format-control "~S is not a binary output stream."
:format-arguments (list stream)))
(defun closed-flame (stream &rest ignore)
(declare (ignore ignore))
(error 'closed-stream-error :stream stream))
(defun closed-flame-saved (stream &rest ignore)
(declare (ignore ignore))
(error 'closed-saved-stream-error :stream stream))
(defun no-op-placeholder (&rest ignore)
(declare (ignore ignore)))
;;; stream manipulation functions
(defun maybe-resolve-synonym-stream (stream)
(labels ((recur (stream)
(if (synonym-stream-p stream)
(recur (symbol-value (synonym-stream-symbol stream)))
stream)))
(recur stream)))
(declaim (inline resolve-synonym-stream))
(defun resolve-synonym-stream (stream)
(let ((result (symbol-value (synonym-stream-symbol stream))))
(if (synonym-stream-p result)
(maybe-resolve-synonym-stream result)
result)))
(defmethod input-stream-p ((stream ansi-stream))
(if (synonym-stream-p stream)
(input-stream-p (resolve-synonym-stream stream))
(and (not (eq (ansi-stream-in stream) #'closed-flame))
: It 's probably not good to have EQ tests on function
;;; values like this. What if someone's redefined the function?
Is there a better way ? ( Perhaps just VALID - FOR - INPUT and
VALID - FOR - OUTPUT flags ? -- WHN 19990902
(or (not (eq (ansi-stream-in stream) #'ill-in))
(not (eq (ansi-stream-bin stream) #'ill-bin))))))
(defmethod output-stream-p ((stream ansi-stream))
(if (synonym-stream-p stream)
(output-stream-p (resolve-synonym-stream stream))
(and (not (eq (ansi-stream-in stream) #'closed-flame))
(or (not (eq (ansi-stream-cout stream) #'ill-out))
(not (eq (ansi-stream-bout stream) #'ill-bout))))))
(defmethod open-stream-p ((stream ansi-stream))
CLHS 21.1.4 lets us not worry about synonym streams here .
(let ((in (ansi-stream-in stream)))
(not (or (eq in (load-time-value #'closed-flame t))
(eq in (load-time-value #'closed-flame-saved t))))))
(defmethod stream-element-type ((stream ansi-stream))
(call-ansi-stream-misc stream :element-type))
(defun stream-external-format (stream)
(stream-api-dispatch (stream)
:simple (s-%stream-external-format stream)
:gray (error "~S is not defined for ~S" 'stream-external-format stream)
:native (call-ansi-stream-misc stream :external-format)))
(defmethod interactive-stream-p ((stream ansi-stream))
(call-ansi-stream-misc stream :interactive-p))
(defmethod close ((stream ansi-stream) &key abort)
(unless (eq (ansi-stream-in stream) #'closed-flame)
(call-ansi-stream-misc stream :close abort))
t)
(defun set-closed-flame (stream)
(setf (ansi-stream-in stream) #'closed-flame)
(setf (ansi-stream-bin stream) #'closed-flame)
(setf (ansi-stream-n-bin stream) #'closed-flame)
(setf (ansi-stream-cout stream) #'closed-flame)
(setf (ansi-stream-bout stream) #'closed-flame)
(setf (ansi-stream-sout stream) #'closed-flame)
(setf (ansi-stream-misc stream) #'closed-flame))
(defun set-closed-flame-by-slad (stream)
(setf (ansi-stream-in stream) #'closed-flame-saved)
(setf (ansi-stream-bin stream) #'closed-flame-saved)
(setf (ansi-stream-n-bin stream) #'closed-flame-saved)
(setf (ansi-stream-cout stream) #'closed-flame-saved)
(setf (ansi-stream-bout stream) #'closed-flame-saved)
(setf (ansi-stream-sout stream) #'closed-flame-saved)
(setf (ansi-stream-misc stream) #'closed-flame-saved))
;;;; for file position and file length
(defun external-format-char-size (external-format)
(ef-char-size (get-external-format external-format)))
;;; Call the MISC method with the :GET-FILE-POSITION operation.
(declaim (inline !ansi-stream-ftell)) ; named for the stdio inquiry function
(defun !ansi-stream-ftell (stream)
(declare (type stream stream))
;; FIXME: It would be good to comment on the stuff that is done here...
;; FIXME: This doesn't look interrupt safe.
(let ((res (call-ansi-stream-misc stream :get-file-position))
(delta (- +ansi-stream-in-buffer-length+
(ansi-stream-in-index stream))))
(if (eql delta 0)
res
(when res
#-sb-unicode
(- res delta)
#+sb-unicode
(let ((char-size (if (fd-stream-p stream)
(fd-stream-char-size stream)
(external-format-char-size (stream-external-format stream)))))
(- res
(etypecase char-size
(function
(loop with buffer = (ansi-stream-cin-buffer stream)
with start = (ansi-stream-in-index stream)
for i from start below +ansi-stream-in-buffer-length+
sum (funcall char-size (aref buffer i))))
(fixnum
(* char-size delta)))))))))
You 're not allowed to specify NIL for the position but we were permitting
;;; it, which made it impossible to test for a bad call that tries to assign
;;; the position, versus a inquiry for the current position.
;;; CLHS specifies: file-position stream position-spec => success-p
and position - spec is a " file position designator " which precludes NIL
;;; but the implementation methods can't detect supplied vs unsupplied.
What a fubar API at the CL : layer . Was # ' ( SETF FILE - POSITION ) not invented ?
(defun file-position (stream &optional (position 0 suppliedp))
(if suppliedp
;; Setter
(let ((arg (the (or index (alien sb-unix:unix-offset) (member :start :end))
position)))
(stream-api-dispatch (stream)
:native (progn
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(call-ansi-stream-misc stream :set-file-position arg))
;; The impl method is expected to return a success indication as
;; a generalized boolean.
:simple (s-%file-position stream arg)
;; I think our fndb entry is overconstrained - it says that this returns
;; either unsigned-byte or strict boolean, however CLHS says that setting
;; FILE-POSITION returns a /generalized boolean/.
;; A stream-specific method should be allowed to convey more information
;; than T/NIL yet we are forced to discard that information,
;; lest the return value constraint on this be violated.
:gray (let ((result (stream-file-position stream arg)))
(if (numberp result) result (and result t)))))
;; Getter
(let ((result (stream-api-dispatch (stream)
:native (!ansi-stream-ftell stream)
:simple (s-%file-position stream nil)
:gray (stream-file-position stream))))
(the (or unsigned-byte null) result))))
(defmethod stream-file-position ((stream ansi-stream) &optional position)
;; Excuse me for asking, but why is this even a thing?
;; Users are not supposed to call the stream implementation directly,
they 're supposed to call the function in the CL : package
;; which indirects to this. But if they do ... make it work.
;; And note that inlining of !ansi-stream-file-position would be pointless,
;; it's nearly 1K of code.
Oh , this is srsly wtf now . If POSITION is NIL ,
;; then you must not call FILE-POSITION with both arguments.
(if position
(file-position stream position)
(file-position stream)))
This is a literal translation of the ANSI glossary entry " stream
;;; associated with a file".
;;;
: Note that since Unix famously thinks " everything is a
file " , and in particular stdin , stdout , and stderr are files , we
;;; end up with this test being satisfied for weird things like
;;; *STANDARD-OUTPUT* (to a tty). That seems unlikely to be what the
;;; ANSI spec really had in mind, especially since this is used as a
qualification for operations like FILE - LENGTH ( so that ANSI was
;;; probably thinking of something like what Unix calls block devices)
but I ca n't see any better way to do it . -- WHN 2001 - 04 - 14
(defun stream-file-stream (stream)
"Test for the ANSI concept \"stream associated with a file\".
Return NIL or the underlying FILE-STREAM."
(typecase stream
(file-stream stream)
(synonym-stream
(stream-file-stream (resolve-synonym-stream stream)))))
(defun stream-file-stream-or-lose (stream)
(declare (type stream stream))
(or (stream-file-stream stream)
(error 'simple-type-error
: The ANSI spec for FILE - LENGTH specifically says
;; this should be TYPE-ERROR. But what then can we use for
;; EXPECTED-TYPE? This SATISFIES type (with a nonstandard
;; private predicate function..) is ugly and confusing, but
I ca n't see any other way . -- WHN 2001 - 04 - 14
:datum stream
:expected-type '(satisfies stream-file-stream)
:format-control
"~@<The stream ~2I~_~S ~I~_isn't associated with a file.~:>"
:format-arguments (list stream))))
(defun stream-file-name-or-lose (stream)
(or (file-name (stream-file-stream-or-lose stream))
(error "~@<The stream ~2I~_~S ~I~_is not associated with a named file.~:>"
stream)))
(defun file-string-length (stream object)
(stream-api-dispatch (stream)
:gray nil
:simple (s-%file-string-length stream object)
:native (call-ansi-stream-misc stream :file-string-length object)))
;;;; input functions
(defun ansi-stream-read-line-from-frc-buffer (stream eof-error-p eof-value)
(prepare-for-fast-read-char stream
(declare (ignore %frc-method%))
(declare (type ansi-stream-cin-buffer %frc-buffer%))
(let ((chunks-total-length 0)
(chunks nil))
(declare (type index chunks-total-length)
(list chunks))
(labels ((refill-buffer ()
(prog1 (fast-read-char-refill stream nil)
(setf %frc-index% (ansi-stream-in-index %frc-stream%))))
(build-result (pos n-more-chars)
(let ((res (make-string (+ chunks-total-length n-more-chars)))
(start1 chunks-total-length))
(declare (type index start1))
(when (>= pos 0)
(replace res %frc-buffer%
:start1 start1 :start2 %frc-index% :end2 pos)
(setf %frc-index% (1+ pos)))
(done-with-fast-read-char)
(dolist (chunk chunks res)
(declare (type (simple-array character (*)) chunk))
(decf start1 (length chunk))
(replace res chunk :start1 start1)))))
(declare (inline refill-buffer))
(if (or (< %frc-index% +ansi-stream-in-buffer-length+) (refill-buffer))
(loop
(let ((pos (position #\Newline %frc-buffer%
:test #'char= :start %frc-index%)))
(when pos
(return (values (build-result pos (- pos %frc-index%)) nil)))
(let ((chunk (subseq %frc-buffer% %frc-index%)))
(incf chunks-total-length (length chunk))
(push chunk chunks))
(unless (refill-buffer)
(return (values (build-result -1 0) t)))))
EOF had been reached before we read anything
at all . Return the EOF value or signal the error .
(progn (done-with-fast-read-char)
(eof-or-lose stream eof-error-p (values eof-value t))))))))
;; to potentially avoid consing a bufer on sucessive calls to read-line
;; (just consing the result string)
(define-load-time-global *read-line-buffers* nil)
(declaim (list *read-line-buffers*))
(declaim (inline ansi-stream-read-line))
(defun ansi-stream-read-line (stream eof-error-p eof-value)
(if (ansi-stream-cin-buffer stream)
;; Stream has a fast-read-char buffer. Copy large chunks directly
;; out of the buffer.
(ansi-stream-read-line-from-frc-buffer stream eof-error-p eof-value)
;; Slow path, character by character.
;; There is no need to use PREPARE-FOR-FAST-READ-CHAR
because the CIN - BUFER is known to be NIL .
(let ((ch (funcall (ansi-stream-in stream) stream nil 0)))
(case ch
(#\newline (values "" nil))
(0 (values (eof-or-lose stream eof-error-p eof-value) t))
(t
(let* ((buffer (or (atomic-pop *read-line-buffers*)
(make-string 128)))
(res buffer)
(len (length res))
(eof)
(index 0))
(declare (type (simple-array character (*)) buffer))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(declare (index index))
(setf (schar res index) (truly-the character ch))
(incf index)
(loop (case (setq ch (funcall (ansi-stream-in stream) stream nil 0))
(#\newline (return))
(0 (return (setq eof t)))
(t
(when (= index len)
(setq len (* len 2))
(let ((new (make-string len)))
(replace new res)
(setq res new)))
(setf (schar res index) (truly-the character ch))
(incf index))))
(if (eq res buffer)
(setq res (subseq buffer 0 index))
(%shrink-vector res index))
;; Do not push an enlarged buffer, only the original one.
(atomic-push buffer *read-line-buffers*)
(values res eof)))))))
(defun read-line (&optional (stream *standard-input*) (eof-error-p t) eof-value
recursive-p)
(declare (explicit-check))
(declare (ignore recursive-p))
(stream-api-dispatch (stream :input)
:simple (s-%read-line stream eof-error-p eof-value)
:native (ansi-stream-read-line stream eof-error-p eof-value)
:gray
(multiple-value-bind (string eof) (stream-read-line stream)
(if (and eof (zerop (length string)))
(values (eof-or-lose stream eof-error-p eof-value) t)
(values string eof)))))
;;; We proclaim them INLINE here, then proclaim them MAYBE-INLINE
;;; later on, so, except in this file, they are not inline by default,
;;; but they can be.
(declaim (inline read-char unread-char read-byte))
(declaim (inline ansi-stream-read-char))
(defun ansi-stream-read-char (stream eof-error-p eof-value recursive-p)
(declare (ignore recursive-p))
(prepare-for-fast-read-char stream
(prog1
(fast-read-char eof-error-p eof-value)
(done-with-fast-read-char))))
(defun read-char (&optional (stream *standard-input*)
(eof-error-p t)
eof-value
recursive-p)
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:native (ansi-stream-read-char stream eof-error-p eof-value recursive-p)
;; The final T is BLOCKING-P. I removed the ignored recursive-p arg.
:simple (let ((char (s-%read-char stream eof-error-p eof-value t)))
(if (eq char eof-value)
char
(the character char)))
:gray
(let ((char (stream-read-char stream)))
(if (eq char :eof)
(eof-or-lose stream eof-error-p eof-value)
(the character char)))))
(declaim (inline ansi-stream-unread-char))
(defun ansi-stream-unread-char (character stream)
(let ((index (1- (ansi-stream-in-index stream)))
(buffer (ansi-stream-cin-buffer stream)))
(declare (fixnum index))
(when (minusp index) (error "nothing to unread"))
(cond (buffer
(setf (aref buffer index) character)
(setf (ansi-stream-in-index stream) index)
;; Ugh. an ANSI-STREAM with a char buffer never gives a chance to
the stream 's misc routine to handle the UNREAD operation .
(when (ansi-stream-input-char-pos stream)
(decf (ansi-stream-input-char-pos stream))))
(t
(call-ansi-stream-misc stream :unread character)))))
(defun unread-char (character &optional (stream *standard-input*))
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:simple (s-%unread-char stream character)
:native (ansi-stream-unread-char character stream)
:gray (stream-unread-char stream character))
nil)
(declaim (inline %ansi-stream-listen))
(defun %ansi-stream-listen (stream)
(or (/= (the fixnum (ansi-stream-in-index stream))
+ansi-stream-in-buffer-length+)
(call-ansi-stream-misc stream :listen)))
(declaim (inline ansi-stream-listen))
(defun ansi-stream-listen (stream)
(let ((result (%ansi-stream-listen stream)))
(if (eq result :eof)
nil
result)))
(defun listen (&optional (stream *standard-input*))
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:simple (error "Unimplemented") ; gets redefined
:native (ansi-stream-listen stream)
:gray (stream-listen stream)))
(declaim (inline ansi-stream-read-char-no-hang))
(defun ansi-stream-read-char-no-hang (stream eof-error-p eof-value recursive-p)
(if (%ansi-stream-listen stream)
On T or : EOF get READ - CHAR to do the work .
(ansi-stream-read-char stream eof-error-p eof-value recursive-p)
nil))
(defun read-char-no-hang (&optional (stream *standard-input*)
(eof-error-p t)
eof-value
recursive-p)
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:native
(ansi-stream-read-char-no-hang stream eof-error-p eof-value
recursive-p)
;; Absence of EOF-OR-LOSE here looks a little suspicious
;; considering that the impl function didn't use recursive-p
:simple (s-%read-char-no-hang stream eof-error-p eof-value)
:gray
(let ((char (stream-read-char-no-hang stream)))
(if (eq char :eof)
(eof-or-lose stream eof-error-p eof-value)
(the (or character null) char)))))
(declaim (inline ansi-stream-clear-input))
(defun ansi-stream-clear-input (stream)
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(call-ansi-stream-misc stream :clear-input))
(defun clear-input (&optional (stream *standard-input*))
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:simple (error "Unimplemented") ; gets redefined
:native (ansi-stream-clear-input stream)
:gray (stream-clear-input stream))
nil)
(declaim (inline ansi-stream-read-byte))
(defun ansi-stream-read-byte (stream eof-error-p eof-value recursive-p)
;; Why the "recursive-p" parameter? a-s-r-b is funcall'ed from
;; a-s-read-sequence and needs a lambda list that's congruent with
;; that of a-s-read-char
(declare (ignore recursive-p))
(with-fast-read-byte (t stream eof-error-p eof-value)
(fast-read-byte)))
(defun read-byte (stream &optional (eof-error-p t) eof-value)
(declare (explicit-check))
(stream-api-dispatch (stream)
:native (ansi-stream-read-byte stream eof-error-p eof-value nil)
:simple (let ((byte (s-%read-byte stream eof-error-p eof-value)))
(if (eq byte eof-value)
byte
(the integer byte)))
:gray
(let ((byte (stream-read-byte stream)))
(if (eq byte :eof)
(eof-or-lose stream eof-error-p eof-value)
(the integer byte)))))
Read NUMBYTES bytes into BUFFER beginning at START , and return the
;;; number of bytes read.
;;;
Note : CMU CL 's version of this had a special interpretation of
EOF - ERROR - P which SBCL does not have . ( In the EOF - ERROR - P = NIL
case , CMU CL 's version would return as soon as any data became
;;; available.) This could be useful behavior for things like pipes in
some cases , but it was n't being used in SBCL , so it was dropped .
If we ever need it , it could be added later as a new variant N - BIN
;;; method (perhaps N-BIN-ASAP?) or something.
(declaim (inline read-n-bytes))
(defun read-n-bytes (stream buffer start numbytes &optional (eof-error-p t))
(if (ansi-stream-p stream)
(ansi-stream-read-n-bytes stream buffer start numbytes eof-error-p)
;; We don't need to worry about element-type size here is that
;; callers are supposed to have checked everything is kosher.
(let* ((end (+ start numbytes))
(read-end (stream-read-sequence stream buffer start end)))
(eof-or-lose stream (and eof-error-p (< read-end end)) (- read-end start)))))
(defun ansi-stream-read-n-bytes (stream buffer start numbytes eof-error-p)
(declare (type ansi-stream stream)
(type index numbytes start)
(type (or (simple-array * (*)) system-area-pointer) buffer))
(let ((in-buffer (ansi-stream-in-buffer stream)))
(unless in-buffer
(return-from ansi-stream-read-n-bytes
(funcall (ansi-stream-n-bin stream) stream buffer start numbytes eof-error-p)))
(let* ((index (ansi-stream-in-index stream))
(num-buffered (- +ansi-stream-in-buffer-length+ index)))
These bytes are of course actual bytes , i.e. 8 - bit octets
;; and not variable-length bytes.
(cond ((<= numbytes num-buffered)
(%byte-blt in-buffer index buffer start (+ start numbytes))
(setf (ansi-stream-in-index stream) (+ index numbytes))
numbytes)
(t
(let ((end (+ start num-buffered)))
(%byte-blt in-buffer index buffer start end)
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(+ (funcall (ansi-stream-n-bin stream) stream buffer
end (- numbytes num-buffered) eof-error-p)
num-buffered)))))))
;;; the amount of space we leave at the start of the in-buffer for
;;; unreading
;;;
( It 's 4 instead of 1 to allow word - aligned copies . )
(defconstant +ansi-stream-in-buffer-extra+
4) ; FIXME: should be symbolic constant
;;; This function is called by the FAST-READ-CHAR expansion to refill
;;; the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
;;; and hence must be an N-BIN method. It's also called by other stream
;;; functions which directly peek into the frc buffer.
If EOF is hit and EOF - ERROR - P is false , then return NIL ,
otherwise return the new index into CIN - BUFFER .
(defun fast-read-char-refill (stream eof-error-p)
(when (ansi-stream-input-char-pos stream)
;; Characters between (ANSI-STREAM-IN-INDEX %FRC-STREAM%)
;; and +ANSI-STREAM-IN-BUFFER-LENGTH+ have to be re-scanned.
(update-input-char-pos stream))
(let* ((ibuf (ansi-stream-cin-buffer stream))
(count (funcall (ansi-stream-n-bin stream)
stream
ibuf
+ansi-stream-in-buffer-extra+
(- +ansi-stream-in-buffer-length+
+ansi-stream-in-buffer-extra+)
nil))
(start (- +ansi-stream-in-buffer-length+ count)))
(declare (type index start count))
(cond ((zerop count)
;; An empty count does not necessarily mean that we reached
the EOF , it 's also possible that it 's e.g. due to a
;; invalid octet sequence in a multibyte stream. To handle
the case correctly we need to call the reading
function and check whether an EOF was really reached . If
not , we can just fill the buffer by one character , and
;; hope that the next refill will not need to resync.
;;
: we ca n't use FD - STREAM functions ( which are the
;; only ones which will give us decoding errors) here,
;; because this code is generic. We can't call the N-BIN
;; function, because near the end of a real file that can
;; legitimately bounce us to the IN function. So we have
;; to call ANSI-STREAM-IN.
(let* ((index (1- +ansi-stream-in-buffer-length+))
(value (funcall (ansi-stream-in stream) stream nil :eof)))
(cond
;; When not signaling an error, it is important that IN-INDEX
;; be set to +ANSI-STREAM-IN-BUFFER-LENGTH+ here, even though
;; DONE-WITH-FAST-READ-CHAR will do the same, thereby writing
;; the caller's %FRC-INDEX% (= +ANSI-STREAM-IN-BUFFER-LENGTH+)
into the slot . But because we 've already bumped INPUT - CHAR - POS
;; and scanned characters between the original %FRC-INDEX%
;; and the buffer end (above), we must *not* do that again.
((eql value :eof)
definitely EOF now
(setf (ansi-stream-in-index stream)
+ansi-stream-in-buffer-length+)
(eof-or-lose stream eof-error-p nil))
;; we resynced or were given something instead
(t
(setf (aref ibuf index) value)
(setf (ansi-stream-in-index stream) index)))))
(t
(when (/= start +ansi-stream-in-buffer-extra+)
(#.(let* ((n-character-array-bits
(sb-vm:saetp-n-bits
(find 'character
sb-vm:*specialized-array-element-type-properties*
:key #'sb-vm:saetp-specifier)))
(bash-function (intern (format nil "UB~D-BASH-COPY" n-character-array-bits)
(find-package "SB-KERNEL"))))
bash-function)
ibuf +ansi-stream-in-buffer-extra+
ibuf start
count))
(setf (ansi-stream-in-index stream) start)))))
;;; This is similar to FAST-READ-CHAR-REFILL, but we don't have to
;;; leave room for unreading.
(defun fast-read-byte-refill (stream eof-error-p eof-value)
(let* ((ibuf (ansi-stream-in-buffer stream))
(count (funcall (ansi-stream-n-bin stream) stream
ibuf 0 +ansi-stream-in-buffer-length+
nil))
(start (- +ansi-stream-in-buffer-length+ count)))
(declare (type index start count))
(cond ((zerop count)
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(funcall (ansi-stream-bin stream) stream eof-error-p eof-value))
(t
(unless (zerop start)
(ub8-bash-copy ibuf 0
ibuf start
count))
(setf (ansi-stream-in-index stream) (1+ start))
(aref ibuf start)))))
;;; output functions
(defun write-char (character &optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (return-from write-char (funcall (ansi-stream-cout stream) stream character))
:simple (s-%write-char stream character)
:gray (stream-write-char stream character))
character)
(defun terpri (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (funcall (ansi-stream-cout stream) stream #\Newline)
:simple (s-%terpri stream)
:gray (stream-terpri stream))
nil)
(defun fresh-line (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (unless (eql (charpos stream) 0)
(funcall (ansi-stream-cout stream) stream #\newline)
t)
:simple (s-%fresh-line stream)
:gray (stream-fresh-line stream)))
(macrolet
((define (name)
`(defun ,name (string stream start end)
;; unclear why the dispatch to simple and gray methods have to receive a simple-string.
;; I'm pretty sure the STREAM-foo methods on gray streams are not specified to be
;; constrained to receive only simple-string.
;; So they must either do their their own "unwrapping" of a complex string, or
instead just access character - at - a - time or inefficiently call SUBSEQ .
(with-array-data ((data string) (start start) (end end) :check-fill-pointer t)
(stream-api-dispatch (stream :output)
:native (progn (funcall (ansi-stream-sout stream) stream data start end)
,@(when (eq name '%write-line)
'((funcall (ansi-stream-cout stream) stream #\newline))))
:simple (,(symbolicate "S-" name) stream data start end)
:gray (progn (stream-write-string stream data start end)
,@(when (eq name '%write-line)
'((stream-write-char stream #\newline))))))
string)))
(define %write-line)
(define %write-string))
(defun write-string (string &optional (stream *standard-output*)
&key (start 0) end)
(declare (explicit-check))
(%write-string string stream start end))
(defun write-line (string &optional (stream *standard-output*)
&key (start 0) end)
(declare (explicit-check))
(%write-line string stream start end))
(defun charpos (&optional (stream *standard-output*))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :charpos)
:simple (s-%charpos stream)
:gray (stream-line-column stream)))
(defun line-length (&optional (stream *standard-output*))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :line-length)
:simple (s-%line-length stream)
:gray (stream-line-length stream)))
(defun finish-output (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :finish-output)
:simple (s-%finish-output stream)
:gray (stream-finish-output stream))
nil)
(defun force-output (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :force-output)
:simple (s-%force-output stream)
:gray (stream-force-output stream))
nil)
(defun clear-output (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :clear-output)
:simple (s-%clear-output stream)
:gray (stream-clear-output stream))
nil)
(defun write-byte (integer stream)
(declare (explicit-check))
;; The STREAM argument is not allowed to be a designator.
(stream-api-dispatch (stream)
:native (return-from write-byte (funcall (ansi-stream-bout stream) stream integer))
:simple (s-%write-byte stream integer)
:gray (stream-write-byte stream integer))
integer)
(declaim (maybe-inline read-char unread-char read-byte)) ; too big
This is called from ANSI - STREAM routines that encapsulate CLOS
;;; streams to handle the misc routines and dispatch to the
appropriate SIMPLE- or FUNDAMENTAL - STREAM functions .
(defun stream-misc-dispatch (stream operation arg)
(if (simple-stream-p stream)
Dispatch to a simple - stream implementation function
(stream-misc-case (operation)
(:listen (listen stream)) ; call the redefined LISTEN
(:unread (s-%unread-char stream arg))
(:close (error "Attempted to close inner stream ~S" stream))
(:clear-input (clear-input stream)) ; call the redefined CLEAR-INPUT
(:force-output (s-%force-output stream))
(:finish-output (s-%finish-output stream))
(:clear-output (s-%clear-output stream))
All simple - streams use ( UNSIGNED - BYTE 8) - it 's one of the
salient distinctions between simple - streams and Gray streams .
See ( DEFMETHOD STREAM - ELEMENT - TYPE ( ( STREAM SIMPLE - STREAM ) ) ... )
(:element-type '(unsigned-byte 8))
;; FIXME: All simple-streams are actually bivalent. We historically have
returned UNSIGNED - BYTE based on element - type . But this is wrong !
(:element-mode 'UNSIGNED-BYTE)
;; This call returns an instance of the format structure defined
;; by the SB-SIMPLE-STREAMS package, not the SB-IMPL:: structure.
;; This also needs to be fixed.
(:external-format (s-%stream-external-format stream))
(:interactive-p (interactive-stream-p stream))
(:line-length (s-%line-length stream))
(:charpos (s-%charpos stream))
(:file-length (s-%file-length stream))
(:file-string-length (s-%file-string-length stream arg))
(:set-file-position (s-%file-position stream arg))
;; yeesh, this wants a _required_ NIL argument to mean "inquire".
(:get-file-position (s-%file-position stream nil)))
;; else call the generic function
(stream-misc-case (operation)
(:listen (stream-listen stream))
specialized arg first
(:close (error "Attempted to close inner stream ~S" stream))
(:clear-input (stream-clear-input stream))
(:force-output (stream-force-output stream))
(:finish-output (stream-finish-output stream))
(:clear-output (stream-clear-output stream))
(:element-type (stream-element-type stream))
(:element-mode
(stream-element-type-stream-element-mode (stream-element-type stream)))
(:interactive-p (interactive-stream-p stream)) ; is generic
(:line-length (stream-line-length stream))
(:charpos (stream-line-column stream))
(:set-file-position (stream-file-position stream arg))
(:get-file-position (stream-file-position stream))
;; This last bunch of pseudo-methods will probably just signal an error
since they are n't generic and do n't work on Gray streams .
(:external-format (stream-external-format stream))
(:file-length (file-length stream))
(:file-string-length (file-string-length stream arg)))))
(declaim (inline stream-element-mode))
(defun stream-element-mode (stream)
(declare (type stream stream))
(cond
((fd-stream-p stream)
(fd-stream-element-mode stream))
((and (ansi-stream-p stream)
(call-ansi-stream-misc stream :element-mode)))
(t
(stream-element-type-stream-element-mode
(stream-element-type stream)))))
;;;; broadcast streams
(defun make-broadcast-stream (&rest streams)
(dolist (stream streams)
(unless (output-stream-p stream)
(error 'type-error
:datum stream
:expected-type '(satisfies output-stream-p))))
(let ((stream (%make-broadcast-stream streams)))
(unless streams
(flet ((out (stream arg)
(declare (ignore stream)
(optimize speed (safety 0)))
arg)
(sout (stream string start end)
(declare (ignore stream string start end)
(optimize speed (safety 0)))))
(setf (broadcast-stream-cout stream) #'out
(broadcast-stream-bout stream) #'out
(broadcast-stream-sout stream) #'sout)))
stream))
(macrolet ((out-fun (name fun args return)
`(defun ,name (stream ,@args)
(dolist (stream (broadcast-stream-streams stream) ,return)
(,fun ,(car args) stream ,@(cdr args))))))
(out-fun broadcast-cout write-char (char) char)
(out-fun broadcast-bout write-byte (byte) byte)
(out-fun broadcast-sout %write-string (string start end) nil))
(defun broadcast-misc (stream operation arg1)
(let ((streams (broadcast-stream-streams stream)))
(stream-misc-case (operation)
;; FIXME: This may not be the best place to note this, but I
;; think the :CHARPOS protocol needs revision. Firstly, I think
;; this is the last place where a NULL return value was possible
;; (before adjusting it to be 0), so a bunch of conditionals IF
CHARPOS can be removed ; secondly , it is my belief that
;; FD-STREAMS, when running FILE-POSITION, do not update the
;; CHARPOS, and consequently there will be much wrongness.
;;
FIXME : see also TWO - WAY - STREAM treatment of : CHARPOS -- why
;; is it testing the :charpos of an input stream?
;;
-- CSR , 2004 - 02 - 04
(:charpos
(dolist (stream streams 0)
(let ((charpos (charpos stream)))
(when charpos
(return charpos)))))
(:line-length
(let ((min nil))
(dolist (stream streams min)
(let ((res (line-length stream)))
(when res (setq min (if min (min res min) res)))))))
(:element-type
(let ((last (last streams)))
(if last
(stream-element-type (car last))
t)))
(:element-mode
(awhen (last streams)
(stream-element-mode (car it))))
(:external-format
(let ((last (last streams)))
(if last
(stream-external-format (car last))
:default)))
(:file-length
(let ((last (last streams)))
(if last
(file-length (car last))
0)))
(:set-file-position
(let ((res (or (eql arg1 :start) (eql arg1 0))))
(dolist (stream streams res)
(setq res (file-position stream arg1)))))
(:get-file-position
(let ((last (last streams)))
(if last
(file-position (car last))
0)))
(:file-string-length
(let ((last (last streams)))
(if last
(file-string-length (car last) arg1)
1)))
(:close
;; I don't know how something is trying to close the
;; universal sink stream, but it is. Stop it from happening.
(unless (eq stream *null-broadcast-stream*)
(set-closed-flame stream)))
(t
(let ((res nil))
(dolist (stream streams res)
(setq res
(if (ansi-stream-p stream)
(call-ansi-stream-misc stream operation arg1)
(stream-misc-dispatch stream operation arg1)))))))))
;;;; synonym streams
(defmethod print-object ((x synonym-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
;;; The output simple output methods just call the corresponding
;;; function on the synonymed stream.
(macrolet ((out-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(declare (optimize (safety 1)))
(let ((syn (symbol-value (synonym-stream-symbol stream))))
(,fun ,(car args) syn ,@(cdr args))))))
(out-fun synonym-out write-char ch)
(out-fun synonym-bout write-byte n)
(out-fun synonym-sout %write-string string start end))
;;; For the input methods, we just call the corresponding function on the
;;; synonymed stream. These functions deal with getting input out of
;;; the In-Buffer if there is any.
(macrolet ((in-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(declare (optimize (safety 1)))
(,fun (symbol-value (synonym-stream-symbol stream))
,@args))))
(in-fun synonym-in read-char eof-error-p eof-value)
(in-fun synonym-bin read-byte eof-error-p eof-value)
(in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
(defun synonym-misc (stream operation arg1)
(declare (optimize (safety 1)))
CLHS 21.1.4 implies that CLOSE on a synonym stream closes the synonym stream in that
;; "The consequences are undefined if the synonym stream symbol is not bound to an open
;; stream from the time of the synonym stream's creation until the time it is closed."
;; The antecent of this "it" is the synonym stream --------------^
;; which means that there exist a way to close synonym streams.
;; We can presume that CLOSE is that way, despite some text seemingly to the contrary
;; "Any operations on a synonym stream will be performed on the stream that is then
;; the value of the dynamic variable named by the synonym stream symbol."
;; so "any" in that sentence mean "almost any, with a notable exception".
(stream-misc-case (operation)
(:close
(set-closed-flame stream))
(t
(let ((syn (symbol-value (synonym-stream-symbol stream))))
(if (ansi-stream-p syn)
;; We have to special-case some operations which interact with
;; the in-buffer of the wrapped stream, since just calling
;; ANSI-STREAM-MISC on them
(stream-misc-case (operation)
(:listen (%ansi-stream-listen syn))
(:clear-input (clear-input syn))
(:unread (unread-char arg1 syn))
(t
(call-ansi-stream-misc syn operation arg1)))
(stream-misc-dispatch syn operation arg1))))))
two - way streams
(defstruct (two-way-stream
(:include ansi-stream
(in #'two-way-in)
(bin #'two-way-bin)
(n-bin #'two-way-n-bin)
(cout #'two-way-out)
(bout #'two-way-bout)
(sout #'two-way-sout)
(misc #'two-way-misc))
(:constructor %make-two-way-stream (input-stream output-stream))
(:copier nil)
(:predicate nil))
(input-stream (missing-arg) :type stream :read-only t)
(output-stream (missing-arg) :type stream :read-only t))
(defmethod print-object ((x two-way-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream
":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
(two-way-stream-input-stream x)
(two-way-stream-output-stream x))))
(defun make-two-way-stream (input-stream output-stream)
"Return a bidirectional stream which gets its input from INPUT-STREAM and
sends its output to OUTPUT-STREAM."
(unless (output-stream-p output-stream)
(error 'type-error
:datum output-stream
:expected-type '(satisfies output-stream-p)))
(unless (input-stream-p input-stream)
(error 'type-error
:datum input-stream
:expected-type '(satisfies input-stream-p)))
(%make-two-way-stream input-stream output-stream))
(macrolet ((out-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(let ((syn (two-way-stream-output-stream stream)))
(,fun ,(car args) syn ,@(cdr args))))))
(out-fun two-way-out write-char ch)
(out-fun two-way-bout write-byte n)
(out-fun two-way-sout %write-string string start end))
(macrolet ((in-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(,fun (two-way-stream-input-stream stream) ,@args))))
(in-fun two-way-in read-char eof-error-p eof-value)
(in-fun two-way-bin read-byte eof-error-p eof-value)
(in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
(defun two-way-misc (stream operation arg1)
(let* ((in (two-way-stream-input-stream stream))
(out (two-way-stream-output-stream stream))
(in-ansi-stream-p (ansi-stream-p in))
(out-ansi-stream-p (ansi-stream-p out)))
(stream-misc-case (operation)
(:listen
(if in-ansi-stream-p
(%ansi-stream-listen in)
(listen in)))
((:finish-output :force-output :clear-output)
(if out-ansi-stream-p
(call-ansi-stream-misc out operation arg1)
(stream-misc-dispatch out operation arg1)))
(:clear-input (clear-input in))
(:unread (unread-char arg1 in))
(:element-type
(let ((in-type (stream-element-type in))
(out-type (stream-element-type out)))
(if (equal in-type out-type)
in-type
`(and ,in-type ,out-type))))
(:element-mode
(let ((in-mode (stream-element-mode in))
(out-mode (stream-element-mode out)))
(when (equal in-mode out-mode)
in-mode)))
(:close
(set-closed-flame stream))
(t
(or (if in-ansi-stream-p
(call-ansi-stream-misc in operation arg1)
(stream-misc-dispatch in operation arg1))
(if out-ansi-stream-p
(call-ansi-stream-misc out operation arg1)
(stream-misc-dispatch out operation arg1)))))))
;;;; concatenated streams
(defstruct (concatenated-stream
(:include ansi-stream
(in #'concatenated-in)
(bin #'concatenated-bin)
(n-bin #'concatenated-n-bin)
(misc #'concatenated-misc))
(:constructor %make-concatenated-stream (streams))
(:copier nil)
(:predicate nil))
;; The car of this is the substream we are reading from now.
(streams nil :type list))
(declaim (freeze-type concatenated-stream))
(defmethod print-object ((x concatenated-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream
":STREAMS ~S"
(concatenated-stream-streams x))))
(defun make-concatenated-stream (&rest streams)
"Return a stream which takes its input from each of the streams in turn,
going on to the next at EOF."
(dolist (stream streams)
(unless (input-stream-p stream)
(error 'type-error
:datum stream
:expected-type '(satisfies input-stream-p))))
(%make-concatenated-stream streams))
(macrolet ((in-fun (name fun)
`(defun ,name (stream eof-error-p eof-value)
(do ((streams (concatenated-stream-streams stream)
(cdr streams)))
((null streams)
(eof-or-lose stream eof-error-p eof-value))
(let* ((stream (car streams))
(result (,fun stream nil nil)))
(when result (return result)))
(pop (concatenated-stream-streams stream))))))
(in-fun concatenated-in read-char)
(in-fun concatenated-bin read-byte))
(defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
(do ((streams (concatenated-stream-streams stream) (cdr streams))
(current-start start)
(remaining-bytes numbytes))
((null streams)
(if eof-errorp
(error 'end-of-file :stream stream)
(- numbytes remaining-bytes)))
(let* ((stream (car streams))
(bytes-read (read-n-bytes stream buffer current-start
remaining-bytes nil)))
(incf current-start bytes-read)
(decf remaining-bytes bytes-read)
(when (zerop remaining-bytes) (return numbytes)))
(setf (concatenated-stream-streams stream) (cdr streams))))
(defun concatenated-misc (stream operation arg1)
(let* ((left (concatenated-stream-streams stream))
(current (car left)))
(stream-misc-case (operation)
(:listen
(unless left
(return-from concatenated-misc :eof))
(loop
(let ((stuff (if (ansi-stream-p current)
(%ansi-stream-listen current)
(stream-misc-dispatch current operation arg1))))
(cond ((eq stuff :eof)
;; Advance STREAMS, and try again.
(pop (concatenated-stream-streams stream))
(setf current
(car (concatenated-stream-streams stream)))
(unless current
;; No further streams. EOF.
(return :eof)))
(stuff
;; Stuff's available.
(return t))
(t
;; Nothing is available yet.
(return nil))))))
(:clear-input (when left (clear-input current)))
(:unread (when left (unread-char arg1 current)))
(:close
(set-closed-flame stream))
(t
(when left
(if (ansi-stream-p current)
(call-ansi-stream-misc current operation arg1)
(stream-misc-dispatch current operation arg1)))))))
;;;; echo streams
(defstruct (echo-stream
(:include two-way-stream
(in #'echo-in)
(bin #'echo-bin)
(misc #'echo-misc)
(n-bin #'echo-n-bin))
(:constructor %make-echo-stream (input-stream output-stream))
(:copier nil)
(:predicate nil))
(unread-stuff nil :type boolean))
(declaim (freeze-type two-way-stream))
(defmethod print-object ((x echo-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream
":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
(two-way-stream-input-stream x)
(two-way-stream-output-stream x))))
(defun make-echo-stream (input-stream output-stream)
"Return a bidirectional stream which gets its input from INPUT-STREAM and
sends its output to OUTPUT-STREAM. In addition, all input is echoed to
the output stream."
(unless (output-stream-p output-stream)
(error 'type-error
:datum output-stream
:expected-type '(satisfies output-stream-p)))
(unless (input-stream-p input-stream)
(error 'type-error
:datum input-stream
:expected-type '(satisfies input-stream-p)))
(%make-echo-stream input-stream output-stream))
(macrolet ((in-fun (name in-fun out-fun &rest args)
`(defun ,name (stream ,@args)
(let* ((unread-stuff-p (echo-stream-unread-stuff stream))
(in (echo-stream-input-stream stream))
(out (echo-stream-output-stream stream))
(result (if eof-error-p
(,in-fun in ,@args)
(,in-fun in nil in))))
(setf (echo-stream-unread-stuff stream) nil)
(cond
((eql result in) eof-value)
;; If unread-stuff was true, the character read
;; from the input stream was previously echoed.
(t (unless unread-stuff-p (,out-fun result out)) result))))))
(in-fun echo-in read-char write-char eof-error-p eof-value)
(in-fun echo-bin read-byte write-byte eof-error-p eof-value))
(defun echo-n-bin (stream buffer start numbytes eof-error-p)
(let ((bytes-read 0))
Note : before ca 1.0.27.18 , the logic for handling unread
;; characters never could have worked, so probably nobody has ever
;; tried doing bivalent block I/O through an echo stream; this may
;; not work either.
(when (echo-stream-unread-stuff stream)
(let* ((char (read-char stream))
(octets (string-to-octets
(string char)
:external-format
(stream-external-format
(echo-stream-input-stream stream))))
(octet-count (length octets))
(blt-count (min octet-count numbytes)))
(replace buffer octets :start1 start :end1 (+ start blt-count))
(incf start blt-count)
(decf numbytes blt-count)))
(incf bytes-read (read-n-bytes (echo-stream-input-stream stream) buffer
start numbytes nil))
(cond
((not eof-error-p)
(write-seq-impl buffer (echo-stream-output-stream stream)
start (+ start bytes-read))
bytes-read)
((> numbytes bytes-read)
(write-seq-impl buffer (echo-stream-output-stream stream)
start (+ start bytes-read))
(error 'end-of-file :stream stream))
(t
(write-seq-impl buffer (echo-stream-output-stream stream)
start (+ start bytes-read))
(aver (= numbytes (+ start bytes-read)))
numbytes))))
;;;; STRING-INPUT-STREAM stuff
(defstruct (string-input-stream
(:include ansi-stream (misc #'string-in-misc))
(:constructor nil)
(:copier nil)
(:predicate nil))
;; Indices into STRING
(index nil :type index)
(limit nil :type index :read-only t)
;; Backing string after following displaced array chain
(string nil :type simple-string :read-only t)
So that we know what string index FILE - POSITION 0 to
(start nil :type index :read-only t))
(declaim (freeze-type string-input-stream))
(defun string-in-misc (stream operation arg1)
(declare (type string-input-stream stream))
(stream-misc-case (operation :default nil)
(:set-file-position
(setf (string-input-stream-index stream)
(case arg1
(:start (string-input-stream-start stream))
(:end (string-input-stream-limit stream))
We allow moving position beyond EOF . Errors happen
;; on read, not move.
(t (+ (string-input-stream-start stream) arg1)))))
(:get-file-position
(- (string-input-stream-index stream)
(string-input-stream-start stream)))
;; According to ANSI: "Should signal an error of type type-error
;; if stream is not a stream associated with a file."
;; This is checked by FILE-LENGTH, so no need to do it here either.
;; (:file-length (length (string-input-stream-string stream)))
(:unread (setf (string-input-stream-index stream)
;; silently ignore attempts to go backwards too far
(max (1- (string-input-stream-index stream))
(string-input-stream-start stream))))
(:close (set-closed-flame stream))
(:listen (if (< (string-input-stream-index stream)
(string-input-stream-limit stream))
t :eof))
(:element-type (array-element-type (string-input-stream-string stream)))
(:element-mode 'character)))
Since we do n't want to insert ~300 bytes of code at every site
;;; of WITH-INPUT-FROM-STRING, and we lack a way to perform partial inline
;;; dx allocation of structures, this'll have to do.
(defun %init-string-input-stream (stream string &optional (start 0) end)
(declare (explicit-check string))
(macrolet ((initforms ()
`(progn
,@(mapcar (lambda (dsd)
;; good thing we have no raw slots in stream structures
`(%instance-set stream ,(dsd-index dsd)
,(case (dsd-name dsd)
((index start) 'start)
(limit 'end)
(string 'simple-string)
(in 'input-routine)
(misc '#'string-in-misc)
(t (dsd-default dsd)))))
(dd-slots
(find-defstruct-description 'string-input-stream)))))
(char-in (element-type)
`(let ((index (string-input-stream-index
(truly-the string-input-stream stream)))
(string (truly-the (simple-array ,element-type (*))
(string-input-stream-string stream))))
(cond ((>= index (string-input-stream-limit stream))
(eof-or-lose stream eof-error-p eof-value))
(t
(setf (string-input-stream-index stream) (1+ index))
(char string index))))))
(flet ((base-char-in (stream eof-error-p eof-value)
(declare (optimize (sb-c::verify-arg-count 0)
(sb-c:insert-array-bounds-checks 0)))
(char-in base-char))
(character-in (stream eof-error-p eof-value)
(declare (optimize (sb-c::verify-arg-count 0)
(sb-c:insert-array-bounds-checks 0)))
(char-in character)))
(let ((input-routine
(etypecase string
(base-string #'base-char-in)
(string #'character-in))))
(with-array-data ((simple-string string :offset-var offset)
(start start)
(end end)
:check-fill-pointer t)
(initforms)
(values (truly-the string-input-stream stream)
offset))))))
;;; It's debatable whether we should try to convert
;;; (let ((s (make-string-input-stream))) (declare (dynamic-extent s)) ...)
;;; into the thing that WITH-INPUT-FROM-STRING does. That's what the macro is for.
(defun make-string-input-stream (string &optional (start 0) end)
"Return an input stream which will supply the characters of STRING between
START and END in order."
(macrolet ((make () `(%make-structure-instance
,(find-defstruct-description 'string-input-stream)
nil)))
;; kill the secondary value
(values (%init-string-input-stream (make) string start end))))
;;;; STRING-OUTPUT-STREAM stuff
;;;;
;;;; FIXME: This, like almost none of the stream code is particularly
;;;; interrupt or thread-safe. While it should not be possible to
;;;; corrupt the heap here, it certainly is possible to end up with
;;;; a string-output-stream whose internal state is messed up.
;;;;
(defun %init-string-output-stream (stream buffer wild-result-type)
(declare (optimize speed (sb-c::verify-arg-count 0)))
(declare (string buffer)
(ignorable wild-result-type)) ; if #-sb-unicode
(macrolet ((initforms ()
`(progn
,@(mapcar (lambda (dsd)
`(%instance-set stream ,(dsd-index dsd)
,(case (dsd-name dsd)
(sout '#'string-sout) ; global fun
(misc '#'misc) ; local fun
((element-type unicode-p cout sout-aux buffer)
(dsd-name dsd))
(t (dsd-default dsd)))))
(dd-slots
(find-defstruct-description 'string-output-stream)))))
(cout (elt-type)
`(let ((pointer (string-output-stream-pointer
(truly-the string-output-stream stream)))
(buffer (truly-the (simple-array ,elt-type (*))
(string-output-stream-buffer stream)))
(index (string-output-stream-index stream)))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(when (= pointer (length buffer))
;; The usual doubling technique: the new buffer shall hold as many
;; characters as were already emplaced.
(setf buffer (string-output-stream-new-buffer stream index)
pointer 0))
(setf (string-output-stream-pointer stream) (truly-the index (1+ pointer)))
(setf (string-output-stream-index stream) (truly-the index (1+ index)))
;; return the character
(setf (aref (truly-the (simple-array ,elt-type (*)) buffer) pointer)
char)))
(sout (elt-type)
Only one case cares whether the string contains non - base chars .
;; base-string source and buffer : OK
;; base-string source, character-string buffer : OK
character - string source , base - string buf verifies base - char on copy
character - string source + buf needs a pre - scan for Unicode .
`(etypecase src
#+sb-unicode
(simple-character-string
,@(when (eq elt-type 'character)
When UNICODE - P is NIL , meaning no non - base chars were seen yet
;; in the input, pre-scan to see whether that still holds.
'((when (and (not (string-output-stream-unicode-p
(truly-the string-output-stream stream)))
(input-contains-unicode))
(setf (string-output-stream-unicode-p stream) t
;; no need to keep checking each character
(ansi-stream-cout stream) #'character-out))))
;; There are transforms for all the necessary REPLACE variations.
(replace (truly-the (simple-array ,elt-type (*)) dst)
(truly-the simple-character-string src)
:start1 start1 :start2 start2 :end2 end2))
(simple-base-string
(replace (truly-the (simple-array ,elt-type (*)) dst)
(truly-the simple-base-string src)
:start1 start1 :start2 start2 :end2 end2))))
(input-contains-unicode ()
For streams with : element - type ( producing the most space - efficient
;; string that can hold the output), checking whether Unicode characters appear
;; in the source material is potentially advantageous versus checking the
;; buffer in GET-OUTPUT-STREAM-STRING, because if all source strings are
;; BASE-STRING, we needn't check anything.
;; Bounds check was already performed
`(let ((s (truly-the simple-character-string src)))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(loop for i from start2 below end2
thereis (>= (char-code (aref s i)) base-char-code-limit)))))
;; The "wonderful" thing is you never know where type checks have already been done.
Is a character for sure ? I have no idea . And how about the indices in SOUT ?
(labels ((base-char-out (stream char)
(cout base-char))
(character-out (stream char)
(cout character))
(default-out (stream char)
(when (>= (char-code char) base-char-code-limit)
(setf (string-output-stream-unicode-p stream) t
;; no need to keep checking each character
(ansi-stream-cout stream) #'character-out))
(cout character))
(base-string-out (stream dst src start1 start2 end2)
(declare (ignorable stream) (index start1 start2 end2))
(sout base-char))
(char-string-out (stream dst src start1 start2 end2)
(declare (ignorable stream) (index start1 start2 end2))
(sout character))
(reject (&rest args)
(declare (ignore args))
(error "Stream can not accept characters"))
(misc (stream operation arg1)
Intercept the misc handler to reset the Unicode state
;; (since the char handlers are local functions).
;; Technically this should be among the actions performed on :CLEAR-OUTPUT,
;; which would also include *actually* clearing the output. But we don't.
(stream-misc-case (operation)
(:reset-unicode-p
(setf (string-output-stream-unicode-p stream) nil
resume checking for Unicode characters
(ansi-stream-cout stream) #'default-out))
(t
(string-out-misc stream operation arg1)))))
(multiple-value-bind (element-type unicode-p cout sout-aux)
(case (%other-pointer-widetag buffer)
#+sb-unicode
(#.sb-vm:simple-character-string-widetag
(if wild-result-type
(values :default nil #'default-out #'char-string-out)
(values 'character t #'character-out #'char-string-out)))
(#.sb-vm:simple-base-string-widetag
(values 'base-char :ignore #'base-char-out #'base-string-out))
(t
(values nil :ignore #'reject #'reject)))
(initforms)
(truly-the string-output-stream stream)))))
;;; Constructors used by the transform of MAKE-STRING-OUTPUT-STREAM,
;;; avoiding parsing of the specified element-type at runtime.
(defun %make-base-string-ostream ()
(%init-string-output-stream (%allocate-string-ostream)
2w + 64b
nil))
(defun %make-character-string-ostream ()
(%init-string-output-stream (%allocate-string-ostream)
2w + 128b
nil))
(defun make-string-output-stream (&key (element-type 'character))
"Return an output stream which will accumulate all output given it for the
benefit of the function GET-OUTPUT-STREAM-STRING."
(declare (explicit-check))
;; No point in optimizing for unsupplied ELEMENT-TYPE.
Compiler transforms into % MAKE - CHARACTER - STRING - OSTREAM .
(let ((ctype (specifier-type element-type)))
(cond ((and (csubtypep ctype (specifier-type 'base-char))
;; Let NIL mean "default", i.e. CHARACTER
(neq ctype *empty-type*))
(%make-base-string-ostream))
((csubtypep ctype (specifier-type 'character))
(%make-character-string-ostream))
(t
(error "~S is not a subtype of CHARACTER" element-type)))))
;;; Now that we support base-char string-output streams, it may be possible to eliminate
;;; this, though the other benefit it confers is that the buffer never needs to extend,
;;; and we merely shrink it to the proper size when done writing.
(defstruct (finite-base-string-output-stream
(:include ansi-stream
(cout #'finite-base-string-ouch)
(sout #'finite-base-string-sout)
(misc #'finite-base-string-out-misc))
(:constructor %make-finite-base-string-output-stream (buffer))
(:copier nil)
(:predicate nil))
(buffer nil :type simple-base-string :read-only t)
(pointer 0 :type index))
(declaim (freeze-type finite-base-string-output-stream))
;;; Pushes the current segment onto the prev-list, and either pops
;;; or allocates a new one.
(defun string-output-stream-new-buffer (stream size)
(declare (index size))
(declare (string-output-stream stream))
(push (string-output-stream-buffer stream)
(string-output-stream-prev stream))
(setf (string-output-stream-buffer stream)
(or (pop (string-output-stream-next stream))
;; There may be a fencepost bug lurking here but I don't think so, and in any case
;; this errs on the side of caution. Given the already dubious state of things
;; with regard to meaning of the INDEX type - see comment in src/code/early-extensions
above its DEF!TYPE - it seems like this ca n't be making things any worse to
;; constrain the chars in a string-output-stream to be even _smaller_ than INDEX.
(let ((maximum-string-length (1- array-dimension-limit))
(current-index (string-output-stream-index stream)))
(when (> (+ current-index size) maximum-string-length)
(setq size (- maximum-string-length current-index)))
(when (<= size 0)
(error "string-output-stream maximum length exceeded"))
(if (member (string-output-stream-element-type stream) '(base-char nil))
(make-array size :element-type 'base-char)
(make-array size :element-type 'character))))))
;;; Moves to the end of the next segment or the current one if there are
;;; no more segments. Returns true as long as there are next segments.
(defun string-output-stream-next-buffer (stream)
(declare (string-output-stream stream))
(let* ((old (string-output-stream-buffer stream))
(new (pop (string-output-stream-next stream)))
(old-size (length old))
(skipped (- old-size (string-output-stream-pointer stream))))
(cond (new
(let ((new-size (length new)))
(push old (string-output-stream-prev stream))
(setf (string-output-stream-buffer stream) new
(string-output-stream-pointer stream) new-size)
(incf (string-output-stream-index stream) (+ skipped new-size)))
t)
(t
(setf (string-output-stream-pointer stream) old-size)
(incf (string-output-stream-index stream) skipped)
nil))))
;;; Moves to the start of the previous segment or the current one if there
;;; are no more segments. Returns true as long as there are prev segments.
(defun string-output-stream-prev-buffer (stream)
(declare (string-output-stream stream))
(let ((old (string-output-stream-buffer stream))
(new (pop (string-output-stream-prev stream)))
(skipped (string-output-stream-pointer stream)))
(cond (new
(push old (string-output-stream-next stream))
(setf (string-output-stream-buffer stream) new
(string-output-stream-pointer stream) 0)
(decf (string-output-stream-index stream) (+ skipped (length new)))
t)
(t
(setf (string-output-stream-pointer stream) 0)
(decf (string-output-stream-index stream) skipped)
nil))))
(defun string-sout (stream string start end)
(declare (explicit-check string)
(type index start end))
FIXME : this contains about 7 OBJECT - NOT - INDEX error traps .
;; We should be able to check once up front that the string-stream will not
exceed the number of allowed characters , and then not do any further tests .
Also , the SOUT - AUX method contains 4 calls to SB - INT : SEQUENCE - BOUNDING - INDICES - BAD - ERROR
;; which may be redundant.
(let* ((full-length (- end start))
(length full-length)
(buffer (string-output-stream-buffer stream))
(pointer (string-output-stream-pointer stream))
(space (- (length buffer) pointer))
(here (min space length))
(stop (+ start here))
(overflow (- length space)))
(declare (index length space here stop full-length)
(fixnum overflow))
(tagbody
:more
(when (plusp here)
(funcall (string-output-stream-sout-aux stream)
stream buffer string pointer start stop)
(setf (string-output-stream-pointer stream) (+ here pointer)))
(when (plusp overflow)
(setf start stop
length (- end start)
;; BUG: doesn't always enlarge as intended. Consider:
- initial buffer capacity of 63 characters
- WRITE - STRING with 2 characters setting INDEX=2 , SPACE=61
- another WRITE - STRING with 62 characters . 61 copied , 1 overflow .
- then new BUFFER length is ( MAX OVERFLOW INDEX ) = 2
buffer (string-output-stream-new-buffer
stream (max overflow (string-output-stream-index stream)))
pointer 0
space (length buffer)
here (min space length)
stop (+ start here)
;; there may be more overflow if we used a buffer
;; already allocated to the stream
overflow (- length space))
(go :more)))
(incf (string-output-stream-index stream) full-length)))
;;; Factored out of the -misc method due to size.
This is a steaming pile of horsecrap ( lp#1839040 )
(defun set-string-output-stream-file-position (stream pos)
(let* ((index (string-output-stream-index stream))
(end (max index (string-output-stream-index-cache stream))))
(declare (index index end))
(setf (string-output-stream-index-cache stream) end)
(cond ((eq :start pos)
(loop while (string-output-stream-prev-buffer stream)))
((eq :end pos)
(loop while (string-output-stream-next-buffer stream))
(let ((over (- (string-output-stream-index stream) end)))
(decf (string-output-stream-pointer stream) over))
(setf (string-output-stream-index stream) end))
((< pos index)
(loop while (< pos index)
do (string-output-stream-prev-buffer stream)
(setf index (string-output-stream-index stream)))
(let ((step (- pos index)))
(incf (string-output-stream-pointer stream) step)
(setf (string-output-stream-index stream) pos)))
((> pos index)
;; We allow moving beyond the end of stream, implicitly
;; extending the output stream.
(let ((next (string-output-stream-next-buffer stream)))
;; Update after -next-buffer, INDEX is kept pointing at
;; the end of the current buffer.
(setf index (string-output-stream-index stream))
(loop while (and next (> pos index))
do (setf next (string-output-stream-next-buffer stream)
index (string-output-stream-index stream))))
;; Allocate new buffer if needed, or step back to
;; the desired index and set pointer and index
;; correctly.
(let ((diff (- pos index)))
(if (plusp diff)
(let* ((new (string-output-stream-new-buffer stream diff))
(size (length new)))
(aver (= pos (+ index size)))
(setf (string-output-stream-pointer stream) size
(string-output-stream-index stream) pos))
(let ((size (length (string-output-stream-buffer stream))))
(setf (string-output-stream-pointer stream) (+ size diff)
(string-output-stream-index stream) pos))))))))
(defun string-out-misc (stream operation arg1)
(declare (optimize speed))
(stream-misc-case (operation :default nil)
(:charpos
Keeping this first is a silly micro - optimization : FRESH - LINE
;; makes this the most common one.
(/noshow0 "/string-out-misc charpos")
(prog ((pointer (string-output-stream-pointer stream))
(buffer (string-output-stream-buffer stream))
(prev (string-output-stream-prev stream))
(base 0))
:next
could be NIL because of SETF below
(string-dispatch (simple-base-string
#+sb-unicode simple-character-string)
buffer
(position #\newline buffer :from-end t :end pointer)))))
(when (or pos (not buffer))
;; If newline is at index I, and pointer at index I+N, charpos
;; is N-1. If there is no newline, and pointer is at index N,
;; charpos is N.
(return (+ base (if pos (- pointer pos 1) pointer))))
(setf base (+ base pointer)
buffer (pop prev)
pointer (length buffer))
(/noshow0 "/string-out-misc charpos next")
(go :next))))
(:set-file-position
(set-string-output-stream-file-position stream arg1)
t) ; just claim it worked, who cares (see lp#1839040)
(:get-file-position
(string-output-stream-index stream))
(:close
(/noshow0 "/string-out-misc close")
(set-closed-flame stream))
(:element-type
(let ((et (string-output-stream-element-type stream)))
;; Always return a valid type-specifier
(if (eq et :default) 'character et)))
(:element-mode 'character)))
;;; Return a string of all the characters sent to a stream made by
;;; MAKE-STRING-OUTPUT-STREAM since the last call to this function.
(defun get-output-stream-string (stream)
(declare (type string-output-stream stream))
(let* ((length (max (string-output-stream-index stream)
(string-output-stream-index-cache stream)))
(prev (nreverse (string-output-stream-prev stream)))
(this (string-output-stream-buffer stream))
(next (string-output-stream-next stream))
(base-string-p (neq (string-output-stream-unicode-p stream) t))
;; This used to contain a FIXME about not allocating a result string,
;; instead shrinking the final buffer down to size. But given the likelihood
of a Unicode buffer and ASCII result , that seems inapplicable nowadays .
;; Also, how it impacts setting FILE-POSITION on a string stream is unclear.
( See )
(result (if base-string-p
(make-string length :element-type 'base-char)
(make-string length))))
(setf (string-output-stream-index stream) 0
(string-output-stream-index-cache stream) 0
(string-output-stream-pointer stream) 0
;; throw them away for simplicity's sake: this way the rest of the
;; implementation can assume that the greater of INDEX and INDEX-CACHE
;; is always within the last buffer.
(string-output-stream-prev stream) nil
(string-output-stream-next stream) nil)
Reset UNICODE - P unless it was : IGNORE or element - type is CHARACTER .
(when (and (eq (string-output-stream-element-type stream) :default)
(eq (string-output-stream-unicode-p stream) t))
(call-ansi-stream-misc stream :reset-unicode-p))
There are exactly 3 cases that we have to deal with when copying :
;; CHARACTER-STRING into BASE-STRING (without type-checking per character)
;; CHARACTER-STRING into CHARACTER-STRING
;; BASE-STRING into BASE-STRING
;; BASE-STRING copied into CHARACTER-STRING is not possible.
;; Strings with element type NIL are not possible.
The first case occurs when and only when the element type is : and
only base characters were written . The other two cases can be handled
using BYTE - BLT with indices multiplied by either 1 or 4 .
(flet ((copy (fun extra)
(let ((start 0)) ; index into RESULT
(declare (index start))
(dolist (buffer prev)
;; It doesn't look as though we should have to pass RESULT
;; in to FUN to avoid closure consing, but indeed we do.
(funcall fun result buffer start extra)
(incf start (length buffer)))
(funcall fun result this start extra)
(incf start (length this))
(dolist (buffer next)
(funcall fun result buffer start extra)
(incf start (length buffer))))))
(if (and (eq (string-output-stream-element-type stream) :default)
base-string-p)
;; This is the most common case, arising from WRITE-TO-STRING,
;; PRINx-TO-STRING, (FORMAT NIL ...), and many other constructs.
;; REPLACE will elide the type test per compilation policy
;; which is fine because we've already checked that it'll work.
(copy (lambda (result source start dummy)
(declare (optimize speed (sb-c::type-check 0)))
(declare (ignore dummy))
(replace (the simple-base-string result)
(the simple-character-string source)
:start1 start))
0)
(with-pinned-objects (result)
BYTE - BLT does n't know that it could use memcpy rather then memmove ,
;; but it nonetheless should be faster than REPLACE.
(copy (lambda (result source start scale)
(declare (index start))
(let* ((length (min (- (length result) start) (length source)))
(end (+ start length)))
(declare (index length end))
(with-pinned-objects (source)
(%byte-blt (vector-sap source)
0
(vector-sap result)
(truly-the index (ash start scale))
(truly-the index (ash end scale))))))
(if base-string-p 0 2)))))
result))
(defun finite-base-string-ouch (stream character)
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(let ((pointer (finite-base-string-output-stream-pointer stream))
(buffer (finite-base-string-output-stream-buffer stream)))
(cond ((= pointer (length buffer))
(bug "Should not happen"))
(t
(setf (finite-base-string-output-stream-pointer stream)
(truly-the index (1+ pointer))
;; return the character
(char buffer pointer) (truly-the base-char character))))))
(defun finite-base-string-sout (stream string start end)
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(let* ((pointer (finite-base-string-output-stream-pointer stream))
(buffer (finite-base-string-output-stream-buffer stream))
(length (- end start))
(new-pointer (+ pointer length)))
(cond ((> new-pointer (length buffer))
(bug "Should not happen"))
#+sb-unicode
((typep string 'simple-character-string)
(replace buffer string
:start1 pointer :start2 start :end2 end))
(t
(replace buffer (the simple-base-string string)
:start1 pointer :start2 start :end2 end)))
(setf (finite-base-string-output-stream-pointer stream) new-pointer)))
(defun finite-base-string-out-misc (stream operation arg1)
(declare (ignore stream operation arg1))
(error "finite-base-string-out-misc needs an implementation"))
;;;; fill-pointer streams
;;; Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
the CLM , but they are required for the implementation of
;;; WITH-OUTPUT-TO-STRING.
FIXME : need to support ( VECTOR NIL ) , ideally without destroying all hope
;;; of efficiency.
(declaim (inline vector-with-fill-pointer-p))
(defun vector-with-fill-pointer-p (x)
(and (vectorp x)
(array-has-fill-pointer-p x)))
(deftype string-with-fill-pointer ()
`(and (or (vector character) (vector base-char))
(satisfies vector-with-fill-pointer-p)))
;;; FIXME: The stream should refuse to accept more characters than the given
;;; string can hold without adjustment unless expressly adjustable.
;;; This is a portability issue - the fact that all of our fill-pointer vectors
;;; are implicitly adjustable is an implementation detail that should not be leaked.
;;; For comparison, when evaluating:
( let ( ( s ( make - array 5 : fill - pointer 0 : element - type ' base - char ) ) )
( with - output - to - string ( stream s ) ( dotimes ( i 6 ) ( write - char # \a stream ) ) ) s )
CLISP :
;;; *** - VECTOR-PUSH-EXTEND works only on adjustable arrays, not on "aaaaa"
CCL :
;;; > Error: "aaaaa" is not an adjustable array.
(defstruct (fill-pointer-output-stream
(:include ansi-stream
(cout #'fill-pointer-ouch)
(sout #'fill-pointer-sout)
(misc #'fill-pointer-misc))
(:constructor nil)
(:copier nil)
(:predicate nil))
;; a string with a fill pointer where we stuff the stuff we write
(string (missing-arg) :type string-with-fill-pointer :read-only t))
(declaim (freeze-type fill-pointer-output-stream))
;;; TODO: specialize on string type?
(defun %init-fill-pointer-output-stream (stream string element-type)
(declare (optimize speed (sb-c::verify-arg-count 0)))
(declare (ignore element-type))
(unless (and (stringp string)
(array-has-fill-pointer-p string))
(error "~S is not a string with a fill-pointer" string))
(macrolet ((initforms ()
`(progn ,@(mapcar (lambda (dsd)
`(%instance-set stream ,(dsd-index dsd)
,(case (dsd-name dsd)
(string 'string)
(t (dsd-default dsd)))))
(dd-slots
(find-defstruct-description 'fill-pointer-output-stream))))))
(initforms)
(truly-the fill-pointer-output-stream stream)))
(defun fill-pointer-ouch (stream character)
FIXME : ridiculously inefficient . Can we throw some TRULY - THEs in here ?
;; I think the prohibition against touching the string - implying that you can't
;; decide to re-displace it - means we should be able to just look at the
;; underlying vector, at least until we run out of space in it.
(let* ((buffer (fill-pointer-output-stream-string stream))
(current (fill-pointer buffer))
(current+1 (1+ current)))
(declare (fixnum current))
(with-array-data ((workspace buffer) (start) (end))
(string-dispatch (simple-character-string simple-base-string) workspace
(let ((offset-current (+ start current)))
(declare (fixnum offset-current))
(if (= offset-current end)
(let* ((new-length (1+ (* current 2)))
(new-workspace
(ecase (array-element-type workspace)
(character (make-string new-length
:element-type 'character))
(base-char (make-string new-length
:element-type 'base-char)))))
(replace new-workspace workspace :start2 start :end2 offset-current)
(setf workspace new-workspace
offset-current current)
(set-array-header buffer workspace new-length
current+1 0 new-length nil nil))
(setf (fill-pointer buffer) current+1))
(setf (char workspace offset-current) character)))))
character)
(defun fill-pointer-sout (stream string start end)
(declare (fixnum start end))
(string-dispatch (simple-character-string simple-base-string) string
(let* ((buffer (fill-pointer-output-stream-string stream))
(current (fill-pointer buffer))
(string-len (- end start))
(dst-end (+ string-len current)))
(declare (fixnum current dst-end string-len))
(with-array-data ((workspace buffer) (dst-start) (dst-length))
(let ((offset-dst-end (+ dst-start dst-end))
(offset-current (+ dst-start current)))
(declare (fixnum offset-dst-end offset-current))
(if (> offset-dst-end dst-length)
(let* ((new-length (+ (the fixnum (* current 2)) string-len))
(new-workspace
(ecase (array-element-type workspace)
(character (make-string new-length
:element-type 'character))
(base-char (make-string new-length
:element-type 'base-char)))))
(replace new-workspace workspace
:start2 dst-start :end2 offset-current)
(setf workspace new-workspace
offset-current current
offset-dst-end dst-end)
(set-array-header buffer workspace new-length
dst-end 0 new-length nil nil))
(setf (fill-pointer buffer) dst-end))
(replace workspace string
:start1 offset-current :start2 start :end2 end)))
dst-end)))
(defun fill-pointer-misc (stream operation arg1
&aux (buffer (fill-pointer-output-stream-string stream)))
(stream-misc-case (operation :default nil)
(:set-file-position
(setf (fill-pointer buffer)
(case arg1
(:start 0)
;; Fill-pointer is always at fill-pointer we will
;; make :END move to the end of the actual string.
(:end (array-total-size buffer))
;; We allow moving beyond the end of string if the
;; string is adjustable.
(t (when (>= arg1 (array-total-size buffer))
(if (adjustable-array-p buffer)
(adjust-array buffer arg1)
(error "Cannot move FILE-POSITION beyond the end ~
of WITH-OUTPUT-TO-STRING stream ~
constructed with non-adjustable string.")))
arg1))))
(:get-file-position
(fill-pointer buffer))
(:charpos
(let ((current (fill-pointer buffer)))
(with-array-data ((string buffer) (start) (end current))
(declare (simple-string string))
(let ((found (position #\newline string :test #'char=
:start start :end end
:from-end t)))
(if found
(1- (- end found))
current)))))
(:element-type
(array-element-type
(fill-pointer-output-stream-string stream)))
(:element-mode 'character)))
;;;; case frobbing streams, used by FORMAT ~(...~)
(defstruct (case-frob-stream
(:include ansi-stream
(misc #'case-frob-misc))
(:constructor %make-case-frob-stream (target cout sout))
(:copier nil))
(target (missing-arg) :type stream :read-only t))
(declaim (freeze-type case-frob-stream))
(defun make-case-frob-stream (target kind)
"Return a stream that sends all output to the stream TARGET, but modifies
the case of letters, depending on KIND, which should be one of:
:UPCASE - convert to upper case.
:DOWNCASE - convert to lower case.
:CAPITALIZE - convert the first letter of words to upper case and the
rest of the word to lower case.
:CAPITALIZE-FIRST - convert the first letter of the first word to upper
case and everything else to lower case."
(declare (type stream target)
(type (member :upcase :downcase :capitalize :capitalize-first)
kind)
(values stream))
(if (case-frob-stream-p target)
;; If we are going to be writing to a stream that already does
;; case frobbing, why bother frobbing the case just so it can
;; frob it again?
target
(multiple-value-bind (cout sout)
(ecase kind
(:upcase
(values #'case-frob-upcase-out
#'case-frob-upcase-sout))
(:downcase
(values #'case-frob-downcase-out
#'case-frob-downcase-sout))
(:capitalize
(values #'case-frob-capitalize-out
#'case-frob-capitalize-sout))
(:capitalize-first
(values #'case-frob-capitalize-first-out
#'case-frob-capitalize-first-sout)))
(%make-case-frob-stream target cout sout))))
(defun case-frob-misc (stream op arg1)
(declare (type case-frob-stream stream))
(case op
(:close
(set-closed-flame stream))
(:element-mode 'character)
(t
(let ((target (case-frob-stream-target stream)))
(if (ansi-stream-p target)
(call-ansi-stream-misc target op arg1)
(stream-misc-dispatch target op arg1))))))
;;; FIXME: formatted output into a simple-stream is currently hampered
;;; by the fact that case-frob streams assume that the stream is either ANSI
or Gray . Probably the easiest fix would be to define STREAM - WRITE - CHAR
;;; and STREAM-WRITE-STRING on simple-stream.
(defun case-frob-upcase-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream))
(c (char-upcase char)))
(if (ansi-stream-p target)
;; ansi stream method for character out has to return the original char
(progn (funcall (ansi-stream-cout target) target c) char)
(stream-write-char target c))))
(defun case-frob-upcase-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(len (length str))
(end (or end len))
(string (if (and (zerop start) (= len end))
(string-upcase str)
(nstring-upcase (subseq str start end))))
(string-len (- end start)))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target string 0 string-len)
(stream-write-string target string 0 string-len))))
(defun case-frob-downcase-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream))
(c (char-downcase char)))
(if (ansi-stream-p target)
(progn (funcall (ansi-stream-cout target) target c) char)
(stream-write-char target c))))
(defun case-frob-downcase-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(len (length str))
(end (or end len))
(string (if (and (zerop start) (= len end))
(string-downcase str)
(nstring-downcase (subseq str start end))))
(string-len (- end start)))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target string 0 string-len)
(stream-write-string target string 0 string-len))))
(defun case-frob-capitalize-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream)))
(cond ((alphanumericp char)
(let ((char (char-upcase char)))
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-aux-out)
(setf (case-frob-stream-sout stream)
#'case-frob-capitalize-aux-sout))
(t
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))))
char)
(defun case-frob-capitalize-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(str (subseq str start end))
(len (length str))
(inside-word nil))
(dotimes (i len)
(let ((char (schar str i)))
(cond ((not (alphanumericp char))
(setf inside-word nil))
(inside-word
(setf (schar str i) (char-downcase char)))
(t
(setf inside-word t)
(setf (schar str i) (char-upcase char))))))
(when inside-word
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-aux-out)
(setf (case-frob-stream-sout stream) #'case-frob-capitalize-aux-sout))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target str 0 len)
(stream-write-string target str 0 len))))
(defun case-frob-capitalize-aux-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream)))
(cond ((alphanumericp char)
(let ((char (char-downcase char)))
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char))))
(t
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char))
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-out)
(setf (case-frob-stream-sout stream) #'case-frob-capitalize-sout))))
char)
(defun case-frob-capitalize-aux-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(str (subseq str start end))
(len (length str))
(inside-word t))
(dotimes (i len)
(let ((char (schar str i)))
(cond ((not (alphanumericp char))
(setf inside-word nil))
(inside-word
(setf (schar str i) (char-downcase char)))
(t
(setf inside-word t)
(setf (schar str i) (char-upcase char))))))
(unless inside-word
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-out)
(setf (case-frob-stream-sout stream) #'case-frob-capitalize-sout))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target str 0 len)
(stream-write-string target str 0 len))))
(defun case-frob-capitalize-first-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream)))
(cond ((alphanumericp char)
(let ((char (char-upcase char)))
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))
(setf (case-frob-stream-cout stream) #'case-frob-downcase-out)
(setf (case-frob-stream-sout stream) #'case-frob-downcase-sout))
(t
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))))
char)
(defun case-frob-capitalize-first-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(str (subseq str start end))
(len (length str)))
(dotimes (i len)
(let ((char (schar str i)))
(when (alphanumericp char)
(setf (schar str i) (char-upcase char))
(do ((i (1+ i) (1+ i)))
((= i len))
(setf (schar str i) (char-downcase (schar str i))))
(setf (case-frob-stream-cout stream) #'case-frob-downcase-out)
(setf (case-frob-stream-sout stream) #'case-frob-downcase-sout)
(return))))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target str 0 len)
(stream-write-string target str 0 len))))
Shared { READ , support functions
(declaim (inline stream-compute-io-function
compatible-vector-and-stream-element-types-p))
(defun stream-compute-io-function (stream
stream-element-mode sequence-element-type
character-io binary-io bivalent-io)
(ecase stream-element-mode
(character
character-io)
((unsigned-byte signed-byte)
binary-io)
(:bivalent
(cond
((member sequence-element-type '(nil t))
bivalent-io)
;; Pick off common subtypes.
((eq sequence-element-type 'character)
character-io)
((or (equal sequence-element-type '(unsigned-byte 8))
(equal sequence-element-type '(signed-byte 8)))
binary-io)
;; Proper subtype tests.
((subtypep sequence-element-type 'character)
character-io)
((subtypep sequence-element-type 'integer)
binary-io)
(t
(error "~@<Cannot select IO functions to use for bivalent ~
stream ~S and a sequence with element-type ~S.~@:>"
stream sequence-element-type))))))
(defun compatible-vector-and-stream-element-types-p (vector stream)
(declare (type vector vector)
(type ansi-stream stream))
(or (and (typep vector '(simple-array (unsigned-byte 8) (*)))
(memq (stream-element-mode stream) '(unsigned-byte :bivalent))
t)
(and (typep vector '(simple-array (signed-byte 8) (*)))
(eq (stream-element-mode stream) 'signed-byte))))
;;;; READ-SEQUENCE
(defun read-sequence (seq stream &key (start 0) end)
"Destructively modify SEQ by reading elements from STREAM.
That part of SEQ bounded by START and END is destructively modified by
copying successive elements into it from STREAM. If the end of file
for STREAM is reached before copying all elements of the subsequence,
then the extra elements near the end of sequence are not updated, and
the index of the next element is returned."
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end end)
(values index))
(stream-api-dispatch (stream)
:simple (error "Unimplemented") ; gets redefined
:native (ansi-stream-read-sequence seq stream start end)
:gray (stream-read-sequence stream seq start end)))
(declaim (maybe-inline read-sequence/read-function))
(defun read-sequence/read-function (seq stream start %end
stream-element-mode
character-read-function binary-read-function)
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end %end)
(type stream-element-mode stream-element-mode)
(type function character-read-function binary-read-function)
(values index &optional))
(let ((end (or %end (length seq))))
(declare (type index end))
(labels ((compute-read-function (sequence-element-type)
(stream-compute-io-function
stream
stream-element-mode sequence-element-type
character-read-function binary-read-function
character-read-function))
(read-list (read-function)
(do ((rem (nthcdr start seq) (rest rem))
(i start (1+ i)))
((or (endp rem) (>= i end)) i)
(declare (type list rem)
(type index i))
(let ((el (funcall read-function stream nil :eof nil)))
(when (eq el :eof)
(return i))
(setf (first rem) el))))
(read-vector/fast (data offset-start)
(let* ((numbytes (- end start))
(bytes-read (read-n-bytes
stream data offset-start numbytes nil)))
(if (< bytes-read numbytes)
(+ start bytes-read)
end)))
(read-vector (read-function data offset-start offset-end)
(do ((i offset-start (1+ i)))
((>= i offset-end) end)
(declare (type index i))
(let ((el (funcall read-function stream nil :eof nil)))
(when (eq el :eof)
(return (+ start (- i offset-start))))
(setf (aref data i) el))))
(read-generic-sequence (read-function)
(declare (ignore read-function))
(error "~@<~A does not yet support generic sequences.~@:>"
'read-sequence)))
(declare (dynamic-extent #'compute-read-function
#'read-list #'read-vector/fast #'read-vector
#'read-generic-sequence))
(cond
((typep seq 'list)
(read-list (compute-read-function nil)))
((and (ansi-stream-p stream)
(ansi-stream-cin-buffer stream)
(typep seq 'simple-string))
(ansi-stream-read-string-from-frc-buffer seq stream start %end))
((typep seq 'vector)
(with-array-data ((data seq) (offset-start start) (offset-end end)
:check-fill-pointer t)
(if (and (ansi-stream-p stream)
(compatible-vector-and-stream-element-types-p data stream))
(read-vector/fast data offset-start)
(read-vector (compute-read-function (array-element-type data))
data offset-start offset-end))))
(t
(read-generic-sequence (compute-read-function nil)))))))
(defun ansi-stream-read-sequence (seq stream start %end)
(declare (type sequence seq)
(type ansi-stream stream)
(type index start)
(type sequence-end %end)
(values index &optional))
(locally (declare (inline read-sequence/read-function))
(read-sequence/read-function
seq stream start %end (stream-element-mode stream)
#'ansi-stream-read-char #'ansi-stream-read-byte)))
(defun ansi-stream-read-string-from-frc-buffer (seq stream start %end)
(declare (type simple-string seq)
(type ansi-stream stream)
(type index start)
(type (or null index) %end))
(let ((needed (- (or %end (length seq))
start))
(read 0))
(prepare-for-fast-read-char stream
(declare (ignore %frc-method%))
(unless %frc-buffer%
(return-from ansi-stream-read-string-from-frc-buffer nil))
(labels ((refill-buffer ()
(prog1 (fast-read-char-refill stream nil)
(setf %frc-index% (ansi-stream-in-index %frc-stream%))))
(add-chunk ()
(let* ((end (length %frc-buffer%))
(len (min (- end %frc-index%)
(- needed read))))
(declare (type index end len read needed))
(string-dispatch (simple-base-string simple-character-string)
seq
(replace seq %frc-buffer%
:start1 (+ start read)
:end1 (+ start read len)
:start2 %frc-index%
:end2 (+ %frc-index% len)))
(incf read len)
(incf %frc-index% len)
(when (or (eql needed read) (not (refill-buffer)))
(done-with-fast-read-char)
(return-from ansi-stream-read-string-from-frc-buffer
(+ start read))))))
(declare (inline refill-buffer))
(when (and (= %frc-index% +ansi-stream-in-buffer-length+)
(not (refill-buffer)))
EOF had been reached before we read anything
;; at all. But READ-SEQUENCE never signals an EOF error.
(done-with-fast-read-char)
(return-from ansi-stream-read-string-from-frc-buffer start))
(loop (add-chunk))))))
;;;; WRITE-SEQUENCE
(defun write-sequence (seq stream &key (start 0) (end nil))
"Write the elements of SEQ bounded by START and END to STREAM."
(let* ((length (length seq))
(end (or end length)))
(unless (<= start end length)
(sequence-bounding-indices-bad-error seq start end)))
(write-seq-impl seq stream start end))
;;; This macro allows sharing code between
WRITE - SEQUENCE / WRITE - FUNCTION and SB - GRAY : STREAM - WRITE - STRING .
(defmacro write-sequence/vector ((seq type) stream start end write-function)
(once-only ((seq seq) (stream stream) (start start) (end end)
(write-function write-function))
`(locally
(declare (type ,type ,seq)
(type index ,start ,end)
(type function ,write-function))
(do ((i ,start (1+ i)))
((>= i ,end))
(declare (type index i))
(funcall ,write-function ,stream (aref ,seq i))))))
(declaim (maybe-inline write-sequence/write-function))
(defun write-sequence/write-function (seq stream start %end
stream-element-mode
character-write-function
binary-write-function)
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end %end)
(type stream-element-mode stream-element-mode)
(type function character-write-function binary-write-function))
(let ((end (or %end (length seq))))
(declare (type index end))
(labels ((compute-write-function (sequence-element-type)
(stream-compute-io-function
stream
stream-element-mode sequence-element-type
character-write-function binary-write-function
#'write-element/bivalent))
(write-element/bivalent (stream object)
(if (characterp object)
(funcall character-write-function stream object)
(funcall binary-write-function stream object)))
(write-list (write-function)
(do ((rem (nthcdr start seq) (rest rem))
(i start (1+ i)))
((or (endp rem) (>= i end)))
(declare (type list rem)
(type index i))
(funcall write-function stream (first rem))))
(write-vector (data start end write-function)
(write-sequence/vector
(data (simple-array * (*))) stream start end write-function))
(write-generic-sequence (write-function)
(declare (ignore write-function))
(error "~@<~A does not yet support generic sequences.~@:>"
'write-sequence)))
(declare (dynamic-extent #'compute-write-function
#'write-element/bivalent #'write-list
#'write-vector #'write-generic-sequence))
(etypecase seq
(list
(write-list (compute-write-function nil)))
(string
(if (ansi-stream-p stream)
(with-array-data ((data seq) (start start) (end end)
:check-fill-pointer t)
(funcall (ansi-stream-sout stream) stream data start end))
(stream-write-string stream seq start end)))
(vector
(with-array-data ((data seq) (offset-start start) (offset-end end)
:check-fill-pointer t)
(cond ((not (and (fd-stream-p stream)
(compatible-vector-and-stream-element-types-p data stream)))
(write-vector data offset-start offset-end
(compute-write-function
(array-element-type seq))))
((eq (fd-stream-buffering stream) :none)
(write-or-buffer-output stream data offset-start offset-end))
(t
(buffer-output stream data offset-start offset-end)))))
(sequence
(write-generic-sequence (compute-write-function nil)))))))
;;; This takes any kind of stream, not just ansi streams, because of recursion.
;;; It's basically just the non-keyword-accepting entry for WRITE-SEQUENCE.
(defun write-seq-impl (seq stream start %end)
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end %end)
(inline write-sequence/write-function))
(stream-api-dispatch (stream)
:simple (s-%write-sequence stream seq start (or %end (length seq)))
:gray (stream-write-sequence stream seq start %end)
:native
(typecase stream
Do n't merely extract one layer of composite stream , because a synonym stream
may redirect to a broadcast stream which wraps a two - way - stream etc etc .
(synonym-stream
(write-seq-impl seq (symbol-value (synonym-stream-symbol stream)) start %end))
(broadcast-stream
(dolist (s (broadcast-stream-streams stream) seq)
(write-seq-impl seq s start %end)))
(two-way-stream ; handles ECHO-STREAM also
(write-seq-impl seq (two-way-stream-output-stream stream) start %end))
;; file, string, pretty, and case-frob streams all fall through to the default,
;; which has special logic for fd-stream.
(t
(write-sequence/write-function
seq stream start %end (stream-element-mode stream)
(ansi-stream-cout stream) (ansi-stream-bout stream)))))
seq)
like FILE - POSITION , only using : FILE - LENGTH
(defun file-length (stream)
;; The description for FILE-LENGTH says that an error must be raised
;; for streams not associated with files (which broadcast streams
;; aren't according to the glossary). However, the behaviour of
;; FILE-LENGTH for broadcast streams is explicitly described in the
BROADCAST - STREAM entry .
(stream-api-dispatch (stream)
:simple (s-%file-length stream)
;; Perhaps if there were a generic function to obtain the pathname?
:gray (error "~S is not defined for ~S" 'file-length stream)
:native (progn
(unless (typep stream 'broadcast-stream)
(stream-file-stream-or-lose stream))
(call-ansi-stream-misc stream :file-length))))
;; Placing this definition (formerly in "toplevel") after the important
;; stream types are known produces smaller+faster code than it did before.
(defun stream-output-stream (stream)
(typecase stream
(fd-stream
stream)
(synonym-stream
(stream-output-stream (resolve-synonym-stream stream)))
(two-way-stream
(stream-output-stream
(two-way-stream-output-stream stream)))
(t
stream)))
;;; STREAM-ERROR-STREAM is supposed to return a stream even if the
;;; stream has dynamic-extent. While technically a stream,
;;; this object is not actually usable as such - it's only for error reporting.
(defstruct (stub-stream
(:include ansi-stream)
(:constructor %make-stub-stream (direction string)))
(direction nil :read-only t)
(string nil :read-only t)) ; string or nil
(defun make-stub-stream (underlying-stream)
(multiple-value-bind (direction string)
(etypecase underlying-stream
(string-input-stream
(values :input (string-input-stream-string underlying-stream)))
(string-output-stream
(values :output nil))
(fill-pointer-output-stream
(values :output (fill-pointer-output-stream-string underlying-stream))))
(%make-stub-stream direction string)))
(defmethod print-object ((stub stub-stream) stream)
(print-unreadable-object (stub stream)
(let ((direction (stub-stream-direction stub))
(string (stub-stream-string stub)))
(format stream "dynamic-extent ~A (unavailable)~@[ ~A ~S~]"
(if (eq direction :input) 'string-input-stream 'string-output-stream)
(if string (if (eq direction :input) "from" "to"))
(if (> (length string) 10)
(concatenate 'string (subseq string 0 8) "...")
string)))))
;;;; initialization
;;; the stream connected to the controlling terminal, or NIL if there is none
(defvar *tty*)
;;; the stream connected to the standard input (file descriptor 0)
(defvar *stdin*)
the stream connected to the standard output ( file descriptor 1 )
(defvar *stdout*)
the stream connected to the standard error output ( file descriptor 2 )
(defvar *stderr*)
This is called when the cold load is first started up , and may also
;;; be called in an attempt to recover from nested errors.
(defun stream-cold-init-or-reset ()
(stream-reinit)
(setf *terminal-io* (make-synonym-stream '*tty*))
(setf *standard-output* (make-synonym-stream '*stdout*))
(setf *standard-input* (make-synonym-stream '*stdin*))
(setf *error-output* (make-synonym-stream '*stderr*))
(setf *query-io* (make-synonym-stream '*terminal-io*))
(setf *debug-io* *query-io*)
(setf *trace-output* *standard-output*)
(values))
(defun stream-deinit ()
(setq *tty* nil *stdin* nil *stdout* nil *stderr* nil)
;; Unbind to make sure we're not accidently dealing with it
;; before we're ready (or after we think it's been deinitialized).
This uses the internal % MAKUNBOUND because the CL : function would
;; rightly complain that *AVAILABLE-BUFFERS* is proclaimed always bound.
(%makunbound '*available-buffers*))
(defvar *streams-closed-by-slad*)
(defun restore-fd-streams ()
(loop for (stream in bin n-bin cout bout sout misc) in *streams-closed-by-slad*
do
(setf (ansi-stream-in stream) in)
(setf (ansi-stream-bin stream) bin)
(setf (ansi-stream-n-bin stream) n-bin)
(setf (ansi-stream-cout stream) cout)
(setf (ansi-stream-bout stream) bout)
(setf (ansi-stream-sout stream) sout)
(setf (ansi-stream-misc stream) misc)))
(defun stdstream-external-format (fd)
#-win32 (declare (ignore fd))
(let* ((keyword (cond #+(and win32 sb-unicode)
((sb-win32::console-handle-p fd)
:ucs-2)
(t
(default-external-format))))
(ef (get-external-format keyword))
(replacement (ef-default-replacement-character ef)))
`(,keyword :replacement ,replacement)))
;;; This is called whenever a saved core is restarted.
(defun stream-reinit (&optional init-buffers-p)
(when init-buffers-p
;; Use the internal %BOUNDP for similar reason to that cited above-
;; BOUNDP on a known global transforms to the constant T.
(aver (not (%boundp '*available-buffers*)))
(setf *available-buffers* nil))
(%with-output-to-string (*error-output*)
(multiple-value-bind (in out err)
#-win32 (values 0 1 2)
#+win32 (sb-win32::get-std-handles)
(labels (#+win32
(nul-stream (name inputp outputp)
(let ((nul-handle
(cond
((and inputp outputp)
(sb-win32:unixlike-open "NUL" sb-unix:o_rdwr))
(inputp
(sb-win32:unixlike-open "NUL" sb-unix:o_rdonly))
(outputp
(sb-win32:unixlike-open "NUL" sb-unix:o_wronly))
(t
;; Not quite sure what to do in this case.
nil))))
(make-fd-stream
nul-handle
:name name
:input inputp
:output outputp
:buffering :line
:element-type :default
:serve-events inputp
:auto-close t
:external-format (stdstream-external-format nul-handle))))
(stdio-stream (handle name inputp outputp)
(cond
#+win32
((null handle)
If no actual handle was present , create a stream to NUL
(nul-stream name inputp outputp))
(t
(make-fd-stream
handle
:name name
:input inputp
:output outputp
:buffering :line
:element-type :default
:serve-events inputp
:external-format (stdstream-external-format handle))))))
(setf *stdin* (stdio-stream in "standard input" t nil)
*stdout* (stdio-stream out "standard output" nil t)
*stderr* (stdio-stream err "standard error" nil t))))
#+win32
(setf *tty* (make-two-way-stream *stdin* *stdout*))
#-win32
(let ((tty (sb-unix:unix-open "/dev/tty" sb-unix:o_rdwr #o666)))
(setf *tty*
(if tty
(make-fd-stream tty :name "the terminal"
:input t :output t :buffering :line
:external-format (stdstream-external-format tty)
:serve-events t
:auto-close t)
(make-two-way-stream *stdin* *stdout*))))
(princ (get-output-stream-string *error-output*) *stderr*))
(values))
| null | https://raw.githubusercontent.com/sbcl/sbcl/077affa9121970175d78296c41d4793f62d96e13/src/code/stream.lisp | lisp | os-independent stream functions
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
standard streams
The initialization of these streams is performed by
STREAM-COLD-INIT-OR-RESET.
stream manipulation functions
values like this. What if someone's redefined the function?
for file position and file length
Call the MISC method with the :GET-FILE-POSITION operation.
named for the stdio inquiry function
FIXME: It would be good to comment on the stuff that is done here...
FIXME: This doesn't look interrupt safe.
it, which made it impossible to test for a bad call that tries to assign
the position, versus a inquiry for the current position.
CLHS specifies: file-position stream position-spec => success-p
but the implementation methods can't detect supplied vs unsupplied.
Setter
The impl method is expected to return a success indication as
a generalized boolean.
I think our fndb entry is overconstrained - it says that this returns
either unsigned-byte or strict boolean, however CLHS says that setting
FILE-POSITION returns a /generalized boolean/.
A stream-specific method should be allowed to convey more information
than T/NIL yet we are forced to discard that information,
lest the return value constraint on this be violated.
Getter
Excuse me for asking, but why is this even a thing?
Users are not supposed to call the stream implementation directly,
which indirects to this. But if they do ... make it work.
And note that inlining of !ansi-stream-file-position would be pointless,
it's nearly 1K of code.
then you must not call FILE-POSITION with both arguments.
associated with a file".
end up with this test being satisfied for weird things like
*STANDARD-OUTPUT* (to a tty). That seems unlikely to be what the
ANSI spec really had in mind, especially since this is used as a
probably thinking of something like what Unix calls block devices)
this should be TYPE-ERROR. But what then can we use for
EXPECTED-TYPE? This SATISFIES type (with a nonstandard
private predicate function..) is ugly and confusing, but
input functions
to potentially avoid consing a bufer on sucessive calls to read-line
(just consing the result string)
Stream has a fast-read-char buffer. Copy large chunks directly
out of the buffer.
Slow path, character by character.
There is no need to use PREPARE-FOR-FAST-READ-CHAR
Do not push an enlarged buffer, only the original one.
We proclaim them INLINE here, then proclaim them MAYBE-INLINE
later on, so, except in this file, they are not inline by default,
but they can be.
The final T is BLOCKING-P. I removed the ignored recursive-p arg.
Ugh. an ANSI-STREAM with a char buffer never gives a chance to
gets redefined
Absence of EOF-OR-LOSE here looks a little suspicious
considering that the impl function didn't use recursive-p
gets redefined
Why the "recursive-p" parameter? a-s-r-b is funcall'ed from
a-s-read-sequence and needs a lambda list that's congruent with
that of a-s-read-char
number of bytes read.
available.) This could be useful behavior for things like pipes in
method (perhaps N-BIN-ASAP?) or something.
We don't need to worry about element-type size here is that
callers are supposed to have checked everything is kosher.
and not variable-length bytes.
the amount of space we leave at the start of the in-buffer for
unreading
FIXME: should be symbolic constant
This function is called by the FAST-READ-CHAR expansion to refill
the IN-BUFFER for text streams. There is definitely an IN-BUFFER,
and hence must be an N-BIN method. It's also called by other stream
functions which directly peek into the frc buffer.
Characters between (ANSI-STREAM-IN-INDEX %FRC-STREAM%)
and +ANSI-STREAM-IN-BUFFER-LENGTH+ have to be re-scanned.
An empty count does not necessarily mean that we reached
invalid octet sequence in a multibyte stream. To handle
hope that the next refill will not need to resync.
only ones which will give us decoding errors) here,
because this code is generic. We can't call the N-BIN
function, because near the end of a real file that can
legitimately bounce us to the IN function. So we have
to call ANSI-STREAM-IN.
When not signaling an error, it is important that IN-INDEX
be set to +ANSI-STREAM-IN-BUFFER-LENGTH+ here, even though
DONE-WITH-FAST-READ-CHAR will do the same, thereby writing
the caller's %FRC-INDEX% (= +ANSI-STREAM-IN-BUFFER-LENGTH+)
and scanned characters between the original %FRC-INDEX%
and the buffer end (above), we must *not* do that again.
we resynced or were given something instead
This is similar to FAST-READ-CHAR-REFILL, but we don't have to
leave room for unreading.
output functions
unclear why the dispatch to simple and gray methods have to receive a simple-string.
I'm pretty sure the STREAM-foo methods on gray streams are not specified to be
constrained to receive only simple-string.
So they must either do their their own "unwrapping" of a complex string, or
The STREAM argument is not allowed to be a designator.
too big
streams to handle the misc routines and dispatch to the
call the redefined LISTEN
call the redefined CLEAR-INPUT
FIXME: All simple-streams are actually bivalent. We historically have
This call returns an instance of the format structure defined
by the SB-SIMPLE-STREAMS package, not the SB-IMPL:: structure.
This also needs to be fixed.
yeesh, this wants a _required_ NIL argument to mean "inquire".
else call the generic function
is generic
This last bunch of pseudo-methods will probably just signal an error
broadcast streams
FIXME: This may not be the best place to note this, but I
think the :CHARPOS protocol needs revision. Firstly, I think
this is the last place where a NULL return value was possible
(before adjusting it to be 0), so a bunch of conditionals IF
secondly , it is my belief that
FD-STREAMS, when running FILE-POSITION, do not update the
CHARPOS, and consequently there will be much wrongness.
is it testing the :charpos of an input stream?
I don't know how something is trying to close the
universal sink stream, but it is. Stop it from happening.
synonym streams
The output simple output methods just call the corresponding
function on the synonymed stream.
For the input methods, we just call the corresponding function on the
synonymed stream. These functions deal with getting input out of
the In-Buffer if there is any.
"The consequences are undefined if the synonym stream symbol is not bound to an open
stream from the time of the synonym stream's creation until the time it is closed."
The antecent of this "it" is the synonym stream --------------^
which means that there exist a way to close synonym streams.
We can presume that CLOSE is that way, despite some text seemingly to the contrary
"Any operations on a synonym stream will be performed on the stream that is then
the value of the dynamic variable named by the synonym stream symbol."
so "any" in that sentence mean "almost any, with a notable exception".
We have to special-case some operations which interact with
the in-buffer of the wrapped stream, since just calling
ANSI-STREAM-MISC on them
concatenated streams
The car of this is the substream we are reading from now.
Advance STREAMS, and try again.
No further streams. EOF.
Stuff's available.
Nothing is available yet.
echo streams
If unread-stuff was true, the character read
from the input stream was previously echoed.
characters never could have worked, so probably nobody has ever
tried doing bivalent block I/O through an echo stream; this may
not work either.
STRING-INPUT-STREAM stuff
Indices into STRING
Backing string after following displaced array chain
on read, not move.
According to ANSI: "Should signal an error of type type-error
if stream is not a stream associated with a file."
This is checked by FILE-LENGTH, so no need to do it here either.
(:file-length (length (string-input-stream-string stream)))
silently ignore attempts to go backwards too far
of WITH-INPUT-FROM-STRING, and we lack a way to perform partial inline
dx allocation of structures, this'll have to do.
good thing we have no raw slots in stream structures
It's debatable whether we should try to convert
(let ((s (make-string-input-stream))) (declare (dynamic-extent s)) ...)
into the thing that WITH-INPUT-FROM-STRING does. That's what the macro is for.
kill the secondary value
STRING-OUTPUT-STREAM stuff
FIXME: This, like almost none of the stream code is particularly
interrupt or thread-safe. While it should not be possible to
corrupt the heap here, it certainly is possible to end up with
a string-output-stream whose internal state is messed up.
if #-sb-unicode
global fun
local fun
The usual doubling technique: the new buffer shall hold as many
characters as were already emplaced.
return the character
base-string source and buffer : OK
base-string source, character-string buffer : OK
in the input, pre-scan to see whether that still holds.
no need to keep checking each character
There are transforms for all the necessary REPLACE variations.
string that can hold the output), checking whether Unicode characters appear
in the source material is potentially advantageous versus checking the
buffer in GET-OUTPUT-STREAM-STRING, because if all source strings are
BASE-STRING, we needn't check anything.
Bounds check was already performed
The "wonderful" thing is you never know where type checks have already been done.
no need to keep checking each character
(since the char handlers are local functions).
Technically this should be among the actions performed on :CLEAR-OUTPUT,
which would also include *actually* clearing the output. But we don't.
Constructors used by the transform of MAKE-STRING-OUTPUT-STREAM,
avoiding parsing of the specified element-type at runtime.
No point in optimizing for unsupplied ELEMENT-TYPE.
Let NIL mean "default", i.e. CHARACTER
Now that we support base-char string-output streams, it may be possible to eliminate
this, though the other benefit it confers is that the buffer never needs to extend,
and we merely shrink it to the proper size when done writing.
Pushes the current segment onto the prev-list, and either pops
or allocates a new one.
There may be a fencepost bug lurking here but I don't think so, and in any case
this errs on the side of caution. Given the already dubious state of things
with regard to meaning of the INDEX type - see comment in src/code/early-extensions
constrain the chars in a string-output-stream to be even _smaller_ than INDEX.
Moves to the end of the next segment or the current one if there are
no more segments. Returns true as long as there are next segments.
Moves to the start of the previous segment or the current one if there
are no more segments. Returns true as long as there are prev segments.
We should be able to check once up front that the string-stream will not
which may be redundant.
BUG: doesn't always enlarge as intended. Consider:
there may be more overflow if we used a buffer
already allocated to the stream
Factored out of the -misc method due to size.
We allow moving beyond the end of stream, implicitly
extending the output stream.
Update after -next-buffer, INDEX is kept pointing at
the end of the current buffer.
Allocate new buffer if needed, or step back to
the desired index and set pointer and index
correctly.
makes this the most common one.
If newline is at index I, and pointer at index I+N, charpos
is N-1. If there is no newline, and pointer is at index N,
charpos is N.
just claim it worked, who cares (see lp#1839040)
Always return a valid type-specifier
Return a string of all the characters sent to a stream made by
MAKE-STRING-OUTPUT-STREAM since the last call to this function.
This used to contain a FIXME about not allocating a result string,
instead shrinking the final buffer down to size. But given the likelihood
Also, how it impacts setting FILE-POSITION on a string stream is unclear.
throw them away for simplicity's sake: this way the rest of the
implementation can assume that the greater of INDEX and INDEX-CACHE
is always within the last buffer.
CHARACTER-STRING into BASE-STRING (without type-checking per character)
CHARACTER-STRING into CHARACTER-STRING
BASE-STRING into BASE-STRING
BASE-STRING copied into CHARACTER-STRING is not possible.
Strings with element type NIL are not possible.
index into RESULT
It doesn't look as though we should have to pass RESULT
in to FUN to avoid closure consing, but indeed we do.
This is the most common case, arising from WRITE-TO-STRING,
PRINx-TO-STRING, (FORMAT NIL ...), and many other constructs.
REPLACE will elide the type test per compilation policy
which is fine because we've already checked that it'll work.
but it nonetheless should be faster than REPLACE.
return the character
fill-pointer streams
Fill pointer STRING-OUTPUT-STREAMs are not explicitly mentioned in
WITH-OUTPUT-TO-STRING.
of efficiency.
FIXME: The stream should refuse to accept more characters than the given
string can hold without adjustment unless expressly adjustable.
This is a portability issue - the fact that all of our fill-pointer vectors
are implicitly adjustable is an implementation detail that should not be leaked.
For comparison, when evaluating:
*** - VECTOR-PUSH-EXTEND works only on adjustable arrays, not on "aaaaa"
> Error: "aaaaa" is not an adjustable array.
a string with a fill pointer where we stuff the stuff we write
TODO: specialize on string type?
I think the prohibition against touching the string - implying that you can't
decide to re-displace it - means we should be able to just look at the
underlying vector, at least until we run out of space in it.
Fill-pointer is always at fill-pointer we will
make :END move to the end of the actual string.
We allow moving beyond the end of string if the
string is adjustable.
case frobbing streams, used by FORMAT ~(...~)
If we are going to be writing to a stream that already does
case frobbing, why bother frobbing the case just so it can
frob it again?
FIXME: formatted output into a simple-stream is currently hampered
by the fact that case-frob streams assume that the stream is either ANSI
and STREAM-WRITE-STRING on simple-stream.
ansi stream method for character out has to return the original char
Pick off common subtypes.
Proper subtype tests.
READ-SEQUENCE
gets redefined
at all. But READ-SEQUENCE never signals an EOF error.
WRITE-SEQUENCE
This macro allows sharing code between
This takes any kind of stream, not just ansi streams, because of recursion.
It's basically just the non-keyword-accepting entry for WRITE-SEQUENCE.
handles ECHO-STREAM also
file, string, pretty, and case-frob streams all fall through to the default,
which has special logic for fd-stream.
The description for FILE-LENGTH says that an error must be raised
for streams not associated with files (which broadcast streams
aren't according to the glossary). However, the behaviour of
FILE-LENGTH for broadcast streams is explicitly described in the
Perhaps if there were a generic function to obtain the pathname?
Placing this definition (formerly in "toplevel") after the important
stream types are known produces smaller+faster code than it did before.
STREAM-ERROR-STREAM is supposed to return a stream even if the
stream has dynamic-extent. While technically a stream,
this object is not actually usable as such - it's only for error reporting.
string or nil
initialization
the stream connected to the controlling terminal, or NIL if there is none
the stream connected to the standard input (file descriptor 0)
be called in an attempt to recover from nested errors.
Unbind to make sure we're not accidently dealing with it
before we're ready (or after we think it's been deinitialized).
rightly complain that *AVAILABLE-BUFFERS* is proclaimed always bound.
This is called whenever a saved core is restarted.
Use the internal %BOUNDP for similar reason to that cited above-
BOUNDP on a known global transforms to the constant T.
Not quite sure what to do in this case. |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-IMPL")
(defvar *terminal-io* () "terminal I/O stream")
(defvar *standard-input* () "default input stream")
(defvar *standard-output* () "default output stream")
(defvar *error-output* () "error output stream")
(defvar *query-io* () "query I/O stream")
(defvar *trace-output* () "trace output stream")
(defvar *debug-io* () "interactive debugging stream")
(defun stream-element-type-stream-element-mode (element-type)
(cond ((or (not element-type)
(eq element-type t)
(eq element-type :default)) :bivalent)
((or (eq element-type 'character)
(eq element-type 'base-char))
'character)
((memq element-type '(signed-byte unsigned-byte))
element-type)
((and (proper-list-of-length-p element-type 2)
(memq (car element-type)
'(signed-byte unsigned-byte)))
(car element-type))
((not (ignore-errors
(setf element-type
(type-or-nil-if-unknown element-type t))))
:bivalent)
((eq element-type *empty-type*)
:bivalent)
((csubtypep element-type (specifier-type 'character))
'character)
((csubtypep element-type (specifier-type 'unsigned-byte))
'unsigned-byte)
((csubtypep element-type (specifier-type 'signed-byte))
'signed-byte)
(t
:bivalent)))
(defun ill-in (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies input-stream-p)
:format-control "~S is not a character input stream."
:format-arguments (list stream)))
(defun ill-out (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies output-stream-p)
:format-control "~S is not a character output stream."
:format-arguments (list stream)))
(defun ill-bin (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies input-stream-p)
:format-control "~S is not a binary input stream."
:format-arguments (list stream)))
(defun ill-bout (stream &rest ignore)
(declare (ignore ignore))
(error 'simple-type-error
:datum stream
:expected-type '(satisfies output-stream-p)
:format-control "~S is not a binary output stream."
:format-arguments (list stream)))
(defun closed-flame (stream &rest ignore)
(declare (ignore ignore))
(error 'closed-stream-error :stream stream))
(defun closed-flame-saved (stream &rest ignore)
(declare (ignore ignore))
(error 'closed-saved-stream-error :stream stream))
(defun no-op-placeholder (&rest ignore)
(declare (ignore ignore)))
(defun maybe-resolve-synonym-stream (stream)
(labels ((recur (stream)
(if (synonym-stream-p stream)
(recur (symbol-value (synonym-stream-symbol stream)))
stream)))
(recur stream)))
(declaim (inline resolve-synonym-stream))
(defun resolve-synonym-stream (stream)
(let ((result (symbol-value (synonym-stream-symbol stream))))
(if (synonym-stream-p result)
(maybe-resolve-synonym-stream result)
result)))
(defmethod input-stream-p ((stream ansi-stream))
(if (synonym-stream-p stream)
(input-stream-p (resolve-synonym-stream stream))
(and (not (eq (ansi-stream-in stream) #'closed-flame))
: It 's probably not good to have EQ tests on function
Is there a better way ? ( Perhaps just VALID - FOR - INPUT and
VALID - FOR - OUTPUT flags ? -- WHN 19990902
(or (not (eq (ansi-stream-in stream) #'ill-in))
(not (eq (ansi-stream-bin stream) #'ill-bin))))))
(defmethod output-stream-p ((stream ansi-stream))
(if (synonym-stream-p stream)
(output-stream-p (resolve-synonym-stream stream))
(and (not (eq (ansi-stream-in stream) #'closed-flame))
(or (not (eq (ansi-stream-cout stream) #'ill-out))
(not (eq (ansi-stream-bout stream) #'ill-bout))))))
(defmethod open-stream-p ((stream ansi-stream))
CLHS 21.1.4 lets us not worry about synonym streams here .
(let ((in (ansi-stream-in stream)))
(not (or (eq in (load-time-value #'closed-flame t))
(eq in (load-time-value #'closed-flame-saved t))))))
(defmethod stream-element-type ((stream ansi-stream))
(call-ansi-stream-misc stream :element-type))
(defun stream-external-format (stream)
(stream-api-dispatch (stream)
:simple (s-%stream-external-format stream)
:gray (error "~S is not defined for ~S" 'stream-external-format stream)
:native (call-ansi-stream-misc stream :external-format)))
(defmethod interactive-stream-p ((stream ansi-stream))
(call-ansi-stream-misc stream :interactive-p))
(defmethod close ((stream ansi-stream) &key abort)
(unless (eq (ansi-stream-in stream) #'closed-flame)
(call-ansi-stream-misc stream :close abort))
t)
(defun set-closed-flame (stream)
(setf (ansi-stream-in stream) #'closed-flame)
(setf (ansi-stream-bin stream) #'closed-flame)
(setf (ansi-stream-n-bin stream) #'closed-flame)
(setf (ansi-stream-cout stream) #'closed-flame)
(setf (ansi-stream-bout stream) #'closed-flame)
(setf (ansi-stream-sout stream) #'closed-flame)
(setf (ansi-stream-misc stream) #'closed-flame))
(defun set-closed-flame-by-slad (stream)
(setf (ansi-stream-in stream) #'closed-flame-saved)
(setf (ansi-stream-bin stream) #'closed-flame-saved)
(setf (ansi-stream-n-bin stream) #'closed-flame-saved)
(setf (ansi-stream-cout stream) #'closed-flame-saved)
(setf (ansi-stream-bout stream) #'closed-flame-saved)
(setf (ansi-stream-sout stream) #'closed-flame-saved)
(setf (ansi-stream-misc stream) #'closed-flame-saved))
(defun external-format-char-size (external-format)
(ef-char-size (get-external-format external-format)))
(defun !ansi-stream-ftell (stream)
(declare (type stream stream))
(let ((res (call-ansi-stream-misc stream :get-file-position))
(delta (- +ansi-stream-in-buffer-length+
(ansi-stream-in-index stream))))
(if (eql delta 0)
res
(when res
#-sb-unicode
(- res delta)
#+sb-unicode
(let ((char-size (if (fd-stream-p stream)
(fd-stream-char-size stream)
(external-format-char-size (stream-external-format stream)))))
(- res
(etypecase char-size
(function
(loop with buffer = (ansi-stream-cin-buffer stream)
with start = (ansi-stream-in-index stream)
for i from start below +ansi-stream-in-buffer-length+
sum (funcall char-size (aref buffer i))))
(fixnum
(* char-size delta)))))))))
You 're not allowed to specify NIL for the position but we were permitting
and position - spec is a " file position designator " which precludes NIL
What a fubar API at the CL : layer . Was # ' ( SETF FILE - POSITION ) not invented ?
(defun file-position (stream &optional (position 0 suppliedp))
(if suppliedp
(let ((arg (the (or index (alien sb-unix:unix-offset) (member :start :end))
position)))
(stream-api-dispatch (stream)
:native (progn
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(call-ansi-stream-misc stream :set-file-position arg))
:simple (s-%file-position stream arg)
:gray (let ((result (stream-file-position stream arg)))
(if (numberp result) result (and result t)))))
(let ((result (stream-api-dispatch (stream)
:native (!ansi-stream-ftell stream)
:simple (s-%file-position stream nil)
:gray (stream-file-position stream))))
(the (or unsigned-byte null) result))))
(defmethod stream-file-position ((stream ansi-stream) &optional position)
they 're supposed to call the function in the CL : package
Oh , this is srsly wtf now . If POSITION is NIL ,
(if position
(file-position stream position)
(file-position stream)))
This is a literal translation of the ANSI glossary entry " stream
: Note that since Unix famously thinks " everything is a
file " , and in particular stdin , stdout , and stderr are files , we
qualification for operations like FILE - LENGTH ( so that ANSI was
but I ca n't see any better way to do it . -- WHN 2001 - 04 - 14
(defun stream-file-stream (stream)
"Test for the ANSI concept \"stream associated with a file\".
Return NIL or the underlying FILE-STREAM."
(typecase stream
(file-stream stream)
(synonym-stream
(stream-file-stream (resolve-synonym-stream stream)))))
(defun stream-file-stream-or-lose (stream)
(declare (type stream stream))
(or (stream-file-stream stream)
(error 'simple-type-error
: The ANSI spec for FILE - LENGTH specifically says
I ca n't see any other way . -- WHN 2001 - 04 - 14
:datum stream
:expected-type '(satisfies stream-file-stream)
:format-control
"~@<The stream ~2I~_~S ~I~_isn't associated with a file.~:>"
:format-arguments (list stream))))
(defun stream-file-name-or-lose (stream)
(or (file-name (stream-file-stream-or-lose stream))
(error "~@<The stream ~2I~_~S ~I~_is not associated with a named file.~:>"
stream)))
(defun file-string-length (stream object)
(stream-api-dispatch (stream)
:gray nil
:simple (s-%file-string-length stream object)
:native (call-ansi-stream-misc stream :file-string-length object)))
(defun ansi-stream-read-line-from-frc-buffer (stream eof-error-p eof-value)
(prepare-for-fast-read-char stream
(declare (ignore %frc-method%))
(declare (type ansi-stream-cin-buffer %frc-buffer%))
(let ((chunks-total-length 0)
(chunks nil))
(declare (type index chunks-total-length)
(list chunks))
(labels ((refill-buffer ()
(prog1 (fast-read-char-refill stream nil)
(setf %frc-index% (ansi-stream-in-index %frc-stream%))))
(build-result (pos n-more-chars)
(let ((res (make-string (+ chunks-total-length n-more-chars)))
(start1 chunks-total-length))
(declare (type index start1))
(when (>= pos 0)
(replace res %frc-buffer%
:start1 start1 :start2 %frc-index% :end2 pos)
(setf %frc-index% (1+ pos)))
(done-with-fast-read-char)
(dolist (chunk chunks res)
(declare (type (simple-array character (*)) chunk))
(decf start1 (length chunk))
(replace res chunk :start1 start1)))))
(declare (inline refill-buffer))
(if (or (< %frc-index% +ansi-stream-in-buffer-length+) (refill-buffer))
(loop
(let ((pos (position #\Newline %frc-buffer%
:test #'char= :start %frc-index%)))
(when pos
(return (values (build-result pos (- pos %frc-index%)) nil)))
(let ((chunk (subseq %frc-buffer% %frc-index%)))
(incf chunks-total-length (length chunk))
(push chunk chunks))
(unless (refill-buffer)
(return (values (build-result -1 0) t)))))
EOF had been reached before we read anything
at all . Return the EOF value or signal the error .
(progn (done-with-fast-read-char)
(eof-or-lose stream eof-error-p (values eof-value t))))))))
(define-load-time-global *read-line-buffers* nil)
(declaim (list *read-line-buffers*))
(declaim (inline ansi-stream-read-line))
(defun ansi-stream-read-line (stream eof-error-p eof-value)
(if (ansi-stream-cin-buffer stream)
(ansi-stream-read-line-from-frc-buffer stream eof-error-p eof-value)
because the CIN - BUFER is known to be NIL .
(let ((ch (funcall (ansi-stream-in stream) stream nil 0)))
(case ch
(#\newline (values "" nil))
(0 (values (eof-or-lose stream eof-error-p eof-value) t))
(t
(let* ((buffer (or (atomic-pop *read-line-buffers*)
(make-string 128)))
(res buffer)
(len (length res))
(eof)
(index 0))
(declare (type (simple-array character (*)) buffer))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(declare (index index))
(setf (schar res index) (truly-the character ch))
(incf index)
(loop (case (setq ch (funcall (ansi-stream-in stream) stream nil 0))
(#\newline (return))
(0 (return (setq eof t)))
(t
(when (= index len)
(setq len (* len 2))
(let ((new (make-string len)))
(replace new res)
(setq res new)))
(setf (schar res index) (truly-the character ch))
(incf index))))
(if (eq res buffer)
(setq res (subseq buffer 0 index))
(%shrink-vector res index))
(atomic-push buffer *read-line-buffers*)
(values res eof)))))))
(defun read-line (&optional (stream *standard-input*) (eof-error-p t) eof-value
recursive-p)
(declare (explicit-check))
(declare (ignore recursive-p))
(stream-api-dispatch (stream :input)
:simple (s-%read-line stream eof-error-p eof-value)
:native (ansi-stream-read-line stream eof-error-p eof-value)
:gray
(multiple-value-bind (string eof) (stream-read-line stream)
(if (and eof (zerop (length string)))
(values (eof-or-lose stream eof-error-p eof-value) t)
(values string eof)))))
(declaim (inline read-char unread-char read-byte))
(declaim (inline ansi-stream-read-char))
(defun ansi-stream-read-char (stream eof-error-p eof-value recursive-p)
(declare (ignore recursive-p))
(prepare-for-fast-read-char stream
(prog1
(fast-read-char eof-error-p eof-value)
(done-with-fast-read-char))))
(defun read-char (&optional (stream *standard-input*)
(eof-error-p t)
eof-value
recursive-p)
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:native (ansi-stream-read-char stream eof-error-p eof-value recursive-p)
:simple (let ((char (s-%read-char stream eof-error-p eof-value t)))
(if (eq char eof-value)
char
(the character char)))
:gray
(let ((char (stream-read-char stream)))
(if (eq char :eof)
(eof-or-lose stream eof-error-p eof-value)
(the character char)))))
(declaim (inline ansi-stream-unread-char))
(defun ansi-stream-unread-char (character stream)
(let ((index (1- (ansi-stream-in-index stream)))
(buffer (ansi-stream-cin-buffer stream)))
(declare (fixnum index))
(when (minusp index) (error "nothing to unread"))
(cond (buffer
(setf (aref buffer index) character)
(setf (ansi-stream-in-index stream) index)
the stream 's misc routine to handle the UNREAD operation .
(when (ansi-stream-input-char-pos stream)
(decf (ansi-stream-input-char-pos stream))))
(t
(call-ansi-stream-misc stream :unread character)))))
(defun unread-char (character &optional (stream *standard-input*))
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:simple (s-%unread-char stream character)
:native (ansi-stream-unread-char character stream)
:gray (stream-unread-char stream character))
nil)
(declaim (inline %ansi-stream-listen))
(defun %ansi-stream-listen (stream)
(or (/= (the fixnum (ansi-stream-in-index stream))
+ansi-stream-in-buffer-length+)
(call-ansi-stream-misc stream :listen)))
(declaim (inline ansi-stream-listen))
(defun ansi-stream-listen (stream)
(let ((result (%ansi-stream-listen stream)))
(if (eq result :eof)
nil
result)))
(defun listen (&optional (stream *standard-input*))
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:native (ansi-stream-listen stream)
:gray (stream-listen stream)))
(declaim (inline ansi-stream-read-char-no-hang))
(defun ansi-stream-read-char-no-hang (stream eof-error-p eof-value recursive-p)
(if (%ansi-stream-listen stream)
On T or : EOF get READ - CHAR to do the work .
(ansi-stream-read-char stream eof-error-p eof-value recursive-p)
nil))
(defun read-char-no-hang (&optional (stream *standard-input*)
(eof-error-p t)
eof-value
recursive-p)
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:native
(ansi-stream-read-char-no-hang stream eof-error-p eof-value
recursive-p)
:simple (s-%read-char-no-hang stream eof-error-p eof-value)
:gray
(let ((char (stream-read-char-no-hang stream)))
(if (eq char :eof)
(eof-or-lose stream eof-error-p eof-value)
(the (or character null) char)))))
(declaim (inline ansi-stream-clear-input))
(defun ansi-stream-clear-input (stream)
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(call-ansi-stream-misc stream :clear-input))
(defun clear-input (&optional (stream *standard-input*))
(declare (explicit-check))
(stream-api-dispatch (stream :input)
:native (ansi-stream-clear-input stream)
:gray (stream-clear-input stream))
nil)
(declaim (inline ansi-stream-read-byte))
(defun ansi-stream-read-byte (stream eof-error-p eof-value recursive-p)
(declare (ignore recursive-p))
(with-fast-read-byte (t stream eof-error-p eof-value)
(fast-read-byte)))
(defun read-byte (stream &optional (eof-error-p t) eof-value)
(declare (explicit-check))
(stream-api-dispatch (stream)
:native (ansi-stream-read-byte stream eof-error-p eof-value nil)
:simple (let ((byte (s-%read-byte stream eof-error-p eof-value)))
(if (eq byte eof-value)
byte
(the integer byte)))
:gray
(let ((byte (stream-read-byte stream)))
(if (eq byte :eof)
(eof-or-lose stream eof-error-p eof-value)
(the integer byte)))))
Read NUMBYTES bytes into BUFFER beginning at START , and return the
Note : CMU CL 's version of this had a special interpretation of
EOF - ERROR - P which SBCL does not have . ( In the EOF - ERROR - P = NIL
case , CMU CL 's version would return as soon as any data became
some cases , but it was n't being used in SBCL , so it was dropped .
If we ever need it , it could be added later as a new variant N - BIN
(declaim (inline read-n-bytes))
(defun read-n-bytes (stream buffer start numbytes &optional (eof-error-p t))
(if (ansi-stream-p stream)
(ansi-stream-read-n-bytes stream buffer start numbytes eof-error-p)
(let* ((end (+ start numbytes))
(read-end (stream-read-sequence stream buffer start end)))
(eof-or-lose stream (and eof-error-p (< read-end end)) (- read-end start)))))
(defun ansi-stream-read-n-bytes (stream buffer start numbytes eof-error-p)
(declare (type ansi-stream stream)
(type index numbytes start)
(type (or (simple-array * (*)) system-area-pointer) buffer))
(let ((in-buffer (ansi-stream-in-buffer stream)))
(unless in-buffer
(return-from ansi-stream-read-n-bytes
(funcall (ansi-stream-n-bin stream) stream buffer start numbytes eof-error-p)))
(let* ((index (ansi-stream-in-index stream))
(num-buffered (- +ansi-stream-in-buffer-length+ index)))
These bytes are of course actual bytes , i.e. 8 - bit octets
(cond ((<= numbytes num-buffered)
(%byte-blt in-buffer index buffer start (+ start numbytes))
(setf (ansi-stream-in-index stream) (+ index numbytes))
numbytes)
(t
(let ((end (+ start num-buffered)))
(%byte-blt in-buffer index buffer start end)
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(+ (funcall (ansi-stream-n-bin stream) stream buffer
end (- numbytes num-buffered) eof-error-p)
num-buffered)))))))
( It 's 4 instead of 1 to allow word - aligned copies . )
(defconstant +ansi-stream-in-buffer-extra+
If EOF is hit and EOF - ERROR - P is false , then return NIL ,
otherwise return the new index into CIN - BUFFER .
(defun fast-read-char-refill (stream eof-error-p)
(when (ansi-stream-input-char-pos stream)
(update-input-char-pos stream))
(let* ((ibuf (ansi-stream-cin-buffer stream))
(count (funcall (ansi-stream-n-bin stream)
stream
ibuf
+ansi-stream-in-buffer-extra+
(- +ansi-stream-in-buffer-length+
+ansi-stream-in-buffer-extra+)
nil))
(start (- +ansi-stream-in-buffer-length+ count)))
(declare (type index start count))
(cond ((zerop count)
the EOF , it 's also possible that it 's e.g. due to a
the case correctly we need to call the reading
function and check whether an EOF was really reached . If
not , we can just fill the buffer by one character , and
: we ca n't use FD - STREAM functions ( which are the
(let* ((index (1- +ansi-stream-in-buffer-length+))
(value (funcall (ansi-stream-in stream) stream nil :eof)))
(cond
into the slot . But because we 've already bumped INPUT - CHAR - POS
((eql value :eof)
definitely EOF now
(setf (ansi-stream-in-index stream)
+ansi-stream-in-buffer-length+)
(eof-or-lose stream eof-error-p nil))
(t
(setf (aref ibuf index) value)
(setf (ansi-stream-in-index stream) index)))))
(t
(when (/= start +ansi-stream-in-buffer-extra+)
(#.(let* ((n-character-array-bits
(sb-vm:saetp-n-bits
(find 'character
sb-vm:*specialized-array-element-type-properties*
:key #'sb-vm:saetp-specifier)))
(bash-function (intern (format nil "UB~D-BASH-COPY" n-character-array-bits)
(find-package "SB-KERNEL"))))
bash-function)
ibuf +ansi-stream-in-buffer-extra+
ibuf start
count))
(setf (ansi-stream-in-index stream) start)))))
(defun fast-read-byte-refill (stream eof-error-p eof-value)
(let* ((ibuf (ansi-stream-in-buffer stream))
(count (funcall (ansi-stream-n-bin stream) stream
ibuf 0 +ansi-stream-in-buffer-length+
nil))
(start (- +ansi-stream-in-buffer-length+ count)))
(declare (type index start count))
(cond ((zerop count)
(setf (ansi-stream-in-index stream) +ansi-stream-in-buffer-length+)
(funcall (ansi-stream-bin stream) stream eof-error-p eof-value))
(t
(unless (zerop start)
(ub8-bash-copy ibuf 0
ibuf start
count))
(setf (ansi-stream-in-index stream) (1+ start))
(aref ibuf start)))))
(defun write-char (character &optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (return-from write-char (funcall (ansi-stream-cout stream) stream character))
:simple (s-%write-char stream character)
:gray (stream-write-char stream character))
character)
(defun terpri (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (funcall (ansi-stream-cout stream) stream #\Newline)
:simple (s-%terpri stream)
:gray (stream-terpri stream))
nil)
(defun fresh-line (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (unless (eql (charpos stream) 0)
(funcall (ansi-stream-cout stream) stream #\newline)
t)
:simple (s-%fresh-line stream)
:gray (stream-fresh-line stream)))
(macrolet
((define (name)
`(defun ,name (string stream start end)
instead just access character - at - a - time or inefficiently call SUBSEQ .
(with-array-data ((data string) (start start) (end end) :check-fill-pointer t)
(stream-api-dispatch (stream :output)
:native (progn (funcall (ansi-stream-sout stream) stream data start end)
,@(when (eq name '%write-line)
'((funcall (ansi-stream-cout stream) stream #\newline))))
:simple (,(symbolicate "S-" name) stream data start end)
:gray (progn (stream-write-string stream data start end)
,@(when (eq name '%write-line)
'((stream-write-char stream #\newline))))))
string)))
(define %write-line)
(define %write-string))
(defun write-string (string &optional (stream *standard-output*)
&key (start 0) end)
(declare (explicit-check))
(%write-string string stream start end))
(defun write-line (string &optional (stream *standard-output*)
&key (start 0) end)
(declare (explicit-check))
(%write-line string stream start end))
(defun charpos (&optional (stream *standard-output*))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :charpos)
:simple (s-%charpos stream)
:gray (stream-line-column stream)))
(defun line-length (&optional (stream *standard-output*))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :line-length)
:simple (s-%line-length stream)
:gray (stream-line-length stream)))
(defun finish-output (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :finish-output)
:simple (s-%finish-output stream)
:gray (stream-finish-output stream))
nil)
(defun force-output (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :force-output)
:simple (s-%force-output stream)
:gray (stream-force-output stream))
nil)
(defun clear-output (&optional (stream *standard-output*))
(declare (explicit-check))
(stream-api-dispatch (stream :output)
:native (call-ansi-stream-misc stream :clear-output)
:simple (s-%clear-output stream)
:gray (stream-clear-output stream))
nil)
(defun write-byte (integer stream)
(declare (explicit-check))
(stream-api-dispatch (stream)
:native (return-from write-byte (funcall (ansi-stream-bout stream) stream integer))
:simple (s-%write-byte stream integer)
:gray (stream-write-byte stream integer))
integer)
This is called from ANSI - STREAM routines that encapsulate CLOS
appropriate SIMPLE- or FUNDAMENTAL - STREAM functions .
(defun stream-misc-dispatch (stream operation arg)
(if (simple-stream-p stream)
Dispatch to a simple - stream implementation function
(stream-misc-case (operation)
(:unread (s-%unread-char stream arg))
(:close (error "Attempted to close inner stream ~S" stream))
(:force-output (s-%force-output stream))
(:finish-output (s-%finish-output stream))
(:clear-output (s-%clear-output stream))
All simple - streams use ( UNSIGNED - BYTE 8) - it 's one of the
salient distinctions between simple - streams and Gray streams .
See ( DEFMETHOD STREAM - ELEMENT - TYPE ( ( STREAM SIMPLE - STREAM ) ) ... )
(:element-type '(unsigned-byte 8))
returned UNSIGNED - BYTE based on element - type . But this is wrong !
(:element-mode 'UNSIGNED-BYTE)
(:external-format (s-%stream-external-format stream))
(:interactive-p (interactive-stream-p stream))
(:line-length (s-%line-length stream))
(:charpos (s-%charpos stream))
(:file-length (s-%file-length stream))
(:file-string-length (s-%file-string-length stream arg))
(:set-file-position (s-%file-position stream arg))
(:get-file-position (s-%file-position stream nil)))
(stream-misc-case (operation)
(:listen (stream-listen stream))
specialized arg first
(:close (error "Attempted to close inner stream ~S" stream))
(:clear-input (stream-clear-input stream))
(:force-output (stream-force-output stream))
(:finish-output (stream-finish-output stream))
(:clear-output (stream-clear-output stream))
(:element-type (stream-element-type stream))
(:element-mode
(stream-element-type-stream-element-mode (stream-element-type stream)))
(:line-length (stream-line-length stream))
(:charpos (stream-line-column stream))
(:set-file-position (stream-file-position stream arg))
(:get-file-position (stream-file-position stream))
since they are n't generic and do n't work on Gray streams .
(:external-format (stream-external-format stream))
(:file-length (file-length stream))
(:file-string-length (file-string-length stream arg)))))
(declaim (inline stream-element-mode))
(defun stream-element-mode (stream)
(declare (type stream stream))
(cond
((fd-stream-p stream)
(fd-stream-element-mode stream))
((and (ansi-stream-p stream)
(call-ansi-stream-misc stream :element-mode)))
(t
(stream-element-type-stream-element-mode
(stream-element-type stream)))))
(defun make-broadcast-stream (&rest streams)
(dolist (stream streams)
(unless (output-stream-p stream)
(error 'type-error
:datum stream
:expected-type '(satisfies output-stream-p))))
(let ((stream (%make-broadcast-stream streams)))
(unless streams
(flet ((out (stream arg)
(declare (ignore stream)
(optimize speed (safety 0)))
arg)
(sout (stream string start end)
(declare (ignore stream string start end)
(optimize speed (safety 0)))))
(setf (broadcast-stream-cout stream) #'out
(broadcast-stream-bout stream) #'out
(broadcast-stream-sout stream) #'sout)))
stream))
(macrolet ((out-fun (name fun args return)
`(defun ,name (stream ,@args)
(dolist (stream (broadcast-stream-streams stream) ,return)
(,fun ,(car args) stream ,@(cdr args))))))
(out-fun broadcast-cout write-char (char) char)
(out-fun broadcast-bout write-byte (byte) byte)
(out-fun broadcast-sout %write-string (string start end) nil))
(defun broadcast-misc (stream operation arg1)
(let ((streams (broadcast-stream-streams stream)))
(stream-misc-case (operation)
FIXME : see also TWO - WAY - STREAM treatment of : CHARPOS -- why
-- CSR , 2004 - 02 - 04
(:charpos
(dolist (stream streams 0)
(let ((charpos (charpos stream)))
(when charpos
(return charpos)))))
(:line-length
(let ((min nil))
(dolist (stream streams min)
(let ((res (line-length stream)))
(when res (setq min (if min (min res min) res)))))))
(:element-type
(let ((last (last streams)))
(if last
(stream-element-type (car last))
t)))
(:element-mode
(awhen (last streams)
(stream-element-mode (car it))))
(:external-format
(let ((last (last streams)))
(if last
(stream-external-format (car last))
:default)))
(:file-length
(let ((last (last streams)))
(if last
(file-length (car last))
0)))
(:set-file-position
(let ((res (or (eql arg1 :start) (eql arg1 0))))
(dolist (stream streams res)
(setq res (file-position stream arg1)))))
(:get-file-position
(let ((last (last streams)))
(if last
(file-position (car last))
0)))
(:file-string-length
(let ((last (last streams)))
(if last
(file-string-length (car last) arg1)
1)))
(:close
(unless (eq stream *null-broadcast-stream*)
(set-closed-flame stream)))
(t
(let ((res nil))
(dolist (stream streams res)
(setq res
(if (ansi-stream-p stream)
(call-ansi-stream-misc stream operation arg1)
(stream-misc-dispatch stream operation arg1)))))))))
(defmethod print-object ((x synonym-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream ":SYMBOL ~S" (synonym-stream-symbol x))))
(macrolet ((out-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(declare (optimize (safety 1)))
(let ((syn (symbol-value (synonym-stream-symbol stream))))
(,fun ,(car args) syn ,@(cdr args))))))
(out-fun synonym-out write-char ch)
(out-fun synonym-bout write-byte n)
(out-fun synonym-sout %write-string string start end))
(macrolet ((in-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(declare (optimize (safety 1)))
(,fun (symbol-value (synonym-stream-symbol stream))
,@args))))
(in-fun synonym-in read-char eof-error-p eof-value)
(in-fun synonym-bin read-byte eof-error-p eof-value)
(in-fun synonym-n-bin read-n-bytes buffer start numbytes eof-error-p))
(defun synonym-misc (stream operation arg1)
(declare (optimize (safety 1)))
CLHS 21.1.4 implies that CLOSE on a synonym stream closes the synonym stream in that
(stream-misc-case (operation)
(:close
(set-closed-flame stream))
(t
(let ((syn (symbol-value (synonym-stream-symbol stream))))
(if (ansi-stream-p syn)
(stream-misc-case (operation)
(:listen (%ansi-stream-listen syn))
(:clear-input (clear-input syn))
(:unread (unread-char arg1 syn))
(t
(call-ansi-stream-misc syn operation arg1)))
(stream-misc-dispatch syn operation arg1))))))
two - way streams
(defstruct (two-way-stream
(:include ansi-stream
(in #'two-way-in)
(bin #'two-way-bin)
(n-bin #'two-way-n-bin)
(cout #'two-way-out)
(bout #'two-way-bout)
(sout #'two-way-sout)
(misc #'two-way-misc))
(:constructor %make-two-way-stream (input-stream output-stream))
(:copier nil)
(:predicate nil))
(input-stream (missing-arg) :type stream :read-only t)
(output-stream (missing-arg) :type stream :read-only t))
(defmethod print-object ((x two-way-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream
":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
(two-way-stream-input-stream x)
(two-way-stream-output-stream x))))
(defun make-two-way-stream (input-stream output-stream)
"Return a bidirectional stream which gets its input from INPUT-STREAM and
sends its output to OUTPUT-STREAM."
(unless (output-stream-p output-stream)
(error 'type-error
:datum output-stream
:expected-type '(satisfies output-stream-p)))
(unless (input-stream-p input-stream)
(error 'type-error
:datum input-stream
:expected-type '(satisfies input-stream-p)))
(%make-two-way-stream input-stream output-stream))
(macrolet ((out-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(let ((syn (two-way-stream-output-stream stream)))
(,fun ,(car args) syn ,@(cdr args))))))
(out-fun two-way-out write-char ch)
(out-fun two-way-bout write-byte n)
(out-fun two-way-sout %write-string string start end))
(macrolet ((in-fun (name fun &rest args)
`(defun ,name (stream ,@args)
(,fun (two-way-stream-input-stream stream) ,@args))))
(in-fun two-way-in read-char eof-error-p eof-value)
(in-fun two-way-bin read-byte eof-error-p eof-value)
(in-fun two-way-n-bin read-n-bytes buffer start numbytes eof-error-p))
(defun two-way-misc (stream operation arg1)
(let* ((in (two-way-stream-input-stream stream))
(out (two-way-stream-output-stream stream))
(in-ansi-stream-p (ansi-stream-p in))
(out-ansi-stream-p (ansi-stream-p out)))
(stream-misc-case (operation)
(:listen
(if in-ansi-stream-p
(%ansi-stream-listen in)
(listen in)))
((:finish-output :force-output :clear-output)
(if out-ansi-stream-p
(call-ansi-stream-misc out operation arg1)
(stream-misc-dispatch out operation arg1)))
(:clear-input (clear-input in))
(:unread (unread-char arg1 in))
(:element-type
(let ((in-type (stream-element-type in))
(out-type (stream-element-type out)))
(if (equal in-type out-type)
in-type
`(and ,in-type ,out-type))))
(:element-mode
(let ((in-mode (stream-element-mode in))
(out-mode (stream-element-mode out)))
(when (equal in-mode out-mode)
in-mode)))
(:close
(set-closed-flame stream))
(t
(or (if in-ansi-stream-p
(call-ansi-stream-misc in operation arg1)
(stream-misc-dispatch in operation arg1))
(if out-ansi-stream-p
(call-ansi-stream-misc out operation arg1)
(stream-misc-dispatch out operation arg1)))))))
(defstruct (concatenated-stream
(:include ansi-stream
(in #'concatenated-in)
(bin #'concatenated-bin)
(n-bin #'concatenated-n-bin)
(misc #'concatenated-misc))
(:constructor %make-concatenated-stream (streams))
(:copier nil)
(:predicate nil))
(streams nil :type list))
(declaim (freeze-type concatenated-stream))
(defmethod print-object ((x concatenated-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream
":STREAMS ~S"
(concatenated-stream-streams x))))
(defun make-concatenated-stream (&rest streams)
"Return a stream which takes its input from each of the streams in turn,
going on to the next at EOF."
(dolist (stream streams)
(unless (input-stream-p stream)
(error 'type-error
:datum stream
:expected-type '(satisfies input-stream-p))))
(%make-concatenated-stream streams))
(macrolet ((in-fun (name fun)
`(defun ,name (stream eof-error-p eof-value)
(do ((streams (concatenated-stream-streams stream)
(cdr streams)))
((null streams)
(eof-or-lose stream eof-error-p eof-value))
(let* ((stream (car streams))
(result (,fun stream nil nil)))
(when result (return result)))
(pop (concatenated-stream-streams stream))))))
(in-fun concatenated-in read-char)
(in-fun concatenated-bin read-byte))
(defun concatenated-n-bin (stream buffer start numbytes eof-errorp)
(do ((streams (concatenated-stream-streams stream) (cdr streams))
(current-start start)
(remaining-bytes numbytes))
((null streams)
(if eof-errorp
(error 'end-of-file :stream stream)
(- numbytes remaining-bytes)))
(let* ((stream (car streams))
(bytes-read (read-n-bytes stream buffer current-start
remaining-bytes nil)))
(incf current-start bytes-read)
(decf remaining-bytes bytes-read)
(when (zerop remaining-bytes) (return numbytes)))
(setf (concatenated-stream-streams stream) (cdr streams))))
(defun concatenated-misc (stream operation arg1)
(let* ((left (concatenated-stream-streams stream))
(current (car left)))
(stream-misc-case (operation)
(:listen
(unless left
(return-from concatenated-misc :eof))
(loop
(let ((stuff (if (ansi-stream-p current)
(%ansi-stream-listen current)
(stream-misc-dispatch current operation arg1))))
(cond ((eq stuff :eof)
(pop (concatenated-stream-streams stream))
(setf current
(car (concatenated-stream-streams stream)))
(unless current
(return :eof)))
(stuff
(return t))
(t
(return nil))))))
(:clear-input (when left (clear-input current)))
(:unread (when left (unread-char arg1 current)))
(:close
(set-closed-flame stream))
(t
(when left
(if (ansi-stream-p current)
(call-ansi-stream-misc current operation arg1)
(stream-misc-dispatch current operation arg1)))))))
(defstruct (echo-stream
(:include two-way-stream
(in #'echo-in)
(bin #'echo-bin)
(misc #'echo-misc)
(n-bin #'echo-n-bin))
(:constructor %make-echo-stream (input-stream output-stream))
(:copier nil)
(:predicate nil))
(unread-stuff nil :type boolean))
(declaim (freeze-type two-way-stream))
(defmethod print-object ((x echo-stream) stream)
(print-unreadable-object (x stream :type t :identity t)
(format stream
":INPUT-STREAM ~S :OUTPUT-STREAM ~S"
(two-way-stream-input-stream x)
(two-way-stream-output-stream x))))
(defun make-echo-stream (input-stream output-stream)
"Return a bidirectional stream which gets its input from INPUT-STREAM and
sends its output to OUTPUT-STREAM. In addition, all input is echoed to
the output stream."
(unless (output-stream-p output-stream)
(error 'type-error
:datum output-stream
:expected-type '(satisfies output-stream-p)))
(unless (input-stream-p input-stream)
(error 'type-error
:datum input-stream
:expected-type '(satisfies input-stream-p)))
(%make-echo-stream input-stream output-stream))
(macrolet ((in-fun (name in-fun out-fun &rest args)
`(defun ,name (stream ,@args)
(let* ((unread-stuff-p (echo-stream-unread-stuff stream))
(in (echo-stream-input-stream stream))
(out (echo-stream-output-stream stream))
(result (if eof-error-p
(,in-fun in ,@args)
(,in-fun in nil in))))
(setf (echo-stream-unread-stuff stream) nil)
(cond
((eql result in) eof-value)
(t (unless unread-stuff-p (,out-fun result out)) result))))))
(in-fun echo-in read-char write-char eof-error-p eof-value)
(in-fun echo-bin read-byte write-byte eof-error-p eof-value))
(defun echo-n-bin (stream buffer start numbytes eof-error-p)
(let ((bytes-read 0))
Note : before ca 1.0.27.18 , the logic for handling unread
(when (echo-stream-unread-stuff stream)
(let* ((char (read-char stream))
(octets (string-to-octets
(string char)
:external-format
(stream-external-format
(echo-stream-input-stream stream))))
(octet-count (length octets))
(blt-count (min octet-count numbytes)))
(replace buffer octets :start1 start :end1 (+ start blt-count))
(incf start blt-count)
(decf numbytes blt-count)))
(incf bytes-read (read-n-bytes (echo-stream-input-stream stream) buffer
start numbytes nil))
(cond
((not eof-error-p)
(write-seq-impl buffer (echo-stream-output-stream stream)
start (+ start bytes-read))
bytes-read)
((> numbytes bytes-read)
(write-seq-impl buffer (echo-stream-output-stream stream)
start (+ start bytes-read))
(error 'end-of-file :stream stream))
(t
(write-seq-impl buffer (echo-stream-output-stream stream)
start (+ start bytes-read))
(aver (= numbytes (+ start bytes-read)))
numbytes))))
(defstruct (string-input-stream
(:include ansi-stream (misc #'string-in-misc))
(:constructor nil)
(:copier nil)
(:predicate nil))
(index nil :type index)
(limit nil :type index :read-only t)
(string nil :type simple-string :read-only t)
So that we know what string index FILE - POSITION 0 to
(start nil :type index :read-only t))
(declaim (freeze-type string-input-stream))
(defun string-in-misc (stream operation arg1)
(declare (type string-input-stream stream))
(stream-misc-case (operation :default nil)
(:set-file-position
(setf (string-input-stream-index stream)
(case arg1
(:start (string-input-stream-start stream))
(:end (string-input-stream-limit stream))
We allow moving position beyond EOF . Errors happen
(t (+ (string-input-stream-start stream) arg1)))))
(:get-file-position
(- (string-input-stream-index stream)
(string-input-stream-start stream)))
(:unread (setf (string-input-stream-index stream)
(max (1- (string-input-stream-index stream))
(string-input-stream-start stream))))
(:close (set-closed-flame stream))
(:listen (if (< (string-input-stream-index stream)
(string-input-stream-limit stream))
t :eof))
(:element-type (array-element-type (string-input-stream-string stream)))
(:element-mode 'character)))
Since we do n't want to insert ~300 bytes of code at every site
(defun %init-string-input-stream (stream string &optional (start 0) end)
(declare (explicit-check string))
(macrolet ((initforms ()
`(progn
,@(mapcar (lambda (dsd)
`(%instance-set stream ,(dsd-index dsd)
,(case (dsd-name dsd)
((index start) 'start)
(limit 'end)
(string 'simple-string)
(in 'input-routine)
(misc '#'string-in-misc)
(t (dsd-default dsd)))))
(dd-slots
(find-defstruct-description 'string-input-stream)))))
(char-in (element-type)
`(let ((index (string-input-stream-index
(truly-the string-input-stream stream)))
(string (truly-the (simple-array ,element-type (*))
(string-input-stream-string stream))))
(cond ((>= index (string-input-stream-limit stream))
(eof-or-lose stream eof-error-p eof-value))
(t
(setf (string-input-stream-index stream) (1+ index))
(char string index))))))
(flet ((base-char-in (stream eof-error-p eof-value)
(declare (optimize (sb-c::verify-arg-count 0)
(sb-c:insert-array-bounds-checks 0)))
(char-in base-char))
(character-in (stream eof-error-p eof-value)
(declare (optimize (sb-c::verify-arg-count 0)
(sb-c:insert-array-bounds-checks 0)))
(char-in character)))
(let ((input-routine
(etypecase string
(base-string #'base-char-in)
(string #'character-in))))
(with-array-data ((simple-string string :offset-var offset)
(start start)
(end end)
:check-fill-pointer t)
(initforms)
(values (truly-the string-input-stream stream)
offset))))))
(defun make-string-input-stream (string &optional (start 0) end)
"Return an input stream which will supply the characters of STRING between
START and END in order."
(macrolet ((make () `(%make-structure-instance
,(find-defstruct-description 'string-input-stream)
nil)))
(values (%init-string-input-stream (make) string start end))))
(defun %init-string-output-stream (stream buffer wild-result-type)
(declare (optimize speed (sb-c::verify-arg-count 0)))
(declare (string buffer)
(macrolet ((initforms ()
`(progn
,@(mapcar (lambda (dsd)
`(%instance-set stream ,(dsd-index dsd)
,(case (dsd-name dsd)
((element-type unicode-p cout sout-aux buffer)
(dsd-name dsd))
(t (dsd-default dsd)))))
(dd-slots
(find-defstruct-description 'string-output-stream)))))
(cout (elt-type)
`(let ((pointer (string-output-stream-pointer
(truly-the string-output-stream stream)))
(buffer (truly-the (simple-array ,elt-type (*))
(string-output-stream-buffer stream)))
(index (string-output-stream-index stream)))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(when (= pointer (length buffer))
(setf buffer (string-output-stream-new-buffer stream index)
pointer 0))
(setf (string-output-stream-pointer stream) (truly-the index (1+ pointer)))
(setf (string-output-stream-index stream) (truly-the index (1+ index)))
(setf (aref (truly-the (simple-array ,elt-type (*)) buffer) pointer)
char)))
(sout (elt-type)
Only one case cares whether the string contains non - base chars .
character - string source , base - string buf verifies base - char on copy
character - string source + buf needs a pre - scan for Unicode .
`(etypecase src
#+sb-unicode
(simple-character-string
,@(when (eq elt-type 'character)
When UNICODE - P is NIL , meaning no non - base chars were seen yet
'((when (and (not (string-output-stream-unicode-p
(truly-the string-output-stream stream)))
(input-contains-unicode))
(setf (string-output-stream-unicode-p stream) t
(ansi-stream-cout stream) #'character-out))))
(replace (truly-the (simple-array ,elt-type (*)) dst)
(truly-the simple-character-string src)
:start1 start1 :start2 start2 :end2 end2))
(simple-base-string
(replace (truly-the (simple-array ,elt-type (*)) dst)
(truly-the simple-base-string src)
:start1 start1 :start2 start2 :end2 end2))))
(input-contains-unicode ()
For streams with : element - type ( producing the most space - efficient
`(let ((s (truly-the simple-character-string src)))
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(loop for i from start2 below end2
thereis (>= (char-code (aref s i)) base-char-code-limit)))))
Is a character for sure ? I have no idea . And how about the indices in SOUT ?
(labels ((base-char-out (stream char)
(cout base-char))
(character-out (stream char)
(cout character))
(default-out (stream char)
(when (>= (char-code char) base-char-code-limit)
(setf (string-output-stream-unicode-p stream) t
(ansi-stream-cout stream) #'character-out))
(cout character))
(base-string-out (stream dst src start1 start2 end2)
(declare (ignorable stream) (index start1 start2 end2))
(sout base-char))
(char-string-out (stream dst src start1 start2 end2)
(declare (ignorable stream) (index start1 start2 end2))
(sout character))
(reject (&rest args)
(declare (ignore args))
(error "Stream can not accept characters"))
(misc (stream operation arg1)
Intercept the misc handler to reset the Unicode state
(stream-misc-case (operation)
(:reset-unicode-p
(setf (string-output-stream-unicode-p stream) nil
resume checking for Unicode characters
(ansi-stream-cout stream) #'default-out))
(t
(string-out-misc stream operation arg1)))))
(multiple-value-bind (element-type unicode-p cout sout-aux)
(case (%other-pointer-widetag buffer)
#+sb-unicode
(#.sb-vm:simple-character-string-widetag
(if wild-result-type
(values :default nil #'default-out #'char-string-out)
(values 'character t #'character-out #'char-string-out)))
(#.sb-vm:simple-base-string-widetag
(values 'base-char :ignore #'base-char-out #'base-string-out))
(t
(values nil :ignore #'reject #'reject)))
(initforms)
(truly-the string-output-stream stream)))))
(defun %make-base-string-ostream ()
(%init-string-output-stream (%allocate-string-ostream)
2w + 64b
nil))
(defun %make-character-string-ostream ()
(%init-string-output-stream (%allocate-string-ostream)
2w + 128b
nil))
(defun make-string-output-stream (&key (element-type 'character))
"Return an output stream which will accumulate all output given it for the
benefit of the function GET-OUTPUT-STREAM-STRING."
(declare (explicit-check))
Compiler transforms into % MAKE - CHARACTER - STRING - OSTREAM .
(let ((ctype (specifier-type element-type)))
(cond ((and (csubtypep ctype (specifier-type 'base-char))
(neq ctype *empty-type*))
(%make-base-string-ostream))
((csubtypep ctype (specifier-type 'character))
(%make-character-string-ostream))
(t
(error "~S is not a subtype of CHARACTER" element-type)))))
(defstruct (finite-base-string-output-stream
(:include ansi-stream
(cout #'finite-base-string-ouch)
(sout #'finite-base-string-sout)
(misc #'finite-base-string-out-misc))
(:constructor %make-finite-base-string-output-stream (buffer))
(:copier nil)
(:predicate nil))
(buffer nil :type simple-base-string :read-only t)
(pointer 0 :type index))
(declaim (freeze-type finite-base-string-output-stream))
(defun string-output-stream-new-buffer (stream size)
(declare (index size))
(declare (string-output-stream stream))
(push (string-output-stream-buffer stream)
(string-output-stream-prev stream))
(setf (string-output-stream-buffer stream)
(or (pop (string-output-stream-next stream))
above its DEF!TYPE - it seems like this ca n't be making things any worse to
(let ((maximum-string-length (1- array-dimension-limit))
(current-index (string-output-stream-index stream)))
(when (> (+ current-index size) maximum-string-length)
(setq size (- maximum-string-length current-index)))
(when (<= size 0)
(error "string-output-stream maximum length exceeded"))
(if (member (string-output-stream-element-type stream) '(base-char nil))
(make-array size :element-type 'base-char)
(make-array size :element-type 'character))))))
(defun string-output-stream-next-buffer (stream)
(declare (string-output-stream stream))
(let* ((old (string-output-stream-buffer stream))
(new (pop (string-output-stream-next stream)))
(old-size (length old))
(skipped (- old-size (string-output-stream-pointer stream))))
(cond (new
(let ((new-size (length new)))
(push old (string-output-stream-prev stream))
(setf (string-output-stream-buffer stream) new
(string-output-stream-pointer stream) new-size)
(incf (string-output-stream-index stream) (+ skipped new-size)))
t)
(t
(setf (string-output-stream-pointer stream) old-size)
(incf (string-output-stream-index stream) skipped)
nil))))
(defun string-output-stream-prev-buffer (stream)
(declare (string-output-stream stream))
(let ((old (string-output-stream-buffer stream))
(new (pop (string-output-stream-prev stream)))
(skipped (string-output-stream-pointer stream)))
(cond (new
(push old (string-output-stream-next stream))
(setf (string-output-stream-buffer stream) new
(string-output-stream-pointer stream) 0)
(decf (string-output-stream-index stream) (+ skipped (length new)))
t)
(t
(setf (string-output-stream-pointer stream) 0)
(decf (string-output-stream-index stream) skipped)
nil))))
(defun string-sout (stream string start end)
(declare (explicit-check string)
(type index start end))
FIXME : this contains about 7 OBJECT - NOT - INDEX error traps .
exceed the number of allowed characters , and then not do any further tests .
Also , the SOUT - AUX method contains 4 calls to SB - INT : SEQUENCE - BOUNDING - INDICES - BAD - ERROR
(let* ((full-length (- end start))
(length full-length)
(buffer (string-output-stream-buffer stream))
(pointer (string-output-stream-pointer stream))
(space (- (length buffer) pointer))
(here (min space length))
(stop (+ start here))
(overflow (- length space)))
(declare (index length space here stop full-length)
(fixnum overflow))
(tagbody
:more
(when (plusp here)
(funcall (string-output-stream-sout-aux stream)
stream buffer string pointer start stop)
(setf (string-output-stream-pointer stream) (+ here pointer)))
(when (plusp overflow)
(setf start stop
length (- end start)
- initial buffer capacity of 63 characters
- WRITE - STRING with 2 characters setting INDEX=2 , SPACE=61
- another WRITE - STRING with 62 characters . 61 copied , 1 overflow .
- then new BUFFER length is ( MAX OVERFLOW INDEX ) = 2
buffer (string-output-stream-new-buffer
stream (max overflow (string-output-stream-index stream)))
pointer 0
space (length buffer)
here (min space length)
stop (+ start here)
overflow (- length space))
(go :more)))
(incf (string-output-stream-index stream) full-length)))
This is a steaming pile of horsecrap ( lp#1839040 )
(defun set-string-output-stream-file-position (stream pos)
(let* ((index (string-output-stream-index stream))
(end (max index (string-output-stream-index-cache stream))))
(declare (index index end))
(setf (string-output-stream-index-cache stream) end)
(cond ((eq :start pos)
(loop while (string-output-stream-prev-buffer stream)))
((eq :end pos)
(loop while (string-output-stream-next-buffer stream))
(let ((over (- (string-output-stream-index stream) end)))
(decf (string-output-stream-pointer stream) over))
(setf (string-output-stream-index stream) end))
((< pos index)
(loop while (< pos index)
do (string-output-stream-prev-buffer stream)
(setf index (string-output-stream-index stream)))
(let ((step (- pos index)))
(incf (string-output-stream-pointer stream) step)
(setf (string-output-stream-index stream) pos)))
((> pos index)
(let ((next (string-output-stream-next-buffer stream)))
(setf index (string-output-stream-index stream))
(loop while (and next (> pos index))
do (setf next (string-output-stream-next-buffer stream)
index (string-output-stream-index stream))))
(let ((diff (- pos index)))
(if (plusp diff)
(let* ((new (string-output-stream-new-buffer stream diff))
(size (length new)))
(aver (= pos (+ index size)))
(setf (string-output-stream-pointer stream) size
(string-output-stream-index stream) pos))
(let ((size (length (string-output-stream-buffer stream))))
(setf (string-output-stream-pointer stream) (+ size diff)
(string-output-stream-index stream) pos))))))))
(defun string-out-misc (stream operation arg1)
(declare (optimize speed))
(stream-misc-case (operation :default nil)
(:charpos
Keeping this first is a silly micro - optimization : FRESH - LINE
(/noshow0 "/string-out-misc charpos")
(prog ((pointer (string-output-stream-pointer stream))
(buffer (string-output-stream-buffer stream))
(prev (string-output-stream-prev stream))
(base 0))
:next
could be NIL because of SETF below
(string-dispatch (simple-base-string
#+sb-unicode simple-character-string)
buffer
(position #\newline buffer :from-end t :end pointer)))))
(when (or pos (not buffer))
(return (+ base (if pos (- pointer pos 1) pointer))))
(setf base (+ base pointer)
buffer (pop prev)
pointer (length buffer))
(/noshow0 "/string-out-misc charpos next")
(go :next))))
(:set-file-position
(set-string-output-stream-file-position stream arg1)
(:get-file-position
(string-output-stream-index stream))
(:close
(/noshow0 "/string-out-misc close")
(set-closed-flame stream))
(:element-type
(let ((et (string-output-stream-element-type stream)))
(if (eq et :default) 'character et)))
(:element-mode 'character)))
(defun get-output-stream-string (stream)
(declare (type string-output-stream stream))
(let* ((length (max (string-output-stream-index stream)
(string-output-stream-index-cache stream)))
(prev (nreverse (string-output-stream-prev stream)))
(this (string-output-stream-buffer stream))
(next (string-output-stream-next stream))
(base-string-p (neq (string-output-stream-unicode-p stream) t))
of a Unicode buffer and ASCII result , that seems inapplicable nowadays .
( See )
(result (if base-string-p
(make-string length :element-type 'base-char)
(make-string length))))
(setf (string-output-stream-index stream) 0
(string-output-stream-index-cache stream) 0
(string-output-stream-pointer stream) 0
(string-output-stream-prev stream) nil
(string-output-stream-next stream) nil)
Reset UNICODE - P unless it was : IGNORE or element - type is CHARACTER .
(when (and (eq (string-output-stream-element-type stream) :default)
(eq (string-output-stream-unicode-p stream) t))
(call-ansi-stream-misc stream :reset-unicode-p))
There are exactly 3 cases that we have to deal with when copying :
The first case occurs when and only when the element type is : and
only base characters were written . The other two cases can be handled
using BYTE - BLT with indices multiplied by either 1 or 4 .
(flet ((copy (fun extra)
(declare (index start))
(dolist (buffer prev)
(funcall fun result buffer start extra)
(incf start (length buffer)))
(funcall fun result this start extra)
(incf start (length this))
(dolist (buffer next)
(funcall fun result buffer start extra)
(incf start (length buffer))))))
(if (and (eq (string-output-stream-element-type stream) :default)
base-string-p)
(copy (lambda (result source start dummy)
(declare (optimize speed (sb-c::type-check 0)))
(declare (ignore dummy))
(replace (the simple-base-string result)
(the simple-character-string source)
:start1 start))
0)
(with-pinned-objects (result)
BYTE - BLT does n't know that it could use memcpy rather then memmove ,
(copy (lambda (result source start scale)
(declare (index start))
(let* ((length (min (- (length result) start) (length source)))
(end (+ start length)))
(declare (index length end))
(with-pinned-objects (source)
(%byte-blt (vector-sap source)
0
(vector-sap result)
(truly-the index (ash start scale))
(truly-the index (ash end scale))))))
(if base-string-p 0 2)))))
result))
(defun finite-base-string-ouch (stream character)
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(let ((pointer (finite-base-string-output-stream-pointer stream))
(buffer (finite-base-string-output-stream-buffer stream)))
(cond ((= pointer (length buffer))
(bug "Should not happen"))
(t
(setf (finite-base-string-output-stream-pointer stream)
(truly-the index (1+ pointer))
(char buffer pointer) (truly-the base-char character))))))
(defun finite-base-string-sout (stream string start end)
(declare (optimize (sb-c:insert-array-bounds-checks 0)))
(let* ((pointer (finite-base-string-output-stream-pointer stream))
(buffer (finite-base-string-output-stream-buffer stream))
(length (- end start))
(new-pointer (+ pointer length)))
(cond ((> new-pointer (length buffer))
(bug "Should not happen"))
#+sb-unicode
((typep string 'simple-character-string)
(replace buffer string
:start1 pointer :start2 start :end2 end))
(t
(replace buffer (the simple-base-string string)
:start1 pointer :start2 start :end2 end)))
(setf (finite-base-string-output-stream-pointer stream) new-pointer)))
(defun finite-base-string-out-misc (stream operation arg1)
(declare (ignore stream operation arg1))
(error "finite-base-string-out-misc needs an implementation"))
the CLM , but they are required for the implementation of
FIXME : need to support ( VECTOR NIL ) , ideally without destroying all hope
(declaim (inline vector-with-fill-pointer-p))
(defun vector-with-fill-pointer-p (x)
(and (vectorp x)
(array-has-fill-pointer-p x)))
(deftype string-with-fill-pointer ()
`(and (or (vector character) (vector base-char))
(satisfies vector-with-fill-pointer-p)))
( let ( ( s ( make - array 5 : fill - pointer 0 : element - type ' base - char ) ) )
( with - output - to - string ( stream s ) ( dotimes ( i 6 ) ( write - char # \a stream ) ) ) s )
CLISP :
CCL :
(defstruct (fill-pointer-output-stream
(:include ansi-stream
(cout #'fill-pointer-ouch)
(sout #'fill-pointer-sout)
(misc #'fill-pointer-misc))
(:constructor nil)
(:copier nil)
(:predicate nil))
(string (missing-arg) :type string-with-fill-pointer :read-only t))
(declaim (freeze-type fill-pointer-output-stream))
(defun %init-fill-pointer-output-stream (stream string element-type)
(declare (optimize speed (sb-c::verify-arg-count 0)))
(declare (ignore element-type))
(unless (and (stringp string)
(array-has-fill-pointer-p string))
(error "~S is not a string with a fill-pointer" string))
(macrolet ((initforms ()
`(progn ,@(mapcar (lambda (dsd)
`(%instance-set stream ,(dsd-index dsd)
,(case (dsd-name dsd)
(string 'string)
(t (dsd-default dsd)))))
(dd-slots
(find-defstruct-description 'fill-pointer-output-stream))))))
(initforms)
(truly-the fill-pointer-output-stream stream)))
(defun fill-pointer-ouch (stream character)
FIXME : ridiculously inefficient . Can we throw some TRULY - THEs in here ?
(let* ((buffer (fill-pointer-output-stream-string stream))
(current (fill-pointer buffer))
(current+1 (1+ current)))
(declare (fixnum current))
(with-array-data ((workspace buffer) (start) (end))
(string-dispatch (simple-character-string simple-base-string) workspace
(let ((offset-current (+ start current)))
(declare (fixnum offset-current))
(if (= offset-current end)
(let* ((new-length (1+ (* current 2)))
(new-workspace
(ecase (array-element-type workspace)
(character (make-string new-length
:element-type 'character))
(base-char (make-string new-length
:element-type 'base-char)))))
(replace new-workspace workspace :start2 start :end2 offset-current)
(setf workspace new-workspace
offset-current current)
(set-array-header buffer workspace new-length
current+1 0 new-length nil nil))
(setf (fill-pointer buffer) current+1))
(setf (char workspace offset-current) character)))))
character)
(defun fill-pointer-sout (stream string start end)
(declare (fixnum start end))
(string-dispatch (simple-character-string simple-base-string) string
(let* ((buffer (fill-pointer-output-stream-string stream))
(current (fill-pointer buffer))
(string-len (- end start))
(dst-end (+ string-len current)))
(declare (fixnum current dst-end string-len))
(with-array-data ((workspace buffer) (dst-start) (dst-length))
(let ((offset-dst-end (+ dst-start dst-end))
(offset-current (+ dst-start current)))
(declare (fixnum offset-dst-end offset-current))
(if (> offset-dst-end dst-length)
(let* ((new-length (+ (the fixnum (* current 2)) string-len))
(new-workspace
(ecase (array-element-type workspace)
(character (make-string new-length
:element-type 'character))
(base-char (make-string new-length
:element-type 'base-char)))))
(replace new-workspace workspace
:start2 dst-start :end2 offset-current)
(setf workspace new-workspace
offset-current current
offset-dst-end dst-end)
(set-array-header buffer workspace new-length
dst-end 0 new-length nil nil))
(setf (fill-pointer buffer) dst-end))
(replace workspace string
:start1 offset-current :start2 start :end2 end)))
dst-end)))
(defun fill-pointer-misc (stream operation arg1
&aux (buffer (fill-pointer-output-stream-string stream)))
(stream-misc-case (operation :default nil)
(:set-file-position
(setf (fill-pointer buffer)
(case arg1
(:start 0)
(:end (array-total-size buffer))
(t (when (>= arg1 (array-total-size buffer))
(if (adjustable-array-p buffer)
(adjust-array buffer arg1)
(error "Cannot move FILE-POSITION beyond the end ~
of WITH-OUTPUT-TO-STRING stream ~
constructed with non-adjustable string.")))
arg1))))
(:get-file-position
(fill-pointer buffer))
(:charpos
(let ((current (fill-pointer buffer)))
(with-array-data ((string buffer) (start) (end current))
(declare (simple-string string))
(let ((found (position #\newline string :test #'char=
:start start :end end
:from-end t)))
(if found
(1- (- end found))
current)))))
(:element-type
(array-element-type
(fill-pointer-output-stream-string stream)))
(:element-mode 'character)))
(defstruct (case-frob-stream
(:include ansi-stream
(misc #'case-frob-misc))
(:constructor %make-case-frob-stream (target cout sout))
(:copier nil))
(target (missing-arg) :type stream :read-only t))
(declaim (freeze-type case-frob-stream))
(defun make-case-frob-stream (target kind)
"Return a stream that sends all output to the stream TARGET, but modifies
the case of letters, depending on KIND, which should be one of:
:UPCASE - convert to upper case.
:DOWNCASE - convert to lower case.
:CAPITALIZE - convert the first letter of words to upper case and the
rest of the word to lower case.
:CAPITALIZE-FIRST - convert the first letter of the first word to upper
case and everything else to lower case."
(declare (type stream target)
(type (member :upcase :downcase :capitalize :capitalize-first)
kind)
(values stream))
(if (case-frob-stream-p target)
target
(multiple-value-bind (cout sout)
(ecase kind
(:upcase
(values #'case-frob-upcase-out
#'case-frob-upcase-sout))
(:downcase
(values #'case-frob-downcase-out
#'case-frob-downcase-sout))
(:capitalize
(values #'case-frob-capitalize-out
#'case-frob-capitalize-sout))
(:capitalize-first
(values #'case-frob-capitalize-first-out
#'case-frob-capitalize-first-sout)))
(%make-case-frob-stream target cout sout))))
(defun case-frob-misc (stream op arg1)
(declare (type case-frob-stream stream))
(case op
(:close
(set-closed-flame stream))
(:element-mode 'character)
(t
(let ((target (case-frob-stream-target stream)))
(if (ansi-stream-p target)
(call-ansi-stream-misc target op arg1)
(stream-misc-dispatch target op arg1))))))
or Gray . Probably the easiest fix would be to define STREAM - WRITE - CHAR
(defun case-frob-upcase-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream))
(c (char-upcase char)))
(if (ansi-stream-p target)
(progn (funcall (ansi-stream-cout target) target c) char)
(stream-write-char target c))))
(defun case-frob-upcase-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(len (length str))
(end (or end len))
(string (if (and (zerop start) (= len end))
(string-upcase str)
(nstring-upcase (subseq str start end))))
(string-len (- end start)))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target string 0 string-len)
(stream-write-string target string 0 string-len))))
(defun case-frob-downcase-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream))
(c (char-downcase char)))
(if (ansi-stream-p target)
(progn (funcall (ansi-stream-cout target) target c) char)
(stream-write-char target c))))
(defun case-frob-downcase-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(len (length str))
(end (or end len))
(string (if (and (zerop start) (= len end))
(string-downcase str)
(nstring-downcase (subseq str start end))))
(string-len (- end start)))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target string 0 string-len)
(stream-write-string target string 0 string-len))))
(defun case-frob-capitalize-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream)))
(cond ((alphanumericp char)
(let ((char (char-upcase char)))
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-aux-out)
(setf (case-frob-stream-sout stream)
#'case-frob-capitalize-aux-sout))
(t
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))))
char)
(defun case-frob-capitalize-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(str (subseq str start end))
(len (length str))
(inside-word nil))
(dotimes (i len)
(let ((char (schar str i)))
(cond ((not (alphanumericp char))
(setf inside-word nil))
(inside-word
(setf (schar str i) (char-downcase char)))
(t
(setf inside-word t)
(setf (schar str i) (char-upcase char))))))
(when inside-word
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-aux-out)
(setf (case-frob-stream-sout stream) #'case-frob-capitalize-aux-sout))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target str 0 len)
(stream-write-string target str 0 len))))
(defun case-frob-capitalize-aux-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream)))
(cond ((alphanumericp char)
(let ((char (char-downcase char)))
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char))))
(t
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char))
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-out)
(setf (case-frob-stream-sout stream) #'case-frob-capitalize-sout))))
char)
(defun case-frob-capitalize-aux-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(str (subseq str start end))
(len (length str))
(inside-word t))
(dotimes (i len)
(let ((char (schar str i)))
(cond ((not (alphanumericp char))
(setf inside-word nil))
(inside-word
(setf (schar str i) (char-downcase char)))
(t
(setf inside-word t)
(setf (schar str i) (char-upcase char))))))
(unless inside-word
(setf (case-frob-stream-cout stream) #'case-frob-capitalize-out)
(setf (case-frob-stream-sout stream) #'case-frob-capitalize-sout))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target str 0 len)
(stream-write-string target str 0 len))))
(defun case-frob-capitalize-first-out (stream char)
(declare (type case-frob-stream stream)
(type character char))
(let ((target (case-frob-stream-target stream)))
(cond ((alphanumericp char)
(let ((char (char-upcase char)))
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))
(setf (case-frob-stream-cout stream) #'case-frob-downcase-out)
(setf (case-frob-stream-sout stream) #'case-frob-downcase-sout))
(t
(if (ansi-stream-p target)
(funcall (ansi-stream-cout target) target char)
(stream-write-char target char)))))
char)
(defun case-frob-capitalize-first-sout (stream str start end)
(declare (type case-frob-stream stream)
(type simple-string str)
(type index start)
(type (or index null) end))
(let* ((target (case-frob-stream-target stream))
(str (subseq str start end))
(len (length str)))
(dotimes (i len)
(let ((char (schar str i)))
(when (alphanumericp char)
(setf (schar str i) (char-upcase char))
(do ((i (1+ i) (1+ i)))
((= i len))
(setf (schar str i) (char-downcase (schar str i))))
(setf (case-frob-stream-cout stream) #'case-frob-downcase-out)
(setf (case-frob-stream-sout stream) #'case-frob-downcase-sout)
(return))))
(if (ansi-stream-p target)
(funcall (ansi-stream-sout target) target str 0 len)
(stream-write-string target str 0 len))))
Shared { READ , support functions
(declaim (inline stream-compute-io-function
compatible-vector-and-stream-element-types-p))
(defun stream-compute-io-function (stream
stream-element-mode sequence-element-type
character-io binary-io bivalent-io)
(ecase stream-element-mode
(character
character-io)
((unsigned-byte signed-byte)
binary-io)
(:bivalent
(cond
((member sequence-element-type '(nil t))
bivalent-io)
((eq sequence-element-type 'character)
character-io)
((or (equal sequence-element-type '(unsigned-byte 8))
(equal sequence-element-type '(signed-byte 8)))
binary-io)
((subtypep sequence-element-type 'character)
character-io)
((subtypep sequence-element-type 'integer)
binary-io)
(t
(error "~@<Cannot select IO functions to use for bivalent ~
stream ~S and a sequence with element-type ~S.~@:>"
stream sequence-element-type))))))
(defun compatible-vector-and-stream-element-types-p (vector stream)
(declare (type vector vector)
(type ansi-stream stream))
(or (and (typep vector '(simple-array (unsigned-byte 8) (*)))
(memq (stream-element-mode stream) '(unsigned-byte :bivalent))
t)
(and (typep vector '(simple-array (signed-byte 8) (*)))
(eq (stream-element-mode stream) 'signed-byte))))
(defun read-sequence (seq stream &key (start 0) end)
"Destructively modify SEQ by reading elements from STREAM.
That part of SEQ bounded by START and END is destructively modified by
copying successive elements into it from STREAM. If the end of file
for STREAM is reached before copying all elements of the subsequence,
then the extra elements near the end of sequence are not updated, and
the index of the next element is returned."
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end end)
(values index))
(stream-api-dispatch (stream)
:native (ansi-stream-read-sequence seq stream start end)
:gray (stream-read-sequence stream seq start end)))
(declaim (maybe-inline read-sequence/read-function))
(defun read-sequence/read-function (seq stream start %end
stream-element-mode
character-read-function binary-read-function)
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end %end)
(type stream-element-mode stream-element-mode)
(type function character-read-function binary-read-function)
(values index &optional))
(let ((end (or %end (length seq))))
(declare (type index end))
(labels ((compute-read-function (sequence-element-type)
(stream-compute-io-function
stream
stream-element-mode sequence-element-type
character-read-function binary-read-function
character-read-function))
(read-list (read-function)
(do ((rem (nthcdr start seq) (rest rem))
(i start (1+ i)))
((or (endp rem) (>= i end)) i)
(declare (type list rem)
(type index i))
(let ((el (funcall read-function stream nil :eof nil)))
(when (eq el :eof)
(return i))
(setf (first rem) el))))
(read-vector/fast (data offset-start)
(let* ((numbytes (- end start))
(bytes-read (read-n-bytes
stream data offset-start numbytes nil)))
(if (< bytes-read numbytes)
(+ start bytes-read)
end)))
(read-vector (read-function data offset-start offset-end)
(do ((i offset-start (1+ i)))
((>= i offset-end) end)
(declare (type index i))
(let ((el (funcall read-function stream nil :eof nil)))
(when (eq el :eof)
(return (+ start (- i offset-start))))
(setf (aref data i) el))))
(read-generic-sequence (read-function)
(declare (ignore read-function))
(error "~@<~A does not yet support generic sequences.~@:>"
'read-sequence)))
(declare (dynamic-extent #'compute-read-function
#'read-list #'read-vector/fast #'read-vector
#'read-generic-sequence))
(cond
((typep seq 'list)
(read-list (compute-read-function nil)))
((and (ansi-stream-p stream)
(ansi-stream-cin-buffer stream)
(typep seq 'simple-string))
(ansi-stream-read-string-from-frc-buffer seq stream start %end))
((typep seq 'vector)
(with-array-data ((data seq) (offset-start start) (offset-end end)
:check-fill-pointer t)
(if (and (ansi-stream-p stream)
(compatible-vector-and-stream-element-types-p data stream))
(read-vector/fast data offset-start)
(read-vector (compute-read-function (array-element-type data))
data offset-start offset-end))))
(t
(read-generic-sequence (compute-read-function nil)))))))
(defun ansi-stream-read-sequence (seq stream start %end)
(declare (type sequence seq)
(type ansi-stream stream)
(type index start)
(type sequence-end %end)
(values index &optional))
(locally (declare (inline read-sequence/read-function))
(read-sequence/read-function
seq stream start %end (stream-element-mode stream)
#'ansi-stream-read-char #'ansi-stream-read-byte)))
(defun ansi-stream-read-string-from-frc-buffer (seq stream start %end)
(declare (type simple-string seq)
(type ansi-stream stream)
(type index start)
(type (or null index) %end))
(let ((needed (- (or %end (length seq))
start))
(read 0))
(prepare-for-fast-read-char stream
(declare (ignore %frc-method%))
(unless %frc-buffer%
(return-from ansi-stream-read-string-from-frc-buffer nil))
(labels ((refill-buffer ()
(prog1 (fast-read-char-refill stream nil)
(setf %frc-index% (ansi-stream-in-index %frc-stream%))))
(add-chunk ()
(let* ((end (length %frc-buffer%))
(len (min (- end %frc-index%)
(- needed read))))
(declare (type index end len read needed))
(string-dispatch (simple-base-string simple-character-string)
seq
(replace seq %frc-buffer%
:start1 (+ start read)
:end1 (+ start read len)
:start2 %frc-index%
:end2 (+ %frc-index% len)))
(incf read len)
(incf %frc-index% len)
(when (or (eql needed read) (not (refill-buffer)))
(done-with-fast-read-char)
(return-from ansi-stream-read-string-from-frc-buffer
(+ start read))))))
(declare (inline refill-buffer))
(when (and (= %frc-index% +ansi-stream-in-buffer-length+)
(not (refill-buffer)))
EOF had been reached before we read anything
(done-with-fast-read-char)
(return-from ansi-stream-read-string-from-frc-buffer start))
(loop (add-chunk))))))
(defun write-sequence (seq stream &key (start 0) (end nil))
"Write the elements of SEQ bounded by START and END to STREAM."
(let* ((length (length seq))
(end (or end length)))
(unless (<= start end length)
(sequence-bounding-indices-bad-error seq start end)))
(write-seq-impl seq stream start end))
WRITE - SEQUENCE / WRITE - FUNCTION and SB - GRAY : STREAM - WRITE - STRING .
(defmacro write-sequence/vector ((seq type) stream start end write-function)
(once-only ((seq seq) (stream stream) (start start) (end end)
(write-function write-function))
`(locally
(declare (type ,type ,seq)
(type index ,start ,end)
(type function ,write-function))
(do ((i ,start (1+ i)))
((>= i ,end))
(declare (type index i))
(funcall ,write-function ,stream (aref ,seq i))))))
(declaim (maybe-inline write-sequence/write-function))
(defun write-sequence/write-function (seq stream start %end
stream-element-mode
character-write-function
binary-write-function)
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end %end)
(type stream-element-mode stream-element-mode)
(type function character-write-function binary-write-function))
(let ((end (or %end (length seq))))
(declare (type index end))
(labels ((compute-write-function (sequence-element-type)
(stream-compute-io-function
stream
stream-element-mode sequence-element-type
character-write-function binary-write-function
#'write-element/bivalent))
(write-element/bivalent (stream object)
(if (characterp object)
(funcall character-write-function stream object)
(funcall binary-write-function stream object)))
(write-list (write-function)
(do ((rem (nthcdr start seq) (rest rem))
(i start (1+ i)))
((or (endp rem) (>= i end)))
(declare (type list rem)
(type index i))
(funcall write-function stream (first rem))))
(write-vector (data start end write-function)
(write-sequence/vector
(data (simple-array * (*))) stream start end write-function))
(write-generic-sequence (write-function)
(declare (ignore write-function))
(error "~@<~A does not yet support generic sequences.~@:>"
'write-sequence)))
(declare (dynamic-extent #'compute-write-function
#'write-element/bivalent #'write-list
#'write-vector #'write-generic-sequence))
(etypecase seq
(list
(write-list (compute-write-function nil)))
(string
(if (ansi-stream-p stream)
(with-array-data ((data seq) (start start) (end end)
:check-fill-pointer t)
(funcall (ansi-stream-sout stream) stream data start end))
(stream-write-string stream seq start end)))
(vector
(with-array-data ((data seq) (offset-start start) (offset-end end)
:check-fill-pointer t)
(cond ((not (and (fd-stream-p stream)
(compatible-vector-and-stream-element-types-p data stream)))
(write-vector data offset-start offset-end
(compute-write-function
(array-element-type seq))))
((eq (fd-stream-buffering stream) :none)
(write-or-buffer-output stream data offset-start offset-end))
(t
(buffer-output stream data offset-start offset-end)))))
(sequence
(write-generic-sequence (compute-write-function nil)))))))
(defun write-seq-impl (seq stream start %end)
(declare (type sequence seq)
(type stream stream)
(type index start)
(type sequence-end %end)
(inline write-sequence/write-function))
(stream-api-dispatch (stream)
:simple (s-%write-sequence stream seq start (or %end (length seq)))
:gray (stream-write-sequence stream seq start %end)
:native
(typecase stream
Do n't merely extract one layer of composite stream , because a synonym stream
may redirect to a broadcast stream which wraps a two - way - stream etc etc .
(synonym-stream
(write-seq-impl seq (symbol-value (synonym-stream-symbol stream)) start %end))
(broadcast-stream
(dolist (s (broadcast-stream-streams stream) seq)
(write-seq-impl seq s start %end)))
(write-seq-impl seq (two-way-stream-output-stream stream) start %end))
(t
(write-sequence/write-function
seq stream start %end (stream-element-mode stream)
(ansi-stream-cout stream) (ansi-stream-bout stream)))))
seq)
like FILE - POSITION , only using : FILE - LENGTH
(defun file-length (stream)
BROADCAST - STREAM entry .
(stream-api-dispatch (stream)
:simple (s-%file-length stream)
:gray (error "~S is not defined for ~S" 'file-length stream)
:native (progn
(unless (typep stream 'broadcast-stream)
(stream-file-stream-or-lose stream))
(call-ansi-stream-misc stream :file-length))))
(defun stream-output-stream (stream)
(typecase stream
(fd-stream
stream)
(synonym-stream
(stream-output-stream (resolve-synonym-stream stream)))
(two-way-stream
(stream-output-stream
(two-way-stream-output-stream stream)))
(t
stream)))
(defstruct (stub-stream
(:include ansi-stream)
(:constructor %make-stub-stream (direction string)))
(direction nil :read-only t)
(defun make-stub-stream (underlying-stream)
(multiple-value-bind (direction string)
(etypecase underlying-stream
(string-input-stream
(values :input (string-input-stream-string underlying-stream)))
(string-output-stream
(values :output nil))
(fill-pointer-output-stream
(values :output (fill-pointer-output-stream-string underlying-stream))))
(%make-stub-stream direction string)))
(defmethod print-object ((stub stub-stream) stream)
(print-unreadable-object (stub stream)
(let ((direction (stub-stream-direction stub))
(string (stub-stream-string stub)))
(format stream "dynamic-extent ~A (unavailable)~@[ ~A ~S~]"
(if (eq direction :input) 'string-input-stream 'string-output-stream)
(if string (if (eq direction :input) "from" "to"))
(if (> (length string) 10)
(concatenate 'string (subseq string 0 8) "...")
string)))))
(defvar *tty*)
(defvar *stdin*)
the stream connected to the standard output ( file descriptor 1 )
(defvar *stdout*)
the stream connected to the standard error output ( file descriptor 2 )
(defvar *stderr*)
This is called when the cold load is first started up , and may also
(defun stream-cold-init-or-reset ()
(stream-reinit)
(setf *terminal-io* (make-synonym-stream '*tty*))
(setf *standard-output* (make-synonym-stream '*stdout*))
(setf *standard-input* (make-synonym-stream '*stdin*))
(setf *error-output* (make-synonym-stream '*stderr*))
(setf *query-io* (make-synonym-stream '*terminal-io*))
(setf *debug-io* *query-io*)
(setf *trace-output* *standard-output*)
(values))
(defun stream-deinit ()
(setq *tty* nil *stdin* nil *stdout* nil *stderr* nil)
This uses the internal % MAKUNBOUND because the CL : function would
(%makunbound '*available-buffers*))
(defvar *streams-closed-by-slad*)
(defun restore-fd-streams ()
(loop for (stream in bin n-bin cout bout sout misc) in *streams-closed-by-slad*
do
(setf (ansi-stream-in stream) in)
(setf (ansi-stream-bin stream) bin)
(setf (ansi-stream-n-bin stream) n-bin)
(setf (ansi-stream-cout stream) cout)
(setf (ansi-stream-bout stream) bout)
(setf (ansi-stream-sout stream) sout)
(setf (ansi-stream-misc stream) misc)))
(defun stdstream-external-format (fd)
#-win32 (declare (ignore fd))
(let* ((keyword (cond #+(and win32 sb-unicode)
((sb-win32::console-handle-p fd)
:ucs-2)
(t
(default-external-format))))
(ef (get-external-format keyword))
(replacement (ef-default-replacement-character ef)))
`(,keyword :replacement ,replacement)))
(defun stream-reinit (&optional init-buffers-p)
(when init-buffers-p
(aver (not (%boundp '*available-buffers*)))
(setf *available-buffers* nil))
(%with-output-to-string (*error-output*)
(multiple-value-bind (in out err)
#-win32 (values 0 1 2)
#+win32 (sb-win32::get-std-handles)
(labels (#+win32
(nul-stream (name inputp outputp)
(let ((nul-handle
(cond
((and inputp outputp)
(sb-win32:unixlike-open "NUL" sb-unix:o_rdwr))
(inputp
(sb-win32:unixlike-open "NUL" sb-unix:o_rdonly))
(outputp
(sb-win32:unixlike-open "NUL" sb-unix:o_wronly))
(t
nil))))
(make-fd-stream
nul-handle
:name name
:input inputp
:output outputp
:buffering :line
:element-type :default
:serve-events inputp
:auto-close t
:external-format (stdstream-external-format nul-handle))))
(stdio-stream (handle name inputp outputp)
(cond
#+win32
((null handle)
If no actual handle was present , create a stream to NUL
(nul-stream name inputp outputp))
(t
(make-fd-stream
handle
:name name
:input inputp
:output outputp
:buffering :line
:element-type :default
:serve-events inputp
:external-format (stdstream-external-format handle))))))
(setf *stdin* (stdio-stream in "standard input" t nil)
*stdout* (stdio-stream out "standard output" nil t)
*stderr* (stdio-stream err "standard error" nil t))))
#+win32
(setf *tty* (make-two-way-stream *stdin* *stdout*))
#-win32
(let ((tty (sb-unix:unix-open "/dev/tty" sb-unix:o_rdwr #o666)))
(setf *tty*
(if tty
(make-fd-stream tty :name "the terminal"
:input t :output t :buffering :line
:external-format (stdstream-external-format tty)
:serve-events t
:auto-close t)
(make-two-way-stream *stdin* *stdout*))))
(princ (get-output-stream-string *error-output*) *stderr*))
(values))
|
2053c51bd4d9c2e77f3f4e685502df5590cb39a88e0180e5cb9142e97504c3c7 | HunterYIboHu/htdp2-solution | ex232-eliminate-quasiquote.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex232-eliminate-quasiquote) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; constants
(define title "ratings")
;; eliminate the quasiquote and unquote with list.
(check-expect `(1 "a" 2 #false 3 "c")
(list 1 "a" 2 #false 3 "c"))
(check-expect `(("alan" ,(* 2 500))
("barb" 2000)
(,(string-append "carl" " , the great") 1500)
("dawn" 2300))
(list (list "alan" 1000)
(list "barb" 2000)
(list "carl , the great" 1500)
(list "dawn" 2300)))
(check-expect `(html
(head
(title ,title))
(body
(h1 ,title)
(p "A second web page")))
(list 'html
(list 'head
(list 'title title))
(list 'body
(list 'h1 title)
(list 'p "A second web page"))))
;; Also written in nested list.
(check-expect `(1 "a" 2 #false 3 "c")
'(1 "a" 2 #false 3 "c"))
(check-expect `(("alan" ,(* 2 500))
("barb" 2000)
(,(string-append "carl" " , the great") 1500)
("dawn" 2300))
'(("alan" 1000)
("barb" 2000)
("carl , the great" 1500)
("dawn" 2300)))
(check-expect `(html
(head
(title ,title))
(body
(h1 ,title)
(p "A second web page")))
'(html
(head
(title "ratings"))
(body
(h1 "ratings")
(p "A second web page")))) | null | https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/intermezzo-quote-unquote/ex232-eliminate-quasiquote.rkt | racket | about the language level of this file in a form that our tools can easily process.
constants
eliminate the quasiquote and unquote with list.
Also written in nested list. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex232-eliminate-quasiquote) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define title "ratings")
(check-expect `(1 "a" 2 #false 3 "c")
(list 1 "a" 2 #false 3 "c"))
(check-expect `(("alan" ,(* 2 500))
("barb" 2000)
(,(string-append "carl" " , the great") 1500)
("dawn" 2300))
(list (list "alan" 1000)
(list "barb" 2000)
(list "carl , the great" 1500)
(list "dawn" 2300)))
(check-expect `(html
(head
(title ,title))
(body
(h1 ,title)
(p "A second web page")))
(list 'html
(list 'head
(list 'title title))
(list 'body
(list 'h1 title)
(list 'p "A second web page"))))
(check-expect `(1 "a" 2 #false 3 "c")
'(1 "a" 2 #false 3 "c"))
(check-expect `(("alan" ,(* 2 500))
("barb" 2000)
(,(string-append "carl" " , the great") 1500)
("dawn" 2300))
'(("alan" 1000)
("barb" 2000)
("carl , the great" 1500)
("dawn" 2300)))
(check-expect `(html
(head
(title ,title))
(body
(h1 ,title)
(p "A second web page")))
'(html
(head
(title "ratings"))
(body
(h1 "ratings")
(p "A second web page")))) |
5fff07926b8456e61c49c7b5fb0ce7f720d22efe6301ef452fbbcca498fc54dc | bcc32/advent-of-code | game.ml | open! Core
open! Async
open! Import
let re =
Re.(
compile
(seq
[ group (rep1 digit)
; str " players; last marble is worth "
; group (rep1 digit)
; str " points"
]))
;;
type t =
{ players : int
; last_marble : int
}
let get () =
let%bind str = Reader.file_contents "input" in
let g = Re.exec re str in
let players = Re.Group.get g 1 |> Int.of_string in
let last_marble = Re.Group.get g 2 |> Int.of_string in
return { players; last_marble }
;;
let simulate { players; last_marble } =
let scores = Array.create 0 ~len:players in
let current_marble = ref (Circle.create 0) in
let current_player = ref 0 in
let add_score n = scores.(!current_player) <- scores.(!current_player) + n in
for marble = 1 to last_marble do
if marble % 23 <> 0
then current_marble := Circle.insert_after !current_marble.next marble
else (
add_score marble;
let seven_left = !current_marble.prev.prev.prev.prev.prev.prev.prev in
add_score seven_left.value;
current_marble := Circle.remove_and_get_next seven_left);
current_player := (!current_player + 1) % players
done;
scores
;;
| null | https://raw.githubusercontent.com/bcc32/advent-of-code/653c0f130e2fb2f599d4e76804e02af54c9bb19f/2018/09/game.ml | ocaml | open! Core
open! Async
open! Import
let re =
Re.(
compile
(seq
[ group (rep1 digit)
; str " players; last marble is worth "
; group (rep1 digit)
; str " points"
]))
;;
type t =
{ players : int
; last_marble : int
}
let get () =
let%bind str = Reader.file_contents "input" in
let g = Re.exec re str in
let players = Re.Group.get g 1 |> Int.of_string in
let last_marble = Re.Group.get g 2 |> Int.of_string in
return { players; last_marble }
;;
let simulate { players; last_marble } =
let scores = Array.create 0 ~len:players in
let current_marble = ref (Circle.create 0) in
let current_player = ref 0 in
let add_score n = scores.(!current_player) <- scores.(!current_player) + n in
for marble = 1 to last_marble do
if marble % 23 <> 0
then current_marble := Circle.insert_after !current_marble.next marble
else (
add_score marble;
let seven_left = !current_marble.prev.prev.prev.prev.prev.prev.prev in
add_score seven_left.value;
current_marble := Circle.remove_and_get_next seven_left);
current_player := (!current_player + 1) % players
done;
scores
;;
|
|
c1c5825f5207538c21b36493044c03c4d1dd0fc10ad7d07cc7bcf9a415e45573 | Frama-C/Frama-C-snapshot | obfuscator_register.ml | (**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2019
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 ) .
(* *)
(**************************************************************************)
let disable_other_analyzers () =
if Options.Run.get () then
let selection =
State_selection.Static.diff
(Parameter_state.get_selection ())
(State_selection.Static.union
(State_selection.of_list
(Kernel.CodeOutput.self :: Options.states))
(* The command-line options that govern the creation of the AST
must be preserved *)
(State_selection.Static.with_codependencies Ast.self))
in
Project.clear ~selection ()
let () = Cmdline.run_after_configuring_stage disable_other_analyzers
let force_run () =
if not (Dictionary.is_computed ()) then begin
let old_printer = Printer.current_printer () in
Obfuscate.obfuscate ();
if Options.Dictionary.is_default () then Log.print_delayed Dictionary.pretty
else begin
let file = Options.Dictionary.get () in
try
let cout = open_out file in
let fmt = Format.formatter_of_out_channel cout in
Dictionary.pretty fmt
with Sys_error _ as exn ->
Options.error
"@[cannot generate the dictionary into file `%s':@ %s@]"
file
(Printexc.to_string exn)
end;
File.pretty_ast ();
Printer.set_printer old_printer
end
let force_run =
Dynamic.register
~plugin:"Obfuscator"
"force_run"
(Datatype.func Datatype.unit Datatype.unit)
~journalize:true
force_run
let run () =
if Options.Run.get () then begin
force_run ();
stop Frama - C as specified by the -help message
and by the discussion in Gitlab issue # 491
and by the discussion in Gitlab issue #491 *)
end
let () = Db.Main.extend run
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/obfuscator/obfuscator_register.ml | 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.
************************************************************************
The command-line options that govern the creation of the AST
must be preserved
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of Frama - C.
Copyright ( C ) 2007 - 2019
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 ) .
let disable_other_analyzers () =
if Options.Run.get () then
let selection =
State_selection.Static.diff
(Parameter_state.get_selection ())
(State_selection.Static.union
(State_selection.of_list
(Kernel.CodeOutput.self :: Options.states))
(State_selection.Static.with_codependencies Ast.self))
in
Project.clear ~selection ()
let () = Cmdline.run_after_configuring_stage disable_other_analyzers
let force_run () =
if not (Dictionary.is_computed ()) then begin
let old_printer = Printer.current_printer () in
Obfuscate.obfuscate ();
if Options.Dictionary.is_default () then Log.print_delayed Dictionary.pretty
else begin
let file = Options.Dictionary.get () in
try
let cout = open_out file in
let fmt = Format.formatter_of_out_channel cout in
Dictionary.pretty fmt
with Sys_error _ as exn ->
Options.error
"@[cannot generate the dictionary into file `%s':@ %s@]"
file
(Printexc.to_string exn)
end;
File.pretty_ast ();
Printer.set_printer old_printer
end
let force_run =
Dynamic.register
~plugin:"Obfuscator"
"force_run"
(Datatype.func Datatype.unit Datatype.unit)
~journalize:true
force_run
let run () =
if Options.Run.get () then begin
force_run ();
stop Frama - C as specified by the -help message
and by the discussion in Gitlab issue # 491
and by the discussion in Gitlab issue #491 *)
end
let () = Db.Main.extend run
|
9cc5810abab6a80e127ab988877417256b32fc6f8248fd3bbc415d4e28995e40 | AndrewMagerman/wizard-book-study | grader.rkt | #lang racket
(require (planet dyoo/simply-scheme))
(provide (all-defined-out))
(require rackunit)
(require rackunit/text-ui)
(require "chatterbot.rkt")
(define file-tests
(test-suite
"All tests for chatterbot"
(test-case
"babybot"
(check-equal?
(babybot '(I am babybot))
'(I am babybot)
"test 1")
;; Add more tests here
)
(test-case
"stupidbot-creator"
(check-equal?
((stupidbot-creator '(I am Groot)) '(who are you))
'(I am Groot)
"test 1")
;; Add more tests here
)
(test-case
"matcherbot-creator"
(check-equal?
((matcherbot-creator '(my name is)) '(my name is starlord))
'(starlord)
"test 1")
(check-equal?
((matcherbot-creator '(my name is)) '(the names starlord))
#f
"test 2")
;; Add more tests here
)
(test-case
"substitutebot-creator"
(check-equal?
((substitutebot-creator '(bad ugly stupid hate sad mad disgusting) '(good pretty smart lov happy calm delicious)) '(bad ugly stupid))
'(good pretty smart)
"test 1")
;; Add more tests here
)
(test-case
"switcherbot"
(check-equal?
(switcherbot '(you are smart but I am smarter than you))
'(I am smart but you are smarter than me)
"test 1")
;; Add more tests here
)
(test-case
"inquisitivebot"
(check-equal?
(inquisitivebot '(I am happy))
'(you are happy ?)
"test 1")
(check-equal?
(inquisitivebot '(I can see you))
'(you can see me ?)
"test 2")
;; Add more tests here
)
(test-case
"eliza"
(check-equal?
(eliza '(hello))
'(hello there!)
"test 1")
(check-equal?
(eliza '(I am tired of being bullied at school))
'(why are you tired of being bullied at school ?)
"test 2")
(check-equal?
(eliza '(how are you today ?))
'(I can not answer your question.)
"test 3")
(check-equal?
(eliza '())
'(how can I help you ?)
"test 4")
;; Add more tests here
)
(test-case
"reactorbot-creator"
(check-equal?
((reactorbot-creator (stupidbot-creator '(I am Groot)) '(no Groot youll die why are you doing this) '(WE are Groot)) '(whats up Groot))
'(I am Groot)
"test 1")
(check-equal?
((reactorbot-creator (stupidbot-creator '(I am Groot)) '(no Groot youll die why are you doing this) '(WE are Groot)) '(no Groot youll die why are you doing this))
'(WE are Groot)
"test 2")
;; Add more tests here
)
(test-case
"replacerbot-creator"
(check-equal?
((replacerbot-creator (lambda (sent) (if (member? '? sent) '(I dont know) '(thats nice))) '(I am) '(hi) '(im dadbot)) '(youre pretty dumb))
'(thats nice)
"test 1")
(check-equal?
((replacerbot-creator (lambda (sent) (if (member? '? sent) '(I dont know) '(thats nice))) '(I am) '(hi) '(im dadbot)) '(I am hungry))
'(hi hungry im dadbot)
"test 2")
;; Add more tests here
)
(test-case
"exaggerate"
(check-equal?
((exaggerate babybot 1) '(this soup is hot and tasty))
'(this soup is very hot and very tasty)
"test 1")
;; Add more tests here
)
))
(run-tests file-tests)
| null | https://raw.githubusercontent.com/AndrewMagerman/wizard-book-study/779854631f17164cbddecf3fde102504df1a83f0/reference/cs61as_library/chatterbot/grader.rkt | racket | Add more tests here
Add more tests here
Add more tests here
Add more tests here
Add more tests here
Add more tests here
Add more tests here
Add more tests here
Add more tests here
Add more tests here | #lang racket
(require (planet dyoo/simply-scheme))
(provide (all-defined-out))
(require rackunit)
(require rackunit/text-ui)
(require "chatterbot.rkt")
(define file-tests
(test-suite
"All tests for chatterbot"
(test-case
"babybot"
(check-equal?
(babybot '(I am babybot))
'(I am babybot)
"test 1")
)
(test-case
"stupidbot-creator"
(check-equal?
((stupidbot-creator '(I am Groot)) '(who are you))
'(I am Groot)
"test 1")
)
(test-case
"matcherbot-creator"
(check-equal?
((matcherbot-creator '(my name is)) '(my name is starlord))
'(starlord)
"test 1")
(check-equal?
((matcherbot-creator '(my name is)) '(the names starlord))
#f
"test 2")
)
(test-case
"substitutebot-creator"
(check-equal?
((substitutebot-creator '(bad ugly stupid hate sad mad disgusting) '(good pretty smart lov happy calm delicious)) '(bad ugly stupid))
'(good pretty smart)
"test 1")
)
(test-case
"switcherbot"
(check-equal?
(switcherbot '(you are smart but I am smarter than you))
'(I am smart but you are smarter than me)
"test 1")
)
(test-case
"inquisitivebot"
(check-equal?
(inquisitivebot '(I am happy))
'(you are happy ?)
"test 1")
(check-equal?
(inquisitivebot '(I can see you))
'(you can see me ?)
"test 2")
)
(test-case
"eliza"
(check-equal?
(eliza '(hello))
'(hello there!)
"test 1")
(check-equal?
(eliza '(I am tired of being bullied at school))
'(why are you tired of being bullied at school ?)
"test 2")
(check-equal?
(eliza '(how are you today ?))
'(I can not answer your question.)
"test 3")
(check-equal?
(eliza '())
'(how can I help you ?)
"test 4")
)
(test-case
"reactorbot-creator"
(check-equal?
((reactorbot-creator (stupidbot-creator '(I am Groot)) '(no Groot youll die why are you doing this) '(WE are Groot)) '(whats up Groot))
'(I am Groot)
"test 1")
(check-equal?
((reactorbot-creator (stupidbot-creator '(I am Groot)) '(no Groot youll die why are you doing this) '(WE are Groot)) '(no Groot youll die why are you doing this))
'(WE are Groot)
"test 2")
)
(test-case
"replacerbot-creator"
(check-equal?
((replacerbot-creator (lambda (sent) (if (member? '? sent) '(I dont know) '(thats nice))) '(I am) '(hi) '(im dadbot)) '(youre pretty dumb))
'(thats nice)
"test 1")
(check-equal?
((replacerbot-creator (lambda (sent) (if (member? '? sent) '(I dont know) '(thats nice))) '(I am) '(hi) '(im dadbot)) '(I am hungry))
'(hi hungry im dadbot)
"test 2")
)
(test-case
"exaggerate"
(check-equal?
((exaggerate babybot 1) '(this soup is hot and tasty))
'(this soup is very hot and very tasty)
"test 1")
)
))
(run-tests file-tests)
|
929485a37c6a00c9d133a995e1f63cc2db24f40994afd0b824bcdc013ee47ff5 | danmey/ocaml-gui | blocks.ml | open Widget
open Draw
open Window
open GL
open Glu
type stickiness = TopBottom | LeftRight
let expand_rect_left dx rect constr =
let real_dx = ( dx / constr) * constr in
{ rect with
Rect.x = rect.Rect.x + real_dx;
Rect.w = rect.Rect.w - real_dx }
let block_cmp l r =
let y = r.Rect.y - l.Rect.y in
if y <> 0 then y
else
r.Rect.x - l.Rect.x
type 'a property_value = { min : 'a; max : 'a; default : 'a; step : float }
type property_type =
| Float of float property_value
| Int of int property_value
type property = string * property_type
class properties props change = object (self : 'self)
inherit frame (Layout.vertical)
initializer
List.iter
(function
| (name, Float { min; max; default; step }) ->
self # add (float_slider ~value:default ~min ~max ~step ~change name)
| (name, Int { min; max; default; step }) ->
self # add (int_slider ~value:default ~min ~max ~step ~change name))
props
(* method delete_properties = *)
(* List.iter (fun (_,widget) -> Window.remove self # window widget # window) widgets; *)
(* widgets <- [] *)
method get key =
let _, w = List.find (fun (_,w) -> w # key = key) self # widgets in
w
end
let properties
?change:(change=(fun _ -> ()))
definition =
new properties definition change
(* end and block name = object ( self : 'self ) *)
class block name click selected = object ( self : 'self )
inherit canvas as canvas
inherit draggable as super
val left_border = new draggable_constrained (HorizontalWith 10)
val right_border = new draggable_constrained (HorizontalWith 10)
val name = name
val mutable focus = false
initializer
canvas#add left_border;
canvas#add right_border
method drag _ (x,y) (dx,dy) =
let grid x = (x + 5) / 10 * 10 in
window.pos.Rect.x <- grid x;
window.pos.Rect.y <- grid y
method name = name
(* method paint state = *)
let caption = Printf.sprintf " % s : % s " name self#value in
caption 0 state
method invalidate rect =
super#invalidate rect;
left_border#invalidate (Rect.rect (0,0) (10, rect.Rect.h));
right_border#invalidate (Rect.rect (rect.Rect.w-10,0) (10, rect.Rect.h))
method dragged widget (dx, dy) =
let grid x = (x + 5) / 10 * 10 in
let rect = self#window.pos in
if widget == left_border then
self # invalidate (expand_rect_left dx rect 10)
else if widget == right_border then
self # invalidate
(Rect.rect
(rect.Rect.x, rect.Rect.y)
(grid (rect.Rect.w + dx), rect.Rect.h))
method mouse_down b p =
let res = (if not (click b self) then
super # mouse_down b p
else
true) in
begin
match b with
| Event.Right ->
begin
state <- Selected;
selected (self :> draggable);
end
| _ -> ()
end;
res
method mouse_up b p =
match b with
| Event.Right ->
begin
match state with
| Selected -> true
| _ -> super # mouse_down b p
end
| _ -> super # mouse_down b p
method key = name
method focus is = focus <- is
method paint state = caption_painter2 self # name state
end
let block
?click:(click = fun _ _ -> false)
?select:(select = fun _ -> ()) name =
new block name click select
open BatFloat
class texture_preview = object ( self : 'self )
inherit graphics as super
val mutable texid = None
initializer
window.Window.painter <- self#draw;
method draw rect =
BatOption.may (fun texid ->
glBindTexture ~target:BindTex.GL_TEXTURE_2D ~texture:texid;
glTexParameter ~target:TexParam.GL_TEXTURE_2D ~param:(TexParam.GL_TEXTURE_MAG_FILTER Mag.GL_NEAREST);
glTexParameter ~target:TexParam.GL_TEXTURE_2D ~param:(TexParam.GL_TEXTURE_MIN_FILTER Min.GL_NEAREST);
glEnable GL_TEXTURE_2D;
glColor3 ~r:1. ~g:1. ~b:1.;
let x, y, w, h = Rect.coordsf rect in
glBegin GL_QUADS;
glTexCoord2 ~s:0.0 ~t:0.0;
glVertex3 ~x ~y ~z:0.;
glTexCoord2 ~s:1.0 ~t:0.0;
glVertex3 ~x:(x + w) ~y ~z:0.;
glTexCoord2 ~s:1.0 ~t:1.0;
glVertex3 ~x:(x + w) ~y:(y + h) ~z:0.;
glTexCoord2 ~s:0.0 ~t:1.0;
glVertex3 ~x ~y:(y + h) ~z:0.;
glEnd ();
glDisable GL_TEXTURE_2D) texid; ()
method set_image id = texid <- Some id
end
let property_pane = new frame Layout.fill
let properties_definition =
["perlin",[
"persistence", Float { min = 0.; max = 3.; default = 0.25; step = 0.01 };
"octaves", Int { min=1; max=8; default=1; step = 0.2 };
"seed", Int { min=0; max=9; default=1; step=0.2};
];
"add",[
];
"light", [
"lx", Float { min = 0.; max = 1.; default = 0.; step = 0.01 };
"ly", Float { min = 0.; max = 1.; default = 1.; step = 0.01 };
"ldx", Float { min = 0.; max = 1.; default = 1.; step = 1./.256. };
"ldy", Float { min = 0.; max = 1.; default = 1.; step = 1./.256. };
];
"glow", [
"x0", Float { min = -1.; max = 1.; default = 0.5; step = 0.01 };
"y0", Float { min = -1.; max = 1.; default = 0.5; step = 0.01 };
"atten", Float { min = -100.; max = 100.; default = 1.; step = 0.1 };
"xr", Float { min = 0.; max = 5.; default = 0.5; step = 0.01 };
"yr", Float { min = 0.; max = 5.; default = 0.5; step = 0.01 };
];
"phi",[
"scale", Float { min = -10.; max = 10.; default = 1.; step = 0.01 };
"base", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };];
"add", [];
"flat",[
"fx", Float { min = 0.; max = 1.; default = 0.25; step = 0.01 };
"fy", Float { min = 0.; max = 1.; default = 0.25; step = 0.01 };
"fw", Float { min = 0.; max = 1.; default = 0.5; step = 0.01 };
"fh", Float { min = 0.; max = 1.; default = 0.5; step = 0.01 };
"fg", Float { min = 0.; max = 1.; default = 0.25; step = 0.01 };
"bg", Float { min = 0.; max = 1.; default = 0.75; step = 0.01 };];
"distort",[
"dscale", Float { min = 0.1; max = 512.; default = 256.; step = 1. };
];
"rgb", [
"rp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"gp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"bp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };];
"hsv", [
"hp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"sp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"vp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };];
"phi3", [
"scale1", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"base1", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };
"scale2", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"base2", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };
"scale3", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"base3", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };
];
"MACRO",["id", Int { min = 0; max = 10; default = 0; step = 0.01 }];
"CALL", ["id", Int { min = 0; max = 10; default = 0; step = 0.01 }];
"modulate", [];
"invert", [];
]
type 'a block_tree = Tree of 'a * 'a block_tree list
class block_canvas generate draw = object ( self : 'self)
inherit canvas as canvas
inherit fixed as super
val mutable last_mouse_pos = (0,0)
val mutable focused_block = None
val mutable block_properties = []
initializer
window.Window.painter <- draw self;
method draw = ()
method mouse_down button pos =
match button with
| Event.Right ->
last_mouse_pos <- pos;
let items, _ = List.split properties_definition in
let m = menu ~pos ~items ~select:(fun pos item -> self # select_menu pos item) in
self # add (m :> draggable);
true
| _ -> super # mouse_down button pos
method layout start_rect =
let open BatInt in
let rects = List.map (fun (_,w) -> w # window.pos) widgets in
let block_rects = List.map (fun (_,w) -> w # window.pos,w) widgets in
let widget_properties = List.combine rects
(List.map (fun (w,_) ->
List.assq w block_properties) widgets) in
let sorted = BatList.sort block_cmp rects in
let rec stack_loop acc cur_y = function
| x :: xs when x.Rect.y = cur_y ->
(match acc with
| [] -> stack_loop ([x] :: acc) cur_y xs
| a :: b -> stack_loop (([x] @ a) :: b) cur_y xs)
| x :: xs -> stack_loop ([x] :: acc) x.Rect.y xs
| [] -> List.rev acc in
let open Pervasives in
let rec loop acc = function
| ({ Rect.x=x1; Rect.w=w1; } as r1) :: xs, ({ Rect.x=x2; Rect.w=w2; } as r2) :: ys ->
if x2 >= x1 && x2 < x1 + w1 (*&& x2 + w2 <= x1 + w1*) then
match acc with
| [] -> loop [r1, [r2]] ((r1 :: xs), ys)
| (r, a) :: rest when r = r1 -> loop ((r, a @ [r2]) :: rest) ((r1 :: xs), ys)
| rest -> loop ([r1, [r2]] @ rest ) ((r1 :: xs), ys)
else
loop acc (xs, (r2::ys))
| [],_ -> acc
| _,[] -> acc
in
let rec flat_loop = function
| row1 :: row2 :: xs -> loop [] (row1, row2) @ flat_loop (row2::xs)
| row :: [] -> loop [] (row, [])
| [] -> [] in
let rec tree_loop nodes =
function
| (a, xs) -> Tree (a, List.map (fun el -> try tree_loop nodes (el, (List.assoc el nodes)) with Not_found -> Tree (el, []) ) xs)
in
let rec loop2 = function
| lst::xs ->
let props = List.map
(fun a ->
List.assoc a block_rects,
List.assoc a widget_properties) lst in
props :: loop2 xs
| a : : [ ] - > print_endline ( " top : " ^ ( snd ( List.assq a widget_rects))#key )
| [] -> []
in
let rec loop_beg start_rect = function
| x :: xs -> if start_rect = x then x :: xs else loop_beg start_rect xs
| [] -> []
in
let start_rect = match start_rect with | Some a -> a | None -> List.hd sorted in
let start_sorted = loop_beg start_rect sorted in
let lst = stack_loop [[]] start_rect.Rect.y start_sorted in
print_endline "stack_loop-----";
List.iter (fun (lst) -> Printf.printf "(%s)\n" (String.concat " | " (List.map Rect.string_of_rect lst))) lst;
match lst with
| (r::_) :: [] -> Tree ((List.assoc r widget_properties, (List.assoc r block_rects)), [])
| lst -> (let lst = flat_loop lst in
print_endline "-----";
List.iter (fun (a, lst) -> Printf.printf "(%s:: %s)\n" (Rect.string_of_rect a) (String.concat " | " (List.map Rect.string_of_rect lst))) lst;
print_endline "-----";
print_endline "-----";
print_endline "-----";
print_endline "-----";
(match lst with
| hd :: tl ->
begin
let tree = tree_loop lst hd in
let rec print_tree = function
| Tree (r,lst) -> Printf.sprintf "(%s %s)"
((List.assoc r block_rects)#key)
(String.concat " " (List.map print_tree lst))
in
print_endline (print_tree tree);
tree;
flush stdout;
let rec block_tree = function
| Tree (r,lst) ->
Tree ((List.assoc r widget_properties, (List.assoc r block_rects)), List.map block_tree lst)
in
block_tree tree
end))
method focus_block block =
BatOption.may (fun block -> block # focus false) focused_block;
block # focus true;
focused_block <- Some block
method create_block item pos =
let definition = List.assoc item properties_definition in
let properties = properties definition ~change:(fun _ -> generate self) in
let b = block
~click:(fun button block -> self # click_block button block)
~select:(fun block -> List.iter (fun (_,w) -> if w != block then w # set_state Normal) widgets)
item in
property_pane # remove_all;
block_properties <- (b#window, properties)::block_properties;
self#add (b :> draggable);
b#invalidate pos;
self # focus_block b;
property_pane # revalidate;
b, properties
method select_menu _ item =
self # create_block item (Rect.rect last_mouse_pos (80, 20));
property_pane # revalidate;
true
method click_block button block =
match button with
| Event.Left ->
begin
let properties_pane = List.assq block # window block_properties in
property_pane # remove_all;
property_pane # add (properties_pane :> draggable);
property_pane # revalidate;
self # focus_block block;
false
end
| Event.Middle ->
begin
canvas # remove (block :> draggable);
BatList.remove_if (fun (b,_) -> b == block#window) block_properties;
property_pane # remove_all;
property_pane # revalidate;
true
end
| _ -> false
method write file_name =
let properties_string property_panel =
String.concat " "
(List.map
(fun (_,property) -> Printf.sprintf ":%s %s" (property # key)
(match property # value with
| Event.Float f -> string_of_float f
| Event.Int i -> string_of_float (float i))) property_panel#widgets)
in
let str =
String.concat "\n"
(List.map
(fun (blockw, properties) ->
let block = self # find blockw in
let x,y,w,h = Rect.coords block # window. pos in
Printf.sprintf "(%s (rect %d %d %d %d) %s)" block # key x y w h (properties_string properties)) block_properties)
in
let ch = open_out file_name in
output_string ch str;
close_out ch
method read a = " " ^ a;()
method read file_name =
let process_line line =
let rec update_parameters properties offset line_rest =
try
Str.search_forward (Str.regexp ":\\([a-z0-9]+\\)[ \t]+\\([.0-9]+\\)[ \t]*") line_rest offset;
let key, value = Str.matched_group 1 line_rest, Str.matched_group 2 line_rest in
let offset' = Str.match_end () in
print_endline key;
print_endline value;
let value' = float_of_string value in
((properties # get key) :> draggable) # set_value value';
update_parameters properties offset' line_rest
with Not_found -> print_endline "First regexp not found!"
in
try
Str.search_forward (Str.regexp
"(\\([a-z0-9]+\\)[ \t]+(rect[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]*\\(.*\\)") line 0;
let m i = int_of_string (Str.matched_group i line) in
let name , x, y, w, h = Str.matched_group 1 line, m 2, m 3, m 4, m 5 in
Printf.printf "(%s %d %d %d %d)" name x y w h;
print_endline name;
print_endline (string_of_int x);
print_endline (Str.matched_group 6 line);
flush stdout;
let block, properties = self # create_block name (Rect.rect (x,y) (w,h)) in
update_parameters properties 0 (Str.matched_group 6 line);
with Not_found -> print_endline "Second regexp not found!"
in
let lines = BatFile.lines_of file_name in
BatEnum.iter process_line lines
end
let block_canvas ?draw:(draw=fun w rect -> ()) ?generate:(generate = fun _ -> ()) ()= new block_canvas generate draw
| null | https://raw.githubusercontent.com/danmey/ocaml-gui/e446fae0af7e0e07414c7970514e2d02166b4293/blocks.ml | ocaml | method delete_properties =
List.iter (fun (_,widget) -> Window.remove self # window widget # window) widgets;
widgets <- []
end and block name = object ( self : 'self )
method paint state =
&& x2 + w2 <= x1 + w1 | open Widget
open Draw
open Window
open GL
open Glu
type stickiness = TopBottom | LeftRight
let expand_rect_left dx rect constr =
let real_dx = ( dx / constr) * constr in
{ rect with
Rect.x = rect.Rect.x + real_dx;
Rect.w = rect.Rect.w - real_dx }
let block_cmp l r =
let y = r.Rect.y - l.Rect.y in
if y <> 0 then y
else
r.Rect.x - l.Rect.x
type 'a property_value = { min : 'a; max : 'a; default : 'a; step : float }
type property_type =
| Float of float property_value
| Int of int property_value
type property = string * property_type
class properties props change = object (self : 'self)
inherit frame (Layout.vertical)
initializer
List.iter
(function
| (name, Float { min; max; default; step }) ->
self # add (float_slider ~value:default ~min ~max ~step ~change name)
| (name, Int { min; max; default; step }) ->
self # add (int_slider ~value:default ~min ~max ~step ~change name))
props
method get key =
let _, w = List.find (fun (_,w) -> w # key = key) self # widgets in
w
end
let properties
?change:(change=(fun _ -> ()))
definition =
new properties definition change
class block name click selected = object ( self : 'self )
inherit canvas as canvas
inherit draggable as super
val left_border = new draggable_constrained (HorizontalWith 10)
val right_border = new draggable_constrained (HorizontalWith 10)
val name = name
val mutable focus = false
initializer
canvas#add left_border;
canvas#add right_border
method drag _ (x,y) (dx,dy) =
let grid x = (x + 5) / 10 * 10 in
window.pos.Rect.x <- grid x;
window.pos.Rect.y <- grid y
method name = name
let caption = Printf.sprintf " % s : % s " name self#value in
caption 0 state
method invalidate rect =
super#invalidate rect;
left_border#invalidate (Rect.rect (0,0) (10, rect.Rect.h));
right_border#invalidate (Rect.rect (rect.Rect.w-10,0) (10, rect.Rect.h))
method dragged widget (dx, dy) =
let grid x = (x + 5) / 10 * 10 in
let rect = self#window.pos in
if widget == left_border then
self # invalidate (expand_rect_left dx rect 10)
else if widget == right_border then
self # invalidate
(Rect.rect
(rect.Rect.x, rect.Rect.y)
(grid (rect.Rect.w + dx), rect.Rect.h))
method mouse_down b p =
let res = (if not (click b self) then
super # mouse_down b p
else
true) in
begin
match b with
| Event.Right ->
begin
state <- Selected;
selected (self :> draggable);
end
| _ -> ()
end;
res
method mouse_up b p =
match b with
| Event.Right ->
begin
match state with
| Selected -> true
| _ -> super # mouse_down b p
end
| _ -> super # mouse_down b p
method key = name
method focus is = focus <- is
method paint state = caption_painter2 self # name state
end
let block
?click:(click = fun _ _ -> false)
?select:(select = fun _ -> ()) name =
new block name click select
open BatFloat
class texture_preview = object ( self : 'self )
inherit graphics as super
val mutable texid = None
initializer
window.Window.painter <- self#draw;
method draw rect =
BatOption.may (fun texid ->
glBindTexture ~target:BindTex.GL_TEXTURE_2D ~texture:texid;
glTexParameter ~target:TexParam.GL_TEXTURE_2D ~param:(TexParam.GL_TEXTURE_MAG_FILTER Mag.GL_NEAREST);
glTexParameter ~target:TexParam.GL_TEXTURE_2D ~param:(TexParam.GL_TEXTURE_MIN_FILTER Min.GL_NEAREST);
glEnable GL_TEXTURE_2D;
glColor3 ~r:1. ~g:1. ~b:1.;
let x, y, w, h = Rect.coordsf rect in
glBegin GL_QUADS;
glTexCoord2 ~s:0.0 ~t:0.0;
glVertex3 ~x ~y ~z:0.;
glTexCoord2 ~s:1.0 ~t:0.0;
glVertex3 ~x:(x + w) ~y ~z:0.;
glTexCoord2 ~s:1.0 ~t:1.0;
glVertex3 ~x:(x + w) ~y:(y + h) ~z:0.;
glTexCoord2 ~s:0.0 ~t:1.0;
glVertex3 ~x ~y:(y + h) ~z:0.;
glEnd ();
glDisable GL_TEXTURE_2D) texid; ()
method set_image id = texid <- Some id
end
let property_pane = new frame Layout.fill
let properties_definition =
["perlin",[
"persistence", Float { min = 0.; max = 3.; default = 0.25; step = 0.01 };
"octaves", Int { min=1; max=8; default=1; step = 0.2 };
"seed", Int { min=0; max=9; default=1; step=0.2};
];
"add",[
];
"light", [
"lx", Float { min = 0.; max = 1.; default = 0.; step = 0.01 };
"ly", Float { min = 0.; max = 1.; default = 1.; step = 0.01 };
"ldx", Float { min = 0.; max = 1.; default = 1.; step = 1./.256. };
"ldy", Float { min = 0.; max = 1.; default = 1.; step = 1./.256. };
];
"glow", [
"x0", Float { min = -1.; max = 1.; default = 0.5; step = 0.01 };
"y0", Float { min = -1.; max = 1.; default = 0.5; step = 0.01 };
"atten", Float { min = -100.; max = 100.; default = 1.; step = 0.1 };
"xr", Float { min = 0.; max = 5.; default = 0.5; step = 0.01 };
"yr", Float { min = 0.; max = 5.; default = 0.5; step = 0.01 };
];
"phi",[
"scale", Float { min = -10.; max = 10.; default = 1.; step = 0.01 };
"base", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };];
"add", [];
"flat",[
"fx", Float { min = 0.; max = 1.; default = 0.25; step = 0.01 };
"fy", Float { min = 0.; max = 1.; default = 0.25; step = 0.01 };
"fw", Float { min = 0.; max = 1.; default = 0.5; step = 0.01 };
"fh", Float { min = 0.; max = 1.; default = 0.5; step = 0.01 };
"fg", Float { min = 0.; max = 1.; default = 0.25; step = 0.01 };
"bg", Float { min = 0.; max = 1.; default = 0.75; step = 0.01 };];
"distort",[
"dscale", Float { min = 0.1; max = 512.; default = 256.; step = 1. };
];
"rgb", [
"rp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"gp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"bp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };];
"hsv", [
"hp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"sp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"vp", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };];
"phi3", [
"scale1", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"base1", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };
"scale2", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"base2", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };
"scale3", Float { min = 0.; max = 10.; default = 1.; step = 0.01 };
"base3", Float { min = -5.; max = 5.; default = 0.; step = 0.01 };
];
"MACRO",["id", Int { min = 0; max = 10; default = 0; step = 0.01 }];
"CALL", ["id", Int { min = 0; max = 10; default = 0; step = 0.01 }];
"modulate", [];
"invert", [];
]
type 'a block_tree = Tree of 'a * 'a block_tree list
class block_canvas generate draw = object ( self : 'self)
inherit canvas as canvas
inherit fixed as super
val mutable last_mouse_pos = (0,0)
val mutable focused_block = None
val mutable block_properties = []
initializer
window.Window.painter <- draw self;
method draw = ()
method mouse_down button pos =
match button with
| Event.Right ->
last_mouse_pos <- pos;
let items, _ = List.split properties_definition in
let m = menu ~pos ~items ~select:(fun pos item -> self # select_menu pos item) in
self # add (m :> draggable);
true
| _ -> super # mouse_down button pos
method layout start_rect =
let open BatInt in
let rects = List.map (fun (_,w) -> w # window.pos) widgets in
let block_rects = List.map (fun (_,w) -> w # window.pos,w) widgets in
let widget_properties = List.combine rects
(List.map (fun (w,_) ->
List.assq w block_properties) widgets) in
let sorted = BatList.sort block_cmp rects in
let rec stack_loop acc cur_y = function
| x :: xs when x.Rect.y = cur_y ->
(match acc with
| [] -> stack_loop ([x] :: acc) cur_y xs
| a :: b -> stack_loop (([x] @ a) :: b) cur_y xs)
| x :: xs -> stack_loop ([x] :: acc) x.Rect.y xs
| [] -> List.rev acc in
let open Pervasives in
let rec loop acc = function
| ({ Rect.x=x1; Rect.w=w1; } as r1) :: xs, ({ Rect.x=x2; Rect.w=w2; } as r2) :: ys ->
match acc with
| [] -> loop [r1, [r2]] ((r1 :: xs), ys)
| (r, a) :: rest when r = r1 -> loop ((r, a @ [r2]) :: rest) ((r1 :: xs), ys)
| rest -> loop ([r1, [r2]] @ rest ) ((r1 :: xs), ys)
else
loop acc (xs, (r2::ys))
| [],_ -> acc
| _,[] -> acc
in
let rec flat_loop = function
| row1 :: row2 :: xs -> loop [] (row1, row2) @ flat_loop (row2::xs)
| row :: [] -> loop [] (row, [])
| [] -> [] in
let rec tree_loop nodes =
function
| (a, xs) -> Tree (a, List.map (fun el -> try tree_loop nodes (el, (List.assoc el nodes)) with Not_found -> Tree (el, []) ) xs)
in
let rec loop2 = function
| lst::xs ->
let props = List.map
(fun a ->
List.assoc a block_rects,
List.assoc a widget_properties) lst in
props :: loop2 xs
| a : : [ ] - > print_endline ( " top : " ^ ( snd ( List.assq a widget_rects))#key )
| [] -> []
in
let rec loop_beg start_rect = function
| x :: xs -> if start_rect = x then x :: xs else loop_beg start_rect xs
| [] -> []
in
let start_rect = match start_rect with | Some a -> a | None -> List.hd sorted in
let start_sorted = loop_beg start_rect sorted in
let lst = stack_loop [[]] start_rect.Rect.y start_sorted in
print_endline "stack_loop-----";
List.iter (fun (lst) -> Printf.printf "(%s)\n" (String.concat " | " (List.map Rect.string_of_rect lst))) lst;
match lst with
| (r::_) :: [] -> Tree ((List.assoc r widget_properties, (List.assoc r block_rects)), [])
| lst -> (let lst = flat_loop lst in
print_endline "-----";
List.iter (fun (a, lst) -> Printf.printf "(%s:: %s)\n" (Rect.string_of_rect a) (String.concat " | " (List.map Rect.string_of_rect lst))) lst;
print_endline "-----";
print_endline "-----";
print_endline "-----";
print_endline "-----";
(match lst with
| hd :: tl ->
begin
let tree = tree_loop lst hd in
let rec print_tree = function
| Tree (r,lst) -> Printf.sprintf "(%s %s)"
((List.assoc r block_rects)#key)
(String.concat " " (List.map print_tree lst))
in
print_endline (print_tree tree);
tree;
flush stdout;
let rec block_tree = function
| Tree (r,lst) ->
Tree ((List.assoc r widget_properties, (List.assoc r block_rects)), List.map block_tree lst)
in
block_tree tree
end))
method focus_block block =
BatOption.may (fun block -> block # focus false) focused_block;
block # focus true;
focused_block <- Some block
method create_block item pos =
let definition = List.assoc item properties_definition in
let properties = properties definition ~change:(fun _ -> generate self) in
let b = block
~click:(fun button block -> self # click_block button block)
~select:(fun block -> List.iter (fun (_,w) -> if w != block then w # set_state Normal) widgets)
item in
property_pane # remove_all;
block_properties <- (b#window, properties)::block_properties;
self#add (b :> draggable);
b#invalidate pos;
self # focus_block b;
property_pane # revalidate;
b, properties
method select_menu _ item =
self # create_block item (Rect.rect last_mouse_pos (80, 20));
property_pane # revalidate;
true
method click_block button block =
match button with
| Event.Left ->
begin
let properties_pane = List.assq block # window block_properties in
property_pane # remove_all;
property_pane # add (properties_pane :> draggable);
property_pane # revalidate;
self # focus_block block;
false
end
| Event.Middle ->
begin
canvas # remove (block :> draggable);
BatList.remove_if (fun (b,_) -> b == block#window) block_properties;
property_pane # remove_all;
property_pane # revalidate;
true
end
| _ -> false
method write file_name =
let properties_string property_panel =
String.concat " "
(List.map
(fun (_,property) -> Printf.sprintf ":%s %s" (property # key)
(match property # value with
| Event.Float f -> string_of_float f
| Event.Int i -> string_of_float (float i))) property_panel#widgets)
in
let str =
String.concat "\n"
(List.map
(fun (blockw, properties) ->
let block = self # find blockw in
let x,y,w,h = Rect.coords block # window. pos in
Printf.sprintf "(%s (rect %d %d %d %d) %s)" block # key x y w h (properties_string properties)) block_properties)
in
let ch = open_out file_name in
output_string ch str;
close_out ch
method read a = " " ^ a;()
method read file_name =
let process_line line =
let rec update_parameters properties offset line_rest =
try
Str.search_forward (Str.regexp ":\\([a-z0-9]+\\)[ \t]+\\([.0-9]+\\)[ \t]*") line_rest offset;
let key, value = Str.matched_group 1 line_rest, Str.matched_group 2 line_rest in
let offset' = Str.match_end () in
print_endline key;
print_endline value;
let value' = float_of_string value in
((properties # get key) :> draggable) # set_value value';
update_parameters properties offset' line_rest
with Not_found -> print_endline "First regexp not found!"
in
try
Str.search_forward (Str.regexp
"(\\([a-z0-9]+\\)[ \t]+(rect[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]*\\(.*\\)") line 0;
let m i = int_of_string (Str.matched_group i line) in
let name , x, y, w, h = Str.matched_group 1 line, m 2, m 3, m 4, m 5 in
Printf.printf "(%s %d %d %d %d)" name x y w h;
print_endline name;
print_endline (string_of_int x);
print_endline (Str.matched_group 6 line);
flush stdout;
let block, properties = self # create_block name (Rect.rect (x,y) (w,h)) in
update_parameters properties 0 (Str.matched_group 6 line);
with Not_found -> print_endline "Second regexp not found!"
in
let lines = BatFile.lines_of file_name in
BatEnum.iter process_line lines
end
let block_canvas ?draw:(draw=fun w rect -> ()) ?generate:(generate = fun _ -> ()) ()= new block_canvas generate draw
|
e6df98c4366df9e497fd2f5bca514b4a4b2fdd35d4b311534a0da6b4a24e0d65 | locusmath/locus | all.clj | (ns locus.number.sequence.all
(:refer-clojure :exclude [+ - * /])
(:require [locus.set.logic.core.set :refer :all :exclude [add]]
[locus.set.logic.numeric.natural :refer [factors]]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.additive.base.generic.arithmetic :refer :all]
[locus.additive.base.core.protocols :refer :all]
[locus.additive.ring.core.object :refer :all]
[locus.additive.semiring.core.object :refer :all]))
; Here we define a special number sequence data type for dealing with rings
; of sequences over number fields.
(deftype NumberSequence [func]
clojure.lang.IFn
(invoke [this arg] (func arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args))
clojure.lang.Seqable
(seq [this] (map func (range))))
(defmethod negate NumberSequence
[seq]
(NumberSequence.
(fn [n]
(- (seq n)))))
(defmethod add [NumberSequence NumberSequence]
[a b]
(NumberSequence.
(fn [i]
(+ (a i) (b i)))))
(defmethod multiply [NumberSequence NumberSequence]
[a b]
(NumberSequence.
(fn [i]
(* (a i) (b i)))))
(defmethod reciprocal NumberSequence
[seq]
(NumberSequence.
(fn [n]
(/ n))))
(defmethod compose* NumberSequence
[a b]
(NumberSequence.
(fn [n]
(a (b n)))))
; Get the consecutive sums, differences, products and divisions
(defn consecutive-differences
[f]
(NumberSequence.
(fn [n]
(if (zero? n)
(f n)
(- (f n) (f (dec n)))))))
(defn consecutive-divisions
[f]
(NumberSequence.
(fn [n]
(if (zero? n)
(f n)
(/ (f n) (f (dec n)))))))
(defn consecutive-sums
[f]
(NumberSequence.
(fn [n]
(apply + (map f (range (inc n)))))))
(defn consecutive-products
[f]
(NumberSequence.
(fn [n]
(apply * (map f (range (inc n)))))))
; Inverse sequences
(defn preceding-elements
[func current-index n]
(if (< n (func current-index))
(list)
(cons (func current-index) (preceding-elements func (inc current-index) n))))
(defn get-inverse-value
[func n]
(let [elems (preceding-elements func 0 n)]
(if (empty? elems)
0
(dec (count elems)))))
(defn inverse-sequence
[func]
(NumberSequence.
(fn [n]
(get-inverse-value func n))))
; Functions for creating integer sequences
(defn periodic-sequence
[initial-segment repeating-elements]
(NumberSequence.
(fn [n]
(if (< n (count initial-segment))
(nth initial-segment n)
(nth repeating-elements (mod (- n (count initial-segment)) (count repeating-elements)))))))
(defn linear-growth-integer-sequence
[x]
(NumberSequence.
(fn [n]
(int (Math/floor (* x n))))))
; Nth negative integer
(def nth-negative-integer
(NumberSequence.
(fn [n] (- (inc n)))))
(def nth-negative-odd
(NumberSequence.
(fn [n]
(- (inc (* 2 n))))))
(def nth-nonpositive-even
(NumberSequence.
(fn [n]
(- (* 2 n)))))
(def nth-negative-even
(NumberSequence.
(fn [n]
(- (* 2 (inc n))))))
(def nth-nonpositive-integer
(NumberSequence.
(fn [n] (- n))))
(def nth-natural-number
(NumberSequence.
(fn [n] n)))
(def nth-positive-integer
(NumberSequence.
(fn [n] (+ n 1))))
(def nth-even
(NumberSequence.
(fn [n] (* 2 n))))
(def nth-positive-even
(NumberSequence.
(fn [n] (* 2 (inc n)))))
(def nth-odd
(NumberSequence.
(fn [n] (inc (* 2 n)))))
; The fundamental polygonal number sequences
(def nth-square
(NumberSequence.
(fn [n]
(* n n))))
(def nth-pronic-number
(NumberSequence.
(fn [n]
(* n (inc n)))))
(def nth-triangular-number
(NumberSequence.
(fn [n]
(/ (* n (inc n))
2))))
(def nth-pentagonal-number
(NumberSequence.
(fn [n]
(/ (- (* 3 n n) n)
2))))
(def nth-hexagonal-number
(NumberSequence.
(fn [n]
(- (* 2 n n) n))))
(def nth-octagonal-number
(NumberSequence.
(fn [n]
(/ (- (* 5 n n) (* 3 n))
2))))
(def nth-nonagonal-number
(NumberSequence.
(fn [n]
(/ (* n (- (* 7 n) 5))
2))))
(def nth-decagonal-number
(NumberSequence.
(fn [n]
(- (* 4 n n) (* 3 n)))))
; Centered figurate numbers
(def nth-centered-triangular-number
(NumberSequence.
(fn [n]
(inc
(/ (* 3 n (dec n))
2)))))
(def nth-centered-square-number
(NumberSequence.
(fn [n]
(+ (* n n)
(* (dec n) (dec n))))))
(def nth-centered-pentagonal-number
(NumberSequence.
(fn [n]
(/ (+ (* 5 n n) (- (* 5 n)) 2)
2))))
(def nth-centered-hexagonal-number
(NumberSequence.
(fn [n]
(+ (* 3 n n)
(* -3 n)
1))))
(def nth-centered-heptagonal-number
(NumberSequence.
(fn [n]
(/ (+ (* 7 n n) (* -7 n) 2)
2))))
(def nth-centered-octagonal-number
(NumberSequence.
(fn [n]
(+ (* 4 n n) (* 4 n) 1))))
(def nth-centered-nonagonal-number
(NumberSequence.
(fn [n]
(/ (* (- (* 3 n) 2)
(- (* 3 n) 1))
2))))
(def nth-centered-decagonal-number
(NumberSequence.
(fn [n]
(+ (* 5 n n)
(* 5 n)
1))))
Three dimensional numbers
(def nth-square-pyramidal-number
(NumberSequence.
(fn [n]
(+ (/ (* n n n) 3)
(/ (* n n) 2)
(/ n 6)))))
; Extra number sequences
(def nth-tetrahedral-number
(NumberSequence.
(fn [n]
(/ (* n (+ n 1) (+ n 2))
6))))
(def nth-cube
(NumberSequence.
(fn [n]
(* n n n))))
; Centered tetrahedral numbers
(def nth-centered-tetrahedral-number
(NumberSequence.
(fn [n]
(/ (* (+ (* 2 n) 1)
(+ (* n n) n 3))
3))))
(def nth-centered-cube-number
(NumberSequence.
(fn [n]
(+ (nth-cube n)
(nth-cube (inc n))))))
Pentatope numbers
(def nth-pentatope-number
(NumberSequence.
(fn [n]
(/ (* n (+ n 1) (+ n 2) (+ n 3))
24))))
; Squared triangular numbers are sums of cubes
(def nth-squared-triangular-number
(NumberSequence.
(fn [n]
(nth-square
(nth-triangular-number n)))))
; Numbers growing at an exponential rate
(def nth-binary-number
(NumberSequence.
(fn [n]
(apply * (repeat n 2N)))))
(def nth-fibonacci-number
(NumberSequence.
(fn fib [n]
(if (< n 2)
1
(+ (fib (- n 1)) (fib (- n 2)))))))
(def nth-factorial
(NumberSequence.
(fn [n]
(locus.set.logic.core.set/factorial n))))
; The sum of divisors function
(def sum-of-divisors
(NumberSequence.
(fn [n]
(apply + (divisors n)))))
(def catalan-number
(NumberSequence.
(fn [n]
(/ (factorial (* 2 n))
(* (factorial n) (factorial (inc n)))))))
; Rational numbers
; Continued fractions are needed
(def nth-unit-fraction
(NumberSequence.
(fn [n]
(/ (inc n)))))
(def nth-fibonacci-ratio
(NumberSequence.
(fn [n]
(/ (nth-fibonacci-number (+ n 1))
(nth-fibonacci-number n)))))
(def nth-factorial-reciprocal
(NumberSequence.
(fn [n]
(/ (nth-factorial n)))))
(def nth-euler-ratio
(NumberSequence.
(fn [n]
(apply
+
(map
(fn [i]
(/ (factorial i)))
(range n))))))
(def nth-basel-ratio
(NumberSequence.
(fn [n]
(apply
+
(map
(fn [i]
(/ (nth-square i)))
(range 1 n))))))
; Continued fractions
(defn continued-fraction-value
[coll]
(if (= (count coll) 1)
(first coll)
(+ (first coll) (/ (continued-fraction-value (rest coll))))))
(defn continued-fraction-sequence
[coll]
(NumberSequence.
(fn [n]
(continued-fraction-value (take (inc n) coll)))))
(def nth-root-ratio
(NumberSequence.
(fn [n]
(continued-fraction-value
(map
(fn [i]
(if (zero? i)
1
2))
(range (inc n)))))))
| null | https://raw.githubusercontent.com/locusmath/locus/fb6068bd78977b51fd3c5783545a5f9986e4235c/src/clojure/locus/number/sequence/all.clj | clojure | Here we define a special number sequence data type for dealing with rings
of sequences over number fields.
Get the consecutive sums, differences, products and divisions
Inverse sequences
Functions for creating integer sequences
Nth negative integer
The fundamental polygonal number sequences
Centered figurate numbers
Extra number sequences
Centered tetrahedral numbers
Squared triangular numbers are sums of cubes
Numbers growing at an exponential rate
The sum of divisors function
Rational numbers
Continued fractions are needed
Continued fractions | (ns locus.number.sequence.all
(:refer-clojure :exclude [+ - * /])
(:require [locus.set.logic.core.set :refer :all :exclude [add]]
[locus.set.logic.numeric.natural :refer [factors]]
[locus.set.logic.structure.protocols :refer :all]
[locus.set.quiver.structure.core.protocols :refer :all]
[locus.set.copresheaf.structure.core.protocols :refer :all]
[locus.additive.base.generic.arithmetic :refer :all]
[locus.additive.base.core.protocols :refer :all]
[locus.additive.ring.core.object :refer :all]
[locus.additive.semiring.core.object :refer :all]))
(deftype NumberSequence [func]
clojure.lang.IFn
(invoke [this arg] (func arg))
(applyTo [this args] (clojure.lang.AFn/applyToHelper this args))
clojure.lang.Seqable
(seq [this] (map func (range))))
(defmethod negate NumberSequence
[seq]
(NumberSequence.
(fn [n]
(- (seq n)))))
(defmethod add [NumberSequence NumberSequence]
[a b]
(NumberSequence.
(fn [i]
(+ (a i) (b i)))))
(defmethod multiply [NumberSequence NumberSequence]
[a b]
(NumberSequence.
(fn [i]
(* (a i) (b i)))))
(defmethod reciprocal NumberSequence
[seq]
(NumberSequence.
(fn [n]
(/ n))))
(defmethod compose* NumberSequence
[a b]
(NumberSequence.
(fn [n]
(a (b n)))))
(defn consecutive-differences
[f]
(NumberSequence.
(fn [n]
(if (zero? n)
(f n)
(- (f n) (f (dec n)))))))
(defn consecutive-divisions
[f]
(NumberSequence.
(fn [n]
(if (zero? n)
(f n)
(/ (f n) (f (dec n)))))))
(defn consecutive-sums
[f]
(NumberSequence.
(fn [n]
(apply + (map f (range (inc n)))))))
(defn consecutive-products
[f]
(NumberSequence.
(fn [n]
(apply * (map f (range (inc n)))))))
(defn preceding-elements
[func current-index n]
(if (< n (func current-index))
(list)
(cons (func current-index) (preceding-elements func (inc current-index) n))))
(defn get-inverse-value
[func n]
(let [elems (preceding-elements func 0 n)]
(if (empty? elems)
0
(dec (count elems)))))
(defn inverse-sequence
[func]
(NumberSequence.
(fn [n]
(get-inverse-value func n))))
(defn periodic-sequence
[initial-segment repeating-elements]
(NumberSequence.
(fn [n]
(if (< n (count initial-segment))
(nth initial-segment n)
(nth repeating-elements (mod (- n (count initial-segment)) (count repeating-elements)))))))
(defn linear-growth-integer-sequence
[x]
(NumberSequence.
(fn [n]
(int (Math/floor (* x n))))))
(def nth-negative-integer
(NumberSequence.
(fn [n] (- (inc n)))))
(def nth-negative-odd
(NumberSequence.
(fn [n]
(- (inc (* 2 n))))))
(def nth-nonpositive-even
(NumberSequence.
(fn [n]
(- (* 2 n)))))
(def nth-negative-even
(NumberSequence.
(fn [n]
(- (* 2 (inc n))))))
(def nth-nonpositive-integer
(NumberSequence.
(fn [n] (- n))))
(def nth-natural-number
(NumberSequence.
(fn [n] n)))
(def nth-positive-integer
(NumberSequence.
(fn [n] (+ n 1))))
(def nth-even
(NumberSequence.
(fn [n] (* 2 n))))
(def nth-positive-even
(NumberSequence.
(fn [n] (* 2 (inc n)))))
(def nth-odd
(NumberSequence.
(fn [n] (inc (* 2 n)))))
(def nth-square
(NumberSequence.
(fn [n]
(* n n))))
(def nth-pronic-number
(NumberSequence.
(fn [n]
(* n (inc n)))))
(def nth-triangular-number
(NumberSequence.
(fn [n]
(/ (* n (inc n))
2))))
(def nth-pentagonal-number
(NumberSequence.
(fn [n]
(/ (- (* 3 n n) n)
2))))
(def nth-hexagonal-number
(NumberSequence.
(fn [n]
(- (* 2 n n) n))))
(def nth-octagonal-number
(NumberSequence.
(fn [n]
(/ (- (* 5 n n) (* 3 n))
2))))
(def nth-nonagonal-number
(NumberSequence.
(fn [n]
(/ (* n (- (* 7 n) 5))
2))))
(def nth-decagonal-number
(NumberSequence.
(fn [n]
(- (* 4 n n) (* 3 n)))))
(def nth-centered-triangular-number
(NumberSequence.
(fn [n]
(inc
(/ (* 3 n (dec n))
2)))))
(def nth-centered-square-number
(NumberSequence.
(fn [n]
(+ (* n n)
(* (dec n) (dec n))))))
(def nth-centered-pentagonal-number
(NumberSequence.
(fn [n]
(/ (+ (* 5 n n) (- (* 5 n)) 2)
2))))
(def nth-centered-hexagonal-number
(NumberSequence.
(fn [n]
(+ (* 3 n n)
(* -3 n)
1))))
(def nth-centered-heptagonal-number
(NumberSequence.
(fn [n]
(/ (+ (* 7 n n) (* -7 n) 2)
2))))
(def nth-centered-octagonal-number
(NumberSequence.
(fn [n]
(+ (* 4 n n) (* 4 n) 1))))
(def nth-centered-nonagonal-number
(NumberSequence.
(fn [n]
(/ (* (- (* 3 n) 2)
(- (* 3 n) 1))
2))))
(def nth-centered-decagonal-number
(NumberSequence.
(fn [n]
(+ (* 5 n n)
(* 5 n)
1))))
Three dimensional numbers
(def nth-square-pyramidal-number
(NumberSequence.
(fn [n]
(+ (/ (* n n n) 3)
(/ (* n n) 2)
(/ n 6)))))
(def nth-tetrahedral-number
(NumberSequence.
(fn [n]
(/ (* n (+ n 1) (+ n 2))
6))))
(def nth-cube
(NumberSequence.
(fn [n]
(* n n n))))
(def nth-centered-tetrahedral-number
(NumberSequence.
(fn [n]
(/ (* (+ (* 2 n) 1)
(+ (* n n) n 3))
3))))
(def nth-centered-cube-number
(NumberSequence.
(fn [n]
(+ (nth-cube n)
(nth-cube (inc n))))))
Pentatope numbers
(def nth-pentatope-number
(NumberSequence.
(fn [n]
(/ (* n (+ n 1) (+ n 2) (+ n 3))
24))))
(def nth-squared-triangular-number
(NumberSequence.
(fn [n]
(nth-square
(nth-triangular-number n)))))
(def nth-binary-number
(NumberSequence.
(fn [n]
(apply * (repeat n 2N)))))
(def nth-fibonacci-number
(NumberSequence.
(fn fib [n]
(if (< n 2)
1
(+ (fib (- n 1)) (fib (- n 2)))))))
(def nth-factorial
(NumberSequence.
(fn [n]
(locus.set.logic.core.set/factorial n))))
(def sum-of-divisors
(NumberSequence.
(fn [n]
(apply + (divisors n)))))
(def catalan-number
(NumberSequence.
(fn [n]
(/ (factorial (* 2 n))
(* (factorial n) (factorial (inc n)))))))
(def nth-unit-fraction
(NumberSequence.
(fn [n]
(/ (inc n)))))
(def nth-fibonacci-ratio
(NumberSequence.
(fn [n]
(/ (nth-fibonacci-number (+ n 1))
(nth-fibonacci-number n)))))
(def nth-factorial-reciprocal
(NumberSequence.
(fn [n]
(/ (nth-factorial n)))))
(def nth-euler-ratio
(NumberSequence.
(fn [n]
(apply
+
(map
(fn [i]
(/ (factorial i)))
(range n))))))
(def nth-basel-ratio
(NumberSequence.
(fn [n]
(apply
+
(map
(fn [i]
(/ (nth-square i)))
(range 1 n))))))
(defn continued-fraction-value
[coll]
(if (= (count coll) 1)
(first coll)
(+ (first coll) (/ (continued-fraction-value (rest coll))))))
(defn continued-fraction-sequence
[coll]
(NumberSequence.
(fn [n]
(continued-fraction-value (take (inc n) coll)))))
(def nth-root-ratio
(NumberSequence.
(fn [n]
(continued-fraction-value
(map
(fn [i]
(if (zero? i)
1
2))
(range (inc n)))))))
|