_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
|
---|---|---|---|---|---|---|---|---|
b01c395737e232a7500272dabf58fe899ac0cbc890fd9c075d07248943c62ff0
|
jmbr/cl-buchberger
|
polynomial.lisp
|
(in-package :com.superadditive.cl-buchberger)
Copyright ( C ) 2007 < >
;;
;; 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 </>.
(defclass polynomial (ring-element)
((base-ring
:initarg :ring
:initform (error "You must specify a base ring")
:accessor base-ring)
(terms
:type hash-table
:initarg :terms
:initform (make-hash-table :test #'equalp)
:accessor terms)))
(defgeneric lt (poly)
(:documentation "Returns the leading term of a polynomial."))
(defgeneric lm (poly)
(:documentation "Returns the leading monomial of a polynomial.
That is, the leading term with 1 as coefficient"))
(defgeneric lc (poly)
(:documentation "Returns the leading coefficient of a polynomial"))
(defgeneric multideg (poly)
(:documentation "Returns the multidegree of a polynomial"))
(defun make-polynomial (term-list &key (ring *ring*))
(let ((poly (make-instance 'polynomial :ring ring)))
(dolist (elem term-list poly)
(setf poly
(add poly
(make-instance 'term
:coefficient (first elem)
:monomial (make-array (1- (length elem))
:initial-contents (rest elem))))))))
(defmacro doterms ((var poly &optional (resultform 'nil)) &body body)
(let ((mono (gensym "DOTERMS"))
(coef (gensym "DOTERMS")))
`(block nil
(loop for ,mono being the hash-keys of (terms ,poly) using (hash-value ,coef) do
(let ((,var (make-instance 'term :coefficient ,coef :monomial ,mono)))
,@body))
(return ,resultform))))
(defun mapterm (function polynomial)
"Apply FUNCTION to successive terms of POLYNOMIAL. Return list
of FUNCTION return values."
(let ((results nil))
(doterms (tt polynomial results)
(push (funcall function tt) results))))
(defmethod print-object ((p polynomial) stream)
(print-unreadable-object (p stream :type t)
(write-string (element->string p) stream)))
(defun terms->list (poly)
(mapterm #'identity poly))
(defmethod element->string ((poly polynomial) &key)
(assert poly)
(if (ring-zero-p poly)
(format nil "0")
(let ((term-list
(sort (terms->list poly) *monomial-ordering* :key #'monomial)))
(format nil "~a~{ ~a~}"
(element->string (first term-list)
:ring (base-ring poly)
:leading-term t)
(mapcar #'(lambda (x)
(element->string x :ring (base-ring poly)))
(rest term-list))))))
(defmethod ring-zero-p ((poly polynomial))
(zerop (hash-table-count (terms poly))))
(defmethod ring-copy ((poly polynomial))
"Returns a (deep) copy of the given polynomial"
(let ((new-poly (make-instance 'polynomial :ring (base-ring poly))))
(maphash #'(lambda (m c)
(setf (gethash (copy-seq m) (terms new-poly)) c))
(terms poly))
new-poly))
(defmethod lt ((poly polynomial))
(let ((term-list (terms->list poly)))
(first (sort term-list *monomial-ordering* :key #'monomial))))
(defmethod lc ((poly polynomial))
(coefficient (lt poly)))
(defmethod lm ((poly polynomial))
(monomial (lt poly)))
(defmethod multideg ((poly polynomial))
(lc poly))
| null |
https://raw.githubusercontent.com/jmbr/cl-buchberger/4503216b4f2e3372daf4c9cca7b2e978cbc8256b/polynomial.lisp
|
lisp
|
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 </>.
|
(in-package :com.superadditive.cl-buchberger)
Copyright ( C ) 2007 < >
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
(defclass polynomial (ring-element)
((base-ring
:initarg :ring
:initform (error "You must specify a base ring")
:accessor base-ring)
(terms
:type hash-table
:initarg :terms
:initform (make-hash-table :test #'equalp)
:accessor terms)))
(defgeneric lt (poly)
(:documentation "Returns the leading term of a polynomial."))
(defgeneric lm (poly)
(:documentation "Returns the leading monomial of a polynomial.
That is, the leading term with 1 as coefficient"))
(defgeneric lc (poly)
(:documentation "Returns the leading coefficient of a polynomial"))
(defgeneric multideg (poly)
(:documentation "Returns the multidegree of a polynomial"))
(defun make-polynomial (term-list &key (ring *ring*))
(let ((poly (make-instance 'polynomial :ring ring)))
(dolist (elem term-list poly)
(setf poly
(add poly
(make-instance 'term
:coefficient (first elem)
:monomial (make-array (1- (length elem))
:initial-contents (rest elem))))))))
(defmacro doterms ((var poly &optional (resultform 'nil)) &body body)
(let ((mono (gensym "DOTERMS"))
(coef (gensym "DOTERMS")))
`(block nil
(loop for ,mono being the hash-keys of (terms ,poly) using (hash-value ,coef) do
(let ((,var (make-instance 'term :coefficient ,coef :monomial ,mono)))
,@body))
(return ,resultform))))
(defun mapterm (function polynomial)
"Apply FUNCTION to successive terms of POLYNOMIAL. Return list
of FUNCTION return values."
(let ((results nil))
(doterms (tt polynomial results)
(push (funcall function tt) results))))
(defmethod print-object ((p polynomial) stream)
(print-unreadable-object (p stream :type t)
(write-string (element->string p) stream)))
(defun terms->list (poly)
(mapterm #'identity poly))
(defmethod element->string ((poly polynomial) &key)
(assert poly)
(if (ring-zero-p poly)
(format nil "0")
(let ((term-list
(sort (terms->list poly) *monomial-ordering* :key #'monomial)))
(format nil "~a~{ ~a~}"
(element->string (first term-list)
:ring (base-ring poly)
:leading-term t)
(mapcar #'(lambda (x)
(element->string x :ring (base-ring poly)))
(rest term-list))))))
(defmethod ring-zero-p ((poly polynomial))
(zerop (hash-table-count (terms poly))))
(defmethod ring-copy ((poly polynomial))
"Returns a (deep) copy of the given polynomial"
(let ((new-poly (make-instance 'polynomial :ring (base-ring poly))))
(maphash #'(lambda (m c)
(setf (gethash (copy-seq m) (terms new-poly)) c))
(terms poly))
new-poly))
(defmethod lt ((poly polynomial))
(let ((term-list (terms->list poly)))
(first (sort term-list *monomial-ordering* :key #'monomial))))
(defmethod lc ((poly polynomial))
(coefficient (lt poly)))
(defmethod lm ((poly polynomial))
(monomial (lt poly)))
(defmethod multideg ((poly polynomial))
(lc poly))
|
7334913d9fbd961844d9d6c64c1e472af83239f2f820c287e6ba24157ef96650
|
lpgauth/foil
|
foil_server.erl
|
-module(foil_server).
-include("foil.hrl").
-export([
start_link/0
]).
-behaviour(metal).
-export([
init/3,
handle_msg/2,
terminate/2
]).
%% public
-spec start_link() ->
{ok, pid()}.
start_link() ->
metal:start_link(?SERVER, ?SERVER, undefined).
%% metal callbacks
-spec init(atom(), pid(), term()) ->
{ok, term()}.
init(_Name, _Parent, undefined) ->
ets:new(?FOIL_TABLE, [public, named_table]),
KVs = ets:tab2list(?FOIL_TABLE),
ok = foil_compiler:load(foil_modules, KVs),
{ok, undefined}.
-spec handle_msg(term(), term()) ->
{ok, term()}.
handle_msg({'ETS-TRANSFER', _, _, _}, State) ->
{ok, State}.
-spec terminate(term(), term()) ->
ok.
terminate(_Reason, _State) ->
ok.
| null |
https://raw.githubusercontent.com/lpgauth/foil/e462829855a745d8f20fb0508ae3eb8e323b03bd/src/foil_server.erl
|
erlang
|
public
metal callbacks
|
-module(foil_server).
-include("foil.hrl").
-export([
start_link/0
]).
-behaviour(metal).
-export([
init/3,
handle_msg/2,
terminate/2
]).
-spec start_link() ->
{ok, pid()}.
start_link() ->
metal:start_link(?SERVER, ?SERVER, undefined).
-spec init(atom(), pid(), term()) ->
{ok, term()}.
init(_Name, _Parent, undefined) ->
ets:new(?FOIL_TABLE, [public, named_table]),
KVs = ets:tab2list(?FOIL_TABLE),
ok = foil_compiler:load(foil_modules, KVs),
{ok, undefined}.
-spec handle_msg(term(), term()) ->
{ok, term()}.
handle_msg({'ETS-TRANSFER', _, _, _}, State) ->
{ok, State}.
-spec terminate(term(), term()) ->
ok.
terminate(_Reason, _State) ->
ok.
|
39d78798d52f4761f6f33396b508546dfc82e9011b882f5f7152080957875ad7
|
flavioc/cl-hurd
|
file-chown.lisp
|
(in-package :translator-test)
(def-test-method file-chown-test ((test fs-test))
(with-testport (p (file-name-lookup +translator-root+))
(let ((stat (io-stat p)))
(assert-equal 0 (stat-get stat 'st-uid))
(assert-equal 0 (stat-get stat 'st-gid))
(assert-true (file-chown p 101 102))
(setf stat (io-stat p))
(assert-equal 101 (stat-get stat 'st-uid))
(assert-equal 102 (stat-get stat 'st-gid))
(assert-true (file-chown p 0 0))
(setf stat (io-stat p))
(assert-equal 0 (stat-get stat 'st-uid))
(assert-equal 0 (stat-get stat 'st-gid)))))
| null |
https://raw.githubusercontent.com/flavioc/cl-hurd/982232f47d1a0ff4df5fde2edad03b9df871470a/tests/file-chown.lisp
|
lisp
|
(in-package :translator-test)
(def-test-method file-chown-test ((test fs-test))
(with-testport (p (file-name-lookup +translator-root+))
(let ((stat (io-stat p)))
(assert-equal 0 (stat-get stat 'st-uid))
(assert-equal 0 (stat-get stat 'st-gid))
(assert-true (file-chown p 101 102))
(setf stat (io-stat p))
(assert-equal 101 (stat-get stat 'st-uid))
(assert-equal 102 (stat-get stat 'st-gid))
(assert-true (file-chown p 0 0))
(setf stat (io-stat p))
(assert-equal 0 (stat-get stat 'st-uid))
(assert-equal 0 (stat-get stat 'st-gid)))))
|
|
94e7762b4ba0b2dd10760fab078f368e218f318d3f4a056a1424cd415a9805f8
|
spurious/sagittarius-scheme-mirror
|
treemap.scm
|
-*- mode : scheme ; coding : utf-8 -*-
;;;
;;; treemap.scm - treemap utilities
;;;
Copyright ( c ) 2010 - 2014 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(library (util treemap)
(export make-rb-treemap
make-rb-treemap/comparator
treemap?
treemap-ref
treemap-set!
treemap-delete!
treemap-update!
treemap-clear!
treemap-copy
treemap-contains?
treemap-size
treemap-entries treemap-entries-list
treemap-keys treemap-keys-list
treemap-values treemap-values-list
treemap-higher-entry treemap-lower-entry
treemap-first-entry treemap-last-entry
treemap-for-each treemap-map treemap-fold
treemap-for-each-reverse treemap-map-reverse treemap-fold-reverse
treemap-find/index treemap-reverse-find/index
treemap-find treemap-reverse-find
treemap->alist alist->treemap
)
(import (rnrs)
(only (core base) wrong-type-argument-message)
(clos user)
(sagittarius)
(sagittarius treemap)
(sagittarius object))
;; for generic ref
(define-method ref ((tm <tree-map>) key)
(treemap-ref tm key #f))
(define-method ref ((tm <tree-map>) key fallback)
(treemap-ref tm key fallback))
(define-method (setter ref) ((tm <tree-map>) key value)
(treemap-set! tm key value))
)
| null |
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/util/treemap.scm
|
scheme
|
coding : utf-8 -*-
treemap.scm - treemap utilities
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
for generic ref
|
Copyright ( c ) 2010 - 2014 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(library (util treemap)
(export make-rb-treemap
make-rb-treemap/comparator
treemap?
treemap-ref
treemap-set!
treemap-delete!
treemap-update!
treemap-clear!
treemap-copy
treemap-contains?
treemap-size
treemap-entries treemap-entries-list
treemap-keys treemap-keys-list
treemap-values treemap-values-list
treemap-higher-entry treemap-lower-entry
treemap-first-entry treemap-last-entry
treemap-for-each treemap-map treemap-fold
treemap-for-each-reverse treemap-map-reverse treemap-fold-reverse
treemap-find/index treemap-reverse-find/index
treemap-find treemap-reverse-find
treemap->alist alist->treemap
)
(import (rnrs)
(only (core base) wrong-type-argument-message)
(clos user)
(sagittarius)
(sagittarius treemap)
(sagittarius object))
(define-method ref ((tm <tree-map>) key)
(treemap-ref tm key #f))
(define-method ref ((tm <tree-map>) key fallback)
(treemap-ref tm key fallback))
(define-method (setter ref) ((tm <tree-map>) key value)
(treemap-set! tm key value))
)
|
5e4c64658c228484fc50f8c8f5439a322b079fa2cadffd95839898242ab04393
|
protz/mezzo
|
GADT4.ml
|
module Stage1 (X : sig
type ('a, 'kind) tag
type 'kind univ =
Univ : ('a, 'kind) tag * 'a -> 'kind univ
end) = struct
open X
type 'a methods = {
map: 'a -> 'a
}
type 'a ty =
| TyUniv : 'kind univ ty
| TyUnit : unit ty
| TyPair : 'a ty * 'b ty -> ('a * 'b) ty
| TyOpaque : 'a methods -> 'a ty
module Stage2 (Y : sig
val describe: ('a, 'kind) tag -> 'a ty
end) = struct
open Y
let rec map : type a . a ty -> a -> a =
fun ty x ->
match ty, x with
| TyUniv,
Univ (tag, arg) ->
let arg' = map (describe tag) arg in
if arg == arg' then
x
else
Univ (tag, arg')
| TyUnit,
() ->
()
| TyPair (ty1, ty2),
(x1, x2) ->
let x1' = map ty1 x1
and x2' = map ty2 x2 in
if x1 == x1' && x2 == x2' then
x
else
(x1', x2')
| TyOpaque { map },
x ->
map x
end
end
type 'name term (* a kind *)
module MyTag = struct
type ('a, 'kind) tag =
| TagVar : ('name, 'name term) tag
| TagAbs : ('name * 'name term univ, 'name term) tag
| TagApp : ('name term univ * 'name term univ, 'name term) tag
and 'kind univ =
Univ : ('a, 'kind) tag * 'a -> 'kind univ
end
module S1 = Stage1(MyTag)
module MyDescribe = struct
open MyTag
open S1
let ty_name : 'name ty =
TyOpaque { map = fun x -> x }
let ty_term : 'name term univ ty =
TyUniv
let describe : type a kind . (a, kind) tag -> a ty =
function
| TagVar ->
ty_name
| TagAbs ->
TyPair (ty_name, ty_term)
| TagApp ->
TyPair (ty_term, ty_term)
end
module S2 = S1.Stage2(MyDescribe)
module Test = struct
open MyTag
open MyDescribe
let map : 'name term univ -> 'name term univ = fun t -> S2.map ty_term t
let t : int term univ =
Univ (TagVar, 0)
let u : int term univ =
map t
let t : string term univ =
Univ (TagVar, "x")
let u : string term univ =
map t
let test (t : int term univ) : int term univ =
match t with
| Univ (TagApp, (
Univ (TagAbs, (x, t)),
u
)) ->
u
| u ->
u
end
| null |
https://raw.githubusercontent.com/protz/mezzo/4e9d917558bd96067437116341b7a6ea02ab9c39/alphaLib/GADT4.ml
|
ocaml
|
a kind
|
module Stage1 (X : sig
type ('a, 'kind) tag
type 'kind univ =
Univ : ('a, 'kind) tag * 'a -> 'kind univ
end) = struct
open X
type 'a methods = {
map: 'a -> 'a
}
type 'a ty =
| TyUniv : 'kind univ ty
| TyUnit : unit ty
| TyPair : 'a ty * 'b ty -> ('a * 'b) ty
| TyOpaque : 'a methods -> 'a ty
module Stage2 (Y : sig
val describe: ('a, 'kind) tag -> 'a ty
end) = struct
open Y
let rec map : type a . a ty -> a -> a =
fun ty x ->
match ty, x with
| TyUniv,
Univ (tag, arg) ->
let arg' = map (describe tag) arg in
if arg == arg' then
x
else
Univ (tag, arg')
| TyUnit,
() ->
()
| TyPair (ty1, ty2),
(x1, x2) ->
let x1' = map ty1 x1
and x2' = map ty2 x2 in
if x1 == x1' && x2 == x2' then
x
else
(x1', x2')
| TyOpaque { map },
x ->
map x
end
end
module MyTag = struct
type ('a, 'kind) tag =
| TagVar : ('name, 'name term) tag
| TagAbs : ('name * 'name term univ, 'name term) tag
| TagApp : ('name term univ * 'name term univ, 'name term) tag
and 'kind univ =
Univ : ('a, 'kind) tag * 'a -> 'kind univ
end
module S1 = Stage1(MyTag)
module MyDescribe = struct
open MyTag
open S1
let ty_name : 'name ty =
TyOpaque { map = fun x -> x }
let ty_term : 'name term univ ty =
TyUniv
let describe : type a kind . (a, kind) tag -> a ty =
function
| TagVar ->
ty_name
| TagAbs ->
TyPair (ty_name, ty_term)
| TagApp ->
TyPair (ty_term, ty_term)
end
module S2 = S1.Stage2(MyDescribe)
module Test = struct
open MyTag
open MyDescribe
let map : 'name term univ -> 'name term univ = fun t -> S2.map ty_term t
let t : int term univ =
Univ (TagVar, 0)
let u : int term univ =
map t
let t : string term univ =
Univ (TagVar, "x")
let u : string term univ =
map t
let test (t : int term univ) : int term univ =
match t with
| Univ (TagApp, (
Univ (TagAbs, (x, t)),
u
)) ->
u
| u ->
u
end
|
17359d811b5740a7a0cc4c1c3d3c6ba4812b9d0bba24620656669fdaf30ea290
|
fractalide/fractalide
|
loader.rkt
|
#lang racket
(require fractalide/modules/rkt/rkt-fbp/agent
fractalide/modules/rkt/rkt-fbp/def
fractalide/modules/rkt/rkt-fbp/graph)
(require (prefix-in g: graph)
json)
(define-agent
#:input '("in") ; in port
#:output '("out" "acc") ; out port
(define msg (recv (input "in")))
Convert fractalide / graph - > g : graph
(define g (g:directed-graph '()))
(for ([agt (graph-agent msg)])
(g:add-vertex! g (g-agent-name agt)))
(for ([edg (graph-edge msg)])
(g:add-directed-edge! g (g-edge-out edg) (g-edge-in edg)))
(for ([in (graph-virtual-in msg)])
(g:add-directed-edge! g
(string-append (g-virtual-virtual-port in)
(g-virtual-agent in)
(g-virtual-agent-port in))
(g-virtual-agent in)))
(for ([out (graph-virtual-out msg)])
(g:add-directed-edge! g
(g-virtual-agent out)
(string-append (g-virtual-agent out)
(g-virtual-agent-port out)
(g-virtual-virtual-port out))))
(for ([mesg (graph-mesg msg)])
(g:add-directed-edge! g
; TODO: possibility to have several mesg towards the same ports
(string-append "msg" (g-mesg-in mesg) (g-mesg-port-in mesg))
(g-mesg-in mesg)))
; Retrieve the position
(define opt-graph-tail (car (string-split (g:graphviz g) "digraph G {")))
(define opt-graph (string-append
"digraph G { node [shape=circle, width=1]; rankdir=LR;"
opt-graph-tail))
(define dot-path (find-executable-path "dot"))
(unless dot-path (error "'dot' not found on PATH"))
(define raw-json (with-output-to-string (lambda ()
(with-input-from-string opt-graph (lambda ()
(unless (equal? 0 (system*/exit-code dot-path "-Tjson"))
(error "Call to 'dot' failed.")))))))
(define json (string->jsexpr raw-json))
; Send the new graph
(define objects (hash-ref json 'objects))
(define nodes (make-hash))
(for ([obj objects])
(define pos (hash-ref obj 'pos #f))
(if pos
; True, display
(begin
(hash-set! nodes (hash-ref obj 'label) pos)
; (send (output "out") (cons 'add-node (vector (string->number (car pos))
( string->number ( cadr pos ) )
; (hash-ref obj 'name))))
)
; False, do nothing
(void)))
(for ([agt (graph-agent msg)])
(define pos (string-split (hash-ref nodes (g-agent-name agt)) ","))
(send (output "out") (cons 'add-node (vector (string->number (car pos))
(string->number (cadr pos))
(substring (g-agent-name agt) 1)
(g-agent-type agt)))))
(for ([msg (graph-mesg msg)])
(define pos (string-split (hash-ref nodes (string-append "msg" (g-mesg-in msg) (g-mesg-port-in msg))) ","))
(send (output "out") (cons 'add-mesg (vector (string->number (car pos))
(string->number (cadr pos))
(g-mesg-mesg msg)
(substring (g-mesg-in msg) 1)
(g-mesg-port-in msg)))))
(for ([edg (graph-edge msg)])
(send (output "out") (cons 'add-edge (vector (substring (g-edge-out edg) 1)
(g-edge-port-out edg)
(g-edge-selection-out edg)
(substring (g-edge-in edg) 1)
(g-edge-port-in edg)
(g-edge-selection-in edg)))))
(send (output "acc") msg))
| null |
https://raw.githubusercontent.com/fractalide/fractalide/9c54ec2615fcc2a1f3363292d4eed2a0fcb9c3a5/modules/rkt/rkt-fbp/agents/hyperflow/graph/loader.rkt
|
racket
|
in port
out port
TODO: possibility to have several mesg towards the same ports
Retrieve the position
Send the new graph
True, display
(send (output "out") (cons 'add-node (vector (string->number (car pos))
(hash-ref obj 'name))))
False, do nothing
|
#lang racket
(require fractalide/modules/rkt/rkt-fbp/agent
fractalide/modules/rkt/rkt-fbp/def
fractalide/modules/rkt/rkt-fbp/graph)
(require (prefix-in g: graph)
json)
(define-agent
(define msg (recv (input "in")))
Convert fractalide / graph - > g : graph
(define g (g:directed-graph '()))
(for ([agt (graph-agent msg)])
(g:add-vertex! g (g-agent-name agt)))
(for ([edg (graph-edge msg)])
(g:add-directed-edge! g (g-edge-out edg) (g-edge-in edg)))
(for ([in (graph-virtual-in msg)])
(g:add-directed-edge! g
(string-append (g-virtual-virtual-port in)
(g-virtual-agent in)
(g-virtual-agent-port in))
(g-virtual-agent in)))
(for ([out (graph-virtual-out msg)])
(g:add-directed-edge! g
(g-virtual-agent out)
(string-append (g-virtual-agent out)
(g-virtual-agent-port out)
(g-virtual-virtual-port out))))
(for ([mesg (graph-mesg msg)])
(g:add-directed-edge! g
(string-append "msg" (g-mesg-in mesg) (g-mesg-port-in mesg))
(g-mesg-in mesg)))
(define opt-graph-tail (car (string-split (g:graphviz g) "digraph G {")))
(define opt-graph (string-append
"digraph G { node [shape=circle, width=1]; rankdir=LR;"
opt-graph-tail))
(define dot-path (find-executable-path "dot"))
(unless dot-path (error "'dot' not found on PATH"))
(define raw-json (with-output-to-string (lambda ()
(with-input-from-string opt-graph (lambda ()
(unless (equal? 0 (system*/exit-code dot-path "-Tjson"))
(error "Call to 'dot' failed.")))))))
(define json (string->jsexpr raw-json))
(define objects (hash-ref json 'objects))
(define nodes (make-hash))
(for ([obj objects])
(define pos (hash-ref obj 'pos #f))
(if pos
(begin
(hash-set! nodes (hash-ref obj 'label) pos)
( string->number ( cadr pos ) )
)
(void)))
(for ([agt (graph-agent msg)])
(define pos (string-split (hash-ref nodes (g-agent-name agt)) ","))
(send (output "out") (cons 'add-node (vector (string->number (car pos))
(string->number (cadr pos))
(substring (g-agent-name agt) 1)
(g-agent-type agt)))))
(for ([msg (graph-mesg msg)])
(define pos (string-split (hash-ref nodes (string-append "msg" (g-mesg-in msg) (g-mesg-port-in msg))) ","))
(send (output "out") (cons 'add-mesg (vector (string->number (car pos))
(string->number (cadr pos))
(g-mesg-mesg msg)
(substring (g-mesg-in msg) 1)
(g-mesg-port-in msg)))))
(for ([edg (graph-edge msg)])
(send (output "out") (cons 'add-edge (vector (substring (g-edge-out edg) 1)
(g-edge-port-out edg)
(g-edge-selection-out edg)
(substring (g-edge-in edg) 1)
(g-edge-port-in edg)
(g-edge-selection-in edg)))))
(send (output "acc") msg))
|
e8d857323fe6151c3ae78979c6bfce2417b225b2b94ccb107c2e203699c95f67
|
examachine/parallpairs
|
test_score.ml
|
* *
* * Author : < >
* *
* * Copyright ( C ) 2011 - 2017 Gok Us Sibernetik Ar&Ge Ltd.
* *
* * This program is free software ; you can redistribute it and/or modify it under * * the terms of the Affero GNU General Public License as published by the Free
* * Software Foundation ; either version 3 of the License , or ( at your option )
* * any later version .
* *
* * Please read the COPYING file .
* *
**
** Author: Eray Ozkural <>
**
** Copyright (C) 2011-2017 Gok Us Sibernetik Ar&Ge Ltd.
**
** This program is free software; you can redistribute it and/or modify it under** the terms of the Affero GNU General Public License as published by the Free
** Software Foundation; either version 3 of the License, or (at your option)
** any later version.
**
** Please read the COPYING file.
**
*)
open Printf
open Parallel
open Util
open Score
open ScoreAccum
module Weight = Types.Fix32Weight
open Weight
let main () =
printf "testing merge_assoc_lists\n";
let a = [ (5,Weight.of_float 0.3); (2,Weight.of_float 0.6); (10,Weight.of_float 0.1)]
and b = [(10,Weight.of_float 0.2); (5, Weight.of_float 0.2); (4, Weight.of_float 0.4);]
and c = [(1, Weight.of_float 0.1); (0,Weight.of_float 0.9)] in
(let m = Score.merge_assoc_lists [ []; [] ] in
printf "test merging of two empty assoc lists";
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
(let m = Score.merge_assoc_lists [a;b] in
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
(printf "test new al merge routine, merge a b\n";
let m = Score.merge_als (Score.sort_al a) (Score.sort_al b) in
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
(printf "test new al merge routine, merge b c\n";
let m = merge_als (sort_al b) (sort_al c) in
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
( let a = [3;5;6;8] and b = [2;4;5;6;7;9] and c = [3;5] in
printf "test merge sets routine, merge a b=";
print_intlist (merge_sets a b);
printf "test merge sets routine, merge b c=";
print_intlist (merge_sets b c);
printf "test merge sets routine, merge a c=";
print_intlist (merge_sets a c);
printf "\n"
);
(
printf "test merge dynarray sets\n";
let a = Dynarray.make 0 in
let b = Dynarray.make 0 in
printf "a = "; Dynarray.print_int a;
printf ", b = "; Dynarray.print_int b;
let r = merge_dynarray_sets a b in
printf ", result = "; Dynarray.print_int r;
print_newline ()
);
(
printf "test merge dynarray sets\n";
let a = Dynarray.make 0 in
let b = Dynarray.make 0 in
Dynarray.append a 1;
Dynarray.append a 2;
Dynarray.append b 1;
Dynarray.append b 2;
Dynarray.append b 5;
printf "a = "; Dynarray.print_int a;
printf ", b = "; Dynarray.print_int b;
let r = merge_dynarray_sets a b in
printf ", result = "; Dynarray.print_int r;
print_newline ()
);
(
printf "test merge dynarray sets\n";
let a = Dynarray.make 0 in
let b = Dynarray.make 0 in
Dynarray.append a 0;
Dynarray.append a 1;
Dynarray.append a 3;
Dynarray.append a 5;
Dynarray.append a 9;
Dynarray.append b 1;
Dynarray.append b 5;
Dynarray.append b 6;
printf "a = "; Dynarray.print_int a;
printf ", b = "; Dynarray.print_int b;
let r = merge_dynarray_sets a b in
printf ", result = "; Dynarray.print_int r;
print_newline ()
);
(
printf "test merge dynarray pair merge\n";
let ay,aw = DynarrayPair.make 0 0 in
let by,bw = DynarrayPair.make 0 0 in
printf "a = "; Dynarray.print_int ay; Dynarray.print_int aw;
printf "b = "; Dynarray.print_int by; Dynarray.print_int bw;
let (ay',aw') = merge_dynarray_pair_sets (ay,aw) (by,bw) in
printf " result = ";
Dynarray.print_int ay'; Dynarray.print_int aw';
print_newline ()
);
(
printf "test merge dynarray pair merge\n";
let ay,aw = DynarrayPair.make 0 0 in
let by,bw = DynarrayPair.make 0 0 in
DynarrayPair.append (ay,aw) 1 5;
DynarrayPair.append (ay,aw) 2 3;
DynarrayPair.append (by,bw) 1 3;
DynarrayPair.append (by,bw) 2 1;
DynarrayPair.append (by,bw) 5 2;
printf "a = "; Dynarray.print_int ay; Dynarray.print_int aw;
printf "b = "; Dynarray.print_int by; Dynarray.print_int bw;
let (ay',aw') = merge_dynarray_pair_sets (ay,aw) (by,bw) in
printf " result = ";
Dynarray.print_int ay'; Dynarray.print_int aw';
print_newline ()
);
(
printf "test merge dynarray pair merge\n";
let ay,aw = DynarrayPair.make 0 0 in
let by,bw = DynarrayPair.make 0 0 in
DynarrayPair.append (ay,aw) 0 3;
DynarrayPair.append (ay,aw) 4 8;
DynarrayPair.append (ay,aw) 6 2;
DynarrayPair.append (by,bw) 1 2;
DynarrayPair.append (by,bw) 3 2;
DynarrayPair.append (by,bw) 4 5;
printf "a = "; Dynarray.print_int ay; Dynarray.print_int aw;
printf "b = "; Dynarray.print_int by; Dynarray.print_int bw;
let (ay',aw') = merge_dynarray_pair_sets (ay,aw) (by,bw) in
printf " result = ";
Dynarray.print_int ay'; Dynarray.print_int aw';
print_newline ()
)
;;
main ()
| null |
https://raw.githubusercontent.com/examachine/parallpairs/6fafe8d6de3a55490cb8ed5ffd3493a28a914e0a/src/test_score.ml
|
ocaml
|
* *
* * Author : < >
* *
* * Copyright ( C ) 2011 - 2017 Gok Us Sibernetik Ar&Ge Ltd.
* *
* * This program is free software ; you can redistribute it and/or modify it under * * the terms of the Affero GNU General Public License as published by the Free
* * Software Foundation ; either version 3 of the License , or ( at your option )
* * any later version .
* *
* * Please read the COPYING file .
* *
**
** Author: Eray Ozkural <>
**
** Copyright (C) 2011-2017 Gok Us Sibernetik Ar&Ge Ltd.
**
** This program is free software; you can redistribute it and/or modify it under** the terms of the Affero GNU General Public License as published by the Free
** Software Foundation; either version 3 of the License, or (at your option)
** any later version.
**
** Please read the COPYING file.
**
*)
open Printf
open Parallel
open Util
open Score
open ScoreAccum
module Weight = Types.Fix32Weight
open Weight
let main () =
printf "testing merge_assoc_lists\n";
let a = [ (5,Weight.of_float 0.3); (2,Weight.of_float 0.6); (10,Weight.of_float 0.1)]
and b = [(10,Weight.of_float 0.2); (5, Weight.of_float 0.2); (4, Weight.of_float 0.4);]
and c = [(1, Weight.of_float 0.1); (0,Weight.of_float 0.9)] in
(let m = Score.merge_assoc_lists [ []; [] ] in
printf "test merging of two empty assoc lists";
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
(let m = Score.merge_assoc_lists [a;b] in
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
(printf "test new al merge routine, merge a b\n";
let m = Score.merge_als (Score.sort_al a) (Score.sort_al b) in
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
(printf "test new al merge routine, merge b c\n";
let m = merge_als (sort_al b) (sort_al c) in
print_list (fun (x,y) -> printf "(%d,%f)" x (Weight.to_float y)) m;
printf "\n");
( let a = [3;5;6;8] and b = [2;4;5;6;7;9] and c = [3;5] in
printf "test merge sets routine, merge a b=";
print_intlist (merge_sets a b);
printf "test merge sets routine, merge b c=";
print_intlist (merge_sets b c);
printf "test merge sets routine, merge a c=";
print_intlist (merge_sets a c);
printf "\n"
);
(
printf "test merge dynarray sets\n";
let a = Dynarray.make 0 in
let b = Dynarray.make 0 in
printf "a = "; Dynarray.print_int a;
printf ", b = "; Dynarray.print_int b;
let r = merge_dynarray_sets a b in
printf ", result = "; Dynarray.print_int r;
print_newline ()
);
(
printf "test merge dynarray sets\n";
let a = Dynarray.make 0 in
let b = Dynarray.make 0 in
Dynarray.append a 1;
Dynarray.append a 2;
Dynarray.append b 1;
Dynarray.append b 2;
Dynarray.append b 5;
printf "a = "; Dynarray.print_int a;
printf ", b = "; Dynarray.print_int b;
let r = merge_dynarray_sets a b in
printf ", result = "; Dynarray.print_int r;
print_newline ()
);
(
printf "test merge dynarray sets\n";
let a = Dynarray.make 0 in
let b = Dynarray.make 0 in
Dynarray.append a 0;
Dynarray.append a 1;
Dynarray.append a 3;
Dynarray.append a 5;
Dynarray.append a 9;
Dynarray.append b 1;
Dynarray.append b 5;
Dynarray.append b 6;
printf "a = "; Dynarray.print_int a;
printf ", b = "; Dynarray.print_int b;
let r = merge_dynarray_sets a b in
printf ", result = "; Dynarray.print_int r;
print_newline ()
);
(
printf "test merge dynarray pair merge\n";
let ay,aw = DynarrayPair.make 0 0 in
let by,bw = DynarrayPair.make 0 0 in
printf "a = "; Dynarray.print_int ay; Dynarray.print_int aw;
printf "b = "; Dynarray.print_int by; Dynarray.print_int bw;
let (ay',aw') = merge_dynarray_pair_sets (ay,aw) (by,bw) in
printf " result = ";
Dynarray.print_int ay'; Dynarray.print_int aw';
print_newline ()
);
(
printf "test merge dynarray pair merge\n";
let ay,aw = DynarrayPair.make 0 0 in
let by,bw = DynarrayPair.make 0 0 in
DynarrayPair.append (ay,aw) 1 5;
DynarrayPair.append (ay,aw) 2 3;
DynarrayPair.append (by,bw) 1 3;
DynarrayPair.append (by,bw) 2 1;
DynarrayPair.append (by,bw) 5 2;
printf "a = "; Dynarray.print_int ay; Dynarray.print_int aw;
printf "b = "; Dynarray.print_int by; Dynarray.print_int bw;
let (ay',aw') = merge_dynarray_pair_sets (ay,aw) (by,bw) in
printf " result = ";
Dynarray.print_int ay'; Dynarray.print_int aw';
print_newline ()
);
(
printf "test merge dynarray pair merge\n";
let ay,aw = DynarrayPair.make 0 0 in
let by,bw = DynarrayPair.make 0 0 in
DynarrayPair.append (ay,aw) 0 3;
DynarrayPair.append (ay,aw) 4 8;
DynarrayPair.append (ay,aw) 6 2;
DynarrayPair.append (by,bw) 1 2;
DynarrayPair.append (by,bw) 3 2;
DynarrayPair.append (by,bw) 4 5;
printf "a = "; Dynarray.print_int ay; Dynarray.print_int aw;
printf "b = "; Dynarray.print_int by; Dynarray.print_int bw;
let (ay',aw') = merge_dynarray_pair_sets (ay,aw) (by,bw) in
printf " result = ";
Dynarray.print_int ay'; Dynarray.print_int aw';
print_newline ()
)
;;
main ()
|
|
82bad2fd2949f3fe75c30f191a0b0fb33188246521373e00d957b6c7d33f485c
|
wenkokke/MonoProc
|
TestCP1.hs
|
module Main where
import PROC
import PROC.MF.Analysis.CP
import PROC.Testing (testAnalysis)
import PROC.Parsing (pCP)
import Data.Foldable (forM_)
import Text.Printf (printf)
import qualified Data.Set as S (toList)
import Text.ParserCombinators.UU.Utils (runParser)
because CP analysis is non - distributive , I 'm testing the MFP against the MOP
solution ( for a known program where MOP works ) to see that at each program
point the result of MFP refines that of MOP .
this is different than with the other analyses where I 'm testing that the MOP
and the MFP solutions both give the exact same results .
test1 = analyse mfp mfCP progCP
test2 = analyse mop mfCP progCP
main :: IO ()
main = do testAnalysis mop mfCP progCP reslCP
testAnalysis mfp mfCP progCP reslCP
-- this one is kinda superfluous, since if we know that the
results are reslCP1 and reslCP2 , and we know that the refinement
-- relation holds between these... well, then this will always succeed...
let mopCP = analyse mop mfCP progCP
let mfpCP = analyse mfp mfCP progCP
let (<:) = refines (getL $ mfCP progCP)
forM_ (S.toList $ labels progCP) $ \l -> do
let mop = mopCP l
let mfp = mfpCP l
if mfp <: mop
then return ()
else fail (printf "expected refinement of %s, found %s (at %d)" (show mop) (show mfp) l)
progCP :: Prog
progCP = mkProg
[ "x = 2;"
, "y = 4;"
, "x = 1;"
, "if (y < x) {"
, " z = y;"
, "}"
, "else {"
, " z = y * y;"
, "}"
, "x = z;"
]
|The result of a MOP CP analysis of @progCP@.
reslCP :: [(Label,CP)]
reslCP = cps
[ "{(x,2)}"
, "{(x,2),(y,4)}"
, "{(x,1),(y,4)}"
, "{(x,1),(y,4)}"
, "{(x,1),(y,4),(z,4)}"
, "{(x,1),(y,4),(z,16)}"
, "{(x,T),(y,4),(z,T)}"
]
cps :: [String] -> [(Label,CP)]
cps = zip [1..] . map (runParser "stdin" pCP)
| null |
https://raw.githubusercontent.com/wenkokke/MonoProc/c3d00bd55ee8a6f2c12ebf5abb226c731e856350/test/TestCP1.hs
|
haskell
|
this one is kinda superfluous, since if we know that the
relation holds between these... well, then this will always succeed...
|
module Main where
import PROC
import PROC.MF.Analysis.CP
import PROC.Testing (testAnalysis)
import PROC.Parsing (pCP)
import Data.Foldable (forM_)
import Text.Printf (printf)
import qualified Data.Set as S (toList)
import Text.ParserCombinators.UU.Utils (runParser)
because CP analysis is non - distributive , I 'm testing the MFP against the MOP
solution ( for a known program where MOP works ) to see that at each program
point the result of MFP refines that of MOP .
this is different than with the other analyses where I 'm testing that the MOP
and the MFP solutions both give the exact same results .
test1 = analyse mfp mfCP progCP
test2 = analyse mop mfCP progCP
main :: IO ()
main = do testAnalysis mop mfCP progCP reslCP
testAnalysis mfp mfCP progCP reslCP
results are reslCP1 and reslCP2 , and we know that the refinement
let mopCP = analyse mop mfCP progCP
let mfpCP = analyse mfp mfCP progCP
let (<:) = refines (getL $ mfCP progCP)
forM_ (S.toList $ labels progCP) $ \l -> do
let mop = mopCP l
let mfp = mfpCP l
if mfp <: mop
then return ()
else fail (printf "expected refinement of %s, found %s (at %d)" (show mop) (show mfp) l)
progCP :: Prog
progCP = mkProg
[ "x = 2;"
, "y = 4;"
, "x = 1;"
, "if (y < x) {"
, " z = y;"
, "}"
, "else {"
, " z = y * y;"
, "}"
, "x = z;"
]
|The result of a MOP CP analysis of @progCP@.
reslCP :: [(Label,CP)]
reslCP = cps
[ "{(x,2)}"
, "{(x,2),(y,4)}"
, "{(x,1),(y,4)}"
, "{(x,1),(y,4)}"
, "{(x,1),(y,4),(z,4)}"
, "{(x,1),(y,4),(z,16)}"
, "{(x,T),(y,4),(z,T)}"
]
cps :: [String] -> [(Label,CP)]
cps = zip [1..] . map (runParser "stdin" pCP)
|
e548851197d4d6f9d1cb645b685e9c27b95eafb69e753912446b9c5ed95af01a
|
jaredly/reason-language-server
|
depend.ml
|
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Asttypes
open Location
open Longident
open Parsetree
let pp_deps = ref []
module StringSet = Set.Make(struct type t = string let compare = compare end)
module StringMap = Map.Make(String)
(* Module resolution map *)
(* Node (set of imports for this path, map for submodules) *)
type map_tree = Node of StringSet.t * bound_map
and bound_map = map_tree StringMap.t
let bound = Node (StringSet.empty, StringMap.empty)
(*let get_free (Node (s, _m)) = s*)
let get_map (Node (_s, m)) = m
let make_leaf s = Node (StringSet.singleton s, StringMap.empty)
let make_node m = Node (StringSet.empty, m)
let rec weaken_map s (Node(s0,m0)) =
Node (StringSet.union s s0, StringMap.map (weaken_map s) m0)
let rec collect_free (Node (s, m)) =
StringMap.fold (fun _ n -> StringSet.union (collect_free n)) m s
(* Returns the imports required to access the structure at path p *)
Only raises Not_found if the head of p is not in the toplevel map
let rec lookup_free p m =
match p with
[] -> raise Not_found
| s::p ->
let Node (f, m') = StringMap.find s m in
try lookup_free p m' with Not_found -> f
(* Returns the node corresponding to the structure at path p *)
let rec lookup_map lid m =
match lid with
Lident s -> StringMap.find s m
| Ldot (l, s) -> StringMap.find s (get_map (lookup_map l m))
| Lapply _ -> raise Not_found
(* Collect free module identifiers in the a.s.t. *)
let free_structure_names = ref StringSet.empty
let add_names s =
free_structure_names := StringSet.union s !free_structure_names
let rec add_path bv ?(p=[]) = function
| Lident s ->
let free =
try lookup_free (s::p) bv with Not_found -> StringSet.singleton s
in
StringSet.iter ( fun s - > Printf.eprintf " % s " s ) free ;
prerr_endline " " ;
prerr_endline "";*)
add_names free
| Ldot(l, s) -> add_path bv ~p:(s::p) l
| Lapply(l1, l2) -> add_path bv l1; add_path bv l2
let open_module bv lid =
match lookup_map lid bv with
| Node (s, m) ->
add_names s;
StringMap.fold StringMap.add m bv
| exception Not_found ->
add_path bv lid; bv
let add_parent bv lid =
match lid.txt with
Ldot(l, _s) -> add_path bv l
| _ -> ()
let add = add_parent
let add_module_path bv lid = add_path bv lid.txt
let handle_extension ext =
match (fst ext).txt with
| "error" | "ocaml.error" ->
raise (Location.Error
(Builtin_attributes.error_of_extension ext))
| _ ->
()
let rec add_type bv ty =
match ty.ptyp_desc with
Ptyp_any -> ()
| Ptyp_var _ -> ()
| Ptyp_arrow(_, t1, t2) -> add_type bv t1; add_type bv t2
| Ptyp_tuple tl -> List.iter (add_type bv) tl
| Ptyp_constr(c, tl) -> add bv c; List.iter (add_type bv) tl
| Ptyp_object (fl, _) ->
List.iter
(function Otag (_, _, t) -> add_type bv t
| Oinherit t -> add_type bv t) fl
| Ptyp_class(c, tl) -> add bv c; List.iter (add_type bv) tl
| Ptyp_alias(t, _) -> add_type bv t
| Ptyp_variant(fl, _, _) ->
List.iter
(function Rtag(_,_,_,stl) -> List.iter (add_type bv) stl
| Rinherit sty -> add_type bv sty)
fl
| Ptyp_poly(_, t) -> add_type bv t
| Ptyp_package pt -> add_package_type bv pt
| Ptyp_extension e -> handle_extension e
and add_package_type bv (lid, l) =
add bv lid;
List.iter (add_type bv) (List.map (fun (_, e) -> e) l)
let add_opt add_fn bv = function
None -> ()
| Some x -> add_fn bv x
let add_constructor_arguments bv = function
| Pcstr_tuple l -> List.iter (add_type bv) l
| Pcstr_record l -> List.iter (fun l -> add_type bv l.pld_type) l
let add_constructor_decl bv pcd =
add_constructor_arguments bv pcd.pcd_args;
Misc.may (add_type bv) pcd.pcd_res
let add_type_declaration bv td =
List.iter
(fun (ty1, ty2, _) -> add_type bv ty1; add_type bv ty2)
td.ptype_cstrs;
add_opt add_type bv td.ptype_manifest;
let add_tkind = function
Ptype_abstract -> ()
| Ptype_variant cstrs ->
List.iter (add_constructor_decl bv) cstrs
| Ptype_record lbls ->
List.iter (fun pld -> add_type bv pld.pld_type) lbls
| Ptype_open -> () in
add_tkind td.ptype_kind
let add_extension_constructor bv ext =
match ext.pext_kind with
Pext_decl(args, rty) ->
add_constructor_arguments bv args;
Misc.may (add_type bv) rty
| Pext_rebind lid -> add bv lid
let add_type_extension bv te =
add bv te.ptyext_path;
List.iter (add_extension_constructor bv) te.ptyext_constructors
let rec add_class_type bv cty =
match cty.pcty_desc with
Pcty_constr(l, tyl) ->
add bv l; List.iter (add_type bv) tyl
| Pcty_signature { pcsig_self = ty; pcsig_fields = fieldl } ->
add_type bv ty;
List.iter (add_class_type_field bv) fieldl
| Pcty_arrow(_, ty1, cty2) ->
add_type bv ty1; add_class_type bv cty2
| Pcty_extension e -> handle_extension e
| Pcty_open (_ovf, m, e) ->
let bv = open_module bv m.txt in add_class_type bv e
and add_class_type_field bv pctf =
match pctf.pctf_desc with
Pctf_inherit cty -> add_class_type bv cty
| Pctf_val(_, _, _, ty) -> add_type bv ty
| Pctf_method(_, _, _, ty) -> add_type bv ty
| Pctf_constraint(ty1, ty2) -> add_type bv ty1; add_type bv ty2
| Pctf_attribute _ -> ()
| Pctf_extension e -> handle_extension e
let add_class_description bv infos =
add_class_type bv infos.pci_expr
let add_class_type_declaration = add_class_description
let pattern_bv = ref StringMap.empty
let rec add_pattern bv pat =
match pat.ppat_desc with
Ppat_any -> ()
| Ppat_var _ -> ()
| Ppat_alias(p, _) -> add_pattern bv p
| Ppat_interval _
| Ppat_constant _ -> ()
| Ppat_tuple pl -> List.iter (add_pattern bv) pl
| Ppat_construct(c, op) -> add bv c; add_opt add_pattern bv op
| Ppat_record(pl, _) ->
List.iter (fun (lbl, p) -> add bv lbl; add_pattern bv p) pl
| Ppat_array pl -> List.iter (add_pattern bv) pl
| Ppat_or(p1, p2) -> add_pattern bv p1; add_pattern bv p2
| Ppat_constraint(p, ty) -> add_pattern bv p; add_type bv ty
| Ppat_variant(_, op) -> add_opt add_pattern bv op
| Ppat_type li -> add bv li
| Ppat_lazy p -> add_pattern bv p
| Ppat_unpack id -> pattern_bv := StringMap.add id.txt bound !pattern_bv
| Ppat_open ( m, p) -> let bv = open_module bv m.txt in add_pattern bv p
| Ppat_exception p -> add_pattern bv p
| Ppat_extension e -> handle_extension e
let add_pattern bv pat =
pattern_bv := bv;
add_pattern bv pat;
!pattern_bv
let rec add_expr bv exp =
match exp.pexp_desc with
Pexp_ident l -> add bv l
| Pexp_constant _ -> ()
| Pexp_let(rf, pel, e) ->
let bv = add_bindings rf bv pel in add_expr bv e
| Pexp_fun (_, opte, p, e) ->
add_opt add_expr bv opte; add_expr (add_pattern bv p) e
| Pexp_function pel ->
add_cases bv pel
| Pexp_apply(e, el) ->
add_expr bv e; List.iter (fun (_,e) -> add_expr bv e) el
| Pexp_match(e, pel) -> add_expr bv e; add_cases bv pel
| Pexp_try(e, pel) -> add_expr bv e; add_cases bv pel
| Pexp_tuple el -> List.iter (add_expr bv) el
| Pexp_construct(c, opte) -> add bv c; add_opt add_expr bv opte
| Pexp_variant(_, opte) -> add_opt add_expr bv opte
| Pexp_record(lblel, opte) ->
List.iter (fun (lbl, e) -> add bv lbl; add_expr bv e) lblel;
add_opt add_expr bv opte
| Pexp_field(e, fld) -> add_expr bv e; add bv fld
| Pexp_setfield(e1, fld, e2) -> add_expr bv e1; add bv fld; add_expr bv e2
| Pexp_array el -> List.iter (add_expr bv) el
| Pexp_ifthenelse(e1, e2, opte3) ->
add_expr bv e1; add_expr bv e2; add_opt add_expr bv opte3
| Pexp_sequence(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexp_while(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexp_for( _, e1, e2, _, e3) ->
add_expr bv e1; add_expr bv e2; add_expr bv e3
| Pexp_coerce(e1, oty2, ty3) ->
add_expr bv e1;
add_opt add_type bv oty2;
add_type bv ty3
| Pexp_constraint(e1, ty2) ->
add_expr bv e1;
add_type bv ty2
| Pexp_send(e, _m) -> add_expr bv e
| Pexp_new li -> add bv li
| Pexp_setinstvar(_v, e) -> add_expr bv e
| Pexp_override sel -> List.iter (fun (_s, e) -> add_expr bv e) sel
| Pexp_letmodule(id, m, e) ->
let b = add_module_binding bv m in
add_expr (StringMap.add id.txt b bv) e
| Pexp_letexception(_, e) -> add_expr bv e
| Pexp_assert (e) -> add_expr bv e
| Pexp_lazy (e) -> add_expr bv e
| Pexp_poly (e, t) -> add_expr bv e; add_opt add_type bv t
| Pexp_object { pcstr_self = pat; pcstr_fields = fieldl } ->
let bv = add_pattern bv pat in List.iter (add_class_field bv) fieldl
| Pexp_newtype (_, e) -> add_expr bv e
| Pexp_pack m -> add_module_expr bv m
| Pexp_open (_ovf, m, e) ->
let bv = open_module bv m.txt in add_expr bv e
| Pexp_extension (({ txt = ("ocaml.extension_constructor"|
"extension_constructor"); _ },
PStr [item]) as e) ->
begin match item.pstr_desc with
| Pstr_eval ({ pexp_desc = Pexp_construct (c, None) }, _) -> add bv c
| _ -> handle_extension e
end
| Pexp_extension e -> handle_extension e
| Pexp_unreachable -> ()
and add_cases bv cases =
List.iter (add_case bv) cases
and add_case bv {pc_lhs; pc_guard; pc_rhs} =
let bv = add_pattern bv pc_lhs in
add_opt add_expr bv pc_guard;
add_expr bv pc_rhs
and add_bindings recf bv pel =
let bv' = List.fold_left (fun bv x -> add_pattern bv x.pvb_pat) bv pel in
let bv = if recf = Recursive then bv' else bv in
List.iter (fun x -> add_expr bv x.pvb_expr) pel;
bv'
and add_modtype bv mty =
match mty.pmty_desc with
Pmty_ident l -> add bv l
| Pmty_alias l -> add_module_path bv l
| Pmty_signature s -> add_signature bv s
| Pmty_functor(id, mty1, mty2) ->
Misc.may (add_modtype bv) mty1;
add_modtype (StringMap.add id.txt bound bv) mty2
| Pmty_with(mty, cstrl) ->
add_modtype bv mty;
List.iter
(function
| Pwith_type (_, td) -> add_type_declaration bv td
| Pwith_module (_, lid) -> add_module_path bv lid
| Pwith_typesubst (_, td) -> add_type_declaration bv td
| Pwith_modsubst (_, lid) -> add_module_path bv lid
)
cstrl
| Pmty_typeof m -> add_module_expr bv m
| Pmty_extension e -> handle_extension e
and add_module_alias bv l =
If we are in delayed dependencies mode , we delay the dependencies
induced by " s "
induced by "Lident s" *)
(if !Clflags.transparent_modules then add_parent else add_module_path) bv l;
try
lookup_map l.txt bv
with Not_found ->
match l.txt with
Lident s -> make_leaf s
| _ -> add_module_path bv l; bound (* cannot delay *)
and add_modtype_binding bv mty =
match mty.pmty_desc with
Pmty_alias l ->
add_module_alias bv l
| Pmty_signature s ->
make_node (add_signature_binding bv s)
| Pmty_typeof modl ->
add_module_binding bv modl
| _ ->
add_modtype bv mty; bound
and add_signature bv sg =
ignore (add_signature_binding bv sg)
and add_signature_binding bv sg =
snd (List.fold_left add_sig_item (bv, StringMap.empty) sg)
and add_sig_item (bv, m) item =
match item.psig_desc with
Psig_value vd ->
add_type bv vd.pval_type; (bv, m)
| Psig_type (_, dcls) ->
List.iter (add_type_declaration bv) dcls; (bv, m)
| Psig_typext te ->
add_type_extension bv te; (bv, m)
| Psig_exception pext ->
add_extension_constructor bv pext; (bv, m)
| Psig_module pmd ->
let m' = add_modtype_binding bv pmd.pmd_type in
let add = StringMap.add pmd.pmd_name.txt m' in
(add bv, add m)
| Psig_recmodule decls ->
let add =
List.fold_right (fun pmd -> StringMap.add pmd.pmd_name.txt bound)
decls
in
let bv' = add bv and m' = add m in
List.iter (fun pmd -> add_modtype bv' pmd.pmd_type) decls;
(bv', m')
| Psig_modtype x ->
begin match x.pmtd_type with
None -> ()
| Some mty -> add_modtype bv mty
end;
(bv, m)
| Psig_open od ->
(open_module bv od.popen_lid.txt, m)
| Psig_include incl ->
let Node (s, m') = add_modtype_binding bv incl.pincl_mod in
add_names s;
let add = StringMap.fold StringMap.add m' in
(add bv, add m)
| Psig_class cdl ->
List.iter (add_class_description bv) cdl; (bv, m)
| Psig_class_type cdtl ->
List.iter (add_class_type_declaration bv) cdtl; (bv, m)
| Psig_attribute _ -> (bv, m)
| Psig_extension (e, _) ->
handle_extension e;
(bv, m)
and add_module_binding bv modl =
match modl.pmod_desc with
Pmod_ident l -> add_module_alias bv l
| Pmod_structure s ->
make_node (snd @@ add_structure_binding bv s)
| _ -> add_module_expr bv modl; bound
and add_module_expr bv modl =
match modl.pmod_desc with
Pmod_ident l -> add_module_path bv l
| Pmod_structure s -> ignore (add_structure bv s)
| Pmod_functor(id, mty, modl) ->
Misc.may (add_modtype bv) mty;
add_module_expr (StringMap.add id.txt bound bv) modl
| Pmod_apply(mod1, mod2) ->
add_module_expr bv mod1; add_module_expr bv mod2
| Pmod_constraint(modl, mty) ->
add_module_expr bv modl; add_modtype bv mty
| Pmod_unpack(e) ->
add_expr bv e
| Pmod_extension e ->
handle_extension e
and add_structure bv item_list =
let (bv, m) = add_structure_binding bv item_list in
add_names (collect_free (make_node m));
bv
and add_structure_binding bv item_list =
List.fold_left add_struct_item (bv, StringMap.empty) item_list
and add_struct_item (bv, m) item : _ StringMap.t * _ StringMap.t =
match item.pstr_desc with
Pstr_eval (e, _attrs) ->
add_expr bv e; (bv, m)
| Pstr_value(rf, pel) ->
let bv = add_bindings rf bv pel in (bv, m)
| Pstr_primitive vd ->
add_type bv vd.pval_type; (bv, m)
| Pstr_type (_, dcls) ->
List.iter (add_type_declaration bv) dcls; (bv, m)
| Pstr_typext te ->
add_type_extension bv te;
(bv, m)
| Pstr_exception pext ->
add_extension_constructor bv pext; (bv, m)
| Pstr_module x ->
let b = add_module_binding bv x.pmb_expr in
let add = StringMap.add x.pmb_name.txt b in
(add bv, add m)
| Pstr_recmodule bindings ->
let add =
List.fold_right (fun x -> StringMap.add x.pmb_name.txt bound) bindings
in
let bv' = add bv and m = add m in
List.iter
(fun x -> add_module_expr bv' x.pmb_expr)
bindings;
(bv', m)
| Pstr_modtype x ->
begin match x.pmtd_type with
None -> ()
| Some mty -> add_modtype bv mty
end;
(bv, m)
| Pstr_open od ->
(open_module bv od.popen_lid.txt, m)
| Pstr_class cdl ->
List.iter (add_class_declaration bv) cdl; (bv, m)
| Pstr_class_type cdtl ->
List.iter (add_class_type_declaration bv) cdtl; (bv, m)
| Pstr_include incl ->
let Node (s, m') as n = add_module_binding bv incl.pincl_mod in
if !Clflags.transparent_modules then
add_names s
else
(* If we are not in the delayed dependency mode, we need to
collect all delayed dependencies imported by the include statement *)
add_names (collect_free n);
let add = StringMap.fold StringMap.add m' in
(add bv, add m)
| Pstr_attribute _ -> (bv, m)
| Pstr_extension (e, _) ->
handle_extension e;
(bv, m)
and add_use_file bv top_phrs =
ignore (List.fold_left add_top_phrase bv top_phrs)
and add_implementation bv l =
ignore (add_structure_binding bv l)
and add_implementation_binding bv l =
snd (add_structure_binding bv l)
and add_top_phrase bv = function
| Ptop_def str -> add_structure bv str
| Ptop_dir (_, _) -> bv
and add_class_expr bv ce =
match ce.pcl_desc with
Pcl_constr(l, tyl) ->
add bv l; List.iter (add_type bv) tyl
| Pcl_structure { pcstr_self = pat; pcstr_fields = fieldl } ->
let bv = add_pattern bv pat in List.iter (add_class_field bv) fieldl
| Pcl_fun(_, opte, pat, ce) ->
add_opt add_expr bv opte;
let bv = add_pattern bv pat in add_class_expr bv ce
| Pcl_apply(ce, exprl) ->
add_class_expr bv ce; List.iter (fun (_,e) -> add_expr bv e) exprl
| Pcl_let(rf, pel, ce) ->
let bv = add_bindings rf bv pel in add_class_expr bv ce
| Pcl_constraint(ce, ct) ->
add_class_expr bv ce; add_class_type bv ct
| Pcl_extension e -> handle_extension e
| Pcl_open (_ovf, m, e) ->
let bv = open_module bv m.txt in add_class_expr bv e
and add_class_field bv pcf =
match pcf.pcf_desc with
Pcf_inherit(_, ce, _) -> add_class_expr bv ce
| Pcf_val(_, _, Cfk_concrete (_, e))
| Pcf_method(_, _, Cfk_concrete (_, e)) -> add_expr bv e
| Pcf_val(_, _, Cfk_virtual ty)
| Pcf_method(_, _, Cfk_virtual ty) -> add_type bv ty
| Pcf_constraint(ty1, ty2) -> add_type bv ty1; add_type bv ty2
| Pcf_initializer e -> add_expr bv e
| Pcf_attribute _ -> ()
| Pcf_extension e -> handle_extension e
and add_class_declaration bv decl =
add_class_expr bv decl.pci_expr
| null |
https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/407/depend.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.
************************************************************************
Module resolution map
Node (set of imports for this path, map for submodules)
let get_free (Node (s, _m)) = s
Returns the imports required to access the structure at path p
Returns the node corresponding to the structure at path p
Collect free module identifiers in the a.s.t.
cannot delay
If we are not in the delayed dependency mode, we need to
collect all delayed dependencies imported by the include statement
|
, projet Cristal , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Asttypes
open Location
open Longident
open Parsetree
let pp_deps = ref []
module StringSet = Set.Make(struct type t = string let compare = compare end)
module StringMap = Map.Make(String)
type map_tree = Node of StringSet.t * bound_map
and bound_map = map_tree StringMap.t
let bound = Node (StringSet.empty, StringMap.empty)
let get_map (Node (_s, m)) = m
let make_leaf s = Node (StringSet.singleton s, StringMap.empty)
let make_node m = Node (StringSet.empty, m)
let rec weaken_map s (Node(s0,m0)) =
Node (StringSet.union s s0, StringMap.map (weaken_map s) m0)
let rec collect_free (Node (s, m)) =
StringMap.fold (fun _ n -> StringSet.union (collect_free n)) m s
Only raises Not_found if the head of p is not in the toplevel map
let rec lookup_free p m =
match p with
[] -> raise Not_found
| s::p ->
let Node (f, m') = StringMap.find s m in
try lookup_free p m' with Not_found -> f
let rec lookup_map lid m =
match lid with
Lident s -> StringMap.find s m
| Ldot (l, s) -> StringMap.find s (get_map (lookup_map l m))
| Lapply _ -> raise Not_found
let free_structure_names = ref StringSet.empty
let add_names s =
free_structure_names := StringSet.union s !free_structure_names
let rec add_path bv ?(p=[]) = function
| Lident s ->
let free =
try lookup_free (s::p) bv with Not_found -> StringSet.singleton s
in
StringSet.iter ( fun s - > Printf.eprintf " % s " s ) free ;
prerr_endline " " ;
prerr_endline "";*)
add_names free
| Ldot(l, s) -> add_path bv ~p:(s::p) l
| Lapply(l1, l2) -> add_path bv l1; add_path bv l2
let open_module bv lid =
match lookup_map lid bv with
| Node (s, m) ->
add_names s;
StringMap.fold StringMap.add m bv
| exception Not_found ->
add_path bv lid; bv
let add_parent bv lid =
match lid.txt with
Ldot(l, _s) -> add_path bv l
| _ -> ()
let add = add_parent
let add_module_path bv lid = add_path bv lid.txt
let handle_extension ext =
match (fst ext).txt with
| "error" | "ocaml.error" ->
raise (Location.Error
(Builtin_attributes.error_of_extension ext))
| _ ->
()
let rec add_type bv ty =
match ty.ptyp_desc with
Ptyp_any -> ()
| Ptyp_var _ -> ()
| Ptyp_arrow(_, t1, t2) -> add_type bv t1; add_type bv t2
| Ptyp_tuple tl -> List.iter (add_type bv) tl
| Ptyp_constr(c, tl) -> add bv c; List.iter (add_type bv) tl
| Ptyp_object (fl, _) ->
List.iter
(function Otag (_, _, t) -> add_type bv t
| Oinherit t -> add_type bv t) fl
| Ptyp_class(c, tl) -> add bv c; List.iter (add_type bv) tl
| Ptyp_alias(t, _) -> add_type bv t
| Ptyp_variant(fl, _, _) ->
List.iter
(function Rtag(_,_,_,stl) -> List.iter (add_type bv) stl
| Rinherit sty -> add_type bv sty)
fl
| Ptyp_poly(_, t) -> add_type bv t
| Ptyp_package pt -> add_package_type bv pt
| Ptyp_extension e -> handle_extension e
and add_package_type bv (lid, l) =
add bv lid;
List.iter (add_type bv) (List.map (fun (_, e) -> e) l)
let add_opt add_fn bv = function
None -> ()
| Some x -> add_fn bv x
let add_constructor_arguments bv = function
| Pcstr_tuple l -> List.iter (add_type bv) l
| Pcstr_record l -> List.iter (fun l -> add_type bv l.pld_type) l
let add_constructor_decl bv pcd =
add_constructor_arguments bv pcd.pcd_args;
Misc.may (add_type bv) pcd.pcd_res
let add_type_declaration bv td =
List.iter
(fun (ty1, ty2, _) -> add_type bv ty1; add_type bv ty2)
td.ptype_cstrs;
add_opt add_type bv td.ptype_manifest;
let add_tkind = function
Ptype_abstract -> ()
| Ptype_variant cstrs ->
List.iter (add_constructor_decl bv) cstrs
| Ptype_record lbls ->
List.iter (fun pld -> add_type bv pld.pld_type) lbls
| Ptype_open -> () in
add_tkind td.ptype_kind
let add_extension_constructor bv ext =
match ext.pext_kind with
Pext_decl(args, rty) ->
add_constructor_arguments bv args;
Misc.may (add_type bv) rty
| Pext_rebind lid -> add bv lid
let add_type_extension bv te =
add bv te.ptyext_path;
List.iter (add_extension_constructor bv) te.ptyext_constructors
let rec add_class_type bv cty =
match cty.pcty_desc with
Pcty_constr(l, tyl) ->
add bv l; List.iter (add_type bv) tyl
| Pcty_signature { pcsig_self = ty; pcsig_fields = fieldl } ->
add_type bv ty;
List.iter (add_class_type_field bv) fieldl
| Pcty_arrow(_, ty1, cty2) ->
add_type bv ty1; add_class_type bv cty2
| Pcty_extension e -> handle_extension e
| Pcty_open (_ovf, m, e) ->
let bv = open_module bv m.txt in add_class_type bv e
and add_class_type_field bv pctf =
match pctf.pctf_desc with
Pctf_inherit cty -> add_class_type bv cty
| Pctf_val(_, _, _, ty) -> add_type bv ty
| Pctf_method(_, _, _, ty) -> add_type bv ty
| Pctf_constraint(ty1, ty2) -> add_type bv ty1; add_type bv ty2
| Pctf_attribute _ -> ()
| Pctf_extension e -> handle_extension e
let add_class_description bv infos =
add_class_type bv infos.pci_expr
let add_class_type_declaration = add_class_description
let pattern_bv = ref StringMap.empty
let rec add_pattern bv pat =
match pat.ppat_desc with
Ppat_any -> ()
| Ppat_var _ -> ()
| Ppat_alias(p, _) -> add_pattern bv p
| Ppat_interval _
| Ppat_constant _ -> ()
| Ppat_tuple pl -> List.iter (add_pattern bv) pl
| Ppat_construct(c, op) -> add bv c; add_opt add_pattern bv op
| Ppat_record(pl, _) ->
List.iter (fun (lbl, p) -> add bv lbl; add_pattern bv p) pl
| Ppat_array pl -> List.iter (add_pattern bv) pl
| Ppat_or(p1, p2) -> add_pattern bv p1; add_pattern bv p2
| Ppat_constraint(p, ty) -> add_pattern bv p; add_type bv ty
| Ppat_variant(_, op) -> add_opt add_pattern bv op
| Ppat_type li -> add bv li
| Ppat_lazy p -> add_pattern bv p
| Ppat_unpack id -> pattern_bv := StringMap.add id.txt bound !pattern_bv
| Ppat_open ( m, p) -> let bv = open_module bv m.txt in add_pattern bv p
| Ppat_exception p -> add_pattern bv p
| Ppat_extension e -> handle_extension e
let add_pattern bv pat =
pattern_bv := bv;
add_pattern bv pat;
!pattern_bv
let rec add_expr bv exp =
match exp.pexp_desc with
Pexp_ident l -> add bv l
| Pexp_constant _ -> ()
| Pexp_let(rf, pel, e) ->
let bv = add_bindings rf bv pel in add_expr bv e
| Pexp_fun (_, opte, p, e) ->
add_opt add_expr bv opte; add_expr (add_pattern bv p) e
| Pexp_function pel ->
add_cases bv pel
| Pexp_apply(e, el) ->
add_expr bv e; List.iter (fun (_,e) -> add_expr bv e) el
| Pexp_match(e, pel) -> add_expr bv e; add_cases bv pel
| Pexp_try(e, pel) -> add_expr bv e; add_cases bv pel
| Pexp_tuple el -> List.iter (add_expr bv) el
| Pexp_construct(c, opte) -> add bv c; add_opt add_expr bv opte
| Pexp_variant(_, opte) -> add_opt add_expr bv opte
| Pexp_record(lblel, opte) ->
List.iter (fun (lbl, e) -> add bv lbl; add_expr bv e) lblel;
add_opt add_expr bv opte
| Pexp_field(e, fld) -> add_expr bv e; add bv fld
| Pexp_setfield(e1, fld, e2) -> add_expr bv e1; add bv fld; add_expr bv e2
| Pexp_array el -> List.iter (add_expr bv) el
| Pexp_ifthenelse(e1, e2, opte3) ->
add_expr bv e1; add_expr bv e2; add_opt add_expr bv opte3
| Pexp_sequence(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexp_while(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexp_for( _, e1, e2, _, e3) ->
add_expr bv e1; add_expr bv e2; add_expr bv e3
| Pexp_coerce(e1, oty2, ty3) ->
add_expr bv e1;
add_opt add_type bv oty2;
add_type bv ty3
| Pexp_constraint(e1, ty2) ->
add_expr bv e1;
add_type bv ty2
| Pexp_send(e, _m) -> add_expr bv e
| Pexp_new li -> add bv li
| Pexp_setinstvar(_v, e) -> add_expr bv e
| Pexp_override sel -> List.iter (fun (_s, e) -> add_expr bv e) sel
| Pexp_letmodule(id, m, e) ->
let b = add_module_binding bv m in
add_expr (StringMap.add id.txt b bv) e
| Pexp_letexception(_, e) -> add_expr bv e
| Pexp_assert (e) -> add_expr bv e
| Pexp_lazy (e) -> add_expr bv e
| Pexp_poly (e, t) -> add_expr bv e; add_opt add_type bv t
| Pexp_object { pcstr_self = pat; pcstr_fields = fieldl } ->
let bv = add_pattern bv pat in List.iter (add_class_field bv) fieldl
| Pexp_newtype (_, e) -> add_expr bv e
| Pexp_pack m -> add_module_expr bv m
| Pexp_open (_ovf, m, e) ->
let bv = open_module bv m.txt in add_expr bv e
| Pexp_extension (({ txt = ("ocaml.extension_constructor"|
"extension_constructor"); _ },
PStr [item]) as e) ->
begin match item.pstr_desc with
| Pstr_eval ({ pexp_desc = Pexp_construct (c, None) }, _) -> add bv c
| _ -> handle_extension e
end
| Pexp_extension e -> handle_extension e
| Pexp_unreachable -> ()
and add_cases bv cases =
List.iter (add_case bv) cases
and add_case bv {pc_lhs; pc_guard; pc_rhs} =
let bv = add_pattern bv pc_lhs in
add_opt add_expr bv pc_guard;
add_expr bv pc_rhs
and add_bindings recf bv pel =
let bv' = List.fold_left (fun bv x -> add_pattern bv x.pvb_pat) bv pel in
let bv = if recf = Recursive then bv' else bv in
List.iter (fun x -> add_expr bv x.pvb_expr) pel;
bv'
and add_modtype bv mty =
match mty.pmty_desc with
Pmty_ident l -> add bv l
| Pmty_alias l -> add_module_path bv l
| Pmty_signature s -> add_signature bv s
| Pmty_functor(id, mty1, mty2) ->
Misc.may (add_modtype bv) mty1;
add_modtype (StringMap.add id.txt bound bv) mty2
| Pmty_with(mty, cstrl) ->
add_modtype bv mty;
List.iter
(function
| Pwith_type (_, td) -> add_type_declaration bv td
| Pwith_module (_, lid) -> add_module_path bv lid
| Pwith_typesubst (_, td) -> add_type_declaration bv td
| Pwith_modsubst (_, lid) -> add_module_path bv lid
)
cstrl
| Pmty_typeof m -> add_module_expr bv m
| Pmty_extension e -> handle_extension e
and add_module_alias bv l =
If we are in delayed dependencies mode , we delay the dependencies
induced by " s "
induced by "Lident s" *)
(if !Clflags.transparent_modules then add_parent else add_module_path) bv l;
try
lookup_map l.txt bv
with Not_found ->
match l.txt with
Lident s -> make_leaf s
and add_modtype_binding bv mty =
match mty.pmty_desc with
Pmty_alias l ->
add_module_alias bv l
| Pmty_signature s ->
make_node (add_signature_binding bv s)
| Pmty_typeof modl ->
add_module_binding bv modl
| _ ->
add_modtype bv mty; bound
and add_signature bv sg =
ignore (add_signature_binding bv sg)
and add_signature_binding bv sg =
snd (List.fold_left add_sig_item (bv, StringMap.empty) sg)
and add_sig_item (bv, m) item =
match item.psig_desc with
Psig_value vd ->
add_type bv vd.pval_type; (bv, m)
| Psig_type (_, dcls) ->
List.iter (add_type_declaration bv) dcls; (bv, m)
| Psig_typext te ->
add_type_extension bv te; (bv, m)
| Psig_exception pext ->
add_extension_constructor bv pext; (bv, m)
| Psig_module pmd ->
let m' = add_modtype_binding bv pmd.pmd_type in
let add = StringMap.add pmd.pmd_name.txt m' in
(add bv, add m)
| Psig_recmodule decls ->
let add =
List.fold_right (fun pmd -> StringMap.add pmd.pmd_name.txt bound)
decls
in
let bv' = add bv and m' = add m in
List.iter (fun pmd -> add_modtype bv' pmd.pmd_type) decls;
(bv', m')
| Psig_modtype x ->
begin match x.pmtd_type with
None -> ()
| Some mty -> add_modtype bv mty
end;
(bv, m)
| Psig_open od ->
(open_module bv od.popen_lid.txt, m)
| Psig_include incl ->
let Node (s, m') = add_modtype_binding bv incl.pincl_mod in
add_names s;
let add = StringMap.fold StringMap.add m' in
(add bv, add m)
| Psig_class cdl ->
List.iter (add_class_description bv) cdl; (bv, m)
| Psig_class_type cdtl ->
List.iter (add_class_type_declaration bv) cdtl; (bv, m)
| Psig_attribute _ -> (bv, m)
| Psig_extension (e, _) ->
handle_extension e;
(bv, m)
and add_module_binding bv modl =
match modl.pmod_desc with
Pmod_ident l -> add_module_alias bv l
| Pmod_structure s ->
make_node (snd @@ add_structure_binding bv s)
| _ -> add_module_expr bv modl; bound
and add_module_expr bv modl =
match modl.pmod_desc with
Pmod_ident l -> add_module_path bv l
| Pmod_structure s -> ignore (add_structure bv s)
| Pmod_functor(id, mty, modl) ->
Misc.may (add_modtype bv) mty;
add_module_expr (StringMap.add id.txt bound bv) modl
| Pmod_apply(mod1, mod2) ->
add_module_expr bv mod1; add_module_expr bv mod2
| Pmod_constraint(modl, mty) ->
add_module_expr bv modl; add_modtype bv mty
| Pmod_unpack(e) ->
add_expr bv e
| Pmod_extension e ->
handle_extension e
and add_structure bv item_list =
let (bv, m) = add_structure_binding bv item_list in
add_names (collect_free (make_node m));
bv
and add_structure_binding bv item_list =
List.fold_left add_struct_item (bv, StringMap.empty) item_list
and add_struct_item (bv, m) item : _ StringMap.t * _ StringMap.t =
match item.pstr_desc with
Pstr_eval (e, _attrs) ->
add_expr bv e; (bv, m)
| Pstr_value(rf, pel) ->
let bv = add_bindings rf bv pel in (bv, m)
| Pstr_primitive vd ->
add_type bv vd.pval_type; (bv, m)
| Pstr_type (_, dcls) ->
List.iter (add_type_declaration bv) dcls; (bv, m)
| Pstr_typext te ->
add_type_extension bv te;
(bv, m)
| Pstr_exception pext ->
add_extension_constructor bv pext; (bv, m)
| Pstr_module x ->
let b = add_module_binding bv x.pmb_expr in
let add = StringMap.add x.pmb_name.txt b in
(add bv, add m)
| Pstr_recmodule bindings ->
let add =
List.fold_right (fun x -> StringMap.add x.pmb_name.txt bound) bindings
in
let bv' = add bv and m = add m in
List.iter
(fun x -> add_module_expr bv' x.pmb_expr)
bindings;
(bv', m)
| Pstr_modtype x ->
begin match x.pmtd_type with
None -> ()
| Some mty -> add_modtype bv mty
end;
(bv, m)
| Pstr_open od ->
(open_module bv od.popen_lid.txt, m)
| Pstr_class cdl ->
List.iter (add_class_declaration bv) cdl; (bv, m)
| Pstr_class_type cdtl ->
List.iter (add_class_type_declaration bv) cdtl; (bv, m)
| Pstr_include incl ->
let Node (s, m') as n = add_module_binding bv incl.pincl_mod in
if !Clflags.transparent_modules then
add_names s
else
add_names (collect_free n);
let add = StringMap.fold StringMap.add m' in
(add bv, add m)
| Pstr_attribute _ -> (bv, m)
| Pstr_extension (e, _) ->
handle_extension e;
(bv, m)
and add_use_file bv top_phrs =
ignore (List.fold_left add_top_phrase bv top_phrs)
and add_implementation bv l =
ignore (add_structure_binding bv l)
and add_implementation_binding bv l =
snd (add_structure_binding bv l)
and add_top_phrase bv = function
| Ptop_def str -> add_structure bv str
| Ptop_dir (_, _) -> bv
and add_class_expr bv ce =
match ce.pcl_desc with
Pcl_constr(l, tyl) ->
add bv l; List.iter (add_type bv) tyl
| Pcl_structure { pcstr_self = pat; pcstr_fields = fieldl } ->
let bv = add_pattern bv pat in List.iter (add_class_field bv) fieldl
| Pcl_fun(_, opte, pat, ce) ->
add_opt add_expr bv opte;
let bv = add_pattern bv pat in add_class_expr bv ce
| Pcl_apply(ce, exprl) ->
add_class_expr bv ce; List.iter (fun (_,e) -> add_expr bv e) exprl
| Pcl_let(rf, pel, ce) ->
let bv = add_bindings rf bv pel in add_class_expr bv ce
| Pcl_constraint(ce, ct) ->
add_class_expr bv ce; add_class_type bv ct
| Pcl_extension e -> handle_extension e
| Pcl_open (_ovf, m, e) ->
let bv = open_module bv m.txt in add_class_expr bv e
and add_class_field bv pcf =
match pcf.pcf_desc with
Pcf_inherit(_, ce, _) -> add_class_expr bv ce
| Pcf_val(_, _, Cfk_concrete (_, e))
| Pcf_method(_, _, Cfk_concrete (_, e)) -> add_expr bv e
| Pcf_val(_, _, Cfk_virtual ty)
| Pcf_method(_, _, Cfk_virtual ty) -> add_type bv ty
| Pcf_constraint(ty1, ty2) -> add_type bv ty1; add_type bv ty2
| Pcf_initializer e -> add_expr bv e
| Pcf_attribute _ -> ()
| Pcf_extension e -> handle_extension e
and add_class_declaration bv decl =
add_class_expr bv decl.pci_expr
|
fad0bd886d62e84f3b7cf9fb15b9151e2c894539ac6902c17ab5851ecf4b9c7e
|
camlp5/camlp5
|
sexp.ml
|
(* camlp5r *)
(* sexp.ml,v *)
open Ploc;
type sexp = [
Atom of (vala string)
| Cons of (vala sexp) and (vala sexp)
| Nil
]
;
| null |
https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/tutorials/sexp_example2/sexp.ml
|
ocaml
|
camlp5r
sexp.ml,v
|
open Ploc;
type sexp = [
Atom of (vala string)
| Cons of (vala sexp) and (vala sexp)
| Nil
]
;
|
456d2872ea32fe613960f7d70a20889c83f7066c6f4e5dc6530383323e65acf2
|
input-output-hk/hydra
|
TxOutValue.hs
|
module Hydra.Cardano.Api.TxOutValue where
import Hydra.Cardano.Api.Prelude
import Hydra.Cardano.Api.MultiAssetSupportedInEra (HasMultiAsset (..))
-- | Inject some 'Value' into a 'TxOutValue'
mkTxOutValue ::
forall era.
(HasMultiAsset era) =>
Value ->
TxOutValue era
mkTxOutValue =
TxOutValue (multiAssetSupportedInEra @era)
| null |
https://raw.githubusercontent.com/input-output-hk/hydra/d873c290b0d9f18fde6c53a9690a1e7d2559e76b/hydra-cardano-api/src/Hydra/Cardano/Api/TxOutValue.hs
|
haskell
|
| Inject some 'Value' into a 'TxOutValue'
|
module Hydra.Cardano.Api.TxOutValue where
import Hydra.Cardano.Api.Prelude
import Hydra.Cardano.Api.MultiAssetSupportedInEra (HasMultiAsset (..))
mkTxOutValue ::
forall era.
(HasMultiAsset era) =>
Value ->
TxOutValue era
mkTxOutValue =
TxOutValue (multiAssetSupportedInEra @era)
|
12aa5ada60d5cd6c05ab1b31028f9d87136d0d3b6033171a50925abec8bdb75c
|
tallaproject/talla
|
talla_or_circuit.erl
|
%%%
Copyright ( c ) 2016 The Talla Authors . All rights reserved .
%%% Use of this source code is governed by a BSD-style
%%% license that can be found in the LICENSE file.
%%%
%%% ----------------------------------------------------------------------------
@author < >
@doc Onion Router Circuit .
%%% @end
%%% ----------------------------------------------------------------------------
-module(talla_or_circuit).
-behaviour(gen_statem).
%% API.
-export([start_link/2,
stop/1,
dispatch/2
]).
States .
-export([create/3,
relay/3
]).
Generic State Machine Callbacks .
-export([init/1,
code_change/4,
terminate/3,
callback_mode/0
]).
%% Types.
-export_type([t/0]).
-type t() :: pid().
-record(state, {
parent :: talla_or_peer:t(),
sibling :: t(),
%% The ID of our circuit.
circuit :: non_neg_integer(),
%% Key material used by this circuit.
forward_hash :: binary(),
forward_aes_key :: term(),
backward_hash :: binary(),
backward_aes_key :: term(),
%% The number of relay_early cell's that have passed through
%% this circuit.
relay_early_count = 0 :: non_neg_integer(),
extend_data :: binary()
}).
-type state() :: #state {}.
%% ----------------------------------------------------------------------------
%% API.
%% ----------------------------------------------------------------------------
-spec start_link(Peer, CircuitID) -> {ok, Circuit} | {error, Reason}
when
Peer :: talla_or_peer:t(),
CircuitID :: onion_circuit:id(),
Circuit :: t(),
Reason :: term().
start_link(Peer, CircuitID) ->
gen_statem:start_link(?MODULE, [Peer, CircuitID], []).
-spec stop(Circuit) -> ok
when
Circuit :: t().
stop(Circuit) ->
gen_statem:stop(Circuit).
-spec dispatch(Circuit, Cell) -> ok
when
Circuit :: t(),
Cell :: onion_cell:t().
dispatch(Circuit, Cell) ->
gen_statem:cast(Circuit, {dispatch, self(), Cell}).
%% ----------------------------------------------------------------------------
%% Protocol States.
%% ----------------------------------------------------------------------------
@private
-spec create(EventType, EventContent, StateData) -> gen_statem:handle_event_result()
when
EventType :: gen_statem:event_type(),
EventContent :: term(),
StateData :: state().
create(internal, {cell, #{ command := create2,
circuit := Circuit,
payload := #{ data := <<Fingerprint:20/binary,
NTorPublicKey:32/binary,
PublicKey:32/binary>>
}}}, StateData) ->
We received a cell and have n't already gotten a Circuit ID .
%% Update our state and reply to the create request.
lager:notice("Creating new relay: ~b", [Circuit]),
%% Reply.
case ntor_handshake(Fingerprint, NTorPublicKey, PublicKey) of
{ok, HandshakeState} ->
%% Send created2 response.
send(onion_cell:created2(Circuit, maps:get(response, HandshakeState))),
%% Update our state.
NewStateData = StateData#state {
circuit = Circuit,
forward_aes_key = maps:get(forward_aes_key, HandshakeState),
backward_aes_key = maps:get(backward_aes_key, HandshakeState),
forward_hash = maps:get(forward_hash, HandshakeState),
backward_hash = maps:get(backward_hash, HandshakeState)
},
%% Continue to the normal loop.
{next_state, relay, NewStateData};
{error, _} = Error ->
{stop, Error, StateData}
end;
create(EventType, EventContent, StateData) ->
handle_event(EventType, EventContent, StateData).
-spec relay(EventType, EventContent, StateData) -> gen_statem:handle_event_result()
when
EventType :: gen_statem:event_type(),
EventContent :: term(),
StateData :: state().
relay(internal, {cell, #{ command := destroy,
circuit := CircuitID }}, StateData) ->
lager:warning("Tearing down circuit: ~p", [CircuitID]),
{keep_state, StateData};
relay(internal, {cell, #{ command := relay_early,
circuit := Circuit,
payload := #{ data := Payload } }}, #state { circuit = Circuit,
forward_aes_key = FAESKey,
forward_hash = FHash,
relay_early_count = RelayEarlyCount } = StateData) ->
case decrypt(FAESKey, FHash, Payload) of
{recognized, NewAESKey, #{ command := relay_extend2,
stream := 0,
payload := #{ data := Data,
type := ntor,
links := [#{ type := tls_over_ipv4,
payload := {Address, Port} } | _] }}} ->
talla_or_peer_manager:connect(Address, Port),
%% Update our state.
NewStateData = StateData#state {
relay_early_count = RelayEarlyCount + 1,
%% FIXME(ahf): Better name.
extend_data = Data
},
{keep_state, NewStateData};
relay ->
lager:warning("Relay"),
{keep_state, StateData};
NoMatch ->
lager:warning("No match: ~p", [NoMatch]),
{keep_state, StateData}
end;
relay(info, {peer_connected, _, Peer}, #state { circuit = CircuitID,
extend_data = ExtendData } = StateData) ->
lager:warning("Peer connected: ~p", [Peer]),
%% Update our state.
case talla_or_peer:create_circuit(Peer) of
{ok, Circuit} ->
lager:warning("Sibling: ~p", [Circuit]),
%% Update our state.
NewStateData = StateData#state {
sibling = Circuit
},
{keep_state, NewStateData};
{error, Reason} ->
lager:warning("Unable to create circuit"),
%% FIXME(ahf): terminate ourself.
{keep_state, StateData}
end;
relay(EventType, EventContent, StateData) ->
handle_event(EventType, EventContent, StateData).
await_peer_connect(EventType, EventContent, StateData) ->
{keep_state, StateData, [postpone]}.
%% ----------------------------------------------------------------------------
Generic State Machine Callbacks .
%% ----------------------------------------------------------------------------
@private
%% This function is used to initialize our state machine.
init([Peer, CircuitID]) ->
%% We want to trap exit signals.
process_flag(trap_exit, true),
%% Our initial state.
StateData = #state {
circuit = CircuitID,
parent = Peer
},
%% We start in the create state.
{ok, create, StateData}.
@private
%% Call when we are doing a code change (live upgrade/downgrade).
-spec code_change(Version, StateName, StateData, Extra) -> {NewCallbackMode, NewStateName, NewStateData}
when
Version :: {down, term()} | term(),
StateName :: atom(),
StateData :: state(),
Extra :: term(),
NewCallbackMode :: atom(),
NewStateName :: StateName,
NewStateData :: StateData.
code_change(_Version, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
@private
%% Called before our process is terminated.
-spec terminate(Reason, StateName, StateData) -> ok
when
Reason :: term(),
StateName :: atom(),
StateData :: state().
terminate(_Reason, _StateName, _StateData) ->
ok.
%% ----------------------------------------------------------------------------
Generic State Handler .
%% ----------------------------------------------------------------------------
@private
%% Handle events that are generic for all states. All state functions should
%% have a catch all function clause that dispatches onto this function.
%%
%% This function should never have a reason to return something other than
{ keep_state , StateData } or { stop , , StateData } .
-spec handle_event(EventType, EventContent, StateData) -> gen_statem:handle_event_result()
when
EventType :: gen_statem:event_type(),
EventContent :: term(),
StateData :: state().
handle_event(internal, {cell_sent, _Cell}, StateData) ->
%% Ignore this.
{keep_state, StateData};
handle_event(cast, {dispatch, Source, #{ command := Command,
circuit := Circuit } = Cell}, #state { circuit = Circuit,
parent = Parent,
sibling = Sibling } = StateData) ->
case Source of
Parent ->
lager:notice("Relay from parent: ~p (Circuit: ~b)", [Command, Circuit]),
ok;
Sibling ->
lager:notice("Relay from sibling: ~p (Circuit: ~b)", [Command, Circuit]),
ok;
_ ->
lager:warning("Relay from unknown (~p): ~p (Circuit: ~b)", [Source, Command, Circuit]),
ok
end,
{keep_state, StateData, [{next_event, internal, {cell, Cell}}]};
handle_event(cast, {send, #{ command := Command,
circuit := Circuit } = Cell}, #state { parent = Parent } = StateData) ->
lager:notice("Relay Response: ~p (Circuit: ~b)", [Command, Circuit]),
talla_or_peer:send(Parent, Cell),
{keep_state, StateData, [{next_event, internal, {cell_sent, Cell}}]};
handle_event(EventType, EventContent, StateData) ->
%% Looks like none of the above handlers was able to handle this message.
%% Continue with the current state and hope for the best, but emit a
%% warning before continuing.
lager:warning("Unhandled circuit event: ~p (Type: ~p)", [EventContent, EventType]),
{keep_state, StateData}.
%% ----------------------------------------------------------------------------
%% Utility Functions.
%% ----------------------------------------------------------------------------
%% This function returns the callback method used by gen_statem. Look at
%% gen_statem's documentation for further information.
-spec callback_mode() -> gen_statem:callback_mode().
callback_mode() ->
state_functions.
@private
%% Update the send or receive context (if it is still needed to be updated).
-spec update_context(Context, Packet) -> NewContext
when
Context :: binary(),
Packet :: binary(),
NewContext :: Context.
update_context(Context, Packet) ->
case Context of
Context when is_binary(Context) ->
crypto:hash_update(Context, Packet);
_ ->
Context
end.
@private
-spec send(Circuit, Cell) -> ok
when
Circuit :: t(),
Cell :: onion_cell:t().
send(Circuit, Cell) ->
gen_statem:cast(Circuit, {send, Cell}).
@private
-spec send(Cell) -> ok
when
Cell :: onion_cell:t().
send(Cell) ->
send(self(), Cell).
@private
%% Check if a given set of keys matches ours.
ntor_handshake(Fingerprint, PublicKey, ClientPublicKey) ->
OurFingerprint = talla_core_identity_key:fingerprint(),
OurPublicKey = talla_core_ntor_key:public_key(),
case Fingerprint =:= OurFingerprint andalso PublicKey =:= OurPublicKey of
true ->
{Response, <<FHash:20/binary, BHash:20/binary,
FKey:16/binary, BKey:16/binary>>} = talla_core_ntor_key:server_handshake(ClientPublicKey, 72),
{ok, #{ response => Response,
forward_hash => crypto:hash_update(crypto:hash_init(sha), FHash),
backward_hash => crypto:hash_update(crypto:hash_init(sha), BHash),
forward_aes_key => onion_aes:init(FKey),
backward_aes_key => onion_aes:init(BKey) }};
false ->
{error, key_mismatch}
end.
@private
digest(Context, Data) ->
<<Start:5/binary, _:32/integer, Rest/binary>> = Data,
<<Result:4/binary, _/binary>> = crypto:hash_final(crypto:hash_update(Context, <<Start/binary, 0:32/integer, Rest/binary>>)),
Result.
@private
decrypt(AESKey, Context, Payload) ->
{NewAESKey, Message} = onion_aes:decrypt(AESKey, Payload),
MessageDigest = digest(Context, Message),
case Message of
<<Command:8/integer, 0:16/integer, StreamID:16/integer, MessageDigest:4/binary, Length:16/integer, Packet:Length/binary, _/binary>> ->
{recognized, NewAESKey, #{ command => decode_command(Command),
stream => StreamID,
payload => decode_relay_packet(Command, Packet) } };
_ ->
relay
end.
@private
decode_relay_packet(14, Payload) ->
decode_extend2_cell(Payload);
decode_relay_packet(_, _) ->
unknown.
decode_htype(0) ->
tap;
decode_htype(2) ->
ntor;
decode_htype(_) ->
unknown.
decode_link_type(0) ->
tls_over_ipv4;
decode_link_type(1) ->
tls_over_ipv6;
decode_link_type(2) ->
legacy_identity;
decode_link_type(_) ->
unknown.
decode_command(1) ->
relay_begin;
decode_command(2) ->
relay_data;
decode_command(3) ->
relay_end;
decode_command(4) ->
relay_connected;
decode_command(5) ->
relay_sendme;
decode_command(6) ->
relay_extend;
decode_command(7) ->
relay_extended;
decode_command(8) ->
relay_truncate;
decode_command(9) ->
relay_truncated;
decode_command(10) ->
relay_drop;
decode_command(11) ->
relay_resolve;
decode_command(12) ->
relay_resolved;
decode_command(13) ->
relay_begin_dir;
decode_command(14) ->
relay_extend2;
decode_command(15) ->
relay_extended2;
decode_command(X) ->
{unknown_command, X}.
decode_extend2_cell(<<NSpec:8/integer, Rest/binary>>) ->
{Links, <<HType:16/integer, HLen:16/integer, HData:HLen/bytes, _/binary>>} = decode_extend2_link_specifiers(Rest, [], NSpec),
#{ type => decode_htype(HType), data => HData, links => Links }.
decode_extend2_link_specifiers(Rest, Result, 0) ->
{lists:reverse(Result), Rest};
decode_extend2_link_specifiers(<<LSType:8/integer, LSLen:8/integer, LSpec:LSLen/binary, Rest/binary>>, Result, NSpec) ->
decode_extend2_link_specifiers(Rest, [#{ type => decode_link_type(LSType), payload => decode_extend2_link_specifier(LSType, LSpec) } | Result], NSpec - 1).
decode_extend2_link_specifier(0, <<A:8/integer, B:8/integer, C:8/integer, D:8/integer, Port:16/integer>>) ->
{{A, B, C, D}, Port};
decode_extend2_link_specifier(1, <<A:16/integer, B:16/integer, C:16/integer, D:16/integer, E:16/integer, F:16/integer, G:16/integer, H:16/integer, Port:16/integer>>) ->
{{A, B, C, D, E, F, G, H}, Port};
decode_extend2_link_specifier(2, <<Fingerprint:20/binary, _/binary>>) ->
Fingerprint.
| null |
https://raw.githubusercontent.com/tallaproject/talla/72cfbd8f48705a7a390cac2b8310ab7550c21c15/apps/talla_or/src/talla_or_circuit.erl
|
erlang
|
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
----------------------------------------------------------------------------
@end
----------------------------------------------------------------------------
API.
Types.
The ID of our circuit.
Key material used by this circuit.
The number of relay_early cell's that have passed through
this circuit.
----------------------------------------------------------------------------
API.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Protocol States.
----------------------------------------------------------------------------
Update our state and reply to the create request.
Reply.
Send created2 response.
Update our state.
Continue to the normal loop.
Update our state.
FIXME(ahf): Better name.
Update our state.
Update our state.
FIXME(ahf): terminate ourself.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
This function is used to initialize our state machine.
We want to trap exit signals.
Our initial state.
We start in the create state.
Call when we are doing a code change (live upgrade/downgrade).
Called before our process is terminated.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Handle events that are generic for all states. All state functions should
have a catch all function clause that dispatches onto this function.
This function should never have a reason to return something other than
Ignore this.
Looks like none of the above handlers was able to handle this message.
Continue with the current state and hope for the best, but emit a
warning before continuing.
----------------------------------------------------------------------------
Utility Functions.
----------------------------------------------------------------------------
This function returns the callback method used by gen_statem. Look at
gen_statem's documentation for further information.
Update the send or receive context (if it is still needed to be updated).
Check if a given set of keys matches ours.
|
Copyright ( c ) 2016 The Talla Authors . All rights reserved .
@author < >
@doc Onion Router Circuit .
-module(talla_or_circuit).
-behaviour(gen_statem).
-export([start_link/2,
stop/1,
dispatch/2
]).
States .
-export([create/3,
relay/3
]).
Generic State Machine Callbacks .
-export([init/1,
code_change/4,
terminate/3,
callback_mode/0
]).
-export_type([t/0]).
-type t() :: pid().
-record(state, {
parent :: talla_or_peer:t(),
sibling :: t(),
circuit :: non_neg_integer(),
forward_hash :: binary(),
forward_aes_key :: term(),
backward_hash :: binary(),
backward_aes_key :: term(),
relay_early_count = 0 :: non_neg_integer(),
extend_data :: binary()
}).
-type state() :: #state {}.
-spec start_link(Peer, CircuitID) -> {ok, Circuit} | {error, Reason}
when
Peer :: talla_or_peer:t(),
CircuitID :: onion_circuit:id(),
Circuit :: t(),
Reason :: term().
start_link(Peer, CircuitID) ->
gen_statem:start_link(?MODULE, [Peer, CircuitID], []).
-spec stop(Circuit) -> ok
when
Circuit :: t().
stop(Circuit) ->
gen_statem:stop(Circuit).
-spec dispatch(Circuit, Cell) -> ok
when
Circuit :: t(),
Cell :: onion_cell:t().
dispatch(Circuit, Cell) ->
gen_statem:cast(Circuit, {dispatch, self(), Cell}).
@private
-spec create(EventType, EventContent, StateData) -> gen_statem:handle_event_result()
when
EventType :: gen_statem:event_type(),
EventContent :: term(),
StateData :: state().
create(internal, {cell, #{ command := create2,
circuit := Circuit,
payload := #{ data := <<Fingerprint:20/binary,
NTorPublicKey:32/binary,
PublicKey:32/binary>>
}}}, StateData) ->
We received a cell and have n't already gotten a Circuit ID .
lager:notice("Creating new relay: ~b", [Circuit]),
case ntor_handshake(Fingerprint, NTorPublicKey, PublicKey) of
{ok, HandshakeState} ->
send(onion_cell:created2(Circuit, maps:get(response, HandshakeState))),
NewStateData = StateData#state {
circuit = Circuit,
forward_aes_key = maps:get(forward_aes_key, HandshakeState),
backward_aes_key = maps:get(backward_aes_key, HandshakeState),
forward_hash = maps:get(forward_hash, HandshakeState),
backward_hash = maps:get(backward_hash, HandshakeState)
},
{next_state, relay, NewStateData};
{error, _} = Error ->
{stop, Error, StateData}
end;
create(EventType, EventContent, StateData) ->
handle_event(EventType, EventContent, StateData).
-spec relay(EventType, EventContent, StateData) -> gen_statem:handle_event_result()
when
EventType :: gen_statem:event_type(),
EventContent :: term(),
StateData :: state().
relay(internal, {cell, #{ command := destroy,
circuit := CircuitID }}, StateData) ->
lager:warning("Tearing down circuit: ~p", [CircuitID]),
{keep_state, StateData};
relay(internal, {cell, #{ command := relay_early,
circuit := Circuit,
payload := #{ data := Payload } }}, #state { circuit = Circuit,
forward_aes_key = FAESKey,
forward_hash = FHash,
relay_early_count = RelayEarlyCount } = StateData) ->
case decrypt(FAESKey, FHash, Payload) of
{recognized, NewAESKey, #{ command := relay_extend2,
stream := 0,
payload := #{ data := Data,
type := ntor,
links := [#{ type := tls_over_ipv4,
payload := {Address, Port} } | _] }}} ->
talla_or_peer_manager:connect(Address, Port),
NewStateData = StateData#state {
relay_early_count = RelayEarlyCount + 1,
extend_data = Data
},
{keep_state, NewStateData};
relay ->
lager:warning("Relay"),
{keep_state, StateData};
NoMatch ->
lager:warning("No match: ~p", [NoMatch]),
{keep_state, StateData}
end;
relay(info, {peer_connected, _, Peer}, #state { circuit = CircuitID,
extend_data = ExtendData } = StateData) ->
lager:warning("Peer connected: ~p", [Peer]),
case talla_or_peer:create_circuit(Peer) of
{ok, Circuit} ->
lager:warning("Sibling: ~p", [Circuit]),
NewStateData = StateData#state {
sibling = Circuit
},
{keep_state, NewStateData};
{error, Reason} ->
lager:warning("Unable to create circuit"),
{keep_state, StateData}
end;
relay(EventType, EventContent, StateData) ->
handle_event(EventType, EventContent, StateData).
await_peer_connect(EventType, EventContent, StateData) ->
{keep_state, StateData, [postpone]}.
Generic State Machine Callbacks .
@private
init([Peer, CircuitID]) ->
process_flag(trap_exit, true),
StateData = #state {
circuit = CircuitID,
parent = Peer
},
{ok, create, StateData}.
@private
-spec code_change(Version, StateName, StateData, Extra) -> {NewCallbackMode, NewStateName, NewStateData}
when
Version :: {down, term()} | term(),
StateName :: atom(),
StateData :: state(),
Extra :: term(),
NewCallbackMode :: atom(),
NewStateName :: StateName,
NewStateData :: StateData.
code_change(_Version, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
@private
-spec terminate(Reason, StateName, StateData) -> ok
when
Reason :: term(),
StateName :: atom(),
StateData :: state().
terminate(_Reason, _StateName, _StateData) ->
ok.
Generic State Handler .
@private
{ keep_state , StateData } or { stop , , StateData } .
-spec handle_event(EventType, EventContent, StateData) -> gen_statem:handle_event_result()
when
EventType :: gen_statem:event_type(),
EventContent :: term(),
StateData :: state().
handle_event(internal, {cell_sent, _Cell}, StateData) ->
{keep_state, StateData};
handle_event(cast, {dispatch, Source, #{ command := Command,
circuit := Circuit } = Cell}, #state { circuit = Circuit,
parent = Parent,
sibling = Sibling } = StateData) ->
case Source of
Parent ->
lager:notice("Relay from parent: ~p (Circuit: ~b)", [Command, Circuit]),
ok;
Sibling ->
lager:notice("Relay from sibling: ~p (Circuit: ~b)", [Command, Circuit]),
ok;
_ ->
lager:warning("Relay from unknown (~p): ~p (Circuit: ~b)", [Source, Command, Circuit]),
ok
end,
{keep_state, StateData, [{next_event, internal, {cell, Cell}}]};
handle_event(cast, {send, #{ command := Command,
circuit := Circuit } = Cell}, #state { parent = Parent } = StateData) ->
lager:notice("Relay Response: ~p (Circuit: ~b)", [Command, Circuit]),
talla_or_peer:send(Parent, Cell),
{keep_state, StateData, [{next_event, internal, {cell_sent, Cell}}]};
handle_event(EventType, EventContent, StateData) ->
lager:warning("Unhandled circuit event: ~p (Type: ~p)", [EventContent, EventType]),
{keep_state, StateData}.
-spec callback_mode() -> gen_statem:callback_mode().
callback_mode() ->
state_functions.
@private
-spec update_context(Context, Packet) -> NewContext
when
Context :: binary(),
Packet :: binary(),
NewContext :: Context.
update_context(Context, Packet) ->
case Context of
Context when is_binary(Context) ->
crypto:hash_update(Context, Packet);
_ ->
Context
end.
@private
-spec send(Circuit, Cell) -> ok
when
Circuit :: t(),
Cell :: onion_cell:t().
send(Circuit, Cell) ->
gen_statem:cast(Circuit, {send, Cell}).
@private
-spec send(Cell) -> ok
when
Cell :: onion_cell:t().
send(Cell) ->
send(self(), Cell).
@private
ntor_handshake(Fingerprint, PublicKey, ClientPublicKey) ->
OurFingerprint = talla_core_identity_key:fingerprint(),
OurPublicKey = talla_core_ntor_key:public_key(),
case Fingerprint =:= OurFingerprint andalso PublicKey =:= OurPublicKey of
true ->
{Response, <<FHash:20/binary, BHash:20/binary,
FKey:16/binary, BKey:16/binary>>} = talla_core_ntor_key:server_handshake(ClientPublicKey, 72),
{ok, #{ response => Response,
forward_hash => crypto:hash_update(crypto:hash_init(sha), FHash),
backward_hash => crypto:hash_update(crypto:hash_init(sha), BHash),
forward_aes_key => onion_aes:init(FKey),
backward_aes_key => onion_aes:init(BKey) }};
false ->
{error, key_mismatch}
end.
@private
digest(Context, Data) ->
<<Start:5/binary, _:32/integer, Rest/binary>> = Data,
<<Result:4/binary, _/binary>> = crypto:hash_final(crypto:hash_update(Context, <<Start/binary, 0:32/integer, Rest/binary>>)),
Result.
@private
decrypt(AESKey, Context, Payload) ->
{NewAESKey, Message} = onion_aes:decrypt(AESKey, Payload),
MessageDigest = digest(Context, Message),
case Message of
<<Command:8/integer, 0:16/integer, StreamID:16/integer, MessageDigest:4/binary, Length:16/integer, Packet:Length/binary, _/binary>> ->
{recognized, NewAESKey, #{ command => decode_command(Command),
stream => StreamID,
payload => decode_relay_packet(Command, Packet) } };
_ ->
relay
end.
@private
decode_relay_packet(14, Payload) ->
decode_extend2_cell(Payload);
decode_relay_packet(_, _) ->
unknown.
decode_htype(0) ->
tap;
decode_htype(2) ->
ntor;
decode_htype(_) ->
unknown.
decode_link_type(0) ->
tls_over_ipv4;
decode_link_type(1) ->
tls_over_ipv6;
decode_link_type(2) ->
legacy_identity;
decode_link_type(_) ->
unknown.
decode_command(1) ->
relay_begin;
decode_command(2) ->
relay_data;
decode_command(3) ->
relay_end;
decode_command(4) ->
relay_connected;
decode_command(5) ->
relay_sendme;
decode_command(6) ->
relay_extend;
decode_command(7) ->
relay_extended;
decode_command(8) ->
relay_truncate;
decode_command(9) ->
relay_truncated;
decode_command(10) ->
relay_drop;
decode_command(11) ->
relay_resolve;
decode_command(12) ->
relay_resolved;
decode_command(13) ->
relay_begin_dir;
decode_command(14) ->
relay_extend2;
decode_command(15) ->
relay_extended2;
decode_command(X) ->
{unknown_command, X}.
decode_extend2_cell(<<NSpec:8/integer, Rest/binary>>) ->
{Links, <<HType:16/integer, HLen:16/integer, HData:HLen/bytes, _/binary>>} = decode_extend2_link_specifiers(Rest, [], NSpec),
#{ type => decode_htype(HType), data => HData, links => Links }.
decode_extend2_link_specifiers(Rest, Result, 0) ->
{lists:reverse(Result), Rest};
decode_extend2_link_specifiers(<<LSType:8/integer, LSLen:8/integer, LSpec:LSLen/binary, Rest/binary>>, Result, NSpec) ->
decode_extend2_link_specifiers(Rest, [#{ type => decode_link_type(LSType), payload => decode_extend2_link_specifier(LSType, LSpec) } | Result], NSpec - 1).
decode_extend2_link_specifier(0, <<A:8/integer, B:8/integer, C:8/integer, D:8/integer, Port:16/integer>>) ->
{{A, B, C, D}, Port};
decode_extend2_link_specifier(1, <<A:16/integer, B:16/integer, C:16/integer, D:16/integer, E:16/integer, F:16/integer, G:16/integer, H:16/integer, Port:16/integer>>) ->
{{A, B, C, D, E, F, G, H}, Port};
decode_extend2_link_specifier(2, <<Fingerprint:20/binary, _/binary>>) ->
Fingerprint.
|
e66122c25ba337e1c7f7b22a72f1823dd5bdbebe2bb6fa7366237b176d2257a9
|
gregtatcam/imaplet-lwt
|
imaplet_irmin_build.ml
|
* Copyright ( c ) 2013 - 2014 < >
*
* 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) 2013-2014 Gregory Tsipenyuk <>
*
* 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.
*)
open Lwt
open Imaplet
open Commands
open Imaplet_types
open Regex
open Storage_meta
open Irmin_core
open Irmin_storage
open Server_config
open Parsemail
exception InvalidCommand
exception PasswordRequired
exception InvalidInput
exception Done
module MapChar = Map.Make(Char)
module MapStr = Map.Make(String)
let timer = ref 0.
let timer_start () =
timer := !timer -. Unix.gettimeofday ()
let timer_stop () =
timer := !timer +. Unix.gettimeofday ()
let with_timer f =
timer_start ();
f() >>= fun res ->
timer_stop ();
return res
let get_mailbox_structure str =
if match_regex str ~regx:"^mbox:\\([^:]+\\):\\(.+\\)$" then
`Mbox (Str.matched_group 1 str,Str.matched_group 2 str)
else if match_regex str ~regx:"^maildir:\\([^:]+\\)\\(:fs\\)?$" then (
let dir = (Str.matched_group 1 str) in
let fs = try let _ = Str.matched_group 2 str in true with _ -> false in
`Maildir (dir,fs)
) else if match_regex str ~regx:"^archive:\\([^:]+\\)$" then (
`Archive (Str.matched_group 1 str)
) else
raise InvalidCommand
let get_filter str =
let p = Str.split (Str.regexp ":") str in
List.fold_left (fun (start,max,folders) n ->
if match_regex ~regx:"^\\([0-9]+\\)-\\([0-9]+\\)$" n then
(int_of_string (Str.matched_group 1 n),int_of_string (Str.matched_group 2 n),folders)
else
(start,max, Str.split (Str.regexp ",") n)
) (1,max_int,[]) p
-u : user
* -m : mailbox structure
* mbox : inbox - path : mailboxes - path
* maildir : - path
* -m : mailbox structure
* mbox:inbox-path:mailboxes-path
* maildir:maildir-path
*)
let rec args i user mailbox filter isappend =
if i >= Array.length Sys.argv then
user,mailbox,filter,isappend
else
match Sys.argv.(i) with
| "-m" -> args (i+2) user (Some (get_mailbox_structure Sys.argv.(i+1))) filter isappend
| "-u" -> args (i+2) (Some Sys.argv.(i+1)) mailbox filter isappend
| "-f" -> args (i+2) user mailbox (get_filter Sys.argv.(i+1)) isappend
| "-a" -> args (i+1) user mailbox filter true
| _ -> raise InvalidCommand
let usage () =
Printf.printf "usage: imaplet_irmin_build -u [user:pswd] -m
[mbox:inbox-path:mailboxes-path|maildir:mailboxes-path|archive:mbox-path]
-f [start-maxmsg:folder,...,folder] -a\n%!"
let get_user_pswd user isappend =
if Regex.match_regex ~regx:"^\\([^:]+\\):\\(.+\\)$" user then
((Str.matched_group 1 user),Some (Str.matched_group 2 user))
else if srv_config.auth_required || isappend = false then
raise PasswordRequired
else
(user,None)
let get_user (u,p) =
u
let commands f =
try
let user,mbx,filter,isappend = args 1 None None (1,max_int,[]) false in
if user = None || mbx = None then
usage ()
else
try
let up = get_user_pswd (Utils.option_value_exn user) isappend in
f up (Utils.option_value_exn mbx) filter isappend
with ex -> Printf.printf "%s\n%!" (Printexc.to_string ex)
with
| PasswordRequired -> Printf.printf "password is required: -u user:pswd\n%!"
| _ -> usage ()
let rec listdir path mailbox f =
Printf.printf "listing %s\n%!" path;
let strm = Lwt_unix.files_of_directory path in
Lwt_stream.iter_s (fun i ->
if i = "." || i = ".." || i = ".imap" || i = ".imaplet" || i = ".subscriptions" then
return ()
else (
let path = Filename.concat path i in
let mailbox = Filename.concat mailbox i in
Lwt_unix.stat path >>= fun stat ->
if stat.Lwt_unix.st_kind = Lwt_unix.S_DIR then
f true path mailbox >>
listdir path mailbox f
else
f false path mailbox
)
) strm
let user_keys = ref None
let get_keys (user,pswd) =
match !user_keys with
| None ->
Ssl_.get_user_keys ~user ?pswd srv_config >>= fun keys ->
user_keys := Some keys;
return keys
| Some keys -> return keys
let create_mailbox user ?uidvalidity mailbox =
Printf.printf "############# creating mailbox %s %s\n%!" (get_user user) mailbox;
with_timer (fun() ->
get_keys user >>= fun keys ->
IrminStorage.create srv_config (get_user user) mailbox keys >>= fun ist ->
IrminStorage.create_mailbox ist >>
return ist) >>= fun ist ->
match uidvalidity with
| Some uidvalidity ->
let metadata = empty_mailbox_metadata ~uidvalidity () in
IrminStorage.store_mailbox_metadata ist metadata >>
return ist
| None -> return ist
let append ist ?uid message size flags mailbox =
catch (fun () ->
with_timer (fun() -> IrminStorage.status ist) >>= fun mailbox_metadata ->
let modseq = Int64.add mailbox_metadata.modseq Int64.one in
let uid = match uid with None -> mailbox_metadata.uidnext|Some uid -> uid in
let message_metadata = {
uid;
modseq;
size;
internal_date = Dates.ImapTime.now();
flags;
} in
let mailbox_metadata = { mailbox_metadata with
uidnext = uid + 1;
count = mailbox_metadata.count + 1;
recent = mailbox_metadata.recent + 1;
unseen =
if mailbox_metadata.unseen = 0 then
mailbox_metadata.count + 1
else
mailbox_metadata.unseen
;
nunseen = mailbox_metadata.nunseen + 1 ;
modseq
} in
with_timer (fun() ->
IrminStorage.store_mailbox_metadata ist mailbox_metadata >>
IrminStorage.append ist message message_metadata >>
IrminStorage.commit ist)
)
(fun ex -> Printf.fprintf stderr "append exception: %s %s\n%!" (Printexc.to_string ex) (Printexc.get_backtrace()); return ())
let mailbox_of_gmail_label message =
if Regex.match_regex message ~regx:"^X-Gmail-Labels: \\(.+\\)$" = false then
("INBOX",[])
else (
let labels = Str.split (Str.regexp ",") (Str.matched_group 1 message) in
let (label,inferred,flags) =
List.fold_left (fun (label,inferred,flags) l ->
match l with
| "Important" -> (label,inferred,(Flags_Keyword "Important") :: flags)
| "Starred" -> (label,inferred,(Flags_Keyword "Starred") :: flags)
| "Sent" -> (label,(Some "Sent Messages"),Flags_Answered :: flags)
| "Trash" -> (label,(Some "Deleted Messages"),Flags_Deleted :: flags)
| "Unread" ->
(label,inferred,Flags_Recent :: ((List.filter (fun f -> f <> Flags_Seen)) flags))
| "Draft" -> (label,(Some "Drafts"),Flags_Draft :: flags)
| label -> ((Some label),inferred, flags)
) (None,None,[Flags_Seen]) labels
in
match label with
| None ->
begin
match inferred with
| None -> ("INBOX",flags)
| Some label -> (label,flags)
end
| Some label ->
let label = Regex.replace ~regx:"\\[Imap\\]/" ~tmpl:"" label in
let label = Regex.replace ~case:false ~regx:"inbox" ~tmpl:"INBOX" label in
(label,flags)
)
let append_messages ist path flags =
Printf.printf "#### appending messages %s\n%!" path;
Utils.fold_email_with_file path (fun acc message ->
if Regex.match_regex ~regx:"^From[ ]+MAILER_DAEMON" message then
return (`Ok acc)
else (
let (_,email) = Utils.make_postmark_email message in
let size = String.length email in
append ist message size flags "" >>
return (`Ok acc)
)
) ()
let gmail_mailboxes = ref MapStr.empty;;
gmail_mailboxes := MapStr.add "INBOX" "" !gmail_mailboxes;;
gmail_mailboxes := MapStr.add "Drafts" "" !gmail_mailboxes;;
gmail_mailboxes := MapStr.add "Deleted Messages" "" !gmail_mailboxes;;
gmail_mailboxes := MapStr.add "Sent Messages" "" !gmail_mailboxes;;
let postmark = "^from [^ ]+ " ^ Regex.dayofweek ^ " " ^ Regex.mon ^ " " ^
"[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9]+"
let is_postmark line =
Regex.match_regex ~case:false ~regx:postmark line
let filter_folder folders f =
let lowercase s = String.lowercase s in
if folders = [] then
false
else
List.exists (fun n -> (lowercase (Regex.dequote n)) = (lowercase f)) folders = false
let parse_message content =
let (_,email) = Utils.make_postmark_email content in
let headers = Utils.substr ~start:0 ~size:(Some 1000) email in
let (mailbox,fl) = mailbox_of_gmail_label headers in
let size = String.length email in
Some (mailbox,size,fl,content)
let rec get_message ic buffer folders =
let parse_content content folders f =
match parse_message content with
| None -> f ()
| Some (mailbox,size,flags,message) ->
if filter_folder folders mailbox then (
f ()
) else (
return (Some (mailbox,size,flags,message))
)
in
Lwt_io.read_line_opt ic >>= function
| None ->
if Buffer.length buffer > 0 then
let content = Buffer.contents buffer in
Buffer.clear buffer;
parse_content content folders (fun () -> return None)
else
return None
| Some line ->
let line = line ^ "\n" in
if is_postmark line then (
let content = Buffer.contents buffer in
Buffer.clear buffer;
Buffer.add_string buffer line;
parse_content content folders (fun () -> get_message ic buffer folders)
) else (
Buffer.add_string buffer line;
get_message ic buffer folders
)
let fill path push_strm start maxmsg folders =
Lwt_io.with_file ~mode:Lwt_io.Input path (fun ic ->
let buffer = Buffer.create 1000 in
let rec loop cnt =
get_message ic buffer folders >>= function
| None -> push_strm None; return ()
| Some (mailbox,size,flags,message) ->
if cnt >= start then
push_strm (Some (cnt,mailbox,size,flags,message));
if cnt < maxmsg then
loop (cnt + 1)
else (
push_strm None;
return ()
)
in
loop 1
)
let populate_mailboxes user isappend =
if isappend then (
Printf.printf "#### fetching current mailboxes\n%!";
get_keys user >>= fun keys ->
IrminStorage.create srv_config (get_user user) "" keys >>= fun ist ->
IrminStorage.list ~subscribed:true ~access:(fun _ -> true) ist ~init:() ~f:(fun _ f ->
match f with
| `Mailbox (f,s) -> Printf.printf "mailbox: %s\n%!" f;gmail_mailboxes := MapStr.add f "" !gmail_mailboxes; return ()
| `Folder (f,s) -> Printf.printf "folder: %s\n%!" f;gmail_mailboxes := MapStr.add f "" !gmail_mailboxes; return ()
)
) else
return ()
let append_archive_messages user path filter flags isappend =
Printf.printf "#### appending archive messages %s\n%!" path;
populate_mailboxes user isappend >>= fun () ->
let (start,maxmsg,folders) = filter in
let (strm,push_strm) = Lwt_stream.create () in
async (fun () -> fill path push_strm start maxmsg folders);
Lwt_stream.fold_s (fun (cnt,mailbox,size,fl,message) _ ->
Printf.printf "-- processing message %d, mailbox %s\n%!" cnt mailbox;
begin
if MapStr.exists (fun mb _ -> mailbox = mb) !gmail_mailboxes then
get_keys user >>= fun keys ->
with_timer (fun() -> IrminStorage.create srv_config (get_user user) mailbox keys)
else (
gmail_mailboxes := MapStr.add mailbox "" !gmail_mailboxes;
create_mailbox user mailbox
)
end >>= fun ist ->
append ist message size (List.concat [flags;fl]) mailbox >>
return ()
) strm ()
let append_maildir_message ist ?uid path flags =
Printf.printf "#### appending maildir message %s\n%!" path;
Lwt_io.file_length path >>= fun size ->
let size = Int64.to_int size in
let buffer = String.create size in
Lwt_io.open_file ~mode:Lwt_io.Input path >>= fun ic ->
Lwt_io.read_into_exactly ic buffer 0 size >>= fun () ->
Lwt_io.close ic >>= fun () ->
if Regex.match_regex buffer ~regx:"^From[ ]+MAILER_DAEMON" then
return ()
else (
let message = Utils.make_message_with_postmark buffer in
append ist ?uid message size flags ""
)
let populate_mbox_msgs ist path =
append_messages ist path [Flags_Recent]
maildir directory structure is flat
let listdir_maildir path f =
let strm = Lwt_unix.files_of_directory path in
Lwt_stream.fold_s (fun i acc ->
if i = "." || i = ".." || Regex.match_regex i ~regx:"^\\..+[^.]$" = false then
return acc
else (
return (i :: acc)
)
) strm [".INBOX"] >>= fun acc ->
let acc = List.sort String.compare acc in
Lwt_list.iter_s (fun d ->
let dirs = Str.split (Str.regexp "\\.") d in
let mailbox = "/" ^ (String.concat "/" dirs) in
let path = if d = ".INBOX" then path else Filename.concat path d in
f false path mailbox
) acc
let populate_maildir_msgs ist path flagsmap uidmap =
Printf.printf "#### populating maildir %s\n%!" path;
let populate ist path initflags flagsmap uidmap =
let strm = Lwt_unix.files_of_directory path in
Lwt_stream.fold_s (fun i acc ->
if i = "." || i = ".." then
return acc
else (
return (i :: acc)
)
) strm [] >>= fun acc ->
(* sort by file name - hopefully it'll sort in chronological order based on the
* unique id
*)
Printf.printf "#### number of messages in %s %d\n%!" path (List.length acc);
let acc = List.sort String.compare acc in
Lwt_list.iter_s (fun name ->
Printf.printf "#### processing %s\n%!" name;
let msgflags =
if Regex.match_regex name ~regx:":2,\\([a-zA-Z]+\\)$" then (
let flags = Str.matched_group 1 name in
let rec fold str i acc =
try
let flag = str.[i] in
try
let flag = MapChar.find flag flagsmap in
fold str (i+1) (flag :: acc)
with _ -> fold str (i+1) acc
with _ -> acc in
fold flags 0 []
) else (
[]
)
in
let flags = List.concat [initflags;msgflags] in
let uid =
if match_regex name ~regx:"^\\([^:]+\\)" then
try
Some (MapStr.find (Str.matched_group 1 name) uidmap)
with _ -> None
else
None
in
append_maildir_message ist ?uid (Filename.concat path name) flags
) acc
in
populate ist (Filename.concat path "new") [Flags_Recent] flagsmap uidmap >>
populate ist (Filename.concat path "cur") [] flagsmap uidmap
let create_inbox user inbx =
Printf.printf "creating mailbox: INBOX\n%!";
create_mailbox user "INBOX" >>= fun ist ->
populate_mbox_msgs ist inbx >>
with_timer(fun() -> IrminStorage.commit ist)
let create_account user subscriptions =
let (u,p) = user in
Printf.printf "#### creating user account %s\n%!" (get_user user);
Lwt_unix.system ("imaplet_create_account -u " ^ u ^ ":" ^ (Utils.option_value_exn p)) >>= fun _ ->
get subscriptions - works for dovecot
get_keys user >>= fun keys ->
catch (fun () ->
let strm = Lwt_io.lines_of_file subscriptions in
Lwt_stream.iter_s (fun line ->
IrminStorage.create srv_config (get_user user) line keys >>= fun ist ->
IrminStorage.subscribe ist >>
IrminStorage.commit ist
) strm
) (fun _ -> return ())
let get_dovecot_params path =
catch (fun () ->
let alpha = "abcdefghijklmnopqrstuvwxyz" in
let strm = Lwt_io.lines_of_file (Filename.concat path "dovecot-keywords") in
Lwt_stream.fold_s (fun line acc ->
if match_regex line ~regx:"^\\([0-9]+\\) \\(.+\\)$" then (
let i = int_of_string (Str.matched_group 1 line) in
if i >= 0 && i <= 26 then (
let key = String.get alpha i in
let data = Flags_Keyword (Str.matched_group 2 line) in
return (MapChar.add key data acc)
) else
return acc
) else
return acc
) strm (MapChar.empty)
) (fun _ -> return (MapChar.empty)) >>= fun flagsmap ->
catch( fun () ->
let strm = Lwt_io.lines_of_file (Filename.concat path "dovecot-uidlist") in
Lwt_stream.fold_s (fun line (first,uidvalidity,acc) ->
if first then (
if match_regex line ~regx:"^[0-9]+ V\\([0-9]+\\) " then
return (false,Some (Str.matched_group 1 line),acc)
else
return (false, uidvalidity, acc)
) else if match_regex line ~regx:"^\\([0-9]+\\)[^:]:\\(.+\\)$" then (
let key = Str.matched_group 2 line in
let data = int_of_string (Str.matched_group 1 line) in
return (first,uidvalidity,MapStr.add key data acc)
) else
raise InvalidInput
) strm (true,None,MapStr.empty) >>= fun (_,uidvalidity,uidmap) ->
return (flagsmap,uidvalidity,uidmap)
)
(fun _ -> return (flagsmap,None,MapStr.empty))
irmin supports both mailbox and folders under the mailbox
let create_mbox user inbox mailboxes filter =
create_inbox user inbox >>
listdir mailboxes "/" (fun is_dir path mailbox ->
Printf.printf "creating mailbox: %s\n%!" mailbox;
create_mailbox user mailbox >>= fun ist ->
begin
if is_dir then
return ()
else
populate_mbox_msgs ist path
end >>
with_timer(fun() -> IrminStorage.commit ist)
)
let maildir_flags flagsmap =
let keys = ['P';'R';'S';'T';'D';'F'] in
let values =
[Flags_Answered;Flags_Answered;Flags_Seen;Flags_Deleted;Flags_Draft;Flags_Flagged] in
let (_,flagsmap) =
List.fold_left (fun (i,flagsmap) key ->
i+1, MapChar.add key (List.nth values i) flagsmap
) (0,flagsmap) keys
in
flagsmap
let create_maildir user mailboxes fs filter =
let list = if fs then listdir mailboxes "/" else listdir_maildir mailboxes in
list (fun _ path mailbox ->
Printf.printf "#### listing %s %s\n%!" path mailbox;
catch (fun () ->
get_dovecot_params path >>= fun (flagsmap,uidvalidity,uidmap) ->
let flagsmap = maildir_flags flagsmap in
Printf.printf "#### got dovecot params %d %d %s\n%!" (MapChar.cardinal
flagsmap) (MapStr.cardinal uidmap) (Utils.option_value uidvalidity ~default:"");
create_mailbox user ?uidvalidity mailbox >>= fun ist ->
populate_maildir_msgs ist path flagsmap uidmap >>= fun () ->
with_timer(fun() -> IrminStorage.commit ist)
)
( fun ex -> Printf.fprintf stderr "create_maildir exception: %s %s\n%!" (Printexc.to_string ex)
(Printexc.get_backtrace());return())
)
let create_archive_maildir user mailbox filter isappend =
append_archive_messages user mailbox filter [] isappend
let () =
commands (fun user mbx filter isappend ->
Lwt_main.run (
catch ( fun () ->
match mbx with
| `Mbox (inbox,mailboxes) ->
Printf.printf "porting from mbox\n%!";
(if isappend then return () else create_account user (Filename.concat mailboxes ".subscriptions")) >>
create_mbox user inbox mailboxes filter
| `Maildir (mailboxes,fs) ->
Printf.printf "porting from maildir\n%!";
(if isappend then return () else create_account user (Filename.concat mailboxes "subscriptions")) >>
create_maildir user mailboxes fs filter
| `Archive mailbox ->
Printf.printf "porting from archive\n%!";
(if isappend then return () else create_account user (Filename.concat mailbox "subscriptions")) >>
create_archive_maildir user mailbox filter isappend
)
(fun ex -> Printf.fprintf stderr "exception: %s %s\n%!" (Printexc.to_string ex)
(Printexc.get_backtrace());return())
)
);
Printf.printf "total irmin time: %04f\n%!" !timer
| null |
https://raw.githubusercontent.com/gregtatcam/imaplet-lwt/d7b51253e79cffa97e98ab899ed833cd7cb44bb6/servers/imaplet_irmin_build.ml
|
ocaml
|
sort by file name - hopefully it'll sort in chronological order based on the
* unique id
|
* Copyright ( c ) 2013 - 2014 < >
*
* 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) 2013-2014 Gregory Tsipenyuk <>
*
* 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.
*)
open Lwt
open Imaplet
open Commands
open Imaplet_types
open Regex
open Storage_meta
open Irmin_core
open Irmin_storage
open Server_config
open Parsemail
exception InvalidCommand
exception PasswordRequired
exception InvalidInput
exception Done
module MapChar = Map.Make(Char)
module MapStr = Map.Make(String)
let timer = ref 0.
let timer_start () =
timer := !timer -. Unix.gettimeofday ()
let timer_stop () =
timer := !timer +. Unix.gettimeofday ()
let with_timer f =
timer_start ();
f() >>= fun res ->
timer_stop ();
return res
let get_mailbox_structure str =
if match_regex str ~regx:"^mbox:\\([^:]+\\):\\(.+\\)$" then
`Mbox (Str.matched_group 1 str,Str.matched_group 2 str)
else if match_regex str ~regx:"^maildir:\\([^:]+\\)\\(:fs\\)?$" then (
let dir = (Str.matched_group 1 str) in
let fs = try let _ = Str.matched_group 2 str in true with _ -> false in
`Maildir (dir,fs)
) else if match_regex str ~regx:"^archive:\\([^:]+\\)$" then (
`Archive (Str.matched_group 1 str)
) else
raise InvalidCommand
let get_filter str =
let p = Str.split (Str.regexp ":") str in
List.fold_left (fun (start,max,folders) n ->
if match_regex ~regx:"^\\([0-9]+\\)-\\([0-9]+\\)$" n then
(int_of_string (Str.matched_group 1 n),int_of_string (Str.matched_group 2 n),folders)
else
(start,max, Str.split (Str.regexp ",") n)
) (1,max_int,[]) p
-u : user
* -m : mailbox structure
* mbox : inbox - path : mailboxes - path
* maildir : - path
* -m : mailbox structure
* mbox:inbox-path:mailboxes-path
* maildir:maildir-path
*)
let rec args i user mailbox filter isappend =
if i >= Array.length Sys.argv then
user,mailbox,filter,isappend
else
match Sys.argv.(i) with
| "-m" -> args (i+2) user (Some (get_mailbox_structure Sys.argv.(i+1))) filter isappend
| "-u" -> args (i+2) (Some Sys.argv.(i+1)) mailbox filter isappend
| "-f" -> args (i+2) user mailbox (get_filter Sys.argv.(i+1)) isappend
| "-a" -> args (i+1) user mailbox filter true
| _ -> raise InvalidCommand
let usage () =
Printf.printf "usage: imaplet_irmin_build -u [user:pswd] -m
[mbox:inbox-path:mailboxes-path|maildir:mailboxes-path|archive:mbox-path]
-f [start-maxmsg:folder,...,folder] -a\n%!"
let get_user_pswd user isappend =
if Regex.match_regex ~regx:"^\\([^:]+\\):\\(.+\\)$" user then
((Str.matched_group 1 user),Some (Str.matched_group 2 user))
else if srv_config.auth_required || isappend = false then
raise PasswordRequired
else
(user,None)
let get_user (u,p) =
u
let commands f =
try
let user,mbx,filter,isappend = args 1 None None (1,max_int,[]) false in
if user = None || mbx = None then
usage ()
else
try
let up = get_user_pswd (Utils.option_value_exn user) isappend in
f up (Utils.option_value_exn mbx) filter isappend
with ex -> Printf.printf "%s\n%!" (Printexc.to_string ex)
with
| PasswordRequired -> Printf.printf "password is required: -u user:pswd\n%!"
| _ -> usage ()
let rec listdir path mailbox f =
Printf.printf "listing %s\n%!" path;
let strm = Lwt_unix.files_of_directory path in
Lwt_stream.iter_s (fun i ->
if i = "." || i = ".." || i = ".imap" || i = ".imaplet" || i = ".subscriptions" then
return ()
else (
let path = Filename.concat path i in
let mailbox = Filename.concat mailbox i in
Lwt_unix.stat path >>= fun stat ->
if stat.Lwt_unix.st_kind = Lwt_unix.S_DIR then
f true path mailbox >>
listdir path mailbox f
else
f false path mailbox
)
) strm
let user_keys = ref None
let get_keys (user,pswd) =
match !user_keys with
| None ->
Ssl_.get_user_keys ~user ?pswd srv_config >>= fun keys ->
user_keys := Some keys;
return keys
| Some keys -> return keys
let create_mailbox user ?uidvalidity mailbox =
Printf.printf "############# creating mailbox %s %s\n%!" (get_user user) mailbox;
with_timer (fun() ->
get_keys user >>= fun keys ->
IrminStorage.create srv_config (get_user user) mailbox keys >>= fun ist ->
IrminStorage.create_mailbox ist >>
return ist) >>= fun ist ->
match uidvalidity with
| Some uidvalidity ->
let metadata = empty_mailbox_metadata ~uidvalidity () in
IrminStorage.store_mailbox_metadata ist metadata >>
return ist
| None -> return ist
let append ist ?uid message size flags mailbox =
catch (fun () ->
with_timer (fun() -> IrminStorage.status ist) >>= fun mailbox_metadata ->
let modseq = Int64.add mailbox_metadata.modseq Int64.one in
let uid = match uid with None -> mailbox_metadata.uidnext|Some uid -> uid in
let message_metadata = {
uid;
modseq;
size;
internal_date = Dates.ImapTime.now();
flags;
} in
let mailbox_metadata = { mailbox_metadata with
uidnext = uid + 1;
count = mailbox_metadata.count + 1;
recent = mailbox_metadata.recent + 1;
unseen =
if mailbox_metadata.unseen = 0 then
mailbox_metadata.count + 1
else
mailbox_metadata.unseen
;
nunseen = mailbox_metadata.nunseen + 1 ;
modseq
} in
with_timer (fun() ->
IrminStorage.store_mailbox_metadata ist mailbox_metadata >>
IrminStorage.append ist message message_metadata >>
IrminStorage.commit ist)
)
(fun ex -> Printf.fprintf stderr "append exception: %s %s\n%!" (Printexc.to_string ex) (Printexc.get_backtrace()); return ())
let mailbox_of_gmail_label message =
if Regex.match_regex message ~regx:"^X-Gmail-Labels: \\(.+\\)$" = false then
("INBOX",[])
else (
let labels = Str.split (Str.regexp ",") (Str.matched_group 1 message) in
let (label,inferred,flags) =
List.fold_left (fun (label,inferred,flags) l ->
match l with
| "Important" -> (label,inferred,(Flags_Keyword "Important") :: flags)
| "Starred" -> (label,inferred,(Flags_Keyword "Starred") :: flags)
| "Sent" -> (label,(Some "Sent Messages"),Flags_Answered :: flags)
| "Trash" -> (label,(Some "Deleted Messages"),Flags_Deleted :: flags)
| "Unread" ->
(label,inferred,Flags_Recent :: ((List.filter (fun f -> f <> Flags_Seen)) flags))
| "Draft" -> (label,(Some "Drafts"),Flags_Draft :: flags)
| label -> ((Some label),inferred, flags)
) (None,None,[Flags_Seen]) labels
in
match label with
| None ->
begin
match inferred with
| None -> ("INBOX",flags)
| Some label -> (label,flags)
end
| Some label ->
let label = Regex.replace ~regx:"\\[Imap\\]/" ~tmpl:"" label in
let label = Regex.replace ~case:false ~regx:"inbox" ~tmpl:"INBOX" label in
(label,flags)
)
let append_messages ist path flags =
Printf.printf "#### appending messages %s\n%!" path;
Utils.fold_email_with_file path (fun acc message ->
if Regex.match_regex ~regx:"^From[ ]+MAILER_DAEMON" message then
return (`Ok acc)
else (
let (_,email) = Utils.make_postmark_email message in
let size = String.length email in
append ist message size flags "" >>
return (`Ok acc)
)
) ()
let gmail_mailboxes = ref MapStr.empty;;
gmail_mailboxes := MapStr.add "INBOX" "" !gmail_mailboxes;;
gmail_mailboxes := MapStr.add "Drafts" "" !gmail_mailboxes;;
gmail_mailboxes := MapStr.add "Deleted Messages" "" !gmail_mailboxes;;
gmail_mailboxes := MapStr.add "Sent Messages" "" !gmail_mailboxes;;
let postmark = "^from [^ ]+ " ^ Regex.dayofweek ^ " " ^ Regex.mon ^ " " ^
"[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9]+"
let is_postmark line =
Regex.match_regex ~case:false ~regx:postmark line
let filter_folder folders f =
let lowercase s = String.lowercase s in
if folders = [] then
false
else
List.exists (fun n -> (lowercase (Regex.dequote n)) = (lowercase f)) folders = false
let parse_message content =
let (_,email) = Utils.make_postmark_email content in
let headers = Utils.substr ~start:0 ~size:(Some 1000) email in
let (mailbox,fl) = mailbox_of_gmail_label headers in
let size = String.length email in
Some (mailbox,size,fl,content)
let rec get_message ic buffer folders =
let parse_content content folders f =
match parse_message content with
| None -> f ()
| Some (mailbox,size,flags,message) ->
if filter_folder folders mailbox then (
f ()
) else (
return (Some (mailbox,size,flags,message))
)
in
Lwt_io.read_line_opt ic >>= function
| None ->
if Buffer.length buffer > 0 then
let content = Buffer.contents buffer in
Buffer.clear buffer;
parse_content content folders (fun () -> return None)
else
return None
| Some line ->
let line = line ^ "\n" in
if is_postmark line then (
let content = Buffer.contents buffer in
Buffer.clear buffer;
Buffer.add_string buffer line;
parse_content content folders (fun () -> get_message ic buffer folders)
) else (
Buffer.add_string buffer line;
get_message ic buffer folders
)
let fill path push_strm start maxmsg folders =
Lwt_io.with_file ~mode:Lwt_io.Input path (fun ic ->
let buffer = Buffer.create 1000 in
let rec loop cnt =
get_message ic buffer folders >>= function
| None -> push_strm None; return ()
| Some (mailbox,size,flags,message) ->
if cnt >= start then
push_strm (Some (cnt,mailbox,size,flags,message));
if cnt < maxmsg then
loop (cnt + 1)
else (
push_strm None;
return ()
)
in
loop 1
)
let populate_mailboxes user isappend =
if isappend then (
Printf.printf "#### fetching current mailboxes\n%!";
get_keys user >>= fun keys ->
IrminStorage.create srv_config (get_user user) "" keys >>= fun ist ->
IrminStorage.list ~subscribed:true ~access:(fun _ -> true) ist ~init:() ~f:(fun _ f ->
match f with
| `Mailbox (f,s) -> Printf.printf "mailbox: %s\n%!" f;gmail_mailboxes := MapStr.add f "" !gmail_mailboxes; return ()
| `Folder (f,s) -> Printf.printf "folder: %s\n%!" f;gmail_mailboxes := MapStr.add f "" !gmail_mailboxes; return ()
)
) else
return ()
let append_archive_messages user path filter flags isappend =
Printf.printf "#### appending archive messages %s\n%!" path;
populate_mailboxes user isappend >>= fun () ->
let (start,maxmsg,folders) = filter in
let (strm,push_strm) = Lwt_stream.create () in
async (fun () -> fill path push_strm start maxmsg folders);
Lwt_stream.fold_s (fun (cnt,mailbox,size,fl,message) _ ->
Printf.printf "-- processing message %d, mailbox %s\n%!" cnt mailbox;
begin
if MapStr.exists (fun mb _ -> mailbox = mb) !gmail_mailboxes then
get_keys user >>= fun keys ->
with_timer (fun() -> IrminStorage.create srv_config (get_user user) mailbox keys)
else (
gmail_mailboxes := MapStr.add mailbox "" !gmail_mailboxes;
create_mailbox user mailbox
)
end >>= fun ist ->
append ist message size (List.concat [flags;fl]) mailbox >>
return ()
) strm ()
let append_maildir_message ist ?uid path flags =
Printf.printf "#### appending maildir message %s\n%!" path;
Lwt_io.file_length path >>= fun size ->
let size = Int64.to_int size in
let buffer = String.create size in
Lwt_io.open_file ~mode:Lwt_io.Input path >>= fun ic ->
Lwt_io.read_into_exactly ic buffer 0 size >>= fun () ->
Lwt_io.close ic >>= fun () ->
if Regex.match_regex buffer ~regx:"^From[ ]+MAILER_DAEMON" then
return ()
else (
let message = Utils.make_message_with_postmark buffer in
append ist ?uid message size flags ""
)
let populate_mbox_msgs ist path =
append_messages ist path [Flags_Recent]
maildir directory structure is flat
let listdir_maildir path f =
let strm = Lwt_unix.files_of_directory path in
Lwt_stream.fold_s (fun i acc ->
if i = "." || i = ".." || Regex.match_regex i ~regx:"^\\..+[^.]$" = false then
return acc
else (
return (i :: acc)
)
) strm [".INBOX"] >>= fun acc ->
let acc = List.sort String.compare acc in
Lwt_list.iter_s (fun d ->
let dirs = Str.split (Str.regexp "\\.") d in
let mailbox = "/" ^ (String.concat "/" dirs) in
let path = if d = ".INBOX" then path else Filename.concat path d in
f false path mailbox
) acc
let populate_maildir_msgs ist path flagsmap uidmap =
Printf.printf "#### populating maildir %s\n%!" path;
let populate ist path initflags flagsmap uidmap =
let strm = Lwt_unix.files_of_directory path in
Lwt_stream.fold_s (fun i acc ->
if i = "." || i = ".." then
return acc
else (
return (i :: acc)
)
) strm [] >>= fun acc ->
Printf.printf "#### number of messages in %s %d\n%!" path (List.length acc);
let acc = List.sort String.compare acc in
Lwt_list.iter_s (fun name ->
Printf.printf "#### processing %s\n%!" name;
let msgflags =
if Regex.match_regex name ~regx:":2,\\([a-zA-Z]+\\)$" then (
let flags = Str.matched_group 1 name in
let rec fold str i acc =
try
let flag = str.[i] in
try
let flag = MapChar.find flag flagsmap in
fold str (i+1) (flag :: acc)
with _ -> fold str (i+1) acc
with _ -> acc in
fold flags 0 []
) else (
[]
)
in
let flags = List.concat [initflags;msgflags] in
let uid =
if match_regex name ~regx:"^\\([^:]+\\)" then
try
Some (MapStr.find (Str.matched_group 1 name) uidmap)
with _ -> None
else
None
in
append_maildir_message ist ?uid (Filename.concat path name) flags
) acc
in
populate ist (Filename.concat path "new") [Flags_Recent] flagsmap uidmap >>
populate ist (Filename.concat path "cur") [] flagsmap uidmap
let create_inbox user inbx =
Printf.printf "creating mailbox: INBOX\n%!";
create_mailbox user "INBOX" >>= fun ist ->
populate_mbox_msgs ist inbx >>
with_timer(fun() -> IrminStorage.commit ist)
let create_account user subscriptions =
let (u,p) = user in
Printf.printf "#### creating user account %s\n%!" (get_user user);
Lwt_unix.system ("imaplet_create_account -u " ^ u ^ ":" ^ (Utils.option_value_exn p)) >>= fun _ ->
get subscriptions - works for dovecot
get_keys user >>= fun keys ->
catch (fun () ->
let strm = Lwt_io.lines_of_file subscriptions in
Lwt_stream.iter_s (fun line ->
IrminStorage.create srv_config (get_user user) line keys >>= fun ist ->
IrminStorage.subscribe ist >>
IrminStorage.commit ist
) strm
) (fun _ -> return ())
let get_dovecot_params path =
catch (fun () ->
let alpha = "abcdefghijklmnopqrstuvwxyz" in
let strm = Lwt_io.lines_of_file (Filename.concat path "dovecot-keywords") in
Lwt_stream.fold_s (fun line acc ->
if match_regex line ~regx:"^\\([0-9]+\\) \\(.+\\)$" then (
let i = int_of_string (Str.matched_group 1 line) in
if i >= 0 && i <= 26 then (
let key = String.get alpha i in
let data = Flags_Keyword (Str.matched_group 2 line) in
return (MapChar.add key data acc)
) else
return acc
) else
return acc
) strm (MapChar.empty)
) (fun _ -> return (MapChar.empty)) >>= fun flagsmap ->
catch( fun () ->
let strm = Lwt_io.lines_of_file (Filename.concat path "dovecot-uidlist") in
Lwt_stream.fold_s (fun line (first,uidvalidity,acc) ->
if first then (
if match_regex line ~regx:"^[0-9]+ V\\([0-9]+\\) " then
return (false,Some (Str.matched_group 1 line),acc)
else
return (false, uidvalidity, acc)
) else if match_regex line ~regx:"^\\([0-9]+\\)[^:]:\\(.+\\)$" then (
let key = Str.matched_group 2 line in
let data = int_of_string (Str.matched_group 1 line) in
return (first,uidvalidity,MapStr.add key data acc)
) else
raise InvalidInput
) strm (true,None,MapStr.empty) >>= fun (_,uidvalidity,uidmap) ->
return (flagsmap,uidvalidity,uidmap)
)
(fun _ -> return (flagsmap,None,MapStr.empty))
irmin supports both mailbox and folders under the mailbox
let create_mbox user inbox mailboxes filter =
create_inbox user inbox >>
listdir mailboxes "/" (fun is_dir path mailbox ->
Printf.printf "creating mailbox: %s\n%!" mailbox;
create_mailbox user mailbox >>= fun ist ->
begin
if is_dir then
return ()
else
populate_mbox_msgs ist path
end >>
with_timer(fun() -> IrminStorage.commit ist)
)
let maildir_flags flagsmap =
let keys = ['P';'R';'S';'T';'D';'F'] in
let values =
[Flags_Answered;Flags_Answered;Flags_Seen;Flags_Deleted;Flags_Draft;Flags_Flagged] in
let (_,flagsmap) =
List.fold_left (fun (i,flagsmap) key ->
i+1, MapChar.add key (List.nth values i) flagsmap
) (0,flagsmap) keys
in
flagsmap
let create_maildir user mailboxes fs filter =
let list = if fs then listdir mailboxes "/" else listdir_maildir mailboxes in
list (fun _ path mailbox ->
Printf.printf "#### listing %s %s\n%!" path mailbox;
catch (fun () ->
get_dovecot_params path >>= fun (flagsmap,uidvalidity,uidmap) ->
let flagsmap = maildir_flags flagsmap in
Printf.printf "#### got dovecot params %d %d %s\n%!" (MapChar.cardinal
flagsmap) (MapStr.cardinal uidmap) (Utils.option_value uidvalidity ~default:"");
create_mailbox user ?uidvalidity mailbox >>= fun ist ->
populate_maildir_msgs ist path flagsmap uidmap >>= fun () ->
with_timer(fun() -> IrminStorage.commit ist)
)
( fun ex -> Printf.fprintf stderr "create_maildir exception: %s %s\n%!" (Printexc.to_string ex)
(Printexc.get_backtrace());return())
)
let create_archive_maildir user mailbox filter isappend =
append_archive_messages user mailbox filter [] isappend
let () =
commands (fun user mbx filter isappend ->
Lwt_main.run (
catch ( fun () ->
match mbx with
| `Mbox (inbox,mailboxes) ->
Printf.printf "porting from mbox\n%!";
(if isappend then return () else create_account user (Filename.concat mailboxes ".subscriptions")) >>
create_mbox user inbox mailboxes filter
| `Maildir (mailboxes,fs) ->
Printf.printf "porting from maildir\n%!";
(if isappend then return () else create_account user (Filename.concat mailboxes "subscriptions")) >>
create_maildir user mailboxes fs filter
| `Archive mailbox ->
Printf.printf "porting from archive\n%!";
(if isappend then return () else create_account user (Filename.concat mailbox "subscriptions")) >>
create_archive_maildir user mailbox filter isappend
)
(fun ex -> Printf.fprintf stderr "exception: %s %s\n%!" (Printexc.to_string ex)
(Printexc.get_backtrace());return())
)
);
Printf.printf "total irmin time: %04f\n%!" !timer
|
e774d6447a77ae4008b578ddbed29751efa93c46ff08b1264cbc02c8af8b0366
|
gfngfn/SATySFi
|
length.mli
|
type t [@@deriving show]
val zero : t
val add : t -> t -> t
val subtr : t -> t -> t
val mult : t -> float -> t
val div : t -> t -> float
val max : t -> t -> t
val min : t -> t -> t
val negate : t -> t
val abs : t -> t
val less_than : t -> t -> bool
val leq : t -> t -> bool
val is_nearly_zero : t -> bool
val of_pdf_point : float -> t
val to_pdf_point : t -> float
val of_centimeter : float -> t
val of_millimeter : float -> t
val of_inch : float -> t
val show : t -> string
| null |
https://raw.githubusercontent.com/gfngfn/SATySFi/9dbd61df0ab05943b3394830c371e927df45251a/src/backend/length.mli
|
ocaml
|
type t [@@deriving show]
val zero : t
val add : t -> t -> t
val subtr : t -> t -> t
val mult : t -> float -> t
val div : t -> t -> float
val max : t -> t -> t
val min : t -> t -> t
val negate : t -> t
val abs : t -> t
val less_than : t -> t -> bool
val leq : t -> t -> bool
val is_nearly_zero : t -> bool
val of_pdf_point : float -> t
val to_pdf_point : t -> float
val of_centimeter : float -> t
val of_millimeter : float -> t
val of_inch : float -> t
val show : t -> string
|
|
ad8f5e269b02b5a831b3836513bc55229399d6ea9b6585534c1527793583cebb
|
rcherrueau/rastache
|
twice.rkt
|
#lang racket/base
(require rastache)
(define template
#<<HERESTRING
{{#person}}{{name}}{{/person}}
{{#person}}{{name}}{{/person}}
HERESTRING
)
(rast-compile/render (open-input-string template)
#hash{(person . #hash{(name . "tom")})}
(current-output-port))
| null |
https://raw.githubusercontent.com/rcherrueau/rastache/059d00c83416f8ba27cc38fa7f8321b075756d14/examples/twice.rkt
|
racket
|
#lang racket/base
(require rastache)
(define template
#<<HERESTRING
{{#person}}{{name}}{{/person}}
{{#person}}{{name}}{{/person}}
HERESTRING
)
(rast-compile/render (open-input-string template)
#hash{(person . #hash{(name . "tom")})}
(current-output-port))
|
|
77cd200522a9ee456d73fc9c6e860b168b3a401c4243f04cce6994ab7c93708d
|
rudolph-miller/cl-gists
|
9.gist-starred-p.lisp
|
(let ((id "gistid"))
(gist-starred-p id))
= > T or NIL
(let ((gist (git-gist "gistid")))
(gist-starred-p gist))
= > T or NIL
| null |
https://raw.githubusercontent.com/rudolph-miller/cl-gists/bcf3687f0af8b2eb5acaeda5db94d67446e56daf/examples/9.gist-starred-p.lisp
|
lisp
|
(let ((id "gistid"))
(gist-starred-p id))
= > T or NIL
(let ((gist (git-gist "gistid")))
(gist-starred-p gist))
= > T or NIL
|
|
5ccca2ad82e440f521eacec5055eb7ca82e669a8161b0a4d198330292b7e760e
|
blynn/compiler
|
Ast2.hs
|
FFI across multiple modules .
-- Rewrite with named fields, deriving.
module Ast where
import Base
import Map
data Type = TC String | TV String | TAp Type Type deriving Eq
arr a b = TAp (TAp (TC "->") a) b
data Extra = Basic String | Const Int | ChrCon Char | StrCon String | Link String String Qual
data Pat = PatLit Extra | PatVar String (Maybe Pat) | PatCon String [Pat]
data Ast = E Extra | V String | A Ast Ast | L String Ast | Pa [([Pat], Ast)] | Proof Pred
data Constr = Constr String [(String, Type)]
data Pred = Pred String Type deriving Eq
data Qual = Qual [Pred] Type
instance Show Type where
showsPrec _ = \case
TC s -> (s++)
TV s -> (s++)
TAp (TAp (TC "->") a) b -> showParen True $ shows a . (" -> "++) . shows b
TAp a b -> showParen True $ shows a . (' ':) . shows b
instance Show Pred where
showsPrec _ (Pred s t) = (s++) . (' ':) . shows t . (" => "++)
instance Show Qual where
showsPrec _ (Qual ps t) = foldr (.) id (map shows ps) . shows t
instance Show Extra where
showsPrec _ = \case
Basic s -> (s++)
Const i -> shows i
ChrCon c -> shows c
StrCon s -> shows s
Link im s _ -> (im++) . ('.':) . (s++)
instance Show Pat where
showsPrec _ = \case
PatLit e -> shows e
PatVar s mp -> (s++) . maybe id ((('@':) .) . shows) mp
PatCon s ps -> (s++) . foldr (.) id (((' ':) .) . shows <$> ps)
showVar s@(h:_) = showParen (elem h ":!#$%&*+./<=>?@\\^|-~") (s++)
instance Show Ast where
showsPrec prec = \case
E e -> shows e
V s -> showVar s
A x y -> showParen (1 <= prec) $ shows x . (' ':) . showsPrec 1 y
L s t -> showParen True $ ('\\':) . (s++) . (" -> "++) . shows t
Pa vsts -> ('\\':) . showParen True (foldr (.) id $ intersperse (';':) $ map (\(vs, t) -> foldr (.) id (intersperse (' ':) $ map (showParen True . shows) vs) . (" -> "++) . shows t) vsts)
Proof p -> ("{Proof "++) . shows p . ("}"++)
data Instance = Instance
-- Type, e.g. Int for Eq Int.
Type
-- Dictionary name, e.g. "{Eq Int}"
String
-- Context.
[Pred]
-- Method definitions
(Map String Ast)
data Neat = Neat
{ typeclasses :: Map String [String]
, instances :: Map String [Instance]
, topDefs :: [(String, Ast)]
-- | Typed ASTs, ready for compilation, including ADTs and methods,
-- e.g. (==), (Eq a => a -> a -> Bool, select-==)
, typedAsts :: [(String, (Qual, Ast))]
, dataCons :: Map String [Constr]
, ffiImports :: Map String Type
, ffiExports :: Map String String
, moduleImports :: [String]
}
neatEmpty = Neat Tip Tip [] [] Tip Tip Tip []
patVars = \case
PatLit _ -> []
PatVar s m -> s : maybe [] patVars m
PatCon _ args -> concat $ patVars <$> args
fvPro bound expr = case expr of
V s | not (elem s bound) -> [s]
A x y -> fvPro bound x `union` fvPro bound y
L s t -> fvPro (s:bound) t
Pa vsts -> foldr union [] $ map (\(vs, t) -> fvPro (concatMap patVars vs ++ bound) t) vsts
_ -> []
beta s a t = case t of
E _ -> t
V v -> if s == v then a else t
A x y -> A (beta s a x) (beta s a y)
L v u -> if s == v then t else L v $ beta s a u
typeVars = \case
TC _ -> []
TV v -> [v]
TAp x y -> typeVars x `union` typeVars y
depthFirstSearch = (foldl .) \relation st@(visited, sequence) vertex ->
if vertex `elem` visited then st else second (vertex:)
$ depthFirstSearch relation (vertex:visited, sequence) (relation vertex)
spanningSearch = (foldl .) \relation st@(visited, setSequence) vertex ->
if vertex `elem` visited then st else second ((:setSequence) . (vertex:))
$ depthFirstSearch relation (vertex:visited, []) (relation vertex)
scc ins outs = spanning . depthFirst where
depthFirst = snd . depthFirstSearch outs ([], [])
spanning = snd . spanningSearch ins ([], [])
| null |
https://raw.githubusercontent.com/blynn/compiler/b9fe455ad4ee4fbabe77f2f5c3c9aaa53cffa85b/inn/Ast2.hs
|
haskell
|
Rewrite with named fields, deriving.
Type, e.g. Int for Eq Int.
Dictionary name, e.g. "{Eq Int}"
Context.
Method definitions
| Typed ASTs, ready for compilation, including ADTs and methods,
e.g. (==), (Eq a => a -> a -> Bool, select-==)
|
FFI across multiple modules .
module Ast where
import Base
import Map
data Type = TC String | TV String | TAp Type Type deriving Eq
arr a b = TAp (TAp (TC "->") a) b
data Extra = Basic String | Const Int | ChrCon Char | StrCon String | Link String String Qual
data Pat = PatLit Extra | PatVar String (Maybe Pat) | PatCon String [Pat]
data Ast = E Extra | V String | A Ast Ast | L String Ast | Pa [([Pat], Ast)] | Proof Pred
data Constr = Constr String [(String, Type)]
data Pred = Pred String Type deriving Eq
data Qual = Qual [Pred] Type
instance Show Type where
showsPrec _ = \case
TC s -> (s++)
TV s -> (s++)
TAp (TAp (TC "->") a) b -> showParen True $ shows a . (" -> "++) . shows b
TAp a b -> showParen True $ shows a . (' ':) . shows b
instance Show Pred where
showsPrec _ (Pred s t) = (s++) . (' ':) . shows t . (" => "++)
instance Show Qual where
showsPrec _ (Qual ps t) = foldr (.) id (map shows ps) . shows t
instance Show Extra where
showsPrec _ = \case
Basic s -> (s++)
Const i -> shows i
ChrCon c -> shows c
StrCon s -> shows s
Link im s _ -> (im++) . ('.':) . (s++)
instance Show Pat where
showsPrec _ = \case
PatLit e -> shows e
PatVar s mp -> (s++) . maybe id ((('@':) .) . shows) mp
PatCon s ps -> (s++) . foldr (.) id (((' ':) .) . shows <$> ps)
showVar s@(h:_) = showParen (elem h ":!#$%&*+./<=>?@\\^|-~") (s++)
instance Show Ast where
showsPrec prec = \case
E e -> shows e
V s -> showVar s
A x y -> showParen (1 <= prec) $ shows x . (' ':) . showsPrec 1 y
L s t -> showParen True $ ('\\':) . (s++) . (" -> "++) . shows t
Pa vsts -> ('\\':) . showParen True (foldr (.) id $ intersperse (';':) $ map (\(vs, t) -> foldr (.) id (intersperse (' ':) $ map (showParen True . shows) vs) . (" -> "++) . shows t) vsts)
Proof p -> ("{Proof "++) . shows p . ("}"++)
data Instance = Instance
Type
String
[Pred]
(Map String Ast)
data Neat = Neat
{ typeclasses :: Map String [String]
, instances :: Map String [Instance]
, topDefs :: [(String, Ast)]
, typedAsts :: [(String, (Qual, Ast))]
, dataCons :: Map String [Constr]
, ffiImports :: Map String Type
, ffiExports :: Map String String
, moduleImports :: [String]
}
neatEmpty = Neat Tip Tip [] [] Tip Tip Tip []
patVars = \case
PatLit _ -> []
PatVar s m -> s : maybe [] patVars m
PatCon _ args -> concat $ patVars <$> args
fvPro bound expr = case expr of
V s | not (elem s bound) -> [s]
A x y -> fvPro bound x `union` fvPro bound y
L s t -> fvPro (s:bound) t
Pa vsts -> foldr union [] $ map (\(vs, t) -> fvPro (concatMap patVars vs ++ bound) t) vsts
_ -> []
beta s a t = case t of
E _ -> t
V v -> if s == v then a else t
A x y -> A (beta s a x) (beta s a y)
L v u -> if s == v then t else L v $ beta s a u
typeVars = \case
TC _ -> []
TV v -> [v]
TAp x y -> typeVars x `union` typeVars y
depthFirstSearch = (foldl .) \relation st@(visited, sequence) vertex ->
if vertex `elem` visited then st else second (vertex:)
$ depthFirstSearch relation (vertex:visited, sequence) (relation vertex)
spanningSearch = (foldl .) \relation st@(visited, setSequence) vertex ->
if vertex `elem` visited then st else second ((:setSequence) . (vertex:))
$ depthFirstSearch relation (vertex:visited, []) (relation vertex)
scc ins outs = spanning . depthFirst where
depthFirst = snd . depthFirstSearch outs ([], [])
spanning = snd . spanningSearch ins ([], [])
|
a5e7a2a458bbc9eb591c525dde812edb71763c3fdb38faad3eb9c83e2e2a0294
|
Ledest/otpbp
|
otpbp_lib.erl
|
-module(otpbp_lib).
-ifndef(HAVE_lib__nonl_1).
OTP < 21.0
-export([nonl/1]).
-endif.
-ifndef(HAVE_lib__send_2).
OTP < 21.0
-export([send/2]).
-endif.
-ifndef(HAVE_lib__sendw_2).
OTP < 21.0
-export([sendw/2]).
-endif.
-ifndef(HAVE_lib__flush_receive_0).
OTP < 21.0
-export([flush_receive/0]).
-endif.
-ifndef(HAVE_lib__error_message_2).
OTP < 21.0
-export([error_message/2]).
-endif.
-ifndef(HAVE_lib__progname_0).
OTP < 21.0
-export([progname/0]).
-endif.
-ifndef(HAVE_lib__nonl_1).
nonl([$\n|T]) -> nonl(T);
nonl([H|T]) -> [H|nonl(T)];
nonl([]) -> [].
-endif.
-ifndef(HAVE_lib__send_2).
send(To, Msg) -> To ! Msg.
-endif.
-ifndef(HAVE_lib__sendw_2).
sendw(To, Msg) ->
To ! {self(), Msg},
receive
Reply -> Reply
end.
-endif.
-ifndef(HAVE_lib__flush_receive_0).
flush_receive() ->
receive
_ -> flush_receive()
after 0 -> ok
end.
-endif.
-ifndef(HAVE_lib__error_message_2).
error_message(Format, Args) -> io:format("** ~ts **\n", [io_lib:format(Format, Args)]).
-endif.
-ifndef(HAVE_lib__progname_0).
progname() ->
case init:get_argument(progname) of
{ok, [[Prog]]} -> list_to_atom(Prog);
_ -> no_prog_name
end.
-endif.
| null |
https://raw.githubusercontent.com/Ledest/otpbp/f93923239b33cc05500733027e6e775090ac80ad/src/otpbp_lib.erl
|
erlang
|
-module(otpbp_lib).
-ifndef(HAVE_lib__nonl_1).
OTP < 21.0
-export([nonl/1]).
-endif.
-ifndef(HAVE_lib__send_2).
OTP < 21.0
-export([send/2]).
-endif.
-ifndef(HAVE_lib__sendw_2).
OTP < 21.0
-export([sendw/2]).
-endif.
-ifndef(HAVE_lib__flush_receive_0).
OTP < 21.0
-export([flush_receive/0]).
-endif.
-ifndef(HAVE_lib__error_message_2).
OTP < 21.0
-export([error_message/2]).
-endif.
-ifndef(HAVE_lib__progname_0).
OTP < 21.0
-export([progname/0]).
-endif.
-ifndef(HAVE_lib__nonl_1).
nonl([$\n|T]) -> nonl(T);
nonl([H|T]) -> [H|nonl(T)];
nonl([]) -> [].
-endif.
-ifndef(HAVE_lib__send_2).
send(To, Msg) -> To ! Msg.
-endif.
-ifndef(HAVE_lib__sendw_2).
sendw(To, Msg) ->
To ! {self(), Msg},
receive
Reply -> Reply
end.
-endif.
-ifndef(HAVE_lib__flush_receive_0).
flush_receive() ->
receive
_ -> flush_receive()
after 0 -> ok
end.
-endif.
-ifndef(HAVE_lib__error_message_2).
error_message(Format, Args) -> io:format("** ~ts **\n", [io_lib:format(Format, Args)]).
-endif.
-ifndef(HAVE_lib__progname_0).
progname() ->
case init:get_argument(progname) of
{ok, [[Prog]]} -> list_to_atom(Prog);
_ -> no_prog_name
end.
-endif.
|
|
ee565fefab2f032cce5cf69b952b40cef0c6868471037634ac8a90c0dd24cb07
|
irastypain/sicp-on-language-racket
|
exercise_1_11i-test.rkt
|
#lang racket
(require rackunit
rackunit/text-ui
"../../src/chapter01/exercise_1_11i.rkt")
(define tests
(test-suite
"Function f(n) [Iterative process]"
(test-case
"When n is less than 3"
(check-equal? -1 (fn -1))
(check-equal? 0 (fn 0))
(check-equal? 1 (fn 1))
(check-equal? 2 (fn 2)))
(test-case
"When n is greater than or equal to 3"
(check-equal? 3 (fn 3))
(check-equal? 6 (fn 4))
(check-equal? 11 (fn 5))
(check-equal? 20 (fn 6)))))
(run-tests tests 'verbose)
| null |
https://raw.githubusercontent.com/irastypain/sicp-on-language-racket/0052f91d3c2432a00e7e15310f416cb77eeb4c9c/test/chapter01/exercise_1_11i-test.rkt
|
racket
|
#lang racket
(require rackunit
rackunit/text-ui
"../../src/chapter01/exercise_1_11i.rkt")
(define tests
(test-suite
"Function f(n) [Iterative process]"
(test-case
"When n is less than 3"
(check-equal? -1 (fn -1))
(check-equal? 0 (fn 0))
(check-equal? 1 (fn 1))
(check-equal? 2 (fn 2)))
(test-case
"When n is greater than or equal to 3"
(check-equal? 3 (fn 3))
(check-equal? 6 (fn 4))
(check-equal? 11 (fn 5))
(check-equal? 20 (fn 6)))))
(run-tests tests 'verbose)
|
|
afb5b4660d8623629aeacb0c8b107d69021406f7ce2f17863165e6c260b5c426
|
GrammaticalFramework/gf-core
|
PGFToCFG.hs
|
----------------------------------------------------------------------
-- |
-- Module : GF.Speech.PGFToCFG
--
Approximates PGF grammars with context - free grammars .
----------------------------------------------------------------------
module GF.Speech.PGFToCFG (bnfPrinter, pgfToCFG) where
import PGF(showCId)
import PGF.Internal as PGF
import GF.Infra . Ident
import GF.Grammar.CFG hiding (Symbol)
import Data.Array.IArray as Array
import Data . List
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.IntMap as IntMap
import Data . Maybe
import Data.Set (Set)
import qualified Data.Set as Set
bnfPrinter :: PGF -> CId -> String
bnfPrinter = toBNF id
toBNF :: (CFG -> CFG) -> PGF -> CId -> String
toBNF f pgf cnc = prCFG $ f $ pgfToCFG pgf cnc
type Profile = [Int]
pgfToCFG :: PGF
-> CId -- ^ Concrete syntax name
-> CFG
pgfToCFG pgf lang = mkCFG (showCId (lookStartCat pgf)) extCats (startRules ++ concatMap ruleToCFRule rules)
where
cnc = lookConcr pgf lang
rules :: [(FId,Production)]
rules = [(fcat,prod) | (fcat,set) <- IntMap.toList (PGF.productions cnc)
, prod <- Set.toList set]
fcatCats :: Map FId Cat
fcatCats = Map.fromList [(fc, showCId c ++ "_" ++ show i)
| (c,CncCat s e lbls) <- Map.toList (cnccats cnc),
(fc,i) <- zip (range (s,e)) [1..]]
fcatCat :: FId -> Cat
fcatCat c = Map.findWithDefault ("Unknown_" ++ show c) c fcatCats
fcatToCat :: FId -> LIndex -> Cat
fcatToCat c l = fcatCat c ++ row
where row = if catLinArity c == 1 then "" else "_" ++ show l
-- gets the number of fields in the lincat for the given category
catLinArity :: FId -> Int
catLinArity c = maximum (1:[rangeSize (bounds rhs) | (CncFun _ rhs, _) <- topdownRules c])
topdownRules cat = f cat []
where
f cat rules = maybe rules (Set.foldr g rules) (IntMap.lookup cat (productions cnc))
g (PApply funid args) rules = (cncfuns cnc ! funid,args) : rules
g (PCoerce cat) rules = f cat rules
extCats :: Set Cat
extCats = Set.fromList $ map ruleLhs startRules
startRules :: [CFRule]
startRules = [Rule (showCId c) [NonTerminal (fcatToCat fc r)] (CFRes 0)
| (c,CncCat s e lbls) <- Map.toList (cnccats cnc),
fc <- range (s,e), not (isPredefFId fc),
r <- [0..catLinArity fc-1]]
ruleToCFRule :: (FId,Production) -> [CFRule]
ruleToCFRule (c,PApply funid args) =
[Rule (fcatToCat c l) (mkRhs row) (profilesToTerm [fixProfile row n | n <- [0..length args-1]])
| (l,seqid) <- Array.assocs rhs
, let row = sequences cnc ! seqid
, not (containsLiterals row)]
where
CncFun f rhs = cncfuns cnc ! funid
mkRhs :: Array DotPos Symbol -> [CFSymbol]
mkRhs = concatMap symbolToCFSymbol . Array.elems
containsLiterals :: Array DotPos Symbol -> Bool
containsLiterals row = not (null ([n | SymLit n _ <- Array.elems row] ++
[n | SymVar n _ <- Array.elems row]))
symbolToCFSymbol :: Symbol -> [CFSymbol]
symbolToCFSymbol (SymCat n l) = [let PArg _ fid = args!!n in NonTerminal (fcatToCat fid l)]
symbolToCFSymbol (SymKS t) = [Terminal t]
symbolToCFSymbol (SymKP syms as) = concatMap symbolToCFSymbol syms
---- ++ [t | Alt ss _ <- as, t <- ss]
---- should be alternatives in [[CFSymbol]]
-- AR 3/6/2010
symbolToCFSymbol SymBIND = [Terminal "&+"]
symbolToCFSymbol SymSOFT_BIND = []
symbolToCFSymbol SymSOFT_SPACE = []
symbolToCFSymbol SymCAPIT = [Terminal "&|"]
symbolToCFSymbol SymALL_CAPIT = [Terminal "&|"]
symbolToCFSymbol SymNE = []
fixProfile :: Array DotPos Symbol -> Int -> Profile
fixProfile row i = [k | (k,j) <- nts, j == i]
where
nts = zip [0..] [j | nt <- Array.elems row, j <- getPos nt]
getPos (SymCat j _) = [j]
getPos (SymLit j _) = [j]
getPos _ = []
profilesToTerm :: [Profile] -> CFTerm
profilesToTerm ps = CFObj f (zipWith profileToTerm argTypes ps)
where (argTypes,_) = catSkeleton $ lookType (abstract pgf) f
profileToTerm :: CId -> Profile -> CFTerm
profileToTerm t [] = CFMeta t
profileToTerm _ xs = CFRes (last xs) -- FIXME: unify
ruleToCFRule (c,PCoerce c') =
[Rule (fcatToCat c l) [NonTerminal (fcatToCat c' l)] (CFRes 0)
| l <- [0..catLinArity c-1]]
| null |
https://raw.githubusercontent.com/GrammaticalFramework/gf-core/f2e52d6f2c2bc90febceebdea0268b40ea37476c/src/compiler/GF/Speech/PGFToCFG.hs
|
haskell
|
--------------------------------------------------------------------
|
Module : GF.Speech.PGFToCFG
--------------------------------------------------------------------
^ Concrete syntax name
gets the number of fields in the lincat for the given category
-- ++ [t | Alt ss _ <- as, t <- ss]
-- should be alternatives in [[CFSymbol]]
AR 3/6/2010
FIXME: unify
|
Approximates PGF grammars with context - free grammars .
module GF.Speech.PGFToCFG (bnfPrinter, pgfToCFG) where
import PGF(showCId)
import PGF.Internal as PGF
import GF.Infra . Ident
import GF.Grammar.CFG hiding (Symbol)
import Data.Array.IArray as Array
import Data . List
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.IntMap as IntMap
import Data . Maybe
import Data.Set (Set)
import qualified Data.Set as Set
bnfPrinter :: PGF -> CId -> String
bnfPrinter = toBNF id
toBNF :: (CFG -> CFG) -> PGF -> CId -> String
toBNF f pgf cnc = prCFG $ f $ pgfToCFG pgf cnc
type Profile = [Int]
pgfToCFG :: PGF
-> CFG
pgfToCFG pgf lang = mkCFG (showCId (lookStartCat pgf)) extCats (startRules ++ concatMap ruleToCFRule rules)
where
cnc = lookConcr pgf lang
rules :: [(FId,Production)]
rules = [(fcat,prod) | (fcat,set) <- IntMap.toList (PGF.productions cnc)
, prod <- Set.toList set]
fcatCats :: Map FId Cat
fcatCats = Map.fromList [(fc, showCId c ++ "_" ++ show i)
| (c,CncCat s e lbls) <- Map.toList (cnccats cnc),
(fc,i) <- zip (range (s,e)) [1..]]
fcatCat :: FId -> Cat
fcatCat c = Map.findWithDefault ("Unknown_" ++ show c) c fcatCats
fcatToCat :: FId -> LIndex -> Cat
fcatToCat c l = fcatCat c ++ row
where row = if catLinArity c == 1 then "" else "_" ++ show l
catLinArity :: FId -> Int
catLinArity c = maximum (1:[rangeSize (bounds rhs) | (CncFun _ rhs, _) <- topdownRules c])
topdownRules cat = f cat []
where
f cat rules = maybe rules (Set.foldr g rules) (IntMap.lookup cat (productions cnc))
g (PApply funid args) rules = (cncfuns cnc ! funid,args) : rules
g (PCoerce cat) rules = f cat rules
extCats :: Set Cat
extCats = Set.fromList $ map ruleLhs startRules
startRules :: [CFRule]
startRules = [Rule (showCId c) [NonTerminal (fcatToCat fc r)] (CFRes 0)
| (c,CncCat s e lbls) <- Map.toList (cnccats cnc),
fc <- range (s,e), not (isPredefFId fc),
r <- [0..catLinArity fc-1]]
ruleToCFRule :: (FId,Production) -> [CFRule]
ruleToCFRule (c,PApply funid args) =
[Rule (fcatToCat c l) (mkRhs row) (profilesToTerm [fixProfile row n | n <- [0..length args-1]])
| (l,seqid) <- Array.assocs rhs
, let row = sequences cnc ! seqid
, not (containsLiterals row)]
where
CncFun f rhs = cncfuns cnc ! funid
mkRhs :: Array DotPos Symbol -> [CFSymbol]
mkRhs = concatMap symbolToCFSymbol . Array.elems
containsLiterals :: Array DotPos Symbol -> Bool
containsLiterals row = not (null ([n | SymLit n _ <- Array.elems row] ++
[n | SymVar n _ <- Array.elems row]))
symbolToCFSymbol :: Symbol -> [CFSymbol]
symbolToCFSymbol (SymCat n l) = [let PArg _ fid = args!!n in NonTerminal (fcatToCat fid l)]
symbolToCFSymbol (SymKS t) = [Terminal t]
symbolToCFSymbol (SymKP syms as) = concatMap symbolToCFSymbol syms
symbolToCFSymbol SymBIND = [Terminal "&+"]
symbolToCFSymbol SymSOFT_BIND = []
symbolToCFSymbol SymSOFT_SPACE = []
symbolToCFSymbol SymCAPIT = [Terminal "&|"]
symbolToCFSymbol SymALL_CAPIT = [Terminal "&|"]
symbolToCFSymbol SymNE = []
fixProfile :: Array DotPos Symbol -> Int -> Profile
fixProfile row i = [k | (k,j) <- nts, j == i]
where
nts = zip [0..] [j | nt <- Array.elems row, j <- getPos nt]
getPos (SymCat j _) = [j]
getPos (SymLit j _) = [j]
getPos _ = []
profilesToTerm :: [Profile] -> CFTerm
profilesToTerm ps = CFObj f (zipWith profileToTerm argTypes ps)
where (argTypes,_) = catSkeleton $ lookType (abstract pgf) f
profileToTerm :: CId -> Profile -> CFTerm
profileToTerm t [] = CFMeta t
ruleToCFRule (c,PCoerce c') =
[Rule (fcatToCat c l) [NonTerminal (fcatToCat c' l)] (CFRes 0)
| l <- [0..catLinArity c-1]]
|
51dc1c7648129c8058723246c8e30c3a3e156d5d908ca70a0482bce28caf2a71
|
craigl64/clim-ccl
|
cloe-activities.lisp
|
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : CLOE - CLIM ; Base : 10 ; Lowercase : Yes -*-
(in-package :cloe-clim)
"Copyright (c) 1990, 1991, 1992 Symbolics, Inc. All rights reserved."
(defun run-cloe-application (name &key (port (find-port)))
(win::show-window (win::get-term-window) :type :minimize)
(run-frame-top-level
(make-application-frame name :frame-manager (find-frame-manager :port port))))
(defun cloe-debugger-hook (condition hook)
(declare (ignore hook))
(let ((term (win::get-term-window)))
(win::show-window term :type :show-normal)
(unwind-protect
(invoke-debugger condition)
(when (frame-top-level-sheet *application-frame*)
(win::show-window term :type :minimize)))))
| null |
https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/cloe/cloe-activities.lisp
|
lisp
|
Syntax : ANSI - Common - Lisp ; Package : CLOE - CLIM ; Base : 10 ; Lowercase : Yes -*-
|
(in-package :cloe-clim)
"Copyright (c) 1990, 1991, 1992 Symbolics, Inc. All rights reserved."
(defun run-cloe-application (name &key (port (find-port)))
(win::show-window (win::get-term-window) :type :minimize)
(run-frame-top-level
(make-application-frame name :frame-manager (find-frame-manager :port port))))
(defun cloe-debugger-hook (condition hook)
(declare (ignore hook))
(let ((term (win::get-term-window)))
(win::show-window term :type :show-normal)
(unwind-protect
(invoke-debugger condition)
(when (frame-top-level-sheet *application-frame*)
(win::show-window term :type :minimize)))))
|
2e51f4540b43bb6c76c28d66a9e90f77d03d34309d1e82952e5fd5606aae9892
|
LivewareProblems/hyper
|
hyper_binary.erl
|
@doc : Registers stored in one large binary
%%
This backend uses one plain Erlang binary to store registers . The
%% cost of rebuilding the binary is amortized by keeping a buffer of
%% inserts to perform in the future.
-module(hyper_binary).
-behaviour(hyper_register).
%%-compile(native).
-export([
new/1,
set/3,
compact/1,
max_merge/1, max_merge/2,
reduce_precision/2,
bytes/1,
register_sum/1,
register_histogram/1,
zero_count/1,
encode_registers/1,
decode_registers/2,
empty_binary/1,
max_registers/1,
precision/1
]).
-define(VALUE_SIZE, 6).
-define(MERGE_THRESHOLD, 0.05).
-type precision() :: 4..16.
-record(buffer, {buf, buf_size, p :: precision(), convert_threshold}).
-record(dense, {b, buf, buf_size, p :: precision(), merge_threshold}).
new(P) ->
new_buffer(P).
new_buffer(P) ->
M = hyper_utils:m(P),
5 words for each entry
ConvertThreshold = M div (5 * 8),
#buffer{
buf = [],
buf_size = 0,
p = P,
convert_threshold = ConvertThreshold
}.
new_dense(P) ->
M = hyper_utils:m(P),
T = max(trunc(M * ?MERGE_THRESHOLD), 16),
#dense{
b = empty_binary(M),
buf = [],
buf_size = 0,
p = P,
merge_threshold = T
}.
set(Index, Value, #buffer{buf = [{Index, OldValue} | Rest]} = Buffer) ->
NewVal = hyper_utils:run_of_zeroes(Value),
Buffer#buffer{buf = [{Index, max(NewVal, OldValue)} | Rest]};
set(Index, Value, #buffer{buf = Buf, buf_size = BufSize} = Buffer) ->
NewVal = hyper_utils:run_of_zeroes(Value),
NewBuffer = Buffer#buffer{buf = [{Index, NewVal} | Buf], buf_size = BufSize + 1},
case NewBuffer#buffer.buf_size < NewBuffer#buffer.convert_threshold of
true ->
NewBuffer;
false ->
buffer2dense(NewBuffer)
end;
set(Index, Value, #dense{buf = Buf, buf_size = BufSize} = Dense) ->
LeftOffset = Index * ?VALUE_SIZE,
<<_:LeftOffset/bitstring, R:?VALUE_SIZE/integer, _/bitstring>> = Dense#dense.b,
NewVal = hyper_utils:run_of_zeroes(Value),
if
R < NewVal ->
New = Dense#dense{buf = [{Index, NewVal} | Buf], buf_size = BufSize + 1},
case New#dense.buf_size < Dense#dense.merge_threshold of
true ->
New;
false ->
compact(New)
end;
true ->
Dense
end.
compact(#buffer{buf_size = BufSize, convert_threshold = ConvertThreshold} = Buffer) ->
case BufSize < ConvertThreshold of
true ->
Buffer;
false ->
buffer2dense(Buffer)
end;
compact(#dense{b = B, buf = Buf} = Dense) ->
NewB = merge_buf(B, max_registers(Buf)),
Dense#dense{
b = NewB,
buf = [],
buf_size = 0
}.
max_merge([First | Rest]) ->
lists:foldl(fun max_merge/2, First, Rest).
max_merge(
#dense{
b = SmallB,
buf = SmallBuf,
buf_size = SmallBufSize
},
#dense{
b = BigB,
buf = BigBuf,
buf_size = BigBufSize
} =
Big
) ->
case SmallBufSize + BigBufSize < Big#dense.merge_threshold of
true ->
Merged = do_merge(SmallB, BigB, <<>>),
Big#dense{
b = Merged,
buf = SmallBuf ++ BigBuf,
buf_size = SmallBufSize + BigBufSize
};
false ->
BigWithBuf = merge_buf(BigB, max_registers(SmallBuf ++ BigBuf)),
Merged = do_merge(SmallB, BigWithBuf, <<>>),
Big#dense{
b = Merged,
buf = [],
buf_size = 0
}
end;
max_merge(
#buffer{buf = Buf, buf_size = BufferSize},
#dense{buf = DenseBuf, buf_size = DenseSize} = Dense
) ->
case BufferSize + DenseSize < Dense#dense.merge_threshold of
true ->
Dense#dense{buf = Buf ++ DenseBuf, buf_size = BufferSize + DenseSize};
false ->
Merged = max_registers(DenseBuf ++ Buf),
Dense#dense{buf = Merged, buf_size = length(Merged)}
end;
max_merge(#dense{} = Dense, #buffer{} = Buffer) ->
max_merge(Buffer, Dense);
max_merge(
#buffer{buf = LeftBuf, buf_size = LeftBufSize},
#buffer{buf = RightBuf, buf_size = RightBufSize} = Right
) ->
case LeftBufSize + RightBufSize < Right#buffer.convert_threshold of
true ->
Right#buffer{buf = LeftBuf ++ RightBuf, buf_size = LeftBufSize + RightBufSize};
false ->
Merged = max_registers(LeftBuf ++ RightBuf),
NewRight = Right#buffer{buf = Merged, buf_size = length(Merged)},
case NewRight#buffer.buf_size < NewRight#buffer.convert_threshold of
true ->
NewRight;
false ->
buffer2dense(NewRight)
end
end.
reduce_precision(NewP, #dense{p = OldP} = Dense) ->
ChangeP = OldP - NewP,
Buf = register_fold(ChangeP, Dense),
Empty = new_dense(NewP),
compact(Empty#dense{buf = Buf});
reduce_precision(NewP, #buffer{p = OldP} = Buffer) ->
ChangeP = OldP - NewP,
Buf = register_fold(ChangeP, Buffer),
Empty = new_dense(NewP),
compact(Empty#dense{buf = Buf}).
fold an HLL to a lower number of registers ` NewM ` by projecting the values
%% onto their new index, see
%% -operations-on-hlls-of-different-sizes/
%% NOTE: this function does not perform the max_registers step
register_fold(ChangeP, B) ->
ChangeM = hyper_utils:m(ChangeP),
element(
3,
fold(
fun
(I, V, {_Index, CurrentList, Acc}) when CurrentList == [] ->
{I, [V], Acc};
(I, V, {Index, CurrentList, Acc}) when I - Index < ChangeM ->
{Index, [V | CurrentList], Acc};
(I, V, {_Index, CurrentList, Acc}) ->
{I, [V], [
{I bsr ChangeP, hyper_utils:changeV(lists:reverse(CurrentList), ChangeP)}
| Acc
]}
end,
{0, [], []},
B
)
).
register_sum(B) ->
fold(
fun
(_, 0, Acc) ->
Acc + 1.0;
(_, 1, Acc) ->
Acc + 0.5;
(_, 2, Acc) ->
Acc + 0.25;
(_, 3, Acc) ->
Acc + 0.125;
(_, 4, Acc) ->
Acc + 0.0625;
(_, 5, Acc) ->
Acc + 0.03125;
(_, 6, Acc) ->
Acc + 0.015625;
(_, 7, Acc) ->
Acc + 0.0078125;
(_, 8, Acc) ->
Acc + 0.00390625;
(_, 9, Acc) ->
Acc + 0.001953125;
(_, V, Acc) ->
Acc + math:pow(2, -V)
end,
0,
B
).
register_histogram(#buffer{p = P} = B) ->
register_histogram(B, P);
register_histogram(#dense{p = P} = B) ->
register_histogram(B, P).
register_histogram(B, P) ->
todo use from_keys once we are at otp 26
fold(
fun(_, Value, Acc) -> maps:update_with(Value, fun(V) -> V + 1 end, 0, Acc) end,
maps:from_list(
lists:map(fun(I) -> {I, 0} end, lists:seq(0, 65 - P))
),
B
).
zero_count(B) ->
fold(
fun
(_, 0, Acc) ->
Acc + 1;
(_, _, Acc) ->
Acc
end,
0,
B
).
encode_registers(#buffer{} = Buffer) ->
encode_registers(buffer2dense(Buffer));
encode_registers(#dense{b = B}) ->
<<<<I:8/integer>> || <<I:?VALUE_SIZE/integer>> <= B>>.
decode_registers(AllBytes, P) ->
M = hyper_utils:m(P),
Bytes =
case AllBytes of
<<B:M/binary>> ->
B;
<<B:M/binary, 0>> ->
B
end,
Dense = new_dense(P),
Dense#dense{b = <<<<I:?VALUE_SIZE/integer>> || <<I:8>> <= Bytes>>}.
bytes(#dense{b = B}) ->
erlang:byte_size(B);
bytes(#buffer{} = Buffer) ->
erts_debug:flat_size(Buffer) * 8.
precision(#dense{p = P}) ->
P;
precision(#buffer{p = P}) ->
P.
%%
INTERNALS
%%
empty_binary(M) ->
list_to_bitstring([<<0:?VALUE_SIZE/integer>> || _ <- lists:seq(0, M - 1)]).
max_registers(Buf) ->
lists:keysort(
1,
maps:to_list(
lists:foldl(
fun({I, V}, Acc) ->
case maps:find(I, Acc) of
{ok, R} when R >= V -> Acc;
_ -> maps:put(I, V, Acc)
end
end,
#{},
Buf
)
)
).
buffer2dense(#buffer{buf = Buf, p = P}) ->
Dense = new_dense(P),
Merged = merge_buf(Dense#dense.b, max_registers(Buf)),
Dense#dense{b = Merged}.
do_merge(<<>>, <<>>, Acc) ->
Acc;
do_merge(
<<Left:?VALUE_SIZE/integer, SmallRest/bitstring>>,
<<Right:?VALUE_SIZE/integer, BigRest/bitstring>>,
Acc
) ->
do_merge(SmallRest, BigRest, <<Acc/bits, (max(Left, Right)):?VALUE_SIZE>>).
fold(F, Acc, #buffer{} = Buffer) ->
TODO fix this to not need to move to a dense , it is not technically neeeded
% We can just fold on the list i think
fold(F, Acc, buffer2dense(Buffer));
fold(F, Acc, #dense{b = B, buf = Buf}) ->
do_fold(F, Acc, merge_buf(B, max_registers(Buf)), 0).
do_fold(_, Acc, <<>>, _) ->
Acc;
do_fold(F, Acc, <<Value:?VALUE_SIZE/integer, Rest/bitstring>>, Index) ->
do_fold(F, F(Index, Value, Acc), Rest, Index + 1).
merge_buf(B, L) ->
merge_buf(B, L, -1, <<>>).
merge_buf(B, [], _PrevIndex, Acc) ->
<<Acc/bitstring, B/bitstring>>;
merge_buf(B, [{Index, Value} | Rest], PrevIndex, Acc) ->
I = (Index - PrevIndex - 1) * ?VALUE_SIZE,
case B of
<<Left:I/bitstring, OldValue:?VALUE_SIZE/integer, Right/bitstring>> ->
case OldValue < Value of
true ->
NewAcc = <<Acc/bitstring, Left/bitstring, Value:?VALUE_SIZE/integer>>,
merge_buf(Right, Rest, Index, NewAcc);
false ->
NewAcc = <<Acc/bitstring, Left/bitstring, OldValue:?VALUE_SIZE/integer>>,
merge_buf(Right, Rest, Index, NewAcc)
end;
<<Left:I/bitstring>> ->
<<Acc/bitstring, Left/bitstring, Value:?VALUE_SIZE/integer>>
end.
| null |
https://raw.githubusercontent.com/LivewareProblems/hyper/9f6ee16c6c0f8cb387737642d63ff153de913ae3/src/hyper_binary.erl
|
erlang
|
cost of rebuilding the binary is amortized by keeping a buffer of
inserts to perform in the future.
-compile(native).
onto their new index, see
-operations-on-hlls-of-different-sizes/
NOTE: this function does not perform the max_registers step
We can just fold on the list i think
|
@doc : Registers stored in one large binary
This backend uses one plain Erlang binary to store registers . The
-module(hyper_binary).
-behaviour(hyper_register).
-export([
new/1,
set/3,
compact/1,
max_merge/1, max_merge/2,
reduce_precision/2,
bytes/1,
register_sum/1,
register_histogram/1,
zero_count/1,
encode_registers/1,
decode_registers/2,
empty_binary/1,
max_registers/1,
precision/1
]).
-define(VALUE_SIZE, 6).
-define(MERGE_THRESHOLD, 0.05).
-type precision() :: 4..16.
-record(buffer, {buf, buf_size, p :: precision(), convert_threshold}).
-record(dense, {b, buf, buf_size, p :: precision(), merge_threshold}).
new(P) ->
new_buffer(P).
new_buffer(P) ->
M = hyper_utils:m(P),
5 words for each entry
ConvertThreshold = M div (5 * 8),
#buffer{
buf = [],
buf_size = 0,
p = P,
convert_threshold = ConvertThreshold
}.
new_dense(P) ->
M = hyper_utils:m(P),
T = max(trunc(M * ?MERGE_THRESHOLD), 16),
#dense{
b = empty_binary(M),
buf = [],
buf_size = 0,
p = P,
merge_threshold = T
}.
set(Index, Value, #buffer{buf = [{Index, OldValue} | Rest]} = Buffer) ->
NewVal = hyper_utils:run_of_zeroes(Value),
Buffer#buffer{buf = [{Index, max(NewVal, OldValue)} | Rest]};
set(Index, Value, #buffer{buf = Buf, buf_size = BufSize} = Buffer) ->
NewVal = hyper_utils:run_of_zeroes(Value),
NewBuffer = Buffer#buffer{buf = [{Index, NewVal} | Buf], buf_size = BufSize + 1},
case NewBuffer#buffer.buf_size < NewBuffer#buffer.convert_threshold of
true ->
NewBuffer;
false ->
buffer2dense(NewBuffer)
end;
set(Index, Value, #dense{buf = Buf, buf_size = BufSize} = Dense) ->
LeftOffset = Index * ?VALUE_SIZE,
<<_:LeftOffset/bitstring, R:?VALUE_SIZE/integer, _/bitstring>> = Dense#dense.b,
NewVal = hyper_utils:run_of_zeroes(Value),
if
R < NewVal ->
New = Dense#dense{buf = [{Index, NewVal} | Buf], buf_size = BufSize + 1},
case New#dense.buf_size < Dense#dense.merge_threshold of
true ->
New;
false ->
compact(New)
end;
true ->
Dense
end.
compact(#buffer{buf_size = BufSize, convert_threshold = ConvertThreshold} = Buffer) ->
case BufSize < ConvertThreshold of
true ->
Buffer;
false ->
buffer2dense(Buffer)
end;
compact(#dense{b = B, buf = Buf} = Dense) ->
NewB = merge_buf(B, max_registers(Buf)),
Dense#dense{
b = NewB,
buf = [],
buf_size = 0
}.
max_merge([First | Rest]) ->
lists:foldl(fun max_merge/2, First, Rest).
max_merge(
#dense{
b = SmallB,
buf = SmallBuf,
buf_size = SmallBufSize
},
#dense{
b = BigB,
buf = BigBuf,
buf_size = BigBufSize
} =
Big
) ->
case SmallBufSize + BigBufSize < Big#dense.merge_threshold of
true ->
Merged = do_merge(SmallB, BigB, <<>>),
Big#dense{
b = Merged,
buf = SmallBuf ++ BigBuf,
buf_size = SmallBufSize + BigBufSize
};
false ->
BigWithBuf = merge_buf(BigB, max_registers(SmallBuf ++ BigBuf)),
Merged = do_merge(SmallB, BigWithBuf, <<>>),
Big#dense{
b = Merged,
buf = [],
buf_size = 0
}
end;
max_merge(
#buffer{buf = Buf, buf_size = BufferSize},
#dense{buf = DenseBuf, buf_size = DenseSize} = Dense
) ->
case BufferSize + DenseSize < Dense#dense.merge_threshold of
true ->
Dense#dense{buf = Buf ++ DenseBuf, buf_size = BufferSize + DenseSize};
false ->
Merged = max_registers(DenseBuf ++ Buf),
Dense#dense{buf = Merged, buf_size = length(Merged)}
end;
max_merge(#dense{} = Dense, #buffer{} = Buffer) ->
max_merge(Buffer, Dense);
max_merge(
#buffer{buf = LeftBuf, buf_size = LeftBufSize},
#buffer{buf = RightBuf, buf_size = RightBufSize} = Right
) ->
case LeftBufSize + RightBufSize < Right#buffer.convert_threshold of
true ->
Right#buffer{buf = LeftBuf ++ RightBuf, buf_size = LeftBufSize + RightBufSize};
false ->
Merged = max_registers(LeftBuf ++ RightBuf),
NewRight = Right#buffer{buf = Merged, buf_size = length(Merged)},
case NewRight#buffer.buf_size < NewRight#buffer.convert_threshold of
true ->
NewRight;
false ->
buffer2dense(NewRight)
end
end.
reduce_precision(NewP, #dense{p = OldP} = Dense) ->
ChangeP = OldP - NewP,
Buf = register_fold(ChangeP, Dense),
Empty = new_dense(NewP),
compact(Empty#dense{buf = Buf});
reduce_precision(NewP, #buffer{p = OldP} = Buffer) ->
ChangeP = OldP - NewP,
Buf = register_fold(ChangeP, Buffer),
Empty = new_dense(NewP),
compact(Empty#dense{buf = Buf}).
fold an HLL to a lower number of registers ` NewM ` by projecting the values
register_fold(ChangeP, B) ->
ChangeM = hyper_utils:m(ChangeP),
element(
3,
fold(
fun
(I, V, {_Index, CurrentList, Acc}) when CurrentList == [] ->
{I, [V], Acc};
(I, V, {Index, CurrentList, Acc}) when I - Index < ChangeM ->
{Index, [V | CurrentList], Acc};
(I, V, {_Index, CurrentList, Acc}) ->
{I, [V], [
{I bsr ChangeP, hyper_utils:changeV(lists:reverse(CurrentList), ChangeP)}
| Acc
]}
end,
{0, [], []},
B
)
).
register_sum(B) ->
fold(
fun
(_, 0, Acc) ->
Acc + 1.0;
(_, 1, Acc) ->
Acc + 0.5;
(_, 2, Acc) ->
Acc + 0.25;
(_, 3, Acc) ->
Acc + 0.125;
(_, 4, Acc) ->
Acc + 0.0625;
(_, 5, Acc) ->
Acc + 0.03125;
(_, 6, Acc) ->
Acc + 0.015625;
(_, 7, Acc) ->
Acc + 0.0078125;
(_, 8, Acc) ->
Acc + 0.00390625;
(_, 9, Acc) ->
Acc + 0.001953125;
(_, V, Acc) ->
Acc + math:pow(2, -V)
end,
0,
B
).
register_histogram(#buffer{p = P} = B) ->
register_histogram(B, P);
register_histogram(#dense{p = P} = B) ->
register_histogram(B, P).
register_histogram(B, P) ->
todo use from_keys once we are at otp 26
fold(
fun(_, Value, Acc) -> maps:update_with(Value, fun(V) -> V + 1 end, 0, Acc) end,
maps:from_list(
lists:map(fun(I) -> {I, 0} end, lists:seq(0, 65 - P))
),
B
).
zero_count(B) ->
fold(
fun
(_, 0, Acc) ->
Acc + 1;
(_, _, Acc) ->
Acc
end,
0,
B
).
encode_registers(#buffer{} = Buffer) ->
encode_registers(buffer2dense(Buffer));
encode_registers(#dense{b = B}) ->
<<<<I:8/integer>> || <<I:?VALUE_SIZE/integer>> <= B>>.
decode_registers(AllBytes, P) ->
M = hyper_utils:m(P),
Bytes =
case AllBytes of
<<B:M/binary>> ->
B;
<<B:M/binary, 0>> ->
B
end,
Dense = new_dense(P),
Dense#dense{b = <<<<I:?VALUE_SIZE/integer>> || <<I:8>> <= Bytes>>}.
bytes(#dense{b = B}) ->
erlang:byte_size(B);
bytes(#buffer{} = Buffer) ->
erts_debug:flat_size(Buffer) * 8.
precision(#dense{p = P}) ->
P;
precision(#buffer{p = P}) ->
P.
INTERNALS
empty_binary(M) ->
list_to_bitstring([<<0:?VALUE_SIZE/integer>> || _ <- lists:seq(0, M - 1)]).
max_registers(Buf) ->
lists:keysort(
1,
maps:to_list(
lists:foldl(
fun({I, V}, Acc) ->
case maps:find(I, Acc) of
{ok, R} when R >= V -> Acc;
_ -> maps:put(I, V, Acc)
end
end,
#{},
Buf
)
)
).
buffer2dense(#buffer{buf = Buf, p = P}) ->
Dense = new_dense(P),
Merged = merge_buf(Dense#dense.b, max_registers(Buf)),
Dense#dense{b = Merged}.
do_merge(<<>>, <<>>, Acc) ->
Acc;
do_merge(
<<Left:?VALUE_SIZE/integer, SmallRest/bitstring>>,
<<Right:?VALUE_SIZE/integer, BigRest/bitstring>>,
Acc
) ->
do_merge(SmallRest, BigRest, <<Acc/bits, (max(Left, Right)):?VALUE_SIZE>>).
fold(F, Acc, #buffer{} = Buffer) ->
TODO fix this to not need to move to a dense , it is not technically neeeded
fold(F, Acc, buffer2dense(Buffer));
fold(F, Acc, #dense{b = B, buf = Buf}) ->
do_fold(F, Acc, merge_buf(B, max_registers(Buf)), 0).
do_fold(_, Acc, <<>>, _) ->
Acc;
do_fold(F, Acc, <<Value:?VALUE_SIZE/integer, Rest/bitstring>>, Index) ->
do_fold(F, F(Index, Value, Acc), Rest, Index + 1).
merge_buf(B, L) ->
merge_buf(B, L, -1, <<>>).
merge_buf(B, [], _PrevIndex, Acc) ->
<<Acc/bitstring, B/bitstring>>;
merge_buf(B, [{Index, Value} | Rest], PrevIndex, Acc) ->
I = (Index - PrevIndex - 1) * ?VALUE_SIZE,
case B of
<<Left:I/bitstring, OldValue:?VALUE_SIZE/integer, Right/bitstring>> ->
case OldValue < Value of
true ->
NewAcc = <<Acc/bitstring, Left/bitstring, Value:?VALUE_SIZE/integer>>,
merge_buf(Right, Rest, Index, NewAcc);
false ->
NewAcc = <<Acc/bitstring, Left/bitstring, OldValue:?VALUE_SIZE/integer>>,
merge_buf(Right, Rest, Index, NewAcc)
end;
<<Left:I/bitstring>> ->
<<Acc/bitstring, Left/bitstring, Value:?VALUE_SIZE/integer>>
end.
|
6374b062f2dbe79ff54d69d2f5ef744bba2fa5fc14f74cc84a4e3014c13e2e50
|
rtoy/cmucl
|
pmax-vm.lisp
|
;;; -*- Package: MIPS -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
(ext:file-comment
"$Header: src/code/pmax-vm.lisp $")
;;;
;;; **********************************************************************
;;;
;;; $Header: src/code/pmax-vm.lisp $
;;;
;;; This file contains the PMAX specific runtime stuff.
;;;
(in-package "MIPS")
(use-package "SYSTEM")
(use-package "ALIEN")
(use-package "C-CALL")
(intl:textdomain "cmucl")
(export '(fixup-code-object internal-error-arguments
sigcontext-program-counter sigcontext-register
sigcontext-float-register sigcontext-floating-point-modes
extern-alien-name sanctify-for-execution))
The sigcontext structure .
(def-alien-type unix:sigcontext
(struct nil
(sc-onstack unsigned-long)
(sc-mask unsigned-long)
(sc-pc system-area-pointer)
(sc-regs (array unsigned-long 32))
(sc-mdlo unsigned-long)
(sc-mdhi unsigned-long)
(sc-ownedfp unsigned-long)
(sc-fpregs (array unsigned-long 32))
(sc-fpc-csr unsigned-long)
(sc-fpc-eir unsigned-long)
(sc-cause unsigned-long)
(sc-badvaddr system-area-pointer)
(sc-badpaddr system-area-pointer)))
;;;; Add machine specific features to *features*
(pushnew :decstation-3100 *features*)
(pushnew :pmax *features*)
;;;; MACHINE-TYPE and MACHINE-VERSION
(defun machine-type ()
"Returns a string describing the type of the local machine."
"DECstation")
(defun machine-version ()
"Returns a string describing the version of the local machine."
"DECstation")
FIXUP - CODE - OBJECT -- Interface
;;;
(defun fixup-code-object (code offset fixup kind)
(unless (zerop (rem offset word-bytes))
(error "Unaligned instruction? offset=#x~X." offset))
(system:without-gcing
(let ((sap (truly-the system-area-pointer
(%primitive c::code-instructions code))))
(ecase kind
(:jump
(assert (zerop (ash fixup -26)))
(setf (ldb (byte 26 0) (system:sap-ref-32 sap offset))
(ash fixup -2)))
(:lui
(setf (sap-ref-16 sap offset)
(+ (ash fixup -16)
(if (logbitp 15 fixup) 1 0))))
(:addi
(setf (sap-ref-16 sap offset)
(ldb (byte 16 0) fixup)))))))
;;;; Internal-error-arguments.
;;; INTERNAL-ERROR-ARGUMENTS -- interface.
;;;
Given the sigcontext , extract the internal error arguments from the
;;; instruction stream.
;;;
(defun internal-error-arguments (scp)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(let ((pc (slot scp 'sc-pc)))
(declare (type system-area-pointer pc))
(when (logbitp 31 (slot scp 'sc-cause))
(setf pc (sap+ pc 4)))
(when (= (sap-ref-8 pc 4) 255)
(setf pc (sap+ pc 1)))
(let* ((length (sap-ref-8 pc 4))
(vector (make-array length :element-type '(unsigned-byte 8))))
(declare (type (unsigned-byte 8) length)
(type (simple-array (unsigned-byte 8) (*)) vector))
(copy-from-system-area pc (* vm:byte-bits 5)
vector (* vm:word-bits
vm:vector-data-offset)
(* length vm:byte-bits))
(let* ((index 0)
(error-number (c::read-var-integer vector index)))
(collect ((sc-offsets))
(loop
(when (>= index length)
(return))
(sc-offsets (c::read-var-integer vector index)))
(values error-number (sc-offsets))))))))
Sigcontext access functions .
SIGCONTEXT - PROGRAM - COUNTER -- Interface .
;;;
(defun sigcontext-program-counter (scp)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(slot scp 'sc-pc)))
SIGCONTEXT - REGISTER -- Interface .
;;;
;;; An escape register saves the value of a register for a frame that someone
;;; interrupts.
;;;
(defun sigcontext-register (scp index)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(deref (slot scp 'sc-regs) index)))
(defun %set-sigcontext-register (scp index new)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(setf (deref (slot scp 'sc-regs) index) new)
new))
(defsetf sigcontext-register %set-sigcontext-register)
SIGCONTEXT - FLOAT - REGISTER -- Interface .
;;;
Like SIGCONTEXT - REGISTER , but returns the value of a float register .
;;; Format is the type of float to return.
;;;
(defun sigcontext-float-register (scp index format)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(let ((sap (alien-sap (slot scp 'sc-fpregs))))
(ecase format
(single-float (system:sap-ref-single sap (* index vm:word-bytes)))
(double-float (system:sap-ref-double sap (* index vm:word-bytes)))))))
;;;
(defun %set-sigcontext-float-register (scp index format new-value)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(let ((sap (alien-sap (slot scp 'sc-fpregs))))
(ecase format
(single-float
(setf (sap-ref-single sap (* index vm:word-bytes)) new-value))
(double-float
(setf (sap-ref-double sap (* index vm:word-bytes)) new-value))))))
;;;
(defsetf sigcontext-float-register %set-sigcontext-float-register)
SIGCONTEXT - FLOATING - POINT - MODES -- Interface
;;;
Given a sigcontext pointer , return the floating point modes word in the
;;; same format as returned by FLOATING-POINT-MODES.
;;;
(defun sigcontext-floating-point-modes (scp)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(slot scp 'sc-fpc-csr)))
EXTERN - ALIEN - NAME -- interface .
;;;
;;; The loader uses this to convert alien names to the form they occure in
the symbol table ( for example , prepending an underscore ) . On the MIPS ,
;;; we don't do anything.
;;;
(defun extern-alien-name (name)
(declare (type simple-base-string name))
name)
;;; SANCTIFY-FOR-EXECUTION -- Interface.
;;;
;;; Do whatever is necessary to make the given code component executable.
;;;
(defun sanctify-for-execution (component)
(declare (ignore component))
nil)
| null |
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/code/pmax-vm.lisp
|
lisp
|
-*- Package: MIPS -*-
**********************************************************************
**********************************************************************
$Header: src/code/pmax-vm.lisp $
This file contains the PMAX specific runtime stuff.
Add machine specific features to *features*
MACHINE-TYPE and MACHINE-VERSION
Internal-error-arguments.
INTERNAL-ERROR-ARGUMENTS -- interface.
instruction stream.
An escape register saves the value of a register for a frame that someone
interrupts.
Format is the type of float to return.
same format as returned by FLOATING-POINT-MODES.
The loader uses this to convert alien names to the form they occure in
we don't do anything.
SANCTIFY-FOR-EXECUTION -- Interface.
Do whatever is necessary to make the given code component executable.
|
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
(ext:file-comment
"$Header: src/code/pmax-vm.lisp $")
(in-package "MIPS")
(use-package "SYSTEM")
(use-package "ALIEN")
(use-package "C-CALL")
(intl:textdomain "cmucl")
(export '(fixup-code-object internal-error-arguments
sigcontext-program-counter sigcontext-register
sigcontext-float-register sigcontext-floating-point-modes
extern-alien-name sanctify-for-execution))
The sigcontext structure .
(def-alien-type unix:sigcontext
(struct nil
(sc-onstack unsigned-long)
(sc-mask unsigned-long)
(sc-pc system-area-pointer)
(sc-regs (array unsigned-long 32))
(sc-mdlo unsigned-long)
(sc-mdhi unsigned-long)
(sc-ownedfp unsigned-long)
(sc-fpregs (array unsigned-long 32))
(sc-fpc-csr unsigned-long)
(sc-fpc-eir unsigned-long)
(sc-cause unsigned-long)
(sc-badvaddr system-area-pointer)
(sc-badpaddr system-area-pointer)))
(pushnew :decstation-3100 *features*)
(pushnew :pmax *features*)
(defun machine-type ()
"Returns a string describing the type of the local machine."
"DECstation")
(defun machine-version ()
"Returns a string describing the version of the local machine."
"DECstation")
FIXUP - CODE - OBJECT -- Interface
(defun fixup-code-object (code offset fixup kind)
(unless (zerop (rem offset word-bytes))
(error "Unaligned instruction? offset=#x~X." offset))
(system:without-gcing
(let ((sap (truly-the system-area-pointer
(%primitive c::code-instructions code))))
(ecase kind
(:jump
(assert (zerop (ash fixup -26)))
(setf (ldb (byte 26 0) (system:sap-ref-32 sap offset))
(ash fixup -2)))
(:lui
(setf (sap-ref-16 sap offset)
(+ (ash fixup -16)
(if (logbitp 15 fixup) 1 0))))
(:addi
(setf (sap-ref-16 sap offset)
(ldb (byte 16 0) fixup)))))))
Given the sigcontext , extract the internal error arguments from the
(defun internal-error-arguments (scp)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(let ((pc (slot scp 'sc-pc)))
(declare (type system-area-pointer pc))
(when (logbitp 31 (slot scp 'sc-cause))
(setf pc (sap+ pc 4)))
(when (= (sap-ref-8 pc 4) 255)
(setf pc (sap+ pc 1)))
(let* ((length (sap-ref-8 pc 4))
(vector (make-array length :element-type '(unsigned-byte 8))))
(declare (type (unsigned-byte 8) length)
(type (simple-array (unsigned-byte 8) (*)) vector))
(copy-from-system-area pc (* vm:byte-bits 5)
vector (* vm:word-bits
vm:vector-data-offset)
(* length vm:byte-bits))
(let* ((index 0)
(error-number (c::read-var-integer vector index)))
(collect ((sc-offsets))
(loop
(when (>= index length)
(return))
(sc-offsets (c::read-var-integer vector index)))
(values error-number (sc-offsets))))))))
Sigcontext access functions .
SIGCONTEXT - PROGRAM - COUNTER -- Interface .
(defun sigcontext-program-counter (scp)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(slot scp 'sc-pc)))
SIGCONTEXT - REGISTER -- Interface .
(defun sigcontext-register (scp index)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(deref (slot scp 'sc-regs) index)))
(defun %set-sigcontext-register (scp index new)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(setf (deref (slot scp 'sc-regs) index) new)
new))
(defsetf sigcontext-register %set-sigcontext-register)
SIGCONTEXT - FLOAT - REGISTER -- Interface .
Like SIGCONTEXT - REGISTER , but returns the value of a float register .
(defun sigcontext-float-register (scp index format)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(let ((sap (alien-sap (slot scp 'sc-fpregs))))
(ecase format
(single-float (system:sap-ref-single sap (* index vm:word-bytes)))
(double-float (system:sap-ref-double sap (* index vm:word-bytes)))))))
(defun %set-sigcontext-float-register (scp index format new-value)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(let ((sap (alien-sap (slot scp 'sc-fpregs))))
(ecase format
(single-float
(setf (sap-ref-single sap (* index vm:word-bytes)) new-value))
(double-float
(setf (sap-ref-double sap (* index vm:word-bytes)) new-value))))))
(defsetf sigcontext-float-register %set-sigcontext-float-register)
SIGCONTEXT - FLOATING - POINT - MODES -- Interface
Given a sigcontext pointer , return the floating point modes word in the
(defun sigcontext-floating-point-modes (scp)
(declare (type (alien (* unix:sigcontext)) scp))
(with-alien ((scp (* unix:sigcontext) scp))
(slot scp 'sc-fpc-csr)))
EXTERN - ALIEN - NAME -- interface .
the symbol table ( for example , prepending an underscore ) . On the MIPS ,
(defun extern-alien-name (name)
(declare (type simple-base-string name))
name)
(defun sanctify-for-execution (component)
(declare (ignore component))
nil)
|
4cd7af4493a81d9b68ffcb28c0898da54bfcd8cfedc804f47737eb722cd4e0c5
|
snapframework/snap-templates
|
Application.hs
|
# LANGUAGE TemplateHaskell #
------------------------------------------------------------------------------
-- | This module defines our application's state type and an alias for its
-- handler monad.
module Application where
------------------------------------------------------------------------------
import Control.Lens
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Snaplet.Auth
import Snap.Snaplet.Session
------------------------------------------------------------------------------
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _auth :: Snaplet (AuthManager App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
------------------------------------------------------------------------------
type AppHandler = Handler App App
| null |
https://raw.githubusercontent.com/snapframework/snap-templates/768db37547fc153ce00160af4bd5b603bfa8b8bb/project_template/default/src/Application.hs
|
haskell
|
----------------------------------------------------------------------------
| This module defines our application's state type and an alias for its
handler monad.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
|
# LANGUAGE TemplateHaskell #
module Application where
import Control.Lens
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Snaplet.Auth
import Snap.Snaplet.Session
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _auth :: Snaplet (AuthManager App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
type AppHandler = Handler App App
|
82a29ecec986acc1096ea1263fcecfd336e982e36219623793779bdc88bb2307
|
orbitz/web_typed
|
frame_test.ml
|
open OUnit
open Stomp
open Ort_prelude
let scaffold d f =
match d with
| Result.Error (Frame.Unknown_cmd cmd) ->
assert_string ("Unknown command: " ^ cmd)
| Result.Error Stream.Failure ->
assert_string "Stream failure"
| Result.Error (Stream.Error error) ->
assert_string ("Stream error: " ^ error)
| Result.Error Frame.Frame_length ->
assert_string "Frame length wrong"
| Result.Error _ ->
assert_string "Unknown exception thrown"
| Result.Ok v ->
f v
let test_parse_single_msg _ =
let data = "CONNECTED\nsession:foo\n\n\000"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame], _) -> begin
assert_equal
~msg:"Not Connected frame"
Frame.Connected
(Frame.get_frame_type frame);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame);
assert_equal
~msg:"Session not foo"
(Some "foo")
(Frame.get_header "session" frame)
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_parse_double_msg _ =
let msg1 = "CONNECTED\nsession:foo\n\n\000"
and msg2 = "RECEIPT\nreceipt-id:bar\n\n\000"
and parse_state = Frame.parse_state
in
let data = msg1 ^ msg2
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame1; frame2], _) -> begin
assert_equal
~msg:"Not Connected frame"
Frame.Connected
(Frame.get_frame_type frame1);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame1);
assert_equal
~msg:"Session not foo"
(Some "foo")
(Frame.get_header "session" frame1);
assert_equal
~msg:"Not Receipt frame"
Frame.Receipt
(Frame.get_frame_type frame2);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame2);
assert_equal
~msg:"receipt-id not bar"
(Some "bar")
(Frame.get_header "receipt-id" frame2);
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_parse_with_null _ =
let data = "MESSAGE\ndestination:/topic/foo\ncontent-length:1\n\n\000\000"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame], _) -> begin
assert_equal
~msg:"Not Message frame"
Frame.Message
(Frame.get_frame_type frame);
assert_equal
~msg:"Body not null byte"
"\000"
(Frame.get_body frame);
assert_equal
~msg:"destination not /topic/foo"
(Some "/topic/foo")
(Frame.get_header "destination" frame)
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_space_in_header _ =
let data = "CONNECTED\nsession: foo\n\n\000"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame], _) -> begin
assert_equal
~msg:"Not Connected frame"
Frame.Connected
(Frame.get_frame_type frame);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame);
assert_equal
~msg:"Session not set to foo"
(Some "foo")
(Frame.get_header "session" frame)
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_partial_msg _ =
let data = "CONNECTED\n"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| (frames, _) ->
assert_equal
~msg:"Not empty message"
[]
frames)
let suite = "STOMP Frame Test" >:::
[ "Single message" >:: test_parse_single_msg
; "Double mssage" >:: test_parse_double_msg
; "Null in body" >:: test_parse_with_null
; "Space in header" >:: test_space_in_header
; "Partial message" >:: test_partial_msg
]
let _ = run_test_tt_main suite
| null |
https://raw.githubusercontent.com/orbitz/web_typed/e224c1be6a2d4fd0013ff9cdb27075c145a4b77e/libs/stomp/frame_test.ml
|
ocaml
|
open OUnit
open Stomp
open Ort_prelude
let scaffold d f =
match d with
| Result.Error (Frame.Unknown_cmd cmd) ->
assert_string ("Unknown command: " ^ cmd)
| Result.Error Stream.Failure ->
assert_string "Stream failure"
| Result.Error (Stream.Error error) ->
assert_string ("Stream error: " ^ error)
| Result.Error Frame.Frame_length ->
assert_string "Frame length wrong"
| Result.Error _ ->
assert_string "Unknown exception thrown"
| Result.Ok v ->
f v
let test_parse_single_msg _ =
let data = "CONNECTED\nsession:foo\n\n\000"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame], _) -> begin
assert_equal
~msg:"Not Connected frame"
Frame.Connected
(Frame.get_frame_type frame);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame);
assert_equal
~msg:"Session not foo"
(Some "foo")
(Frame.get_header "session" frame)
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_parse_double_msg _ =
let msg1 = "CONNECTED\nsession:foo\n\n\000"
and msg2 = "RECEIPT\nreceipt-id:bar\n\n\000"
and parse_state = Frame.parse_state
in
let data = msg1 ^ msg2
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame1; frame2], _) -> begin
assert_equal
~msg:"Not Connected frame"
Frame.Connected
(Frame.get_frame_type frame1);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame1);
assert_equal
~msg:"Session not foo"
(Some "foo")
(Frame.get_header "session" frame1);
assert_equal
~msg:"Not Receipt frame"
Frame.Receipt
(Frame.get_frame_type frame2);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame2);
assert_equal
~msg:"receipt-id not bar"
(Some "bar")
(Frame.get_header "receipt-id" frame2);
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_parse_with_null _ =
let data = "MESSAGE\ndestination:/topic/foo\ncontent-length:1\n\n\000\000"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame], _) -> begin
assert_equal
~msg:"Not Message frame"
Frame.Message
(Frame.get_frame_type frame);
assert_equal
~msg:"Body not null byte"
"\000"
(Frame.get_body frame);
assert_equal
~msg:"destination not /topic/foo"
(Some "/topic/foo")
(Frame.get_header "destination" frame)
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_space_in_header _ =
let data = "CONNECTED\nsession: foo\n\n\000"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| ([frame], _) -> begin
assert_equal
~msg:"Not Connected frame"
Frame.Connected
(Frame.get_frame_type frame);
assert_equal
~msg:"Body not empty"
""
(Frame.get_body frame);
assert_equal
~msg:"Session not set to foo"
(Some "foo")
(Frame.get_header "session" frame)
end
| (_, _) ->
assert_string "Parse wrong number of messages")
let test_partial_msg _ =
let data = "CONNECTED\n"
and parse_state = Frame.parse_state
in
scaffold
(Frame.frames_of_data
~s:parse_state
~d:data
~len:(String.length data))
(function
| (frames, _) ->
assert_equal
~msg:"Not empty message"
[]
frames)
let suite = "STOMP Frame Test" >:::
[ "Single message" >:: test_parse_single_msg
; "Double mssage" >:: test_parse_double_msg
; "Null in body" >:: test_parse_with_null
; "Space in header" >:: test_space_in_header
; "Partial message" >:: test_partial_msg
]
let _ = run_test_tt_main suite
|
|
84ee4c92634a62133eba66280d0485494fa48b1cfd7e2cb99c5d475df6365618
|
input-output-hk/project-icarus-importer
|
Monad.hs
|
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
-- | Monads used for explorer's toil.
module Pos.Explorer.Txp.Toil.Monad
(
ExplorerExtraM
, getTxExtra
, getAddrHistory
, getAddrBalance
, getUtxoSum
, putTxExtra
, delTxExtra
, updateAddrHistory
, putAddrBalance
, delAddrBalance
, putUtxoSum
, ELocalToilM
, explorerExtraMToELocalToilM
, EGlobalToilM
, explorerExtraMToEGlobalToilM
) where
import Universum
import Control.Lens (at, magnify, zoom, (%=), (.=))
import Control.Monad.Free.Church (F (..))
import Control.Monad.Morph (generalize, hoist)
import Control.Monad.Reader (mapReaderT)
import Control.Monad.State.Strict (mapStateT)
import System.Wlog (NamedPureLogger)
import Pos.Core (Address, Coin, TxId)
import Pos.Explorer.Core (AddrHistory, TxExtra)
import Pos.Explorer.Txp.Toil.Types (ExplorerExtraLookup (..), ExplorerExtraModifier,
eemAddrBalances, eemAddrHistories, eemLocalTxsExtra,
eemNewUtxoSum)
import Pos.Txp.Toil (ExtendedGlobalToilM, ExtendedLocalToilM, StakesLookupF)
import qualified Pos.Util.Modifier as MM
import Pos.Util (type (~>))
----------------------------------------------------------------------------
Monadic actions with extra txp data .
----------------------------------------------------------------------------
-- | Utility monad which allows to lookup extra values related to txp and modify them.
type ExplorerExtraM
= ReaderT ExplorerExtraLookup (StateT ExplorerExtraModifier (NamedPureLogger Identity))
getTxExtra :: TxId -> ExplorerExtraM (Maybe TxExtra)
getTxExtra txId = do
baseLookup <- eelGetTxExtra <$> ask
MM.lookup baseLookup txId <$> use eemLocalTxsExtra
getAddrHistory :: Address -> ExplorerExtraM AddrHistory
getAddrHistory addr = do
use (eemAddrHistories . at addr) >>= \case
Nothing -> eelGetAddrHistory <$> ask <*> pure addr
Just hist -> pure hist
getAddrBalance :: Address -> ExplorerExtraM (Maybe Coin)
getAddrBalance addr = do
baseLookup <- eelGetAddrBalance <$> ask
MM.lookup baseLookup addr <$> use eemAddrBalances
getUtxoSum :: ExplorerExtraM Integer
getUtxoSum = fromMaybe <$> (eelGetUtxoSum <$> ask) <*> use eemNewUtxoSum
putTxExtra :: TxId -> TxExtra -> ExplorerExtraM ()
putTxExtra txId extra = eemLocalTxsExtra %= MM.insert txId extra
delTxExtra :: TxId -> ExplorerExtraM ()
delTxExtra txId = eemLocalTxsExtra %= MM.delete txId
updateAddrHistory :: Address -> AddrHistory -> ExplorerExtraM ()
updateAddrHistory addr hist = eemAddrHistories . at addr .= Just hist
putAddrBalance :: Address -> Coin -> ExplorerExtraM ()
putAddrBalance addr coin = eemAddrBalances %= MM.insert addr coin
delAddrBalance :: Address -> ExplorerExtraM ()
delAddrBalance addr = eemAddrBalances %= MM.delete addr
putUtxoSum :: Integer -> ExplorerExtraM ()
putUtxoSum utxoSum = eemNewUtxoSum .= Just utxoSum
----------------------------------------------------------------------------
Monad used for local Toil in Explorer .
----------------------------------------------------------------------------
type ELocalToilM = ExtendedLocalToilM ExplorerExtraLookup ExplorerExtraModifier
explorerExtraMToELocalToilM :: ExplorerExtraM ~> ELocalToilM
explorerExtraMToELocalToilM = zoom _2 . magnify _2
----------------------------------------------------------------------------
Monad used for global Toil in Explorer .
----------------------------------------------------------------------------
type EGlobalToilM
= ExtendedGlobalToilM ExplorerExtraLookup ExplorerExtraModifier
explorerExtraMToEGlobalToilM :: ExplorerExtraM ~> EGlobalToilM
explorerExtraMToEGlobalToilM = mapReaderT (mapStateT f . zoom _2) . magnify _2
where
f :: NamedPureLogger Identity ~> NamedPureLogger (F StakesLookupF)
f = hoist generalize
| null |
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/explorer/src/Pos/Explorer/Txp/Toil/Monad.hs
|
haskell
|
| Monads used for explorer's toil.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
| Utility monad which allows to lookup extra values related to txp and modify them.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
|
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Pos.Explorer.Txp.Toil.Monad
(
ExplorerExtraM
, getTxExtra
, getAddrHistory
, getAddrBalance
, getUtxoSum
, putTxExtra
, delTxExtra
, updateAddrHistory
, putAddrBalance
, delAddrBalance
, putUtxoSum
, ELocalToilM
, explorerExtraMToELocalToilM
, EGlobalToilM
, explorerExtraMToEGlobalToilM
) where
import Universum
import Control.Lens (at, magnify, zoom, (%=), (.=))
import Control.Monad.Free.Church (F (..))
import Control.Monad.Morph (generalize, hoist)
import Control.Monad.Reader (mapReaderT)
import Control.Monad.State.Strict (mapStateT)
import System.Wlog (NamedPureLogger)
import Pos.Core (Address, Coin, TxId)
import Pos.Explorer.Core (AddrHistory, TxExtra)
import Pos.Explorer.Txp.Toil.Types (ExplorerExtraLookup (..), ExplorerExtraModifier,
eemAddrBalances, eemAddrHistories, eemLocalTxsExtra,
eemNewUtxoSum)
import Pos.Txp.Toil (ExtendedGlobalToilM, ExtendedLocalToilM, StakesLookupF)
import qualified Pos.Util.Modifier as MM
import Pos.Util (type (~>))
Monadic actions with extra txp data .
type ExplorerExtraM
= ReaderT ExplorerExtraLookup (StateT ExplorerExtraModifier (NamedPureLogger Identity))
getTxExtra :: TxId -> ExplorerExtraM (Maybe TxExtra)
getTxExtra txId = do
baseLookup <- eelGetTxExtra <$> ask
MM.lookup baseLookup txId <$> use eemLocalTxsExtra
getAddrHistory :: Address -> ExplorerExtraM AddrHistory
getAddrHistory addr = do
use (eemAddrHistories . at addr) >>= \case
Nothing -> eelGetAddrHistory <$> ask <*> pure addr
Just hist -> pure hist
getAddrBalance :: Address -> ExplorerExtraM (Maybe Coin)
getAddrBalance addr = do
baseLookup <- eelGetAddrBalance <$> ask
MM.lookup baseLookup addr <$> use eemAddrBalances
getUtxoSum :: ExplorerExtraM Integer
getUtxoSum = fromMaybe <$> (eelGetUtxoSum <$> ask) <*> use eemNewUtxoSum
putTxExtra :: TxId -> TxExtra -> ExplorerExtraM ()
putTxExtra txId extra = eemLocalTxsExtra %= MM.insert txId extra
delTxExtra :: TxId -> ExplorerExtraM ()
delTxExtra txId = eemLocalTxsExtra %= MM.delete txId
updateAddrHistory :: Address -> AddrHistory -> ExplorerExtraM ()
updateAddrHistory addr hist = eemAddrHistories . at addr .= Just hist
putAddrBalance :: Address -> Coin -> ExplorerExtraM ()
putAddrBalance addr coin = eemAddrBalances %= MM.insert addr coin
delAddrBalance :: Address -> ExplorerExtraM ()
delAddrBalance addr = eemAddrBalances %= MM.delete addr
putUtxoSum :: Integer -> ExplorerExtraM ()
putUtxoSum utxoSum = eemNewUtxoSum .= Just utxoSum
Monad used for local Toil in Explorer .
type ELocalToilM = ExtendedLocalToilM ExplorerExtraLookup ExplorerExtraModifier
explorerExtraMToELocalToilM :: ExplorerExtraM ~> ELocalToilM
explorerExtraMToELocalToilM = zoom _2 . magnify _2
Monad used for global Toil in Explorer .
type EGlobalToilM
= ExtendedGlobalToilM ExplorerExtraLookup ExplorerExtraModifier
explorerExtraMToEGlobalToilM :: ExplorerExtraM ~> EGlobalToilM
explorerExtraMToEGlobalToilM = mapReaderT (mapStateT f . zoom _2) . magnify _2
where
f :: NamedPureLogger Identity ~> NamedPureLogger (F StakesLookupF)
f = hoist generalize
|
ce60a5d1d8b03b1bbfc862574beb356249a14de0279ce49582fd0268c9f2e1e9
|
syntax-objects/syntax-parse-example
|
rec-contract.rkt
|
#lang racket/base
(provide rec/c)
(require racket/contract (for-syntax racket/base syntax/parse))
(define-syntax-rule (rec/c t ctc)
(letrec ([rec-ctc
(let-syntax ([t (syntax-parser (_:id #'(recursive-contract rec-ctc)))])
ctc)])
rec-ctc))
| null |
https://raw.githubusercontent.com/syntax-objects/syntax-parse-example/0675ce0717369afcde284202ec7df661d7af35aa/rec-contract/rec-contract.rkt
|
racket
|
#lang racket/base
(provide rec/c)
(require racket/contract (for-syntax racket/base syntax/parse))
(define-syntax-rule (rec/c t ctc)
(letrec ([rec-ctc
(let-syntax ([t (syntax-parser (_:id #'(recursive-contract rec-ctc)))])
ctc)])
rec-ctc))
|
|
edbdbe14edc31a7902f4d5d9e091d9dd16b2a8ee8753efd32c1bf997539c9079
|
DianaPajon/tiger
|
Parser.hs
|
import Text.Parsec
import TigerParser
import Tools
main :: IO ()
main =
putStrLn "\n======= Test PARSER in progress =======" >>
putStrLn "escapa.tig" >>
( test "./test/test_code" (badRes . show) (const $ bluenice) tester "escapa.tig") >>
putStrLn "intro.tig" >>
( test "./test/test_code" (badRes . show) (const $ bluenice) tester "intro.tig") >>
putStrLn "Good:" >>
testDir good_loc (testGood good_loc tester) >>
putStrLn "Type:" >>
testDir type_loc (testGood type_loc tester) >>
putStrLn "Bad:" >>
testDir bad_loc (testBad bad_loc tester) >>
putStrLn "\n======= Test FIN ======="
tester s = runParser expression () s s
| null |
https://raw.githubusercontent.com/DianaPajon/tiger/30d360f02f5fc57883f988a1cbb581208ecd2744/test/Parser.hs
|
haskell
|
import Text.Parsec
import TigerParser
import Tools
main :: IO ()
main =
putStrLn "\n======= Test PARSER in progress =======" >>
putStrLn "escapa.tig" >>
( test "./test/test_code" (badRes . show) (const $ bluenice) tester "escapa.tig") >>
putStrLn "intro.tig" >>
( test "./test/test_code" (badRes . show) (const $ bluenice) tester "intro.tig") >>
putStrLn "Good:" >>
testDir good_loc (testGood good_loc tester) >>
putStrLn "Type:" >>
testDir type_loc (testGood type_loc tester) >>
putStrLn "Bad:" >>
testDir bad_loc (testBad bad_loc tester) >>
putStrLn "\n======= Test FIN ======="
tester s = runParser expression () s s
|
|
56dc70dc194b454b15a5a3c38f5d7c1fddc226009adf84d8f1703065c07d51d9
|
reactiveml/rml
|
subst.mli
|
Js_of_ocaml compiler
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Code
val program : (Var.t -> Var.t) -> program -> program
val expr : (Var.t -> Var.t) -> expr -> expr
val instr : (Var.t -> Var.t) -> instr -> instr
val instrs : (Var.t -> Var.t) -> instr list -> instr list
val last : (Var.t -> Var.t) -> last -> last
val from_array : Var.t option array -> Var.t -> Var.t
val build_mapping : Var.t list -> Var.t list -> Var.t VarMap.t
val from_map : Var.t VarMap.t -> Var.t -> Var.t
| null |
https://raw.githubusercontent.com/reactiveml/rml/d178d49ed923290fa7eee642541bdff3ee90b3b4/toplevel-alt/js/js-of-ocaml/compiler/subst.mli
|
ocaml
|
Js_of_ocaml compiler
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open Code
val program : (Var.t -> Var.t) -> program -> program
val expr : (Var.t -> Var.t) -> expr -> expr
val instr : (Var.t -> Var.t) -> instr -> instr
val instrs : (Var.t -> Var.t) -> instr list -> instr list
val last : (Var.t -> Var.t) -> last -> last
val from_array : Var.t option array -> Var.t -> Var.t
val build_mapping : Var.t list -> Var.t list -> Var.t VarMap.t
val from_map : Var.t VarMap.t -> Var.t -> Var.t
|
|
3acc556452b053d9d5db768218a0d28e2f160905abd9aba9a955db79248286f7
|
ucsd-progsys/liquidhaskell
|
BadData1.hs
|
{-@ LIQUID "--expect-error-containing=Data constructors in refinement do not match original datatype for `EntityField`" @-}
{-@ LIQUID "--no-adt" @-}
{-@ LIQUID "--exact-data-con" @-}
# LANGUAGE ExistentialQuantification , KindSignatures , TypeFamilies , GADTs #
module BadData1 where
class PersistEntity record where
data EntityField record :: * -> *
-- The reason this fails is because the refinement uses 'record'
instead of ' ' . Therefore , the lookup for the GHC datatype
will return no constructors , and consequently , LH complains
that our refinement has two .
--
instance PersistEntity Blob where
@ data EntityField record typ where
BlobXVal : : EntityField { v : Int | v > = 0 }
BlobYVal : : EntityField Blob Int
@
BlobXVal :: EntityField Blob {v:Int | v >= 0}
BlobYVal :: EntityField Blob Int
@-}
data EntityField Blob typ where
BlobXVal :: EntityField Blob Int
BlobYVal :: EntityField Blob Int
@ data = B { xVal : : { v : Int | v > = 0 } , : : Int } @
data Blob = B { xVal :: Int, yVal :: Int }
@ blobXVal : : EntityField { v : Int | v > = 0 } @
blobXVal :: EntityField Blob Int
blobXVal = BlobXVal
-- OK
testUpdateQuery : : ( ) - > Update
testUpdateQuery ( ) = createUpdate blobXVal 3
-- BAD
testUpdateQueryFail : : ( ) - > Update
testUpdateQueryFail ( ) = createUpdate blobXVal ( -1 )
main :: IO ()
main = pure ()
| null |
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/errors/BadData1.hs
|
haskell
|
@ LIQUID "--expect-error-containing=Data constructors in refinement do not match original datatype for `EntityField`" @
@ LIQUID "--no-adt" @
@ LIQUID "--exact-data-con" @
The reason this fails is because the refinement uses 'record'
OK
BAD
|
# LANGUAGE ExistentialQuantification , KindSignatures , TypeFamilies , GADTs #
module BadData1 where
class PersistEntity record where
data EntityField record :: * -> *
instead of ' ' . Therefore , the lookup for the GHC datatype
will return no constructors , and consequently , LH complains
that our refinement has two .
instance PersistEntity Blob where
@ data EntityField record typ where
BlobXVal : : EntityField { v : Int | v > = 0 }
BlobYVal : : EntityField Blob Int
@
BlobXVal :: EntityField Blob {v:Int | v >= 0}
BlobYVal :: EntityField Blob Int
@-}
data EntityField Blob typ where
BlobXVal :: EntityField Blob Int
BlobYVal :: EntityField Blob Int
@ data = B { xVal : : { v : Int | v > = 0 } , : : Int } @
data Blob = B { xVal :: Int, yVal :: Int }
@ blobXVal : : EntityField { v : Int | v > = 0 } @
blobXVal :: EntityField Blob Int
blobXVal = BlobXVal
testUpdateQuery : : ( ) - > Update
testUpdateQuery ( ) = createUpdate blobXVal 3
testUpdateQueryFail : : ( ) - > Update
testUpdateQueryFail ( ) = createUpdate blobXVal ( -1 )
main :: IO ()
main = pure ()
|
114fe93b51f983afdfeaae303218dfa58af97c006008b685d25852c9d53c7fa5
|
macalimlim/programming-in-haskell
|
CaesarCipher.hs
|
module CaesarCipher where
import Data.Char hiding (isLower, isUpper)
a Caesar cipher , also known as the shift cipher , 's code or Caesar shift ,
is one of the simplest and most widely known encryption techniques .
It is a type of substitution cipher in which each letter in the plaintext
is replaced by a letter some fixed number of positions down the alphabet .
For example , with a left shift of 3 , D would be replaced by A , E
would become B , and so on .
The method is named after , who used it in his private correspondence .
" haskell is fun "
with a shift factor of 3
" "
shift factor of 10
" rkcuovv sc pex "
a Caesar cipher, also known as the shift cipher, Caesar's code or Caesar shift,
is one of the simplest and most widely known encryption techniques.
It is a type of substitution cipher in which each letter in the plaintext
is replaced by a letter some fixed number of positions down the alphabet.
For example, with a left shift of 3, D would be replaced by A, E
would become B, and so on.
The method is named after Julius Caesar, who used it in his private correspondence.
"haskell is fun"
with a shift factor of 3
"kdvnhoo lv ixq"
shift factor of 10
"rkcuovv sc pex"
-}
isInRange :: Char -> Char -> Char -> Bool
isInRange l u c = (c >= l) && (c <= u)
isLower :: Char -> Bool
isLower = isInRange 'a' 'z'
isUpper :: Char -> Bool
isUpper = isInRange 'A' 'Z'
--
let2Int :: Char -> Char -> Int
let2Int x c = ord c - ord x
lcLet2Int :: Char -> Int
lcLet2Int = let2Int 'a'
ucLet2Int :: Char -> Int
ucLet2Int = let2Int 'A'
--
int2Let :: Char -> Int -> Char
int2Let x n = chr (ord x + n)
int2LcLet :: Int -> Char
int2LcLet = int2Let 'a'
int2UcLet :: Int -> Char
int2UcLet = int2Let 'A'
--
shift :: Int -> Char -> Char
shift n c | isLower c = int2LcLet ((lcLet2Int c + n) `mod` 26)
| isUpper c = int2UcLet ((ucLet2Int c + n) `mod` 26)
| otherwise = c
encode :: Int -> String -> String
encode n xs = [shift n x | x <- xs]
decode :: Int -> String -> String
decode n = encode (-n)
-- Assignment: how to crack it! :D
| null |
https://raw.githubusercontent.com/macalimlim/programming-in-haskell/47d7d9b92c3d79eeedc1123e6eb690f96fa8a4fc/CaesarCipher.hs
|
haskell
|
Assignment: how to crack it! :D
|
module CaesarCipher where
import Data.Char hiding (isLower, isUpper)
a Caesar cipher , also known as the shift cipher , 's code or Caesar shift ,
is one of the simplest and most widely known encryption techniques .
It is a type of substitution cipher in which each letter in the plaintext
is replaced by a letter some fixed number of positions down the alphabet .
For example , with a left shift of 3 , D would be replaced by A , E
would become B , and so on .
The method is named after , who used it in his private correspondence .
" haskell is fun "
with a shift factor of 3
" "
shift factor of 10
" rkcuovv sc pex "
a Caesar cipher, also known as the shift cipher, Caesar's code or Caesar shift,
is one of the simplest and most widely known encryption techniques.
It is a type of substitution cipher in which each letter in the plaintext
is replaced by a letter some fixed number of positions down the alphabet.
For example, with a left shift of 3, D would be replaced by A, E
would become B, and so on.
The method is named after Julius Caesar, who used it in his private correspondence.
"haskell is fun"
with a shift factor of 3
"kdvnhoo lv ixq"
shift factor of 10
"rkcuovv sc pex"
-}
isInRange :: Char -> Char -> Char -> Bool
isInRange l u c = (c >= l) && (c <= u)
isLower :: Char -> Bool
isLower = isInRange 'a' 'z'
isUpper :: Char -> Bool
isUpper = isInRange 'A' 'Z'
let2Int :: Char -> Char -> Int
let2Int x c = ord c - ord x
lcLet2Int :: Char -> Int
lcLet2Int = let2Int 'a'
ucLet2Int :: Char -> Int
ucLet2Int = let2Int 'A'
int2Let :: Char -> Int -> Char
int2Let x n = chr (ord x + n)
int2LcLet :: Int -> Char
int2LcLet = int2Let 'a'
int2UcLet :: Int -> Char
int2UcLet = int2Let 'A'
shift :: Int -> Char -> Char
shift n c | isLower c = int2LcLet ((lcLet2Int c + n) `mod` 26)
| isUpper c = int2UcLet ((ucLet2Int c + n) `mod` 26)
| otherwise = c
encode :: Int -> String -> String
encode n xs = [shift n x | x <- xs]
decode :: Int -> String -> String
decode n = encode (-n)
|
0201fb9abc3442397ddd811ba273e0e4401f7b752d55529101be1d604797c0bd
|
eval/deps-try
|
repl.clj
|
(ns rebel-readline.cljs.repl
(:require
[cljs.repl]
[clojure.tools.reader :as r]
[clojure.tools.reader.reader-types :as rtypes]
[rebel-readline.core :as rebel]
[rebel-readline.clojure.line-reader :as clj-line-reader]
[rebel-readline.cljs.service.local :as cljs-service]
[rebel-readline.jline-api :as api])
(:import
[org.jline.utils OSUtils]))
(defn has-remaining?
"Takes a clojure.tools.reader.reader-types/SourceLoggingPushbackReader
and returns true if there is another character in the stream.
i.e not the end of the readers stream."
[pbr]
(boolean
(when-let [x (rtypes/read-char pbr)]
(rtypes/unread pbr x)
true)))
(def create-repl-read
"Creates a drop in replacement for cljs.repl/repl-read, since a
readline can return multiple Clojure forms this function is stateful
and buffers the forms and returns the next form on subsequent reads.
This function is a constructor that takes a line-reader and returns
a function that can replace `cljs.repl/repl-read`.
Example Usage:
(let [repl-env (nash/repl-env)]
(cljs-repl/repl
repl-env
:prompt (fn [])
:read (cljs-repl-read
(rebel-readline.core/line-reader
(rebel-readline-cljs.service/create {:repl-env repl-env}))])))"
(rebel/create-buffered-repl-reader-fn
(fn [s] (rtypes/source-logging-push-back-reader
(java.io.StringReader. s)))
has-remaining?
cljs.repl/repl-read))
(defn syntax-highlight-println
"Print a syntax highlighted clojure value.
This printer respects the current color settings set in the
service.
The `rebel-readline.jline-api/*line-reader*` and
`rebel-readline.jline-api/*service*` dynamic vars have to be set for
this to work.
See `rebel-readline-cljs.main` for an example of how this function is normally used"
[x]
(binding [*out* (.. api/*line-reader* getTerminal writer)]
(try
(println (api/->ansi (clj-line-reader/highlight-clj-str (or x ""))))
(catch java.lang.StackOverflowError e
(println (or x ""))))))
;; enable evil alter-var-root
(let [cljs-repl* cljs.repl/repl*]
(defn repl* [repl-env opts]
(rebel/with-line-reader
(clj-line-reader/create
(cljs-service/create (assoc
(when api/*line-reader*
@api/*line-reader*)
:repl-env repl-env)))
(when-let [prompt-fn (:prompt opts)]
(swap! api/*line-reader* assoc :prompt prompt-fn))
(println (rebel/help-message))
(binding [*out* (api/safe-terminal-writer api/*line-reader*)]
(cljs-repl*
repl-env
(merge
{:print syntax-highlight-println
:read (create-repl-read)}
opts
{:prompt (fn [])}))))))
(defn repl [repl-env & opts]
(repl* repl-env (apply hash-map opts)))
| null |
https://raw.githubusercontent.com/eval/deps-try/da691c68b527ad5f9e770dbad82cce6cbbe16fb4/vendor/rebel-readline/rebel-readline-cljs/src/rebel_readline/cljs/repl.clj
|
clojure
|
enable evil alter-var-root
|
(ns rebel-readline.cljs.repl
(:require
[cljs.repl]
[clojure.tools.reader :as r]
[clojure.tools.reader.reader-types :as rtypes]
[rebel-readline.core :as rebel]
[rebel-readline.clojure.line-reader :as clj-line-reader]
[rebel-readline.cljs.service.local :as cljs-service]
[rebel-readline.jline-api :as api])
(:import
[org.jline.utils OSUtils]))
(defn has-remaining?
"Takes a clojure.tools.reader.reader-types/SourceLoggingPushbackReader
and returns true if there is another character in the stream.
i.e not the end of the readers stream."
[pbr]
(boolean
(when-let [x (rtypes/read-char pbr)]
(rtypes/unread pbr x)
true)))
(def create-repl-read
"Creates a drop in replacement for cljs.repl/repl-read, since a
readline can return multiple Clojure forms this function is stateful
and buffers the forms and returns the next form on subsequent reads.
This function is a constructor that takes a line-reader and returns
a function that can replace `cljs.repl/repl-read`.
Example Usage:
(let [repl-env (nash/repl-env)]
(cljs-repl/repl
repl-env
:prompt (fn [])
:read (cljs-repl-read
(rebel-readline.core/line-reader
(rebel-readline-cljs.service/create {:repl-env repl-env}))])))"
(rebel/create-buffered-repl-reader-fn
(fn [s] (rtypes/source-logging-push-back-reader
(java.io.StringReader. s)))
has-remaining?
cljs.repl/repl-read))
(defn syntax-highlight-println
"Print a syntax highlighted clojure value.
This printer respects the current color settings set in the
service.
The `rebel-readline.jline-api/*line-reader*` and
`rebel-readline.jline-api/*service*` dynamic vars have to be set for
this to work.
See `rebel-readline-cljs.main` for an example of how this function is normally used"
[x]
(binding [*out* (.. api/*line-reader* getTerminal writer)]
(try
(println (api/->ansi (clj-line-reader/highlight-clj-str (or x ""))))
(catch java.lang.StackOverflowError e
(println (or x ""))))))
(let [cljs-repl* cljs.repl/repl*]
(defn repl* [repl-env opts]
(rebel/with-line-reader
(clj-line-reader/create
(cljs-service/create (assoc
(when api/*line-reader*
@api/*line-reader*)
:repl-env repl-env)))
(when-let [prompt-fn (:prompt opts)]
(swap! api/*line-reader* assoc :prompt prompt-fn))
(println (rebel/help-message))
(binding [*out* (api/safe-terminal-writer api/*line-reader*)]
(cljs-repl*
repl-env
(merge
{:print syntax-highlight-println
:read (create-repl-read)}
opts
{:prompt (fn [])}))))))
(defn repl [repl-env & opts]
(repl* repl-env (apply hash-map opts)))
|
5f2bb36258d87b5f70aa65ea347b8a309517a012f68745bcf1e0d523531da89d
|
manuel-serrano/hop
|
event.scm
|
;*=====================================================================*/
* serrano / prgm / project / hop / hop / runtime / event.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Tue Sep 27 05:45:08 2005 * /
* Last change : Fri Jun 14 14:57:28 2019 ( serrano ) * /
* Copyright : 2005 - 20 * /
;* ------------------------------------------------------------- */
;* The implementation of server events */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __hop_event
(library web)
(cond-expand
(enable-ssl
(library ssl)))
(include "thread.sch")
(include "xml.sch"
"service.sch"
"verbose.sch"
"param.sch")
(import __hop_configure
__hop_param
__hop_thread
__hop_types
__hop_user
__hop_xml-types
__hop_xml
__hop_html-head
__hop_misc
__hop_hop
__hop_http-response
__hop_json
__hop_js-comp
__hop_read
__hop_service
__hop_http-response
__hop_http-error
__hop_websocket
__hop_watch)
(static (class http-response-event::%http-response-server
(name::bstring read-only)))
(export (class event
(name::bstring read-only)
(target::obj read-only)
(stopped::bool (default #f))
(value::obj (default #unspecified)))
(class websocket-event::event
(data::obj (default #unspecified)))
(class server-event::websocket-event)
(class server
(mutex::mutex read-only (default (make-mutex)))
(host::bstring read-only)
(port::int read-only)
(ssl::bool (default #f))
(authorization read-only (default #f))
(version::bstring read-only (default (hop-version)))
(listeners::pair-nil (default '()))
(ready-listeners::pair-nil (default '()))
(down-listeners::pair-nil (default '()))
(trigger::procedure read-only (default (lambda (f) (f))))
(ctx (default #f))
(%websocket (default #f))
(%key (default #f)))
(generic server-init! ::server)
(generic server-reset! ::server)
(generic add-event-listener! ::obj ::obj ::procedure . l)
(generic remove-event-listener! ::obj ::obj ::procedure . l)
(generic stop-event-propagation ::event ::bool)
(apply-listeners ::obj ::event)
(hop-event-init!)
(hop-event-tables)
(hop-event-signal! ::bstring ::obj #!optional ctx)
(hop-event-broadcast! ::bstring ::obj #!optional ctx)
(hop-event-client-ready? ::bstring)
(hop-event-policy-file ::http-request)
(hop-event-info-service::procedure)
(hop-event-register-service::procedure)
(hop-event-unregister-service::procedure)))
;*---------------------------------------------------------------------*/
;* debug ... */
;*---------------------------------------------------------------------*/
(define debug-multipart #f)
;*---------------------------------------------------------------------*/
;* add-event-listener! ::obj ... */
;*---------------------------------------------------------------------*/
(define-generic (add-event-listener! obj::obj event proc . capture)
(cond
((and (string? event) (string? obj))
(add-server-listener! obj event proc capture))
((eq? obj 'hop)
(add-hop-listener! event proc capture))
(else
(error "add-event-listener!"
(format "Illegal ~s listener" event) obj))))
(define-generic (remove-event-listener! obj::obj event proc . capture)
(cond
((and (string? event) (string? obj))
(remove-server-listener! obj event proc capture))
((eq? obj 'hop)
(remove-hop-listener! event proc capture))
(else
(error "remove-event-listener!"
(format "Illegal ~s listener" event) obj))))
(define-generic (stop-event-propagation event::event default::bool)
(with-access::event event (stopped)
(set! stopped #t)))
;*---------------------------------------------------------------------*/
;* envelope-re ... */
;*---------------------------------------------------------------------*/
(define envelope-re
(pregexp "^<([rsxifj]) name='([^']+)'>(.*)</[rsxifj]>$" 'MULTILINE))
(define cdata-re
(pregexp "^<!\\[CDATA\\[(.*)\\]\\]>$" 'MULTILINE))
;*---------------------------------------------------------------------*/
;* server-init! ... */
;*---------------------------------------------------------------------*/
(define-generic (server-init! srv::server)
(define (message->event k id text)
(case (string-ref k 0)
((#\i)
(let ((val (string->integer text)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\f)
(let ((val (string->real text)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\x)
(let ((val (call-with-input-string text
(lambda (p)
(car
(last-pair
(parse-html p (string-length text))))))))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\s)
(let ((val (url-decode text)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\j)
(with-access::server srv (ctx)
(let ((val (string->obj
(url-decode (cadr (pregexp-match cdata-re text)))
#f ctx)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val)))))
((#\r)
(let ((val (url-decode text)))
(instantiate::server-event
(target srv)
(name "ready")
(value val)
(data val))))))
(define (parse-message v)
(with-access::websocket-event v (data)
(let ((m (pregexp-match envelope-re data)))
(when (pair? m)
(let* ((k (cadr m))
(id (caddr m))
(text (cadddr m)))
(if (char=? (string-ref k 0) #\r)
(with-access::server srv (ready-listeners trigger)
(trigger
(lambda ()
(apply-listeners ready-listeners
(message->event k id text)))))
(with-access::server srv (listeners trigger)
(let ((ltns (filter-map (lambda (l)
(when (string=? (car l) id)
(cdr l)))
listeners)))
(when (pair? ltns)
(trigger
(lambda ()
(let ((event (message->event k id text)))
(apply-listeners ltns event)))))))))))))
(define (down e)
(with-trace 'event "down@server-init!"
(trace-item "e=" e)
(with-access::server srv (down-listeners trigger)
(trigger
(lambda ()
(apply-listeners down-listeners e))))))
(with-access::server srv (host port ssl authorization %websocket %key mutex)
(synchronize mutex
(unless %websocket
(with-hop ((hop-event-info-service))
:host host :port port
:authorization authorization
:ssl ssl
:sync #t
(lambda (v)
(let* ((key (vector-ref v 2))
(url (format "~a://~a:~a~a/public/server-event/websocket?key=~a"
(if ssl "wss" "ws") host port (hop-service-base)
key)))
(set! %key key)
(set! %websocket
(instantiate::websocket
(url url)
(authorization authorization)
(oncloses (list down))
(onmessages (list parse-message))))
(websocket-connect! %websocket))))))))
;*---------------------------------------------------------------------*/
;* server-reset! ... */
;*---------------------------------------------------------------------*/
(define-generic (server-reset! obj::server)
(with-access::server obj (mutex)
(synchronize mutex
(server-reset-sans-lock! obj))))
;*---------------------------------------------------------------------*/
;* server-reset-sans-lock! ... */
;*---------------------------------------------------------------------*/
(define (server-reset-sans-lock! obj::server)
(with-access::server obj (%websocket %key host port)
(websocket-close %websocket)
(set! %websocket #f)
(set! %key #f)))
;*---------------------------------------------------------------------*/
;* add-event-listener! ::server ... */
;*---------------------------------------------------------------------*/
(define-method (add-event-listener! obj::server event proc . capture)
(let loop ((armed #f))
(server-init! obj)
(with-access::server obj (mutex host port ssl authorization %key)
(cond
((string=? event "ready")
(synchronize mutex
(with-access::server obj (ready-listeners)
(set! ready-listeners (cons proc ready-listeners)))))
((string=? event "down")
(synchronize mutex
(with-access::server obj (down-listeners)
(set! down-listeners (cons proc down-listeners)))))
(else
(with-hop ((hop-event-register-service) :event event
:key %key :mode "websocket")
:host host :port port
:authorization authorization
:ssl ssl
(lambda (v)
(synchronize mutex
(with-access::server obj (listeners)
(set! listeners (cons (cons event proc) listeners)))))
(lambda (exn)
(if (isa? exn xml-http-request)
(with-access::xml-http-request exn (status input-port header)
(if (and (not armed) (=fx status 500))
(let ((badkey (read-string input-port)))
(when (string=? (md5sum %key) badkey)
(server-reset! obj)
(loop #t)))
(tprint "error: " (read-string input-port))))
(exception-notify exn)))))))))
;*---------------------------------------------------------------------*/
;* remove-event-listener! ::server ... */
;*---------------------------------------------------------------------*/
(define-method (remove-event-listener! obj::server event proc . capture)
(with-access::server obj (listeners mutex host port ssl authorization %key)
(let ((key %key))
(when (synchronize mutex
(let loop ((ls listeners))
(when (pair? ls)
(let ((l (car ls)))
(if (and (eq? (cdr l) proc) (string=? (car l) event))
(begin
(set! listeners (remq! l listeners))
(when (null? listeners)
(server-reset-sans-lock! obj))
#t)
(loop (cdr ls)))))))
(when key
(with-hop ((hop-event-unregister-service) :event event :key key)
:host host :port port
:authorization authorization
:ssl ssl))))))
;*---------------------------------------------------------------------*/
;* *event-mutex* ... */
;*---------------------------------------------------------------------*/
(define *event-mutex* (make-mutex "hop-event"))
(define *listener-mutex* (make-mutex "hop-listener"))
;*---------------------------------------------------------------------*/
;* hop-multipart-key ... */
;*---------------------------------------------------------------------*/
(define hop-multipart-key "hop-multipart")
;*---------------------------------------------------------------------*/
;* event services ... */
;*---------------------------------------------------------------------*/
(define *info-service* #f)
(define *websocket-service* #t)
(define *register-service* #f)
(define *unregister-service* #f)
(define *init-service* #f)
(define *policy-file-service #f)
(define *close-service* #f)
(define *client-key* 0)
(define *default-request* (instantiate::http-server-request))
(define *ping* (symbol->string (gensym 'ping)))
(define *clients-number* 0)
;*---------------------------------------------------------------------*/
;* websocket-register-new-connection! ... */
;*---------------------------------------------------------------------*/
(define (websocket-register-new-connection! req key)
(define (get-header header key default)
(let ((c (assq key header)))
(if (pair? c)
(cdr c)
default)))
(with-access::http-request req (header connection socket)
(let ((host (get-header header host: #f))
(version (get-header header sec-websocket-version: "-1")))
;; see http_response.scm for the source code that actually sends
;; the bytes of the response to the client.
(with-trace 'event "ws-register-new-connection"
(trace-item "protocol-version=" version)
(let ((resp (websocket-server-response req key :protocol '("json"))))
(watch-socket! socket
(lambda (s)
(with-trace 'event
"watch@websocket-register-new-connection!"
(trace-item "CLOSING s=" s)
(socket-close s)
(notify-client! "disconnect" #f req
*disconnect-listeners*))))
(trace-item "resp=" (typeof resp))
;; register the websocket
(synchronize *event-mutex*
(set! *websocket-response-list*
(cons (cons (string->symbol key) (cons resp req))
*websocket-response-list*))
(trace-item "key=" key)
(trace-item "socket=" socket )
(trace-item "connected clients=" *websocket-response-list*))
resp)))))
;*---------------------------------------------------------------------*/
;* hop-event-init! ... */
;*---------------------------------------------------------------------*/
(define (hop-event-init!)
(synchronize *event-mutex*
(when (=fx *client-key* 0)
(set! *client-key* (elong->fixnum (current-seconds)))
(set! *websocket-service*
(service :name "public/server-event/websocket"
:id server-event
:timeout 0
(#!key key)
(with-trace 'event "start websocket service"
(trace-item "key=" key)
(let ((req (current-request)))
(with-access::http-request req (header socket)
(trace-item "req.socket=" socket)
(if (websocket-proxy-request? header)
(websocket-proxy-response req)
(websocket-register-new-connection! req key)))))))
(set! *info-service*
(service :name "public/server-event/info"
:id server-event
:timeout 0
()
(let* ((req (current-request))
(hd (with-access::http-request req (header) header))
(host (assq host: hd))
(key (get-server-event-key req))
(sock (with-access::http-request req (socket) socket))
(port (with-access::http-request req (port) port))
(ssl (cond-expand
(enable-ssl (ssl-socket? sock))
(else #f))))
(if (pair? host)
(let ((s (string-split (cdr host) ":")))
(vector (car s) port key ssl))
(with-access::http-request req (host)
(vector host port key ssl))))))
(set! *policy-file-service
(service :name "public/server-event/policy-file"
:id server-event
:timeout 0
(#!key port key)
(instantiate::http-response-string
(content-type "application/xml")
(body (hop-event-policy port)))))
(set! *close-service*
(service :name "public/server-event/close" :timeout 0 (#!key key)
:id server-event
(synchronize *event-mutex*
(lambda ()
(let ((key (string->symbol key)))
(set! *clients-number* (-fx *clients-number* 1)))))))
(set! *unregister-service*
(service :name "public/server-event/unregister"
:id server-event
:timeout 0
(#!key event key)
(server-event-unregister event key)))
(set! *register-service*
(service :name "public/server-event/register"
:id server-event
:timeout 0
(#!key event key mode padding)
(server-event-register event key mode padding (current-request)))))))
;*---------------------------------------------------------------------*/
;* hop-event-tables ... */
;* ------------------------------------------------------------- */
;* Dump the content of the event table for debug purposes. */
;*---------------------------------------------------------------------*/
(define (hop-event-tables)
(synchronize *event-mutex*
`((*clients-number* ,*clients-number*)
(*multipart-request-list* ,*multipart-request-list*)
(*multipart-socket-table* ,*multipart-socket-table*)
(*websocket-response-list* ,*websocket-response-list*)
(*websocket-socket-table* ,*websocket-socket-table*))))
;*---------------------------------------------------------------------*/
;* server-event-register ... */
;*---------------------------------------------------------------------*/
(define (server-event-register event key mode padding req)
(define (multipart-register-event! req key name)
(with-trace 'event "multipart-register-event!"
(let ((content (format "--~a\nContent-type: text/xml\n\n<r name='~a'></r>\n--~a\n"
hop-multipart-key name hop-multipart-key))
(c (assq key *multipart-request-list*)))
(if (pair? c)
(let ((oreq (cdr c)))
;; we already have a connection for that
;; client, we simply re-use it
(hashtable-update! *multipart-socket-table*
name
(lambda (l) (cons oreq l))
(list oreq))
;; we must response as a multipart response because
;; that's the way we have configured the xhr
;; on the client side but we must close the connection
(instantiate::http-response-string
(header '((Transfer-Encoding: . "chunked")))
(content-length #e-2)
(content-type (format "multipart/x-mixed-replace; boundary=\"~a\"" hop-multipart-key))
(body (format "~a\r\n~a" (integer->string (string-length content) 16) content))))
;; we create a new connection for that client
;; multipart never sends a complete answer. In order to
;; traverse proxy, we use a chunked response
(with-access::http-request req (socket)
(output-port-flush-hook-set!
(socket-output socket)
(lambda (port size)
(output-port-flush-hook-set! port chunked-flush-hook)
""))
(set! *multipart-request-list*
(cons (cons key req)
*multipart-request-list*))
(hashtable-update! *multipart-socket-table*
name
(lambda (l) (cons req l))
(list req))
(instantiate::http-response-persistent
(request req)
(body (format "HTTP/1.1 200 Ok\r\nTransfer-Encoding: chunked\r\nContent-type: multipart/x-mixed-replace; boundary=\"~a\"\r\n\r\n~a\r\n~a"
hop-multipart-key
(integer->string (string-length content) 16)
content))))))))
(define (websocket-register-event! req key name)
(with-trace 'event "websocket-register-event!"
(let ((c (assq key *websocket-response-list*)))
(trace-item "key=" key)
(trace-item "name=" name)
;;(trace-item "c=" c)
(if (pair? c)
(let ((resp (cadr c)))
(websocket-signal resp
(format "<r name='ready'>~a</r>"
(url-path-encode name)))
(hashtable-update! *websocket-socket-table*
name
(lambda (l) (cons resp l))
(list resp))
(instantiate::http-response-string))
(begin
(trace-item "keylist=" *websocket-response-list*)
(instantiate::http-response-string
(start-line "HTTP/1.0 500 Illegal key")
(body (md5sum (symbol->string! key)))))))))
(with-trace 'event "ws-register-event!"
(synchronize *event-mutex*
(trace-item "event=" (url-decode event))
(trace-item "key=" key)
(trace-item "mode=" mode)
(trace-item "padding=" padding)
(if (<fx *clients-number* (hop-event-max-clients))
(if (string? key)
(let ((key (string->symbol key))
(event (url-decode! event)))
;; set an output timeout on the socket
(with-access::http-request req (socket)
(output-timeout-set!
(socket-output socket) (hop-connection-timeout)))
;; register the client
(let ((r (cond
((string=? mode "xhr-multipart")
(multipart-register-event! req key event))
((string=? mode "websocket")
(websocket-register-event! req key event))
(else
(error "register-event" "unsupported mode" mode)))))
(notify-client! "connect" event req
*connect-listeners*)
r))
(http-service-unavailable event))
(http-service-unavailable event)))))
;*---------------------------------------------------------------------*/
;* server-event-unregister ... */
;*---------------------------------------------------------------------*/
(define (server-event-unregister event key)
(define (unregister-multipart-event! event key)
(let ((c (assq (string->symbol key) *multipart-request-list*)))
(when (pair? c)
(let ((req (cadr c)))
(hashtable-update! *multipart-socket-table*
event
(lambda (l) (delete! req l))
'())
;; Ping the client to check it still exists. If the client
;; no longer exists, an error will be raised and the client
;; will be removed from the tables.
(multipart-signal req
(envelope-value *ping* #unspecified #f))))))
(define (remq-one! x y)
(let laap ((x x)
(y y))
(cond
((null? y) y)
((eq? x (car y)) (cdr y))
(else (let loop ((prev y))
(cond ((null? (cdr prev))
y)
((eq? (cadr prev) x)
(set-cdr! prev (cddr prev))
y)
(else (loop (cdr prev)))))))))
(define (unregister-websocket-event! event key)
(let ((c (assq (string->symbol key) *websocket-response-list*)))
(when (pair? c)
(let ((resp (cadr c))
(req (cddr c)))
(hashtable-update! *websocket-socket-table*
event
(lambda (l)
(notify-client! "disconnect" event req
*disconnect-listeners*)
(remq-one! resp l))
'())
;; Ping the client to check if it still exists. If the client
;; no longer exists, an error will be raised and the client
;; will be removed from the tables.
(websocket-signal resp
(envelope-value *ping* #unspecified #f))))))
(synchronize *event-mutex*
(let ((event (url-decode! event)))
(when (and (string? key) event)
(unregister-websocket-event! event key)
(unregister-multipart-event! event key)
#f))))
;*---------------------------------------------------------------------*/
;* multipart-close-request! ... */
;* ------------------------------------------------------------- */
;* This assumes that the event-mutex has been acquired. */
;*---------------------------------------------------------------------*/
(define (multipart-close-request! req)
;; close the socket
(with-access::http-request req (socket)
(socket-shutdown socket))
(set! *clients-number* (-fx *clients-number* 1))
;; remove the request from the *multipart-request-list*
(set! *multipart-request-list*
(filter! (lambda (e) (not (eq? (cdr e) req)))
*multipart-request-list*))
;; remove the request from the *multipart-socket-table*
(hashtable-for-each *multipart-socket-table*
(lambda (k l)
(hashtable-update! *multipart-socket-table*
k
(lambda (l) (delete! req l))
'())))
(hashtable-filter! *multipart-socket-table* (lambda (k l) (pair? l))))
;*---------------------------------------------------------------------*/
;* websocket-close-request! ... */
;* ------------------------------------------------------------- */
;* This assumes that the event-mutex has been acquired. */
;*---------------------------------------------------------------------*/
(define (websocket-close-request! resp::http-response-websocket)
(with-access::http-response-websocket resp ((req request))
;; close the socket
(with-access::http-request req (socket)
(socket-close socket)
(with-trace 'event "ws-close-request!"
(trace-item "socket=" socket)))
;; decrement the current number of connected clients
(set! *clients-number* (-fx *clients-number* 1))
;; remove the request from the *websocket-response-list*
(set! *websocket-response-list*
(filter! (lambda (e)
(not (eq? (cadr e) resp)))
*websocket-response-list*))
;; remove the response from the *websocket-socket-table*
(hashtable-for-each *websocket-socket-table*
(lambda (k l)
(hashtable-update! *websocket-socket-table*
k
(lambda (l) (delete! resp l))
'())))
(hashtable-filter! *websocket-socket-table* (lambda (k l) (pair? l)))))
;*---------------------------------------------------------------------*/
;* hop-event-client-ready? ... */
;*---------------------------------------------------------------------*/
(define (hop-event-client-ready? name)
(define (multipart-event-client-ready? name)
(let ((l (hashtable-get *multipart-socket-table* name)))
(and (pair? l)
(any (lambda (req)
(with-access::http-request req (socket)
(not (socket-down? socket))))
l))))
(define (websocket-event-client-ready? name)
(let ((l (hashtable-get *websocket-socket-table* name)))
(and (pair? l)
(any (lambda (req)
(with-access::http-request req (socket)
(not (socket-down? socket))))
l))))
(or (multipart-event-client-ready? name)
(websocket-event-client-ready? name)))
;*---------------------------------------------------------------------*/
;* *multipart-socket-table* */
;*---------------------------------------------------------------------*/
(define *multipart-socket-table* (make-hashtable))
(define *multipart-request-list* '())
;*---------------------------------------------------------------------*/
;* *websocket-request-table* */
;*---------------------------------------------------------------------*/
(define *websocket-socket-table* (make-hashtable))
(define *websocket-response-list* '())
;*---------------------------------------------------------------------*/
;* http-response ::http-response-event ... */
;*---------------------------------------------------------------------*/
(define-method (http-response r::http-response-event request socket)
(let ((p (socket-output socket)))
(with-access::http-response-event r (name)
(fprintf p "<acknowledge name='~a'/>" name))
(display #a000 p)
(flush-output-port p)
'persistent))
;*---------------------------------------------------------------------*/
;* get-server-event-key ... */
;*---------------------------------------------------------------------*/
(define (get-server-event-key req::http-request)
(synchronize *event-mutex*
(set! *client-key* (+fx 1 *client-key*))
(with-access::http-request req (host port)
(format "~a:~a://~a" host port *client-key*))))
;*---------------------------------------------------------------------*/
;* multipart-signal ... */
;*---------------------------------------------------------------------*/
(define (multipart-signal req vstr::bstring)
(with-access::http-request req (socket)
(let ((p (socket-output socket)))
(with-handler
(lambda (e)
(when debug-multipart
(tprint "MULTIPART EVENT ERROR: "
e " thread=" (current-thread)))
(if (isa? e &io-error)
(multipart-close-request! req)
(raise e)))
(begin
(fprintf p "Content-type: text/xml\n\n")
(display-string vstr p)
(fprintf p "\n--~a\n" hop-multipart-key p)
(flush-output-port p))))))
;*---------------------------------------------------------------------*/
;* websocket-signal ... */
;*---------------------------------------------------------------------*/
(define (websocket-signal resp::http-response-websocket vstr::bstring)
(define (hixie-signal-value vstr socket)
(let ((p (socket-output socket)))
(display #a000 p)
(display-string vstr p)
(display #a255 p)
(flush-output-port p)))
(define (hybi-signal-value vstr socket)
(with-trace 'event "hybi-signal-value"
(let ((p (socket-output socket)))
(trace-item "p=" p " closed=" (closed-output-port? p))
(let ((l (string-length vstr)))
;; FIN=1, OPCODE=x1 (text)
(display (integer->char #x81) p)
(cond
((<=fx l 125)
1 byte length
(display (integer->char l) p))
((<=fx l 65535)
2 bytes length
(display #a126 p)
(display (integer->char (bit-rsh l 8)) p)
(display (integer->char (bit-and l #xff)) p))
(else
4 bytes length
(display #a127 p)
(display "\000\000\000\000" p)
(display (integer->char (bit-rsh l 24)) p)
(display (integer->char (bit-and (bit-rsh l 16) #xff)) p)
(display (integer->char (bit-and (bit-rsh l 8) #xff)) p)
(display (integer->char (bit-and l #xff)) p)))
;; payload data
(display-string vstr p)
(flush-output-port p)))))
(with-access::http-response-websocket resp ((req request))
(with-access::http-request req (socket)
(with-handler
(lambda (e)
(with-trace 'event "ws-signal-error"
(trace-item "err=" e)
(trace-item "socket=" socket)
(trace-item "thread=" (current-thread))
(trace-item "req=" req )
(trace-item "vlen=" (string-length vstr))
(if (isa? e &io-error)
(begin
(with-trace 'event "ws-error-close"
(websocket-close-request! resp))
#f)
(raise e))))
(with-access::http-response-websocket resp (accept)
(with-trace 'event "ws-signal"
(trace-item "resp=" resp)
(trace-item "accept=" accept)
(if accept
(hybi-signal-value vstr socket)
(hixie-signal-value vstr socket))))))))
;*---------------------------------------------------------------------*/
;* envelope-value ... */
;*---------------------------------------------------------------------*/
(define (envelope-value::bstring name value ctx)
(let ((n (url-path-encode name)))
(cond
((isa? value xml)
(format "<x name='~a'>~a</x>" n (xml->string value (hop-xml-backend))))
((string? value)
(format "<s name='~a'>~a</s>" n (url-path-encode value)))
((integer? value)
(format "<i name='~a'>~a</i>" n value))
((real? value)
(format "<f name='~a'>~a</f>" n value))
(else
(let ((op (open-output-string)))
(fprintf op "<j name='~a'><![CDATA[" n)
ICI utiliser ctx
(display (url-path-encode (obj->string value (or ctx 'hop-client))) op)
(display "]]></j>" op)
(close-output-port op))))))
;*---------------------------------------------------------------------*/
;* envelope-json-value ... */
;*---------------------------------------------------------------------*/
(define (envelope-json-value name value ctx)
(let ((n (url-path-encode name)))
(let ((op (open-output-string)))
(fprintf op "<o name='~a'><![CDATA[" n)
(let ((json (call-with-output-string
(lambda (op)
(obj->json value op ctx)))))
(display (url-path-encode json) op)
(display "]]></o>" op)
(close-output-port op)))))
;*---------------------------------------------------------------------*/
;* for-each-socket ... */
;*---------------------------------------------------------------------*/
(define (for-each-socket table name proc)
(let ((l (hashtable-get table name)))
(when l
(proc l))))
;*---------------------------------------------------------------------*/
;* hop-signal-id ... */
;*---------------------------------------------------------------------*/
(define hop-signal-id 0)
;*---------------------------------------------------------------------*/
;* hop-event-signal! ... */
;*---------------------------------------------------------------------*/
(define (hop-event-signal! name value #!optional ctx)
(define (multipart-event-signal! name value)
(for-each-socket
*multipart-socket-table*
name
(lambda (l)
(when (pair? l)
(let ((val (envelope-value name value ctx)))
(when debug-multipart
(tprint "MULTIPART SIGNAL: " name))
(multipart-signal (car l) val)
#t)))))
(define (websocket-event-signal! name value)
(for-each-socket
*websocket-socket-table*
name
(lambda (l)
(when (pair? l)
(with-access::http-response-websocket (car l) (protocol)
(let ((val (if (and (string? protocol)
(string=? protocol "json"))
(envelope-json-value name value ctx)
(envelope-value name value ctx))))
(websocket-signal (car l) val)
#t))))))
(set! hop-signal-id (-fx hop-signal-id 1))
(hop-verb 2 (hop-color hop-signal-id hop-signal-id " SIGNAL")
": " name)
(hop-verb 3 " value=" (with-output-to-string (lambda () (write value))))
(hop-verb 2 "\n")
(synchronize *event-mutex*
(case (random 2)
((0)
(unless (multipart-event-signal! name value)
(websocket-event-signal! name value)))
((3)
(unless (websocket-event-signal! name value)
(multipart-event-signal! name value)))))
#unspecified)
;*---------------------------------------------------------------------*/
;* hop-event-broadcast! ... */
;*---------------------------------------------------------------------*/
(define (hop-event-broadcast! name value #!optional ctx)
(define jsvalue #f)
(define jsonvalue #f)
(define (hopjs-value name value)
(unless jsvalue (set! jsvalue (envelope-value name value ctx)))
jsvalue)
(define (json-value name value)
(unless jsonvalue (set! jsonvalue (envelope-json-value name value ctx)))
jsonvalue)
(define (websocket-event-broadcast! name value)
(with-trace 'event "ws-event-broadcast!"
(trace-item "name=" name)
(trace-item "value="
(if (or (string? value) (symbol? value) (number? value))
value
(typeof value)))
(trace-item "ws-table=" (hashtable-key-list *websocket-socket-table*))
(for-each-socket *websocket-socket-table*
name
(lambda (l)
(with-trace 'event "ws-event-broadcast"
(trace-item "name=" name)
(trace-item "# clients=" (length l))
(trace-item "cients="
(map (lambda (resp)
(with-access::http-response-websocket resp (request)
(with-access::http-request request (socket)
socket)))
l))
(when (pair? l)
(for-each (lambda (resp)
(with-access::http-response-websocket resp (protocol)
(websocket-signal resp
(if (and (string? protocol)
(string=? protocol "json"))
(json-value name value)
(hopjs-value name value)))))
l)))))))
(define (multipart-event-broadcast! name value)
(let ((val (envelope-value name value ctx)))
(for-each-socket
*multipart-socket-table*
name
(lambda (l)
(when (pair? l)
(for-each (lambda (req)
(multipart-signal req val))
l))))))
(synchronize *event-mutex*
(websocket-event-broadcast! name value)
(multipart-event-broadcast! name value))
#unspecified)
;*---------------------------------------------------------------------*/
;* hop-event-policy ... */
;*---------------------------------------------------------------------*/
(define (hop-event-policy port)
(format "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<cross-domain-policy xmlns:xsi=\"-instance\" xsi:noNamespaceSchemaLocation=\"\">
<allow-access-from domain=\"*\" to-ports=\"~a\" />
</cross-domain-policy>" port))
;*---------------------------------------------------------------------*/
;* hop-event-policy-file ... */
;*---------------------------------------------------------------------*/
(define (hop-event-policy-file req)
(instantiate::http-response-raw
(connection 'close)
(proc (lambda (p)
(with-access::http-request req (port)
(display (hop-event-policy port) p))
(write-char #a000 p)))))
;*---------------------------------------------------------------------*/
;* *server-listeners* ... */
;*---------------------------------------------------------------------*/
(define *server-listeners*
(make-hashtable 16))
;*---------------------------------------------------------------------*/
;* add-server-listener! ... */
;*---------------------------------------------------------------------*/
(define (add-server-listener! event::bstring srv::bstring proc::procedure capture)
(define (parse-host host auth)
(let ((l (string-split host ":")))
(if (null? (cdr l))
(values host 8080 #f)
(values (car l) (string->integer (cadr l)) auth))))
(define (parse-authenticated-host str)
(let ((s (string-split str "@")))
(if (null? (cdr s))
(parse-host str #f)
(parse-host (cadr s) (car s)))))
(let ((olds (synchronize *listener-mutex*
(hashtable-get *server-listeners* srv))))
(if (isa? olds server)
(add-event-listener! olds event proc capture)
(multiple-value-bind (host port auth)
(parse-authenticated-host srv)
(let ((news (instantiate::server
(host host)
(port port)
(ssl #f)
(authorization auth))))
(synchronize *listener-mutex*
(hashtable-put! *server-listeners* srv news))
(add-event-listener! news event proc capture))))))
;*---------------------------------------------------------------------*/
;* remove-server-listener! ... */
;*---------------------------------------------------------------------*/
(define (remove-server-listener! event srv proc capture)
(let ((olds (synchronize *listener-mutex*
(hashtable-get *server-listeners* srv))))
(when (isa? olds server)
(apply remove-event-listener! olds event proc capture))))
;*---------------------------------------------------------------------*/
;* *connect-listeners* ... */
;*---------------------------------------------------------------------*/
(define *connect-listeners* '())
(define *disconnect-listeners* '())
;*---------------------------------------------------------------------*/
;* add-hop-listener! ... */
;*---------------------------------------------------------------------*/
(define (add-hop-listener! event::bstring proc::procedure capture)
(cond
((string=? event "connect")
(synchronize *listener-mutex*
(set! *connect-listeners*
(cons proc *connect-listeners*))))
((string=? event "disconnect")
(synchronize *listener-mutex*
(set! *disconnect-listeners*
(cons proc *disconnect-listeners*))))))
;*---------------------------------------------------------------------*/
;* remove-hop-listener! ... */
;*---------------------------------------------------------------------*/
(define (remove-hop-listener! event::bstring proc::procedure capture)
(cond
((string=? event "connect")
(synchronize *listener-mutex*
(set! *connect-listeners*
(delete! proc *connect-listeners*))))
((string=? event "disconnect")
(synchronize *listener-mutex*
(set! *disconnect-listeners*
(delete! proc *disconnect-listeners*))))))
;*---------------------------------------------------------------------*/
;* padding-response ... */
;*---------------------------------------------------------------------*/
(define (padding-response rep padding)
(when padding
(with-access::http-response-hop rep ((p padding) content-type)
(set! p padding)
(set! content-type "application/x-javascript")))
rep)
;*---------------------------------------------------------------------*/
;* hop-event-info-service ... */
;*---------------------------------------------------------------------*/
(define (hop-event-info-service)
(hop-event-init!)
*info-service*)
;*---------------------------------------------------------------------*/
;* hop-event-register-service ... */
;*---------------------------------------------------------------------*/
(define (hop-event-register-service)
(hop-event-init!)
*register-service*)
;*---------------------------------------------------------------------*/
;* hop-event-unregister-service ... */
;*---------------------------------------------------------------------*/
(define (hop-event-unregister-service)
(hop-event-init!)
*unregister-service*)
;*---------------------------------------------------------------------*/
;* apply-listeners ... */
;*---------------------------------------------------------------------*/
(define (apply-listeners listeners::obj e::event)
(let loop ((l listeners))
(when (pair? l)
((car l) e)
(with-access::event e (stopped)
(unless stopped
(loop (cdr l)))))))
;*---------------------------------------------------------------------*/
;* notify-client! ... */
;*---------------------------------------------------------------------*/
(define (notify-client! event id req ltns)
(when (pair? ltns)
(let ((e (instantiate::server-event
(target req)
(name event)
(value id)
(data id))))
(apply-listeners ltns e))))
| null |
https://raw.githubusercontent.com/manuel-serrano/hop/481cb10478286796addd2ec9ee29c95db27aa390/runtime/event.scm
|
scheme
|
*=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* The implementation of server events */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* debug ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* add-event-listener! ::obj ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* envelope-re ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* server-init! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* server-reset! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* server-reset-sans-lock! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* add-event-listener! ::server ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* remove-event-listener! ::server ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *event-mutex* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-multipart-key ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* event services ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* websocket-register-new-connection! ... */
*---------------------------------------------------------------------*/
see http_response.scm for the source code that actually sends
the bytes of the response to the client.
register the websocket
*---------------------------------------------------------------------*/
* hop-event-init! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-tables ... */
* ------------------------------------------------------------- */
* Dump the content of the event table for debug purposes. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* server-event-register ... */
*---------------------------------------------------------------------*/
we already have a connection for that
client, we simply re-use it
we must response as a multipart response because
that's the way we have configured the xhr
on the client side but we must close the connection
we create a new connection for that client
multipart never sends a complete answer. In order to
traverse proxy, we use a chunked response
(trace-item "c=" c)
set an output timeout on the socket
register the client
*---------------------------------------------------------------------*/
* server-event-unregister ... */
*---------------------------------------------------------------------*/
Ping the client to check it still exists. If the client
no longer exists, an error will be raised and the client
will be removed from the tables.
Ping the client to check if it still exists. If the client
no longer exists, an error will be raised and the client
will be removed from the tables.
*---------------------------------------------------------------------*/
* multipart-close-request! ... */
* ------------------------------------------------------------- */
* This assumes that the event-mutex has been acquired. */
*---------------------------------------------------------------------*/
close the socket
remove the request from the *multipart-request-list*
remove the request from the *multipart-socket-table*
*---------------------------------------------------------------------*/
* websocket-close-request! ... */
* ------------------------------------------------------------- */
* This assumes that the event-mutex has been acquired. */
*---------------------------------------------------------------------*/
close the socket
decrement the current number of connected clients
remove the request from the *websocket-response-list*
remove the response from the *websocket-socket-table*
*---------------------------------------------------------------------*/
* hop-event-client-ready? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *multipart-socket-table* */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *websocket-request-table* */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* http-response ::http-response-event ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* get-server-event-key ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* multipart-signal ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* websocket-signal ... */
*---------------------------------------------------------------------*/
FIN=1, OPCODE=x1 (text)
payload data
*---------------------------------------------------------------------*/
* envelope-value ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* envelope-json-value ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* for-each-socket ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-signal-id ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-signal! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-broadcast! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-policy ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-policy-file ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *server-listeners* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* add-server-listener! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* remove-server-listener! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* *connect-listeners* ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* add-hop-listener! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* remove-hop-listener! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* padding-response ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-info-service ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-register-service ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* hop-event-unregister-service ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* apply-listeners ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* notify-client! ... */
*---------------------------------------------------------------------*/
|
* serrano / prgm / project / hop / hop / runtime / event.scm * /
* Author : * /
* Creation : Tue Sep 27 05:45:08 2005 * /
* Last change : Fri Jun 14 14:57:28 2019 ( serrano ) * /
* Copyright : 2005 - 20 * /
(module __hop_event
(library web)
(cond-expand
(enable-ssl
(library ssl)))
(include "thread.sch")
(include "xml.sch"
"service.sch"
"verbose.sch"
"param.sch")
(import __hop_configure
__hop_param
__hop_thread
__hop_types
__hop_user
__hop_xml-types
__hop_xml
__hop_html-head
__hop_misc
__hop_hop
__hop_http-response
__hop_json
__hop_js-comp
__hop_read
__hop_service
__hop_http-response
__hop_http-error
__hop_websocket
__hop_watch)
(static (class http-response-event::%http-response-server
(name::bstring read-only)))
(export (class event
(name::bstring read-only)
(target::obj read-only)
(stopped::bool (default #f))
(value::obj (default #unspecified)))
(class websocket-event::event
(data::obj (default #unspecified)))
(class server-event::websocket-event)
(class server
(mutex::mutex read-only (default (make-mutex)))
(host::bstring read-only)
(port::int read-only)
(ssl::bool (default #f))
(authorization read-only (default #f))
(version::bstring read-only (default (hop-version)))
(listeners::pair-nil (default '()))
(ready-listeners::pair-nil (default '()))
(down-listeners::pair-nil (default '()))
(trigger::procedure read-only (default (lambda (f) (f))))
(ctx (default #f))
(%websocket (default #f))
(%key (default #f)))
(generic server-init! ::server)
(generic server-reset! ::server)
(generic add-event-listener! ::obj ::obj ::procedure . l)
(generic remove-event-listener! ::obj ::obj ::procedure . l)
(generic stop-event-propagation ::event ::bool)
(apply-listeners ::obj ::event)
(hop-event-init!)
(hop-event-tables)
(hop-event-signal! ::bstring ::obj #!optional ctx)
(hop-event-broadcast! ::bstring ::obj #!optional ctx)
(hop-event-client-ready? ::bstring)
(hop-event-policy-file ::http-request)
(hop-event-info-service::procedure)
(hop-event-register-service::procedure)
(hop-event-unregister-service::procedure)))
(define debug-multipart #f)
(define-generic (add-event-listener! obj::obj event proc . capture)
(cond
((and (string? event) (string? obj))
(add-server-listener! obj event proc capture))
((eq? obj 'hop)
(add-hop-listener! event proc capture))
(else
(error "add-event-listener!"
(format "Illegal ~s listener" event) obj))))
(define-generic (remove-event-listener! obj::obj event proc . capture)
(cond
((and (string? event) (string? obj))
(remove-server-listener! obj event proc capture))
((eq? obj 'hop)
(remove-hop-listener! event proc capture))
(else
(error "remove-event-listener!"
(format "Illegal ~s listener" event) obj))))
(define-generic (stop-event-propagation event::event default::bool)
(with-access::event event (stopped)
(set! stopped #t)))
(define envelope-re
(pregexp "^<([rsxifj]) name='([^']+)'>(.*)</[rsxifj]>$" 'MULTILINE))
(define cdata-re
(pregexp "^<!\\[CDATA\\[(.*)\\]\\]>$" 'MULTILINE))
(define-generic (server-init! srv::server)
(define (message->event k id text)
(case (string-ref k 0)
((#\i)
(let ((val (string->integer text)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\f)
(let ((val (string->real text)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\x)
(let ((val (call-with-input-string text
(lambda (p)
(car
(last-pair
(parse-html p (string-length text))))))))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\s)
(let ((val (url-decode text)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val))))
((#\j)
(with-access::server srv (ctx)
(let ((val (string->obj
(url-decode (cadr (pregexp-match cdata-re text)))
#f ctx)))
(instantiate::server-event
(target srv)
(name id)
(value val)
(data val)))))
((#\r)
(let ((val (url-decode text)))
(instantiate::server-event
(target srv)
(name "ready")
(value val)
(data val))))))
(define (parse-message v)
(with-access::websocket-event v (data)
(let ((m (pregexp-match envelope-re data)))
(when (pair? m)
(let* ((k (cadr m))
(id (caddr m))
(text (cadddr m)))
(if (char=? (string-ref k 0) #\r)
(with-access::server srv (ready-listeners trigger)
(trigger
(lambda ()
(apply-listeners ready-listeners
(message->event k id text)))))
(with-access::server srv (listeners trigger)
(let ((ltns (filter-map (lambda (l)
(when (string=? (car l) id)
(cdr l)))
listeners)))
(when (pair? ltns)
(trigger
(lambda ()
(let ((event (message->event k id text)))
(apply-listeners ltns event)))))))))))))
(define (down e)
(with-trace 'event "down@server-init!"
(trace-item "e=" e)
(with-access::server srv (down-listeners trigger)
(trigger
(lambda ()
(apply-listeners down-listeners e))))))
(with-access::server srv (host port ssl authorization %websocket %key mutex)
(synchronize mutex
(unless %websocket
(with-hop ((hop-event-info-service))
:host host :port port
:authorization authorization
:ssl ssl
:sync #t
(lambda (v)
(let* ((key (vector-ref v 2))
(url (format "~a://~a:~a~a/public/server-event/websocket?key=~a"
(if ssl "wss" "ws") host port (hop-service-base)
key)))
(set! %key key)
(set! %websocket
(instantiate::websocket
(url url)
(authorization authorization)
(oncloses (list down))
(onmessages (list parse-message))))
(websocket-connect! %websocket))))))))
(define-generic (server-reset! obj::server)
(with-access::server obj (mutex)
(synchronize mutex
(server-reset-sans-lock! obj))))
(define (server-reset-sans-lock! obj::server)
(with-access::server obj (%websocket %key host port)
(websocket-close %websocket)
(set! %websocket #f)
(set! %key #f)))
(define-method (add-event-listener! obj::server event proc . capture)
(let loop ((armed #f))
(server-init! obj)
(with-access::server obj (mutex host port ssl authorization %key)
(cond
((string=? event "ready")
(synchronize mutex
(with-access::server obj (ready-listeners)
(set! ready-listeners (cons proc ready-listeners)))))
((string=? event "down")
(synchronize mutex
(with-access::server obj (down-listeners)
(set! down-listeners (cons proc down-listeners)))))
(else
(with-hop ((hop-event-register-service) :event event
:key %key :mode "websocket")
:host host :port port
:authorization authorization
:ssl ssl
(lambda (v)
(synchronize mutex
(with-access::server obj (listeners)
(set! listeners (cons (cons event proc) listeners)))))
(lambda (exn)
(if (isa? exn xml-http-request)
(with-access::xml-http-request exn (status input-port header)
(if (and (not armed) (=fx status 500))
(let ((badkey (read-string input-port)))
(when (string=? (md5sum %key) badkey)
(server-reset! obj)
(loop #t)))
(tprint "error: " (read-string input-port))))
(exception-notify exn)))))))))
(define-method (remove-event-listener! obj::server event proc . capture)
(with-access::server obj (listeners mutex host port ssl authorization %key)
(let ((key %key))
(when (synchronize mutex
(let loop ((ls listeners))
(when (pair? ls)
(let ((l (car ls)))
(if (and (eq? (cdr l) proc) (string=? (car l) event))
(begin
(set! listeners (remq! l listeners))
(when (null? listeners)
(server-reset-sans-lock! obj))
#t)
(loop (cdr ls)))))))
(when key
(with-hop ((hop-event-unregister-service) :event event :key key)
:host host :port port
:authorization authorization
:ssl ssl))))))
(define *event-mutex* (make-mutex "hop-event"))
(define *listener-mutex* (make-mutex "hop-listener"))
(define hop-multipart-key "hop-multipart")
(define *info-service* #f)
(define *websocket-service* #t)
(define *register-service* #f)
(define *unregister-service* #f)
(define *init-service* #f)
(define *policy-file-service #f)
(define *close-service* #f)
(define *client-key* 0)
(define *default-request* (instantiate::http-server-request))
(define *ping* (symbol->string (gensym 'ping)))
(define *clients-number* 0)
(define (websocket-register-new-connection! req key)
(define (get-header header key default)
(let ((c (assq key header)))
(if (pair? c)
(cdr c)
default)))
(with-access::http-request req (header connection socket)
(let ((host (get-header header host: #f))
(version (get-header header sec-websocket-version: "-1")))
(with-trace 'event "ws-register-new-connection"
(trace-item "protocol-version=" version)
(let ((resp (websocket-server-response req key :protocol '("json"))))
(watch-socket! socket
(lambda (s)
(with-trace 'event
"watch@websocket-register-new-connection!"
(trace-item "CLOSING s=" s)
(socket-close s)
(notify-client! "disconnect" #f req
*disconnect-listeners*))))
(trace-item "resp=" (typeof resp))
(synchronize *event-mutex*
(set! *websocket-response-list*
(cons (cons (string->symbol key) (cons resp req))
*websocket-response-list*))
(trace-item "key=" key)
(trace-item "socket=" socket )
(trace-item "connected clients=" *websocket-response-list*))
resp)))))
(define (hop-event-init!)
(synchronize *event-mutex*
(when (=fx *client-key* 0)
(set! *client-key* (elong->fixnum (current-seconds)))
(set! *websocket-service*
(service :name "public/server-event/websocket"
:id server-event
:timeout 0
(#!key key)
(with-trace 'event "start websocket service"
(trace-item "key=" key)
(let ((req (current-request)))
(with-access::http-request req (header socket)
(trace-item "req.socket=" socket)
(if (websocket-proxy-request? header)
(websocket-proxy-response req)
(websocket-register-new-connection! req key)))))))
(set! *info-service*
(service :name "public/server-event/info"
:id server-event
:timeout 0
()
(let* ((req (current-request))
(hd (with-access::http-request req (header) header))
(host (assq host: hd))
(key (get-server-event-key req))
(sock (with-access::http-request req (socket) socket))
(port (with-access::http-request req (port) port))
(ssl (cond-expand
(enable-ssl (ssl-socket? sock))
(else #f))))
(if (pair? host)
(let ((s (string-split (cdr host) ":")))
(vector (car s) port key ssl))
(with-access::http-request req (host)
(vector host port key ssl))))))
(set! *policy-file-service
(service :name "public/server-event/policy-file"
:id server-event
:timeout 0
(#!key port key)
(instantiate::http-response-string
(content-type "application/xml")
(body (hop-event-policy port)))))
(set! *close-service*
(service :name "public/server-event/close" :timeout 0 (#!key key)
:id server-event
(synchronize *event-mutex*
(lambda ()
(let ((key (string->symbol key)))
(set! *clients-number* (-fx *clients-number* 1)))))))
(set! *unregister-service*
(service :name "public/server-event/unregister"
:id server-event
:timeout 0
(#!key event key)
(server-event-unregister event key)))
(set! *register-service*
(service :name "public/server-event/register"
:id server-event
:timeout 0
(#!key event key mode padding)
(server-event-register event key mode padding (current-request)))))))
(define (hop-event-tables)
(synchronize *event-mutex*
`((*clients-number* ,*clients-number*)
(*multipart-request-list* ,*multipart-request-list*)
(*multipart-socket-table* ,*multipart-socket-table*)
(*websocket-response-list* ,*websocket-response-list*)
(*websocket-socket-table* ,*websocket-socket-table*))))
(define (server-event-register event key mode padding req)
(define (multipart-register-event! req key name)
(with-trace 'event "multipart-register-event!"
(let ((content (format "--~a\nContent-type: text/xml\n\n<r name='~a'></r>\n--~a\n"
hop-multipart-key name hop-multipart-key))
(c (assq key *multipart-request-list*)))
(if (pair? c)
(let ((oreq (cdr c)))
(hashtable-update! *multipart-socket-table*
name
(lambda (l) (cons oreq l))
(list oreq))
(instantiate::http-response-string
(header '((Transfer-Encoding: . "chunked")))
(content-length #e-2)
(content-type (format "multipart/x-mixed-replace; boundary=\"~a\"" hop-multipart-key))
(body (format "~a\r\n~a" (integer->string (string-length content) 16) content))))
(with-access::http-request req (socket)
(output-port-flush-hook-set!
(socket-output socket)
(lambda (port size)
(output-port-flush-hook-set! port chunked-flush-hook)
""))
(set! *multipart-request-list*
(cons (cons key req)
*multipart-request-list*))
(hashtable-update! *multipart-socket-table*
name
(lambda (l) (cons req l))
(list req))
(instantiate::http-response-persistent
(request req)
(body (format "HTTP/1.1 200 Ok\r\nTransfer-Encoding: chunked\r\nContent-type: multipart/x-mixed-replace; boundary=\"~a\"\r\n\r\n~a\r\n~a"
hop-multipart-key
(integer->string (string-length content) 16)
content))))))))
(define (websocket-register-event! req key name)
(with-trace 'event "websocket-register-event!"
(let ((c (assq key *websocket-response-list*)))
(trace-item "key=" key)
(trace-item "name=" name)
(if (pair? c)
(let ((resp (cadr c)))
(websocket-signal resp
(format "<r name='ready'>~a</r>"
(url-path-encode name)))
(hashtable-update! *websocket-socket-table*
name
(lambda (l) (cons resp l))
(list resp))
(instantiate::http-response-string))
(begin
(trace-item "keylist=" *websocket-response-list*)
(instantiate::http-response-string
(start-line "HTTP/1.0 500 Illegal key")
(body (md5sum (symbol->string! key)))))))))
(with-trace 'event "ws-register-event!"
(synchronize *event-mutex*
(trace-item "event=" (url-decode event))
(trace-item "key=" key)
(trace-item "mode=" mode)
(trace-item "padding=" padding)
(if (<fx *clients-number* (hop-event-max-clients))
(if (string? key)
(let ((key (string->symbol key))
(event (url-decode! event)))
(with-access::http-request req (socket)
(output-timeout-set!
(socket-output socket) (hop-connection-timeout)))
(let ((r (cond
((string=? mode "xhr-multipart")
(multipart-register-event! req key event))
((string=? mode "websocket")
(websocket-register-event! req key event))
(else
(error "register-event" "unsupported mode" mode)))))
(notify-client! "connect" event req
*connect-listeners*)
r))
(http-service-unavailable event))
(http-service-unavailable event)))))
(define (server-event-unregister event key)
(define (unregister-multipart-event! event key)
(let ((c (assq (string->symbol key) *multipart-request-list*)))
(when (pair? c)
(let ((req (cadr c)))
(hashtable-update! *multipart-socket-table*
event
(lambda (l) (delete! req l))
'())
(multipart-signal req
(envelope-value *ping* #unspecified #f))))))
(define (remq-one! x y)
(let laap ((x x)
(y y))
(cond
((null? y) y)
((eq? x (car y)) (cdr y))
(else (let loop ((prev y))
(cond ((null? (cdr prev))
y)
((eq? (cadr prev) x)
(set-cdr! prev (cddr prev))
y)
(else (loop (cdr prev)))))))))
(define (unregister-websocket-event! event key)
(let ((c (assq (string->symbol key) *websocket-response-list*)))
(when (pair? c)
(let ((resp (cadr c))
(req (cddr c)))
(hashtable-update! *websocket-socket-table*
event
(lambda (l)
(notify-client! "disconnect" event req
*disconnect-listeners*)
(remq-one! resp l))
'())
(websocket-signal resp
(envelope-value *ping* #unspecified #f))))))
(synchronize *event-mutex*
(let ((event (url-decode! event)))
(when (and (string? key) event)
(unregister-websocket-event! event key)
(unregister-multipart-event! event key)
#f))))
(define (multipart-close-request! req)
(with-access::http-request req (socket)
(socket-shutdown socket))
(set! *clients-number* (-fx *clients-number* 1))
(set! *multipart-request-list*
(filter! (lambda (e) (not (eq? (cdr e) req)))
*multipart-request-list*))
(hashtable-for-each *multipart-socket-table*
(lambda (k l)
(hashtable-update! *multipart-socket-table*
k
(lambda (l) (delete! req l))
'())))
(hashtable-filter! *multipart-socket-table* (lambda (k l) (pair? l))))
(define (websocket-close-request! resp::http-response-websocket)
(with-access::http-response-websocket resp ((req request))
(with-access::http-request req (socket)
(socket-close socket)
(with-trace 'event "ws-close-request!"
(trace-item "socket=" socket)))
(set! *clients-number* (-fx *clients-number* 1))
(set! *websocket-response-list*
(filter! (lambda (e)
(not (eq? (cadr e) resp)))
*websocket-response-list*))
(hashtable-for-each *websocket-socket-table*
(lambda (k l)
(hashtable-update! *websocket-socket-table*
k
(lambda (l) (delete! resp l))
'())))
(hashtable-filter! *websocket-socket-table* (lambda (k l) (pair? l)))))
(define (hop-event-client-ready? name)
(define (multipart-event-client-ready? name)
(let ((l (hashtable-get *multipart-socket-table* name)))
(and (pair? l)
(any (lambda (req)
(with-access::http-request req (socket)
(not (socket-down? socket))))
l))))
(define (websocket-event-client-ready? name)
(let ((l (hashtable-get *websocket-socket-table* name)))
(and (pair? l)
(any (lambda (req)
(with-access::http-request req (socket)
(not (socket-down? socket))))
l))))
(or (multipart-event-client-ready? name)
(websocket-event-client-ready? name)))
(define *multipart-socket-table* (make-hashtable))
(define *multipart-request-list* '())
(define *websocket-socket-table* (make-hashtable))
(define *websocket-response-list* '())
(define-method (http-response r::http-response-event request socket)
(let ((p (socket-output socket)))
(with-access::http-response-event r (name)
(fprintf p "<acknowledge name='~a'/>" name))
(display #a000 p)
(flush-output-port p)
'persistent))
(define (get-server-event-key req::http-request)
(synchronize *event-mutex*
(set! *client-key* (+fx 1 *client-key*))
(with-access::http-request req (host port)
(format "~a:~a://~a" host port *client-key*))))
(define (multipart-signal req vstr::bstring)
(with-access::http-request req (socket)
(let ((p (socket-output socket)))
(with-handler
(lambda (e)
(when debug-multipart
(tprint "MULTIPART EVENT ERROR: "
e " thread=" (current-thread)))
(if (isa? e &io-error)
(multipart-close-request! req)
(raise e)))
(begin
(fprintf p "Content-type: text/xml\n\n")
(display-string vstr p)
(fprintf p "\n--~a\n" hop-multipart-key p)
(flush-output-port p))))))
(define (websocket-signal resp::http-response-websocket vstr::bstring)
(define (hixie-signal-value vstr socket)
(let ((p (socket-output socket)))
(display #a000 p)
(display-string vstr p)
(display #a255 p)
(flush-output-port p)))
(define (hybi-signal-value vstr socket)
(with-trace 'event "hybi-signal-value"
(let ((p (socket-output socket)))
(trace-item "p=" p " closed=" (closed-output-port? p))
(let ((l (string-length vstr)))
(display (integer->char #x81) p)
(cond
((<=fx l 125)
1 byte length
(display (integer->char l) p))
((<=fx l 65535)
2 bytes length
(display #a126 p)
(display (integer->char (bit-rsh l 8)) p)
(display (integer->char (bit-and l #xff)) p))
(else
4 bytes length
(display #a127 p)
(display "\000\000\000\000" p)
(display (integer->char (bit-rsh l 24)) p)
(display (integer->char (bit-and (bit-rsh l 16) #xff)) p)
(display (integer->char (bit-and (bit-rsh l 8) #xff)) p)
(display (integer->char (bit-and l #xff)) p)))
(display-string vstr p)
(flush-output-port p)))))
(with-access::http-response-websocket resp ((req request))
(with-access::http-request req (socket)
(with-handler
(lambda (e)
(with-trace 'event "ws-signal-error"
(trace-item "err=" e)
(trace-item "socket=" socket)
(trace-item "thread=" (current-thread))
(trace-item "req=" req )
(trace-item "vlen=" (string-length vstr))
(if (isa? e &io-error)
(begin
(with-trace 'event "ws-error-close"
(websocket-close-request! resp))
#f)
(raise e))))
(with-access::http-response-websocket resp (accept)
(with-trace 'event "ws-signal"
(trace-item "resp=" resp)
(trace-item "accept=" accept)
(if accept
(hybi-signal-value vstr socket)
(hixie-signal-value vstr socket))))))))
(define (envelope-value::bstring name value ctx)
(let ((n (url-path-encode name)))
(cond
((isa? value xml)
(format "<x name='~a'>~a</x>" n (xml->string value (hop-xml-backend))))
((string? value)
(format "<s name='~a'>~a</s>" n (url-path-encode value)))
((integer? value)
(format "<i name='~a'>~a</i>" n value))
((real? value)
(format "<f name='~a'>~a</f>" n value))
(else
(let ((op (open-output-string)))
(fprintf op "<j name='~a'><![CDATA[" n)
ICI utiliser ctx
(display (url-path-encode (obj->string value (or ctx 'hop-client))) op)
(display "]]></j>" op)
(close-output-port op))))))
(define (envelope-json-value name value ctx)
(let ((n (url-path-encode name)))
(let ((op (open-output-string)))
(fprintf op "<o name='~a'><![CDATA[" n)
(let ((json (call-with-output-string
(lambda (op)
(obj->json value op ctx)))))
(display (url-path-encode json) op)
(display "]]></o>" op)
(close-output-port op)))))
(define (for-each-socket table name proc)
(let ((l (hashtable-get table name)))
(when l
(proc l))))
(define hop-signal-id 0)
(define (hop-event-signal! name value #!optional ctx)
(define (multipart-event-signal! name value)
(for-each-socket
*multipart-socket-table*
name
(lambda (l)
(when (pair? l)
(let ((val (envelope-value name value ctx)))
(when debug-multipart
(tprint "MULTIPART SIGNAL: " name))
(multipart-signal (car l) val)
#t)))))
(define (websocket-event-signal! name value)
(for-each-socket
*websocket-socket-table*
name
(lambda (l)
(when (pair? l)
(with-access::http-response-websocket (car l) (protocol)
(let ((val (if (and (string? protocol)
(string=? protocol "json"))
(envelope-json-value name value ctx)
(envelope-value name value ctx))))
(websocket-signal (car l) val)
#t))))))
(set! hop-signal-id (-fx hop-signal-id 1))
(hop-verb 2 (hop-color hop-signal-id hop-signal-id " SIGNAL")
": " name)
(hop-verb 3 " value=" (with-output-to-string (lambda () (write value))))
(hop-verb 2 "\n")
(synchronize *event-mutex*
(case (random 2)
((0)
(unless (multipart-event-signal! name value)
(websocket-event-signal! name value)))
((3)
(unless (websocket-event-signal! name value)
(multipart-event-signal! name value)))))
#unspecified)
(define (hop-event-broadcast! name value #!optional ctx)
(define jsvalue #f)
(define jsonvalue #f)
(define (hopjs-value name value)
(unless jsvalue (set! jsvalue (envelope-value name value ctx)))
jsvalue)
(define (json-value name value)
(unless jsonvalue (set! jsonvalue (envelope-json-value name value ctx)))
jsonvalue)
(define (websocket-event-broadcast! name value)
(with-trace 'event "ws-event-broadcast!"
(trace-item "name=" name)
(trace-item "value="
(if (or (string? value) (symbol? value) (number? value))
value
(typeof value)))
(trace-item "ws-table=" (hashtable-key-list *websocket-socket-table*))
(for-each-socket *websocket-socket-table*
name
(lambda (l)
(with-trace 'event "ws-event-broadcast"
(trace-item "name=" name)
(trace-item "# clients=" (length l))
(trace-item "cients="
(map (lambda (resp)
(with-access::http-response-websocket resp (request)
(with-access::http-request request (socket)
socket)))
l))
(when (pair? l)
(for-each (lambda (resp)
(with-access::http-response-websocket resp (protocol)
(websocket-signal resp
(if (and (string? protocol)
(string=? protocol "json"))
(json-value name value)
(hopjs-value name value)))))
l)))))))
(define (multipart-event-broadcast! name value)
(let ((val (envelope-value name value ctx)))
(for-each-socket
*multipart-socket-table*
name
(lambda (l)
(when (pair? l)
(for-each (lambda (req)
(multipart-signal req val))
l))))))
(synchronize *event-mutex*
(websocket-event-broadcast! name value)
(multipart-event-broadcast! name value))
#unspecified)
(define (hop-event-policy port)
(format "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<cross-domain-policy xmlns:xsi=\"-instance\" xsi:noNamespaceSchemaLocation=\"\">
<allow-access-from domain=\"*\" to-ports=\"~a\" />
</cross-domain-policy>" port))
(define (hop-event-policy-file req)
(instantiate::http-response-raw
(connection 'close)
(proc (lambda (p)
(with-access::http-request req (port)
(display (hop-event-policy port) p))
(write-char #a000 p)))))
(define *server-listeners*
(make-hashtable 16))
(define (add-server-listener! event::bstring srv::bstring proc::procedure capture)
(define (parse-host host auth)
(let ((l (string-split host ":")))
(if (null? (cdr l))
(values host 8080 #f)
(values (car l) (string->integer (cadr l)) auth))))
(define (parse-authenticated-host str)
(let ((s (string-split str "@")))
(if (null? (cdr s))
(parse-host str #f)
(parse-host (cadr s) (car s)))))
(let ((olds (synchronize *listener-mutex*
(hashtable-get *server-listeners* srv))))
(if (isa? olds server)
(add-event-listener! olds event proc capture)
(multiple-value-bind (host port auth)
(parse-authenticated-host srv)
(let ((news (instantiate::server
(host host)
(port port)
(ssl #f)
(authorization auth))))
(synchronize *listener-mutex*
(hashtable-put! *server-listeners* srv news))
(add-event-listener! news event proc capture))))))
(define (remove-server-listener! event srv proc capture)
(let ((olds (synchronize *listener-mutex*
(hashtable-get *server-listeners* srv))))
(when (isa? olds server)
(apply remove-event-listener! olds event proc capture))))
(define *connect-listeners* '())
(define *disconnect-listeners* '())
(define (add-hop-listener! event::bstring proc::procedure capture)
(cond
((string=? event "connect")
(synchronize *listener-mutex*
(set! *connect-listeners*
(cons proc *connect-listeners*))))
((string=? event "disconnect")
(synchronize *listener-mutex*
(set! *disconnect-listeners*
(cons proc *disconnect-listeners*))))))
(define (remove-hop-listener! event::bstring proc::procedure capture)
(cond
((string=? event "connect")
(synchronize *listener-mutex*
(set! *connect-listeners*
(delete! proc *connect-listeners*))))
((string=? event "disconnect")
(synchronize *listener-mutex*
(set! *disconnect-listeners*
(delete! proc *disconnect-listeners*))))))
(define (padding-response rep padding)
(when padding
(with-access::http-response-hop rep ((p padding) content-type)
(set! p padding)
(set! content-type "application/x-javascript")))
rep)
(define (hop-event-info-service)
(hop-event-init!)
*info-service*)
(define (hop-event-register-service)
(hop-event-init!)
*register-service*)
(define (hop-event-unregister-service)
(hop-event-init!)
*unregister-service*)
(define (apply-listeners listeners::obj e::event)
(let loop ((l listeners))
(when (pair? l)
((car l) e)
(with-access::event e (stopped)
(unless stopped
(loop (cdr l)))))))
(define (notify-client! event id req ltns)
(when (pair? ltns)
(let ((e (instantiate::server-event
(target req)
(name event)
(value id)
(data id))))
(apply-listeners ltns e))))
|
367197b294618de77de1c7f3fd37a72067408abe152c1272bbaf33740141ceb3
|
gnl/ghostwheel
|
core.cljc
|
Copyright ( c ) . All rights reserved .
;; The use and distribution terms for this software are covered by the
Eclipse Public License 2.0 ( -2.0/ )
;; which can be found in the file LICENSE at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ghostwheel.core
#?(:cljs (:require-macros ghostwheel.core))
(:require [clojure.string :as string]
[clojure.set :refer [union difference map-invert]]
[clojure.walk :as walk]
[clojure.test :as t]
[clojure.test.check]
[clojure.test.check.generators]
[clojure.test.check.properties]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.spec.gen.alpha :as gen]
[ghostwheel.reporting :as r]
[ghostwheel.unghost :refer [clean-defn]]
[ghostwheel.utils :as u :refer [cljs-env? clj->cljs]]
[ghostwheel.logging :as l]
[ghostwheel.threading-macros :include-macros true]
[expound.alpha :as exp]
;; REVIEW: Not requiring the clojure.core.specs.alpha
;; namespaces for now because they break a lot
of older code including lein - figwheel < 0.5.18
#?@(:clj [;[clojure.core.specs.alpha]
[orchestra.spec.test :as ost]]
:cljs [;[cljs.core.specs.alpha :include-macros true]
[cljs.analyzer.api :as ana-api]
[orchestra-cljs.spec.test :as ost]])))
;; REVIEW: Replace this pattern:
;; `(let [fn-name (fn ...)] (defn ...))` with
;; `letfn` when the ClojureScript bug is fixed:
-1965
Global vars and state
;; This isn't particularly pretty, but it's how we avoid
having ClojureScript as a required dependency on Clojure
#?(:clj (try
(do
(ns-unalias (find-ns 'ghostwheel.core) 'ana-api)
(require '[cljs.analyzer.api :as ana-api]))
(catch Exception _ (require '[ghostwheel.stubs.ana-api :as ana-api]))))
(when-let [expound-cfg (::expound (u/get-base-config false))]
#?(:clj (alter-var-root #'s/*explain-out* (constantly (exp/custom-printer expound-cfg)))
:cljs (set! s/*explain-out* (exp/custom-printer expound-cfg))))
(def ^:private test-suffix "__ghostwheel-test")
(def ^:private *after-check-callbacks (atom []))
(def ^:private ^:dynamic *unsafe-bound-ops* #{})
(def ^:dynamic *global-trace-allowed?* true)
(def ^:dynamic *global-check-allowed?* true) ; REVIEW: Is anyone using this?
;;;; Misc helper functions
(defn- set-trace [enabled]
#?(:clj (alter-var-root #'*global-trace-allowed?* (constantly enabled))
:cljs (set! *global-trace-allowed?* enabled)))
(defn enable-trace! [] (set-trace true) "Tracing enabled.")
(defn disable-trace! [] (set-trace false) "Tracing disabled.")
(defn- set-check [enabled]
#?(:clj (alter-var-root #'*global-check-allowed?* (constantly enabled))
:cljs (set! *global-check-allowed?* enabled)))
(defn enable-check! [] (set-check true) "Check enabled.")
(defn disable-check! [] (set-check false) "Check disabled.")
(defn- count-args
"Returns a tuple with the number of regular and non-variadic arguments."
[conformed-args]
[(count (:args conformed-args))
(if (:varargs conformed-args) 1 0)])
(defn- resolve-trace-color [color]
(let [[color-type color-value] (s/conform ::trace-color color)]
(case color-type
:literal color-value
:keyword (if-let [color-value (get l/ghostwheel-colors color)]
color-value
(:black l/ghostwheel-colors)))))
Operators
;; It doesn't actually matter what these are bound to, they are stripped by
;; the macros they're used in and never end up in the final code. This is just
;; so they can be used without '=> cannot be resolved' errors in the IDE.
(def => :ret)
(def | :st)
(def <- :gen)
(defmacro ? [& forms]
(cond-> `(s/nilable ~@forms)
(cljs-env? &env) clj->cljs))
Specs
(s/def ::trace #{0 1 2 3 4 5 6 true})
(s/def ::trace-color (s/or :keyword keyword?
:literal (s/and string?
#(re-matches #"#[a-fA-F0-9]+" %)
#(or (= (count %) 7)
(= (count %) 4)))))
(s/def ::check boolean?)
(s/def ::check-coverage boolean?)
(s/def ::ignore-fx boolean?)
(s/def ::num-tests nat-int?)
(s/def ::num-tests-ext nat-int?)
(s/def ::extensive-tests boolean?)
(s/def ::defn-macro (s/nilable string?))
(s/def ::instrument boolean?)
(s/def ::outstrument boolean?)
(s/def ::extrument (s/nilable (s/coll-of qualified-symbol? :kind vector?)))
(s/def ::expound (s/nilable (s/map-of keyword? any?)))
(s/def ::report-output #{:repl :js-console})
;; TODO: Integrate bhauman/spell-spec
(s/def ::ghostwheel-config
(s/and (s/keys :req [::trace ::trace-color ::check ::check-coverage ::ignore-fx
::num-tests ::num-tests-ext ::extensive-tests ::defn-macro
::instrument ::outstrument ::extrument ::expound ::report-output])))
(s/assert ::ghostwheel-config u/ghostwheel-default-config)
;; TODO: Add check to make sure instrument and outstrument aren't both on
;; These are lifted straight from clojure.core.specs.alpha, because it
;; didn't seem possible to access them directly in the original namespace.
(s/def ::local-name (s/and simple-symbol? #(not= '& %)))
;; sequential destructuring
(s/def ::seq-binding-form
(s/and vector?
(s/cat :elems (s/* ::binding-form)
:rest (s/? (s/cat :amp #{'&} :form ::binding-form))
:as (s/? (s/cat :as #{:as} :sym ::local-name)))))
;; map destructuring
(s/def ::keys (s/coll-of ident? :kind vector?))
(s/def ::syms (s/coll-of symbol? :kind vector?))
(s/def ::strs (s/coll-of simple-symbol? :kind vector?))
(s/def ::or (s/map-of simple-symbol? any?))
(s/def ::as ::local-name)
(s/def ::map-special-binding
(s/keys :opt-un [::as ::or ::keys ::syms ::strs]))
(s/def ::map-binding (s/tuple ::binding-form any?))
(s/def ::ns-keys
(s/tuple
(s/and qualified-keyword? #(-> % name #{"keys" "syms"}))
(s/coll-of simple-symbol? :kind vector?)))
(s/def ::map-bindings
(s/every (s/or :mb ::map-binding
:nsk ::ns-keys
:msb (s/tuple #{:as :or :keys :syms :strs} any?))
:into {}))
(s/def ::map-binding-form (s/merge ::map-bindings ::map-special-binding))
(s/def ::binding-form
(s/or :sym ::local-name
:seq ::seq-binding-form
:map ::map-binding-form))
Function and > defn specs
(s/def ::arg-list
(s/and vector?
(s/cat :args (s/* ::binding-form)
:varargs (s/? (s/cat :amp #{'&} :form ::binding-form)))))
(s/def ::pred-arg-list
(s/and vector?
(s/cat :args (s/* (s/or :sym ::local-name)))))
(s/def ::anon-args+body
(s/cat :args ::arg-list
:body (s/* any?)))
(s/def ::anon-fn
(s/and seq?
(s/cat :op #{'fn* 'fn}
:name (s/? simple-symbol?)
:bs (s/alt :arity-1 ::anon-args+body
:arity-n (s/+ (s/spec ::anon-args+body))))))
(s/def ::pred-fn
(s/and seq?
(s/cat :op #{'fn* 'fn}
:name (s/? simple-symbol?)
:args ::pred-arg-list
:body any?)))
(s/def ::spec-elem
(s/or :set set?
:pred-sym (s/and symbol?
(complement #{'| '=>})
;; REVIEW: should the `?` be a requirement?
#(string/ends-with? (str %) "?"))
:gspec (s/or :nilable-gspec ::nilable-gspec :gspec ::gspec)
:spec-key qualified-keyword?
:fun ::pred-fn
:list seq?))
(s/def ::such-that-op #{:st '|})
(s/def ::ret-op #{:ret '=>})
(s/def ::gen-op #{:gen '<-})
(s/def ::gspec
(s/and vector?
(s/cat :args (s/? (s/cat :args (s/+ ::spec-elem)
:args-such-that (s/? (s/cat :op ::such-that-op
:preds (s/+ ::pred-fn)))))
:ret-op ::ret-op
:ret ::spec-elem
:fn-such-that (s/? (s/cat :op ::such-that-op
:preds (s/+ ::pred-fn)))
:gen (s/? (s/cat :op ::gen-op
:gen-fn (s/? (some-fn seq? symbol?)))))))
(s/def ::nilable-gspec
(s/and vector?
(s/cat :maybe #{'? 's/nilable}
:gspec ::gspec)))
(s/def ::prepost (s/map-of #{:pre :post}
(s/coll-of seq?
:kind vector?
:distinct true)))
(s/def ::args+body
(s/cat :args ::arg-list
:body (s/alt :prepost+body (s/cat :prepost ::prepost
:body (s/+ any?))
:body (s/* any?))))
(s/def ::args+gspec+body
(s/&
(s/cat :args ::arg-list
:gspec (s/nilable ::gspec)
:body (s/alt :prepost+body (s/cat :prepost ::prepost
:body (s/+ any?))
:body (s/* any?)))
(fn arg-specs-match-param-count? [{:keys [args gspec]}]
(if-not gspec
true
(let [argcount (->> args count-args (apply +))
spec-args (:args gspec)]
(if spec-args
(-> spec-args :args count (= argcount))
(= argcount 0)))))))
(s/def ::defn
(s/and seq?
(s/cat :op #{'defn 'defn-}
:name simple-symbol?
:docstring (s/? string?)
:meta (s/? map?)
:bs (s/alt :arity-1 ::args+body
:arity-n (s/cat :bodies (s/+ (s/spec ::args+body))
:attr (s/? map?))))))
(s/def ::deftest
(s/and seq?
(s/cat :op #{'clojure.test/deftest 'cljs.test/deftest}
:name symbol?
:body any?)))
;;; Side effect detection specs
(def threading-macro-syms
#{'-> '->> 'as-> 'cond-> 'cond->> 'some-> 'some->>
'*-> '*->> '*as-> '*cond-> '*cond->> '*some-> '*some->>})
(s/def ::threading-macro-op threading-macro-syms)
(s/def ::binding-op
#{'let 'for 'doseq 'binding})
(s/def ::single-function-composition
#{'partial 'fnil})
(s/def ::safe-single-function-composition
#{'memoize 'complement})
(s/def ::multi-function-composition
#{'comp})
(s/def ::safe-multi-function-composition
#{'juxt 'every-pred 'some-fn})
(s/def ::function-application
#{'apply 'map 'fmap 'map-indexed 'reduce})
(s/def ::safe-function-application
#{'mapcat 'reduce-kv 'mapv 'reductions 'iterate 'keep 'keep-indexed
'remove 'filter 'filterv 'take-while 'drop-while
'sort 'sort-by 'sorted-map-by 'group-by 'merge-with})
(s/def ::unsafe-clj-block #{'do
'doseq
'dotimes})
;; REVIEW: maybe move the re-frame stuff out of here
(s/def ::unsafe-clj-call #{'dorun
'repeatedly
'dispatch
'js-delete
'aset})
(s/def ::unsafe-clj-comp
(s/alt :single-fn (s/cat :composition (s/alt :generic ::single-function-composition
:safe ::safe-single-function-composition)
:unsafe-op ::unsafe-op
:rest ::rest)
:multi-fn (s/cat :composition (s/alt :generic ::multi-function-composition
:safe ::safe-multi-function-composition)
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest)))
(let [bang-suffix? #(string/ends-with? (str %) "!")]
(s/def ::bang-suffix (every-pred symbol? bang-suffix?))
(s/def ::unsafe-op
(s/alt :bang-suffix ::bang-suffix
:unsafe-anon-fn (s/and seq?
(s/alt :unsafe-body (s/cat :fun #{'fn 'fn*}
:name (s/? simple-symbol?)
:args ::arg-list
:body ::unsafe-form)
:unsafe-name (s/cat :fun #{'fn 'fn*}
:name (every-pred simple-symbol?
bang-suffix?)
:args ::arg-list
:body any?)))
:unsafe-clj-call ::unsafe-clj-call
:unsafe-clj-comp (s/spec ::unsafe-clj-comp)
:unsafe-bound-call #(contains? *unsafe-bound-ops* %)
:multi-form-op (s/cat :op #{'when 'when-not 'when-let 'when-first
'when-some 'let 'binding}
:pred-or-bindings any?
:fx (s/+ any?)
:return any?))))
(s/def ::safe-op #(not (s/valid? ::unsafe-op (list %))))
(s/def ::some-unsafe-ops (s/+ (s/cat :skipped-ops (s/* ::safe-op)
:unsafe-op ::unsafe-op)))
(s/def ::rest (s/* any?))
(s/def ::some-unsafe-bindings
(s/and vector?
(s/+ (s/cat :skipped-bindings (s/* (s/cat :binding ::binding-form
:value ::safe-op))
:unsafe-binding (s/cat :binding ::binding-form
:value ::unsafe-op)))))
(s/def ::unsafe-form
;; REVIEW: maybe make sure we are only matching on the simple symbol part
(s/or :unsafe-block (s/and seq?
(s/cat :unsafe-clj-block ::unsafe-clj-block
:rest ::rest))
:unsafe-call
(s/and seq?
(s/alt :direct (s/cat :application
(s/? (s/alt :generic ::function-application
:safe ::safe-function-application))
:unsafe-op ::unsafe-op
:rest ::rest)
:threading (s/cat :threading-macro-op ::threading-macro-op
:threaded-form any?
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest)
:update (s/cat :update #{'update 'update-in}
:map any?
:path any?
:unsafe-op ::unsafe-op
:rest ::rest)))
:unsafe-composition (s/and seq? ::unsafe-clj-comp)
:unsafe-binding (s/and seq?
(s/cat :binding-op ::binding-op
:bindings ::some-unsafe-bindings
:rest ::rest))
:unsafe-argument (s/and seq?
(s/cat :fun ::safe-op
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest))
#_::unsafe-something #_(s/spec (s/cat ::some-unsafe-ops ::some-unsafe-ops
::rest ::rest))))
;;;; Main code generating functions
(let [find-fx
(fn find-fx [form]
(let [maybe-fx (s/conform ::unsafe-form form)
[found-fx
unsafe-bindings] (if (= maybe-fx ::s/invalid)
[nil nil]
[(conj {} maybe-fx)
(when (= (key maybe-fx) :unsafe-binding)
(-> maybe-fx
val
:bindings))])
TODO implement map and support for bindings
unsafe-binding-set (when unsafe-bindings
(->> unsafe-bindings
(map #(-> % :unsafe-binding :binding val))
(set)))]
[found-fx (vec
(for [nested-form form
:when (and (coll? nested-form))]
REVIEW go into nested anon - fns or not ?
( not ( contains ? # { ' fn ' fn * } ( first nested - form ) ) ) ) ]
(binding [*unsafe-bound-ops* (cond-> *unsafe-bound-ops*
unsafe-bindings (union unsafe-binding-set))]
(find-fx nested-form))))]))
check-arity-fx
(fn [unformed-args-gspec-body]
(let [effects (->> (find-fx unformed-args-gspec-body)
(flatten)
(remove nil?)
(map first)
(vec))]
(-> (for [fx effects]
[(-> fx key name keyword)
(->> fx
(s/unform ::unsafe-form)
(apply list)
(str))
(->> fx
val
(walk/postwalk #(if (qualified-keyword? %)
(keyword (name %))
%))
vec)])
(cond->> (next unformed-args-gspec-body) (cons [:multiple-body-forms])))))]
(defn- generate-test [fn-name fspecs body-forms config cljs?]
(let [{:keys [::check ::num-tests ::num-tests-ext ::extensive-tests
::check-coverage ::ignore-fx]}
config
num-tests (if extensive-tests num-tests-ext num-tests)
marked-unsafe (s/valid? ::bang-suffix fn-name)
found-fx (if ignore-fx
[]
(->> (case (key body-forms)
:arity-1 [(val body-forms)]
:arity-n (val body-forms))
(map #(->> % (s/unform ::args+gspec+body) (drop 2)))
(mapcat check-arity-fx)
distinct
vec))
unexpected-fx (boolean (and (not ignore-fx)
(not marked-unsafe)
(seq found-fx)))
unexpected-safety (boolean (and (not ignore-fx)
marked-unsafe
(empty? found-fx)))
spec-keyword-ns (if cljs? 'clojure.test.check 'clojure.spec.test.check)
spec-checks (let [defined-fspecs (->> fspecs (remove nil?) vec)]
(when (and (seq defined-fspecs)
(not marked-unsafe)
(empty? found-fx)
(> num-tests 0))
`(for [spec# ~defined-fspecs]
(st/check-fn
~fn-name
spec#
{~(keyword (str spec-keyword-ns) "opts")
{:num-tests ~num-tests}}))))]
[unexpected-fx
`(t/deftest ~(symbol (str fn-name test-suffix))
(let [spec-checks# ~spec-checks]
TODO The ` spec - checks # ` thing trips up clairvoyant
;; and prevents tracing during ghostwheel development
(t/is (and (every? #(-> %
~(keyword (str spec-keyword-ns) "ret")
:pass?)
spec-checks#)
~(not unexpected-fx)
~(not unexpected-safety))
{::r/fn-name (quote ~fn-name)
::r/fspec ~(every? some? fspecs)
::r/spec-checks spec-checks#
::r/check-coverage ~check-coverage
::r/failure ~(cond unexpected-fx ::r/unexpected-fx
unexpected-safety ::r/unexpected-safety
:else ::r/spec-failure)
::r/found-fx (quote ~found-fx)
::r/marked-unsafe ~marked-unsafe})))])))
(defn- unscrew-vec-unform
"Half-arsed workaround for spec bugs CLJ-2003 and CLJ-2021."
[unformed-arg]
(if-not (sequential? unformed-arg)
unformed-arg
(let [malformed-seq-destructuring? (every-pred seq? (comp #{:as '&} first))
[unformed malformed] (split-with (complement malformed-seq-destructuring?) unformed-arg)]
(vec (concat unformed (apply concat malformed))))))
(defn- gspec->fspec*
[conformed-arg-list conformed-gspec anon-fspec? multi-arity-args? nilable?]
(let [{argspec-def :args
retspec :ret
fn-such-that :fn-such-that
{:keys [gen-fn] :as gen} :gen}
conformed-gspec]
(if (and anon-fspec?
argspec-def
(not gen)
(some #{'any?} (-> argspec-def :args vals)))
(if nilable? `(s/nilable ifn?) `ifn?)
(let [extract-spec
(fn extract-spec [[spec-type spec]]
(if (= spec-type :gspec)
(if (= (key spec) :nilable-gspec)
(gspec->fspec* nil (-> spec val :gspec) true false true)
(gspec->fspec* nil (val spec) true false false))
spec))
named-conformed-args
(when argspec-def
(let [all-args (remove nil? (concat (:args conformed-arg-list)
[(-> conformed-arg-list :varargs :form)]))
gen-arg-name (fn [index] (str "arg" (inc index)))
gen-name (fn [index [arg-type arg :as full-arg]]
(let [arg-name (if-not arg-type
(gen-arg-name index)
(case arg-type
:sym arg
:seq (or (-> arg :as :sym)
(gen-arg-name index))
:map (or (-> arg :as)
(gen-arg-name index))))]
[(keyword arg-name) full-arg]))]
(map-indexed gen-name (or (seq all-args)
(-> argspec-def :args count (repeat nil))))))
arg-binding-map
(if-not conformed-arg-list
{}
(if (every? #(= (-> % second key) :sym) named-conformed-args)
`{:keys ~(vec (map #(-> % first name symbol) named-conformed-args))}
(->> named-conformed-args
(map (fn [[arg-key conformed-arg]]
[(->> conformed-arg (s/unform ::binding-form) unscrew-vec-unform)
arg-key]))
(into {}))))
process-arg-pred
(fn process-arg-pred [{:keys [name args body]}]
(let [bindings (if-let [anon-arg (some-> args :args first second)]
(assoc arg-binding-map :as anon-arg)
arg-binding-map)]
(remove nil? `(fn ~name [~bindings] ~body))))
processed-args
(if-not argspec-def
`(s/cat)
(let [wrapped-params (->> argspec-def
:args
(map extract-spec)
(interleave (map first named-conformed-args))
(cons `s/cat))]
(if-let [args-such-that (:args-such-that argspec-def)]
(->> args-such-that
:preds
(map process-arg-pred)
(list* `s/and wrapped-params))
wrapped-params)))
process-ret-pred
(fn process-ret-pred [{:keys [name args body]}]
(let [anon-arg (some-> args :args first second)
ret-sym (gensym "ret__")
bindings [{(if multi-arity-args?
['_ arg-binding-map]
arg-binding-map) :args
ret-sym :ret}]
processed-body (if anon-arg
(walk/postwalk-replace {anon-arg ret-sym} body)
body)]
(remove nil? `(fn ~name ~bindings ~processed-body))))
fn-spec
(when fn-such-that
(let [processed-ret-preds (map process-ret-pred (:preds fn-such-that))]
(if (next processed-ret-preds)
(cons `s/and processed-ret-preds)
(first processed-ret-preds))))
final-fspec
(concat (when anon-fspec? [`s/fspec])
[:args processed-args]
[:ret (extract-spec retspec)]
(when fn-spec [:fn fn-spec])
(when gen-fn [:gen gen-fn]))]
(if nilable? `(s/nilable ~final-fspec) final-fspec)))))
TODO make sure we check whether the variadic bodies are legit
Can not have more than one
Can not have one with more regular args than the variadic one
;; To what extent does the compiler already check this?
(let [get-fspecs (fn [fn-body]
(let [[param-count variadic] (-> fn-body :args count-args)
gspec (or (:gspec fn-body)
(s/conform ::gspec
(vec (concat (repeat param-count 'any?)
(when (> variadic 0)
`[(s/* any?)])
'[=> any?]))))]
[(->> (if (> variadic 0) "n" param-count)
(str "arity-")
keyword)
(gspec->fspec* (:args fn-body) gspec false true false)]))
get-spec-part (fn [part spec]
(->> spec
(drop-while (complement #{part}))
second))]
(defn- generate-fspec-body [fn-bodies]
(case (key fn-bodies)
:arity-1
(when-let [gspec (-> fn-bodies val :gspec)]
(gspec->fspec* (-> fn-bodies val :args) gspec false false false))
:arity-n
(when (some :gspec (val fn-bodies))
(let [fspecs (map get-fspecs (val fn-bodies))
arg-specs (mapcat (fn [[arity spec]]
[arity (or (get-spec-part :args spec) `empty?)])
fspecs)
fn-param (gensym "p1__")
multi-ret-specs (when (->> fspecs
(map #(get-spec-part :ret (second %)))
distinct
count
(not= 1))
(mapcat (fn [[arity spec]]
[arity `(s/valid? ~(get-spec-part :ret spec)
(:ret ~fn-param))])
fspecs))
get-fn-clause (partial get-spec-part :fn)
fn-specs (when (->> fspecs (map second) (some get-fn-clause))
(mapcat (fn [[arity spec]]
[arity (if-let [fn-spec (get-fn-clause spec)]
`(s/valid? ~fn-spec ~fn-param)
true)])
fspecs))
NOTE : destructure args and ret in the arg vec
multi-ret-clause (when multi-ret-specs
`(fn ~'valid-multi-arity-ret? [~fn-param]
(case (-> ~fn-param :args key)
~@multi-ret-specs)))
multi-fn-clause (when fn-specs
`(fn ~'valid-multi-arity-fn? [~fn-param]
(case (-> ~fn-param :args key)
~@fn-specs)))]
;; Using s/or here even though s/alt seems to be more common
;; for multi-arity specs in the wild. The spec error reporting
;; is much better and it's immediately clear what didn't match.
(concat [:args `(s/or ~@arg-specs)]
(when-not multi-ret-clause
[:ret (get-spec-part :ret (-> fspecs first second))])
(when (or multi-ret-clause multi-fn-clause)
[:fn (if multi-fn-clause
(if multi-ret-clause
`(s/and ~multi-ret-clause ~multi-fn-clause)
multi-fn-clause)
multi-ret-clause)])))))))
(def ^:private spec-op->type
(let [map-prot "cljs.core.IMap"
coll-prot "cljs.core.ICollection"
;; Needed because Closure compiler/JS doesn't consider strings seqable
seqable-prot "(cljs.core.ISeqable|string)"]
{'number? "number"
'integer? "number"
'int? "number"
'nat-int? "number"
'pos-int? "number"
'neg-int? "number"
'float? "number"
'double? "number"
'int-in "number"
'double-in "number"
'string? "string"
'boolean? "boolean"
'keys map-prot
'map-of map-prot
'map? map-prot
'merge map-prot
'set? "cljs.core.ISet"
'vector? "cljs.core.IVector"
'tuple "cljs.core.IVector"
'seq? "cljs.core.ISeq"
'seqable? seqable-prot
'associative? "cljs.core.IAssociative"
'atom? "cljs.core.IAtom"
'coll-of coll-prot
'every coll-prot
'keyword? "cljs.core.Keyword"
'ifn? "cljs.core.IFn"
'fn? "Function"}))
(declare get-gspec-type)
(defn- get-type [recursive-call conformed-spec-elem]
(let [[spec-type spec-def] conformed-spec-elem
spec-op
;; REVIEW: This kinda wants to be a multi-method when it grows up.
(case spec-type
:list (let [op (-> spec-def first name symbol)]
(cond
(#{'nilable '?} op) (concat (->> spec-def
second
(s/conform ::spec-elem)
(get-type true))
[::nilable])
(#{'* '+} op) (concat (->> spec-def
second
(s/conform ::spec-elem)
(get-type true))
[::variadic])
TODO
(#{'coll-of 'every} op) [(or (->> spec-def
(drop-while (complement #{:kind}))
second)
op)]
:else [op]))
;;TODO support (some-fn and (s/or
:gspec (let [gspec-def (val spec-def)]
(if (= (key spec-def) :nilable-gspec)
[(get-gspec-type (:gspec gspec-def)) ::nilable]
[(get-gspec-type gspec-def)]))
:pred-sym [spec-def]
[nil])]
(if recursive-call
spec-op
(if-let [js-type (spec-op->type (first spec-op))]
(let [modifiers (set (rest spec-op))]
(as-> js-type t
(str (if (::nilable modifiers) "?" "!") t)
(str (when (::variadic modifiers) "...") t)))
"*"))))
(defn- get-gspec-type [conformed-gspec]
(let [argspec-def (:args conformed-gspec)
args-jstype (if-not argspec-def
""
(->> (-> conformed-gspec :args :args)
(map (partial get-type false))
(string/join ", ")))
ret-jstype (get-type false (:ret conformed-gspec))]
(str "function(" args-jstype "): " ret-jstype)))
(defn- generate-type-annotations [env conformed-bs]
(when (cljs-env? env)
(case (key conformed-bs)
:arity-1 (when-let [gspec (-> conformed-bs val :gspec)]
{:jsdoc [(str "@type {" (get-gspec-type gspec) "}")]})
;; REVIEW: There doesn't seem to be a way to get valid annotations for args of
;; multi-arity functions and attempts to just annotate the return value(s) failed
;; as well. It wasn't possible to put together an annotation which was both
;; considered valid and resulted in a successful type check.
:arity-n nil #_(when-let [ret-types (as-> (val conformed-bs) x
(map #(get-type false (-> % :gspec :ret)) x)
(distinct x)
(when (not-any? #{"*" "?"} x) x))]
{:jsdoc [(str "@return {" (string/join "|" ret-types) "}")]}))))
(defn- merge-config [metadata]
(s/assert ::ghostwheel-config
(->> (merge (u/get-base-config)
(meta *ns*)
metadata)
(filter #(= (-> % key namespace) (name `ghostwheel.core)))
(into {}))))
(defn- get-quoted-qualified-fn-name [fn-name]
`(quote ~(symbol (str (.-name *ns*)) (str fn-name))))
(defn- trace-threading-macros [forms trace]
(if (< trace 4)
forms
(let [threading-macros-mappings
{'-> 'ghostwheel.threading-macros/*->
'->> 'ghostwheel.threading-macros/*->>
'as-> 'ghostwheel.threading-macros/*as->
'cond-> 'ghostwheel.threading-macros/*cond->
'cond->> 'ghostwheel.threading-macros/*cond->>
'some-> 'ghostwheel.threading-macros/*some->
'some->> 'ghostwheel.threading-macros/*some->>}]
(cond->> (walk/postwalk-replace threading-macros-mappings forms)
Make sure we do n't trace threading macros in anon - fns
when anon - fns themselves are n't traced
(< trace 5)
(walk/postwalk
#(if (and (list? %)
(#{'fn 'fn*} (first %)))
(walk/postwalk-replace (map-invert threading-macros-mappings) %)
%))))))
(defn- clairvoyant-trace [forms trace color env]
(let [clairvoyant 'clairvoyant.core/trace-forms
tracer 'ghostwheel.tracer/tracer
exclude (case trace
2 '#{'fn 'fn* 'let}
3 '#{'fn 'fn*}
4 '#{'fn 'fn*}
nil)
inline-trace? (fn [form]
(and (seq? form)
(symbol? (first form))
(let [sym (first form)
qualified-sym
(if (cljs-env? env)
(:name (ana-api/resolve env sym))
;; REVIEW: Clairvoyant doesn't work on
Clojure yet – check this when it does
#?(:clj (name (resolve sym))))]
(contains? #{'ghostwheel.core/|> 'ghostwheel.core/tr} qualified-sym))))
forms (walk/postwalk
#(if (inline-trace? %) (second %) %)
forms)]
;; REVIEW: This doesn't quite work right and seems to cause issues for some people. Disabling for now.
(comment
#?(:clj (if cljs?
(when-not (and (find-ns (symbol (namespace clairvoyant)))
(find-ns (symbol (namespace tracer))))
(throw (Exception. "Can't find tracing namespaces. Either add `gnl/ghostwheel-tracer` artifact and `(:require [ghostwheel.tracer])`, or disable tracing in order to compile.")))
(throw (Exception. "Tracing is not yet implemented for Clojure.")))))
(if (< trace 2)
forms
`(~clairvoyant
{:enabled true
:tracer (~tracer
:color "#fff"
:background ~color
:expand ~(cond (= trace 6) '#{:bindings 'let 'defn 'defn- 'fn 'fn*}
(>= trace 3) '#{:bindings 'let 'defn 'defn-}
:else '#{'defn 'defn-}))
:exclude ~exclude}
~forms))))
(defn- generate-fdef
[forms]
(let [{[type fn-name] :name bs :bs} (s/conform ::>fdef-args forms)]
(case type
:sym (let [quoted-qualified-fn-name (get-quoted-qualified-fn-name fn-name)
{:keys [::instrument ::outstrument]} (merge-config (meta fn-name))
instrumentation (cond outstrument `(ost/instrument ~quoted-qualified-fn-name)
instrument `(st/instrument ~quoted-qualified-fn-name)
:else nil)
fdef `(s/fdef ~fn-name ~@(generate-fspec-body bs))]
(if instrumentation
`(do ~fdef ~instrumentation)
fdef))
:key `(s/def ~fn-name (s/fspec ~@(generate-fspec-body bs))))))
(defn- process-defn-body
[cfg fspec args+gspec+body]
(let [{:keys [env fn-name traced-fn-name trace color unexpected-fx]} cfg
{:keys [args body]} args+gspec+body
[prepost orig-body-forms] (case (key body)
:prepost+body [(-> body val :prepost)
(-> body val :body)]
:body [nil (val body)])
process-arg (fn [[arg-type arg]]
(as-> arg arg
(case arg-type
:sym [arg-type arg]
:seq [arg-type (update arg :as #(or % {:as :as :sym (gensym "arg_")}))]
:map [arg-type (update arg :as #(or % (gensym "arg_")))])))
;; NOTE: usage of extract-arg isn't elegant, there's duplication, refactor
extract-arg (fn [[arg-type arg]]
(case arg-type
:sym arg
:seq (get-in arg [:as :sym])
:map (:as arg)
nil))
unform-arg #(->> % (s/unform ::binding-form) unscrew-vec-unform)
reg-args (->> args :args (map process-arg))
var-arg (some-> args :varargs :form process-arg)
arg-list (vec (concat (map unform-arg reg-args)
(when var-arg ['& (unform-arg var-arg)])))
body-forms (if (and fspec (every? nil? orig-body-forms))
TODO error handling when specs too fancy for stub auto - generation
[`(apply (-> ~fspec s/gen gen/generate)
~@(map extract-arg reg-args) ~(extract-arg var-arg))]
(cond unexpected-fx
[`(throw (~(if (cljs-env? env) 'js/Error. 'Exception.)
~(str "Calling function `"
fn-name
"` which has unexpected side effects.")))]
(= trace :dispatch)
[`(if *global-trace-allowed?*
(apply ~traced-fn-name
~@(map extract-arg reg-args)
~(extract-arg var-arg))
(do ~@orig-body-forms))]
(= trace 1)
`[(do
(l/pr-clog ~(str (list fn-name arg-list))
nil
{::r/background ~color})
~@orig-body-forms)]
(>= trace 4)
(trace-threading-macros orig-body-forms trace)
:else
orig-body-forms))]
(remove nil? `(~arg-list ~prepost ~@body-forms))))
(defn- generate-defn
[forms private env]
(let [cljs? (cljs-env? env)
conformed-gdefn (s/conform ::>defn-args forms)
fn-bodies (:bs conformed-gdefn)
empty-bodies (every? empty?
(case (key fn-bodies)
:arity-1 (list (-> fn-bodies val :body val))
:arity-n (->> fn-bodies
val
(map :body)
(map val))))
arity (key fn-bodies)
fn-name (:name conformed-gdefn)
quoted-qualified-fn-name
(get-quoted-qualified-fn-name fn-name)
traced-fn-name (gensym (str fn-name "__"))
docstring (:docstring conformed-gdefn)
meta-map (merge (:meta conformed-gdefn)
(generate-type-annotations env fn-bodies)
{::ghostwheel true})
;;; Assemble the config
config (merge-config (merge (meta fn-name) meta-map))
color (resolve-trace-color (::trace-color config))
{:keys [::defn-macro ::instrument ::outstrument ::trace ::check]} config
defn-sym (cond defn-macro (with-meta (symbol defn-macro) {:private private})
private 'defn-
:else 'defn)
trace (if (cljs-env? env)
(cond empty-bodies 0
(true? trace) 4
:else trace)
0) ; TODO: Clojure
;;; Code generation
fdef-body (generate-fspec-body fn-bodies)
fdef (when fdef-body `(s/fdef ~fn-name ~@fdef-body))
instrumentation (when (not empty-bodies)
(cond outstrument `(ost/instrument ~quoted-qualified-fn-name)
instrument `(st/instrument ~quoted-qualified-fn-name)
:else nil))
individual-arity-fspecs
(map (fn [{:keys [args gspec]}]
(when gspec
(gspec->fspec* args gspec true false false)))
(val fn-bodies))
[unexpected-fx generated-test] (when (and check (not empty-bodies))
(let [fspecs (case arity
:arity-1 [(when fdef-body `(s/fspec ~@fdef-body))]
:arity-n individual-arity-fspecs)]
(generate-test fn-name fspecs fn-bodies config cljs?)))
process-fn-bodies (fn [trace]
(let [process-cfg {:env env
:fn-name fn-name
:traced-fn-name traced-fn-name
:trace trace
:color color
:unexpected-fx unexpected-fx}]
(case arity
:arity-1 (->> fn-bodies val (process-defn-body process-cfg `(s/fspec ~@fdef-body)))
:arity-n (map (partial process-defn-body process-cfg)
individual-arity-fspecs
(val fn-bodies)))))
main-defn (remove nil? `(~defn-sym
~fn-name
~docstring
~meta-map
~@(process-fn-bodies (if (> trace 0) :dispatch 0))))
traced-defn (when (> trace 0)
(let [traced-defn (remove nil? `(~defn-sym
~traced-fn-name
~@(process-fn-bodies trace)))]
(if (= trace 1)
traced-defn
(clairvoyant-trace traced-defn trace color env))))]
`(do ~fdef ~traced-defn ~main-defn ~instrumentation ~generated-test)))
(defn after-check-async [done]
(let [success @r/*all-tests-successful]
(when success (doseq [f @*after-check-callbacks] (f)))
(reset! r/*all-tests-successful true)
(reset! *after-check-callbacks [])
(when success (done))))
(defn- generate-coverage-check [env nspace]
(let [cljs? (cljs-env? env)
{:keys [::check-coverage ::check]} (merge (u/get-base-config)
(if cljs?
(:meta (ana-api/find-ns nspace))
#?(:clj (meta nspace))))
get-intern-meta (comp meta (if cljs? key val))
all-checked-fns (when check-coverage
(some->> (if cljs? (ana-api/ns-interns nspace) #?(:clj (ns-interns nspace)))
(filter #(if cljs? (-> % val :fn-var) #?(:clj (t/function? (key %)))))
(remove #(-> % key str (string/ends-with? test-suffix)))
(remove #(-> % get-intern-meta ::check-coverage false?))))
plain-defns (when check-coverage
(some->> all-checked-fns
(remove #(-> % get-intern-meta ::ghostwheel))
(map (comp str key))
vec))
unchecked-defns (when check-coverage
(some->> all-checked-fns
(filter #(-> % get-intern-meta ::ghostwheel))
(filter #(-> % get-intern-meta ::check false?))
(map (comp str key))
vec))]
`(do
~(when (not check)
`(do
(l/group ~(str "WARNING: "
"`::g/check` disabled for "
nspace
(::r/incomplete-coverage r/snippets))
~r/warning-style)
(l/group-end)))
~(when (not-empty plain-defns)
`(do
(l/group ~(str "WARNING: "
"Plain `defn` functions detected in "
nspace
(::r/incomplete-coverage r/snippets))
~r/warning-style)
(l/log (mapv symbol ~plain-defns))
(l/log-bold "=> Use `>defn` instead.")
(l/group-end)))
~(when (not-empty unchecked-defns)
`(do
(l/group ~(str "WARNING: "
"`::g/check` disabled for some functions in "
nspace
(::r/incomplete-coverage r/snippets))
~r/warning-style)
(l/log (mapv symbol ~unchecked-defns))
(l/group-end))))))
(defn- generate-check [env targets]
(let [base-config
(u/get-base-config)
cljs?
(cljs-env? env)
{:keys [::extrument ::report-output]}
base-config
conformed-targets
(let [conformed-targets (s/conform ::check-targets targets)]
(if (= (key conformed-targets) :multi)
(val conformed-targets)
[(val conformed-targets)]))
processed-targets
(mapcat (fn [[type target]]
(if (not= type :regex)
[[type (:sym target)]]
(for [ns (if cljs? (ana-api/all-ns) #?(:clj (all-ns)))
:when (re-matches target (str (if cljs? ns #?(:clj (ns-name ns)))))]
[:ns ns])))
conformed-targets)
errors
(->> (for [target processed-targets
:let [[type sym] target]]
(case type
:fn (let [fn-data (if cljs? (ana-api/resolve env sym) #?(:clj (resolve sym)))
metadata (if cljs? (:meta fn-data) #?(:clj (meta fn-data)))
{:keys [::check-coverage ::check]}
(merge (u/get-base-config)
(meta (:ns fn-data))
metadata)]
(cond (not fn-data)
(str "Cannot resolve `" (str sym) "`")
(not (if cljs? (:fn-var fn-data) #?(:clj (t/function? sym))))
(str "`" sym "` is not a function.")
(not (::ghostwheel metadata))
(str "`" sym "` is not a Ghostwheel function => Use `>defn` to define it.")
(not check)
(str "Checking disabled for `" sym "` => Set `{:ghostwheel.core/check true}` to enable.")
:else
nil))
:ns (let [ns-data (if cljs? (ana-api/find-ns sym) #?(:clj sym))
metadata (if cljs? (:meta ns-data) #?(:clj (meta ns-data)))
{:keys [::check]} (merge base-config metadata)]
(cond (not ns-data)
(str "Cannot resolve `" (str sym) "`")
(not check)
(str "Checking disabled for `" sym "` => Set `{:ghostwheel.core/check true}` to enable.")
:else
nil))))
(remove nil?))]
(if (not-empty errors)
(u/gen-exception env (str "\n" (string/join "\n" errors)))
`(when *global-check-allowed?*
(binding [*global-trace-allowed?* false
l/*report-output* ~(if cljs? report-output :repl)]
(do
~@(remove nil?
`[~(when extrument
`(st/instrument (quote ~extrument)))
~@(for [target processed-targets
:let [[type sym] target]]
(case type
:fn `(binding [t/report r/report]
(~(symbol (str sym test-suffix))))
:ns `(binding [t/report r/report]
(t/run-tests (quote ~sym)))))
~@(->> (for [target processed-targets
:let [[type sym] target]
:when (= type :ns)]
(generate-coverage-check env sym))
(remove nil?))
~(when extrument
`(st/unstrument (quote ~extrument)))])))))))
(defn- generate-after-check [callbacks]
(let [{:keys [::check]}
(merge (u/get-base-config)
(meta *ns*))]
TODO implement for clj
(when (and check (seq callbacks))
`(swap! *after-check-callbacks (comp vec concat) ~(vec callbacks)))))
(defn- generate-traced-expr
[expr env]
(if (and (seq? expr)
(or (contains? l/ops-with-bindings (first expr))
(contains? threading-macro-syms (first expr))))
(let [cfg (merge-config (meta expr))
color (resolve-trace-color (::trace-color cfg))
trace (let [trace (::trace cfg)]
(if (= trace 0) 5 trace))]
(cond-> (trace-threading-macros expr trace)
REVIEW : Clairvoyant does n't work on Clojure yet
(cljs-env? env) (clairvoyant-trace trace color env)))
`(l/clog ~expr)))
;;;; Main macros and public API
(s/def ::>defn-args
(s/and seq? ; REVIEW
(s/cat :name simple-symbol?
:docstring (s/? string?)
:meta (s/? map?)
:bs (s/alt :arity-1 ::args+gspec+body
;; TODO: add tail-attr-map support after this
:arity-n (s/+ (s/and seq? ::args+gspec+body))))))
(s/fdef >defn :args ::>defn-args)
(defmacro >defn
"Like defn, but requires a (nilable) gspec definition and generates
additional `s/fdef`, generative tests, instrumentation code, an
fspec-based stub, and/or tracing code, depending on the configuration
metadata and the existence of a valid gspec and non-nil body."
{:arglists '([name doc-string? attr-map? [params*] gspec prepost-map? body?]
[name doc-string? attr-map? ([params*] gspec prepost-map? body?) + attr-map?])}
[& forms]
(if (u/get-env-config)
(cond-> (remove nil? (generate-defn forms false &env))
(cljs-env? &env) clj->cljs)
(clean-defn 'defn forms)))
(s/fdef >defn- :args ::>defn-args)
NOTE : lots of duplication - refactor this to set / pass ^:private differently and call >
(defmacro >defn-
"Like defn-, but requires a (nilable) gspec definition and generates
additional `s/fdef`, generative tests, instrumentation code, an
fspec-based stub, and/or tracing code, depending on the configuration
metadata and the existence of a valid gspec and non-nil body."
{:arglists '([name doc-string? attr-map? [params*] gspec prepost-map? body?]
[name doc-string? attr-map? ([params*] gspec prepost-map? body?) + attr-map?])}
[& forms]
(if (u/get-env-config)
(cond-> (remove nil? (generate-defn forms true &env))
(cljs-env? &env) clj->cljs)
(clean-defn 'defn- forms)))
(defmacro after-check
"Takes a number of 0-arity functions to run
after all checks are completed successfully.
Meant to be used in a hot-reloading environment by putting it at the bottom
of a `(g/check)`-ed namespace and calling `ghostwheel.core/after-check-async`
correctly in the build system post-reload hooks."
[& callbacks]
(when (u/get-env-config)
(cond-> (generate-after-check callbacks)
(cljs-env? &env) (clj->cljs false))))
(s/def ::check-target
(s/or :fn (s/and seq?
(s/cat :quote #{'quote}
:sym (s/and symbol?
#(let [s (str %)]
(or (string/includes? s "/")
(not (string/includes? s ".")))))))
:ns (s/and seq? (s/cat :quote #{'quote} :sym symbol?))
:regex #?(:clj #(instance? java.util.regex.Pattern %)
:cljs regexp?)))
(s/def ::check-targets
(s/or :single ::check-target
:multi (s/spec (s/+ ::check-target))))
(s/fdef check
:args (s/spec (s/? ::check-targets)))
(defmacro check
"Runs Ghostwheel checks on the given namespaces and/or functions.
Checks the current namespace if called without arguments."
{:arglists '([]
[ns-regex-or-quoted-ns-or-fn]
[[ns-regex-or-quoted-ns-or-fn+]])}
([]
`(check (quote ~(.-name *ns*))))
([things]
(if (u/get-env-config)
(cond-> (generate-check &env things)
(cljs-env? &env) (clj->cljs false))
(str "Ghostwheel disabled => "
(if (cljs-env? &env)
"Add `:external-config {:ghostwheel {}}` to your compiler options to enable."
"Start the REPL with the `-Dghostwheel.enabled=true` JVM system property to enable.")))))
(s/def ::>fdef-args
(s/and seq? ;REVIEW
(s/cat :name (s/or :sym symbol? :key qualified-keyword?)
:bs (s/alt :arity-1 ::args+gspec+body
:arity-n (s/+ (s/and seq? ::args+gspec+body))))))
(s/fdef >fdef :args ::>fdef-args)
(defmacro >fdef
"Defines an fspec using gspec syntax – pretty much a `>defn` without the body.
`name` can be a symbol or a qualified keyword, depending on whether the
fspec is meant to be registered as a top-level fspec (=> s/fdef fn-sym
...) or used in other specs (=> s/def ::spec-keyword (s/fspec ...)).
When defining global fspecs, instrumentation can be directly enabled by
setting the `^::g/instrument` or `^::g/outstrument` metadata on the symbol."
{:arglists '([name [params*] gspec]
[name ([params*] gspec) +])}
[& forms]
(when (u/get-env-config)
(cond-> (remove nil? (generate-fdef forms))
(cljs-env? &env) clj->cljs)))
(defmacro |>
"Traces or logs+returns the wrapped expression, depending on its type"
[expr]
(if (u/get-env-config)
(cond-> (generate-traced-expr expr &env)
(cljs-env? &env) clj->cljs)
expr))
(defmacro tr "Alias for |>" [expr] `(|> ~expr))
| null |
https://raw.githubusercontent.com/gnl/ghostwheel/a85c3510178fc4fbcb95125b86116d698e2a232a/src/ghostwheel/core.cljc
|
clojure
|
The use and distribution terms for this software are covered by the
which can be found in the file LICENSE at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
REVIEW: Not requiring the clojure.core.specs.alpha
namespaces for now because they break a lot
[clojure.core.specs.alpha]
[cljs.core.specs.alpha :include-macros true]
REVIEW: Replace this pattern:
`(let [fn-name (fn ...)] (defn ...))` with
`letfn` when the ClojureScript bug is fixed:
This isn't particularly pretty, but it's how we avoid
REVIEW: Is anyone using this?
Misc helper functions
It doesn't actually matter what these are bound to, they are stripped by
the macros they're used in and never end up in the final code. This is just
so they can be used without '=> cannot be resolved' errors in the IDE.
TODO: Integrate bhauman/spell-spec
TODO: Add check to make sure instrument and outstrument aren't both on
These are lifted straight from clojure.core.specs.alpha, because it
didn't seem possible to access them directly in the original namespace.
sequential destructuring
map destructuring
REVIEW: should the `?` be a requirement?
Side effect detection specs
REVIEW: maybe move the re-frame stuff out of here
REVIEW: maybe make sure we are only matching on the simple symbol part
Main code generating functions
and prevents tracing during ghostwheel development
To what extent does the compiler already check this?
Using s/or here even though s/alt seems to be more common
for multi-arity specs in the wild. The spec error reporting
is much better and it's immediately clear what didn't match.
Needed because Closure compiler/JS doesn't consider strings seqable
REVIEW: This kinda wants to be a multi-method when it grows up.
TODO support (some-fn and (s/or
REVIEW: There doesn't seem to be a way to get valid annotations for args of
multi-arity functions and attempts to just annotate the return value(s) failed
as well. It wasn't possible to put together an annotation which was both
considered valid and resulted in a successful type check.
REVIEW: Clairvoyant doesn't work on
REVIEW: This doesn't quite work right and seems to cause issues for some people. Disabling for now.
NOTE: usage of extract-arg isn't elegant, there's duplication, refactor
Assemble the config
TODO: Clojure
Code generation
Main macros and public API
REVIEW
TODO: add tail-attr-map support after this
REVIEW
|
Copyright ( c ) . All rights reserved .
Eclipse Public License 2.0 ( -2.0/ )
(ns ghostwheel.core
#?(:cljs (:require-macros ghostwheel.core))
(:require [clojure.string :as string]
[clojure.set :refer [union difference map-invert]]
[clojure.walk :as walk]
[clojure.test :as t]
[clojure.test.check]
[clojure.test.check.generators]
[clojure.test.check.properties]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.spec.gen.alpha :as gen]
[ghostwheel.reporting :as r]
[ghostwheel.unghost :refer [clean-defn]]
[ghostwheel.utils :as u :refer [cljs-env? clj->cljs]]
[ghostwheel.logging :as l]
[ghostwheel.threading-macros :include-macros true]
[expound.alpha :as exp]
of older code including lein - figwheel < 0.5.18
[orchestra.spec.test :as ost]]
[cljs.analyzer.api :as ana-api]
[orchestra-cljs.spec.test :as ost]])))
-1965
Global vars and state
having ClojureScript as a required dependency on Clojure
#?(:clj (try
(do
(ns-unalias (find-ns 'ghostwheel.core) 'ana-api)
(require '[cljs.analyzer.api :as ana-api]))
(catch Exception _ (require '[ghostwheel.stubs.ana-api :as ana-api]))))
(when-let [expound-cfg (::expound (u/get-base-config false))]
#?(:clj (alter-var-root #'s/*explain-out* (constantly (exp/custom-printer expound-cfg)))
:cljs (set! s/*explain-out* (exp/custom-printer expound-cfg))))
(def ^:private test-suffix "__ghostwheel-test")
(def ^:private *after-check-callbacks (atom []))
(def ^:private ^:dynamic *unsafe-bound-ops* #{})
(def ^:dynamic *global-trace-allowed?* true)
(defn- set-trace [enabled]
#?(:clj (alter-var-root #'*global-trace-allowed?* (constantly enabled))
:cljs (set! *global-trace-allowed?* enabled)))
(defn enable-trace! [] (set-trace true) "Tracing enabled.")
(defn disable-trace! [] (set-trace false) "Tracing disabled.")
(defn- set-check [enabled]
#?(:clj (alter-var-root #'*global-check-allowed?* (constantly enabled))
:cljs (set! *global-check-allowed?* enabled)))
(defn enable-check! [] (set-check true) "Check enabled.")
(defn disable-check! [] (set-check false) "Check disabled.")
(defn- count-args
"Returns a tuple with the number of regular and non-variadic arguments."
[conformed-args]
[(count (:args conformed-args))
(if (:varargs conformed-args) 1 0)])
(defn- resolve-trace-color [color]
(let [[color-type color-value] (s/conform ::trace-color color)]
(case color-type
:literal color-value
:keyword (if-let [color-value (get l/ghostwheel-colors color)]
color-value
(:black l/ghostwheel-colors)))))
Operators
(def => :ret)
(def | :st)
(def <- :gen)
(defmacro ? [& forms]
(cond-> `(s/nilable ~@forms)
(cljs-env? &env) clj->cljs))
Specs
(s/def ::trace #{0 1 2 3 4 5 6 true})
(s/def ::trace-color (s/or :keyword keyword?
:literal (s/and string?
#(re-matches #"#[a-fA-F0-9]+" %)
#(or (= (count %) 7)
(= (count %) 4)))))
(s/def ::check boolean?)
(s/def ::check-coverage boolean?)
(s/def ::ignore-fx boolean?)
(s/def ::num-tests nat-int?)
(s/def ::num-tests-ext nat-int?)
(s/def ::extensive-tests boolean?)
(s/def ::defn-macro (s/nilable string?))
(s/def ::instrument boolean?)
(s/def ::outstrument boolean?)
(s/def ::extrument (s/nilable (s/coll-of qualified-symbol? :kind vector?)))
(s/def ::expound (s/nilable (s/map-of keyword? any?)))
(s/def ::report-output #{:repl :js-console})
(s/def ::ghostwheel-config
(s/and (s/keys :req [::trace ::trace-color ::check ::check-coverage ::ignore-fx
::num-tests ::num-tests-ext ::extensive-tests ::defn-macro
::instrument ::outstrument ::extrument ::expound ::report-output])))
(s/assert ::ghostwheel-config u/ghostwheel-default-config)
(s/def ::local-name (s/and simple-symbol? #(not= '& %)))
(s/def ::seq-binding-form
(s/and vector?
(s/cat :elems (s/* ::binding-form)
:rest (s/? (s/cat :amp #{'&} :form ::binding-form))
:as (s/? (s/cat :as #{:as} :sym ::local-name)))))
(s/def ::keys (s/coll-of ident? :kind vector?))
(s/def ::syms (s/coll-of symbol? :kind vector?))
(s/def ::strs (s/coll-of simple-symbol? :kind vector?))
(s/def ::or (s/map-of simple-symbol? any?))
(s/def ::as ::local-name)
(s/def ::map-special-binding
(s/keys :opt-un [::as ::or ::keys ::syms ::strs]))
(s/def ::map-binding (s/tuple ::binding-form any?))
(s/def ::ns-keys
(s/tuple
(s/and qualified-keyword? #(-> % name #{"keys" "syms"}))
(s/coll-of simple-symbol? :kind vector?)))
(s/def ::map-bindings
(s/every (s/or :mb ::map-binding
:nsk ::ns-keys
:msb (s/tuple #{:as :or :keys :syms :strs} any?))
:into {}))
(s/def ::map-binding-form (s/merge ::map-bindings ::map-special-binding))
(s/def ::binding-form
(s/or :sym ::local-name
:seq ::seq-binding-form
:map ::map-binding-form))
Function and > defn specs
(s/def ::arg-list
(s/and vector?
(s/cat :args (s/* ::binding-form)
:varargs (s/? (s/cat :amp #{'&} :form ::binding-form)))))
(s/def ::pred-arg-list
(s/and vector?
(s/cat :args (s/* (s/or :sym ::local-name)))))
(s/def ::anon-args+body
(s/cat :args ::arg-list
:body (s/* any?)))
(s/def ::anon-fn
(s/and seq?
(s/cat :op #{'fn* 'fn}
:name (s/? simple-symbol?)
:bs (s/alt :arity-1 ::anon-args+body
:arity-n (s/+ (s/spec ::anon-args+body))))))
(s/def ::pred-fn
(s/and seq?
(s/cat :op #{'fn* 'fn}
:name (s/? simple-symbol?)
:args ::pred-arg-list
:body any?)))
(s/def ::spec-elem
(s/or :set set?
:pred-sym (s/and symbol?
(complement #{'| '=>})
#(string/ends-with? (str %) "?"))
:gspec (s/or :nilable-gspec ::nilable-gspec :gspec ::gspec)
:spec-key qualified-keyword?
:fun ::pred-fn
:list seq?))
(s/def ::such-that-op #{:st '|})
(s/def ::ret-op #{:ret '=>})
(s/def ::gen-op #{:gen '<-})
(s/def ::gspec
(s/and vector?
(s/cat :args (s/? (s/cat :args (s/+ ::spec-elem)
:args-such-that (s/? (s/cat :op ::such-that-op
:preds (s/+ ::pred-fn)))))
:ret-op ::ret-op
:ret ::spec-elem
:fn-such-that (s/? (s/cat :op ::such-that-op
:preds (s/+ ::pred-fn)))
:gen (s/? (s/cat :op ::gen-op
:gen-fn (s/? (some-fn seq? symbol?)))))))
(s/def ::nilable-gspec
(s/and vector?
(s/cat :maybe #{'? 's/nilable}
:gspec ::gspec)))
(s/def ::prepost (s/map-of #{:pre :post}
(s/coll-of seq?
:kind vector?
:distinct true)))
(s/def ::args+body
(s/cat :args ::arg-list
:body (s/alt :prepost+body (s/cat :prepost ::prepost
:body (s/+ any?))
:body (s/* any?))))
(s/def ::args+gspec+body
(s/&
(s/cat :args ::arg-list
:gspec (s/nilable ::gspec)
:body (s/alt :prepost+body (s/cat :prepost ::prepost
:body (s/+ any?))
:body (s/* any?)))
(fn arg-specs-match-param-count? [{:keys [args gspec]}]
(if-not gspec
true
(let [argcount (->> args count-args (apply +))
spec-args (:args gspec)]
(if spec-args
(-> spec-args :args count (= argcount))
(= argcount 0)))))))
(s/def ::defn
(s/and seq?
(s/cat :op #{'defn 'defn-}
:name simple-symbol?
:docstring (s/? string?)
:meta (s/? map?)
:bs (s/alt :arity-1 ::args+body
:arity-n (s/cat :bodies (s/+ (s/spec ::args+body))
:attr (s/? map?))))))
(s/def ::deftest
(s/and seq?
(s/cat :op #{'clojure.test/deftest 'cljs.test/deftest}
:name symbol?
:body any?)))
(def threading-macro-syms
#{'-> '->> 'as-> 'cond-> 'cond->> 'some-> 'some->>
'*-> '*->> '*as-> '*cond-> '*cond->> '*some-> '*some->>})
(s/def ::threading-macro-op threading-macro-syms)
(s/def ::binding-op
#{'let 'for 'doseq 'binding})
(s/def ::single-function-composition
#{'partial 'fnil})
(s/def ::safe-single-function-composition
#{'memoize 'complement})
(s/def ::multi-function-composition
#{'comp})
(s/def ::safe-multi-function-composition
#{'juxt 'every-pred 'some-fn})
(s/def ::function-application
#{'apply 'map 'fmap 'map-indexed 'reduce})
(s/def ::safe-function-application
#{'mapcat 'reduce-kv 'mapv 'reductions 'iterate 'keep 'keep-indexed
'remove 'filter 'filterv 'take-while 'drop-while
'sort 'sort-by 'sorted-map-by 'group-by 'merge-with})
(s/def ::unsafe-clj-block #{'do
'doseq
'dotimes})
(s/def ::unsafe-clj-call #{'dorun
'repeatedly
'dispatch
'js-delete
'aset})
(s/def ::unsafe-clj-comp
(s/alt :single-fn (s/cat :composition (s/alt :generic ::single-function-composition
:safe ::safe-single-function-composition)
:unsafe-op ::unsafe-op
:rest ::rest)
:multi-fn (s/cat :composition (s/alt :generic ::multi-function-composition
:safe ::safe-multi-function-composition)
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest)))
(let [bang-suffix? #(string/ends-with? (str %) "!")]
(s/def ::bang-suffix (every-pred symbol? bang-suffix?))
(s/def ::unsafe-op
(s/alt :bang-suffix ::bang-suffix
:unsafe-anon-fn (s/and seq?
(s/alt :unsafe-body (s/cat :fun #{'fn 'fn*}
:name (s/? simple-symbol?)
:args ::arg-list
:body ::unsafe-form)
:unsafe-name (s/cat :fun #{'fn 'fn*}
:name (every-pred simple-symbol?
bang-suffix?)
:args ::arg-list
:body any?)))
:unsafe-clj-call ::unsafe-clj-call
:unsafe-clj-comp (s/spec ::unsafe-clj-comp)
:unsafe-bound-call #(contains? *unsafe-bound-ops* %)
:multi-form-op (s/cat :op #{'when 'when-not 'when-let 'when-first
'when-some 'let 'binding}
:pred-or-bindings any?
:fx (s/+ any?)
:return any?))))
(s/def ::safe-op #(not (s/valid? ::unsafe-op (list %))))
(s/def ::some-unsafe-ops (s/+ (s/cat :skipped-ops (s/* ::safe-op)
:unsafe-op ::unsafe-op)))
(s/def ::rest (s/* any?))
(s/def ::some-unsafe-bindings
(s/and vector?
(s/+ (s/cat :skipped-bindings (s/* (s/cat :binding ::binding-form
:value ::safe-op))
:unsafe-binding (s/cat :binding ::binding-form
:value ::unsafe-op)))))
(s/def ::unsafe-form
(s/or :unsafe-block (s/and seq?
(s/cat :unsafe-clj-block ::unsafe-clj-block
:rest ::rest))
:unsafe-call
(s/and seq?
(s/alt :direct (s/cat :application
(s/? (s/alt :generic ::function-application
:safe ::safe-function-application))
:unsafe-op ::unsafe-op
:rest ::rest)
:threading (s/cat :threading-macro-op ::threading-macro-op
:threaded-form any?
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest)
:update (s/cat :update #{'update 'update-in}
:map any?
:path any?
:unsafe-op ::unsafe-op
:rest ::rest)))
:unsafe-composition (s/and seq? ::unsafe-clj-comp)
:unsafe-binding (s/and seq?
(s/cat :binding-op ::binding-op
:bindings ::some-unsafe-bindings
:rest ::rest))
:unsafe-argument (s/and seq?
(s/cat :fun ::safe-op
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest))
#_::unsafe-something #_(s/spec (s/cat ::some-unsafe-ops ::some-unsafe-ops
::rest ::rest))))
(let [find-fx
(fn find-fx [form]
(let [maybe-fx (s/conform ::unsafe-form form)
[found-fx
unsafe-bindings] (if (= maybe-fx ::s/invalid)
[nil nil]
[(conj {} maybe-fx)
(when (= (key maybe-fx) :unsafe-binding)
(-> maybe-fx
val
:bindings))])
TODO implement map and support for bindings
unsafe-binding-set (when unsafe-bindings
(->> unsafe-bindings
(map #(-> % :unsafe-binding :binding val))
(set)))]
[found-fx (vec
(for [nested-form form
:when (and (coll? nested-form))]
REVIEW go into nested anon - fns or not ?
( not ( contains ? # { ' fn ' fn * } ( first nested - form ) ) ) ) ]
(binding [*unsafe-bound-ops* (cond-> *unsafe-bound-ops*
unsafe-bindings (union unsafe-binding-set))]
(find-fx nested-form))))]))
check-arity-fx
(fn [unformed-args-gspec-body]
(let [effects (->> (find-fx unformed-args-gspec-body)
(flatten)
(remove nil?)
(map first)
(vec))]
(-> (for [fx effects]
[(-> fx key name keyword)
(->> fx
(s/unform ::unsafe-form)
(apply list)
(str))
(->> fx
val
(walk/postwalk #(if (qualified-keyword? %)
(keyword (name %))
%))
vec)])
(cond->> (next unformed-args-gspec-body) (cons [:multiple-body-forms])))))]
(defn- generate-test [fn-name fspecs body-forms config cljs?]
(let [{:keys [::check ::num-tests ::num-tests-ext ::extensive-tests
::check-coverage ::ignore-fx]}
config
num-tests (if extensive-tests num-tests-ext num-tests)
marked-unsafe (s/valid? ::bang-suffix fn-name)
found-fx (if ignore-fx
[]
(->> (case (key body-forms)
:arity-1 [(val body-forms)]
:arity-n (val body-forms))
(map #(->> % (s/unform ::args+gspec+body) (drop 2)))
(mapcat check-arity-fx)
distinct
vec))
unexpected-fx (boolean (and (not ignore-fx)
(not marked-unsafe)
(seq found-fx)))
unexpected-safety (boolean (and (not ignore-fx)
marked-unsafe
(empty? found-fx)))
spec-keyword-ns (if cljs? 'clojure.test.check 'clojure.spec.test.check)
spec-checks (let [defined-fspecs (->> fspecs (remove nil?) vec)]
(when (and (seq defined-fspecs)
(not marked-unsafe)
(empty? found-fx)
(> num-tests 0))
`(for [spec# ~defined-fspecs]
(st/check-fn
~fn-name
spec#
{~(keyword (str spec-keyword-ns) "opts")
{:num-tests ~num-tests}}))))]
[unexpected-fx
`(t/deftest ~(symbol (str fn-name test-suffix))
(let [spec-checks# ~spec-checks]
TODO The ` spec - checks # ` thing trips up clairvoyant
(t/is (and (every? #(-> %
~(keyword (str spec-keyword-ns) "ret")
:pass?)
spec-checks#)
~(not unexpected-fx)
~(not unexpected-safety))
{::r/fn-name (quote ~fn-name)
::r/fspec ~(every? some? fspecs)
::r/spec-checks spec-checks#
::r/check-coverage ~check-coverage
::r/failure ~(cond unexpected-fx ::r/unexpected-fx
unexpected-safety ::r/unexpected-safety
:else ::r/spec-failure)
::r/found-fx (quote ~found-fx)
::r/marked-unsafe ~marked-unsafe})))])))
(defn- unscrew-vec-unform
"Half-arsed workaround for spec bugs CLJ-2003 and CLJ-2021."
[unformed-arg]
(if-not (sequential? unformed-arg)
unformed-arg
(let [malformed-seq-destructuring? (every-pred seq? (comp #{:as '&} first))
[unformed malformed] (split-with (complement malformed-seq-destructuring?) unformed-arg)]
(vec (concat unformed (apply concat malformed))))))
(defn- gspec->fspec*
[conformed-arg-list conformed-gspec anon-fspec? multi-arity-args? nilable?]
(let [{argspec-def :args
retspec :ret
fn-such-that :fn-such-that
{:keys [gen-fn] :as gen} :gen}
conformed-gspec]
(if (and anon-fspec?
argspec-def
(not gen)
(some #{'any?} (-> argspec-def :args vals)))
(if nilable? `(s/nilable ifn?) `ifn?)
(let [extract-spec
(fn extract-spec [[spec-type spec]]
(if (= spec-type :gspec)
(if (= (key spec) :nilable-gspec)
(gspec->fspec* nil (-> spec val :gspec) true false true)
(gspec->fspec* nil (val spec) true false false))
spec))
named-conformed-args
(when argspec-def
(let [all-args (remove nil? (concat (:args conformed-arg-list)
[(-> conformed-arg-list :varargs :form)]))
gen-arg-name (fn [index] (str "arg" (inc index)))
gen-name (fn [index [arg-type arg :as full-arg]]
(let [arg-name (if-not arg-type
(gen-arg-name index)
(case arg-type
:sym arg
:seq (or (-> arg :as :sym)
(gen-arg-name index))
:map (or (-> arg :as)
(gen-arg-name index))))]
[(keyword arg-name) full-arg]))]
(map-indexed gen-name (or (seq all-args)
(-> argspec-def :args count (repeat nil))))))
arg-binding-map
(if-not conformed-arg-list
{}
(if (every? #(= (-> % second key) :sym) named-conformed-args)
`{:keys ~(vec (map #(-> % first name symbol) named-conformed-args))}
(->> named-conformed-args
(map (fn [[arg-key conformed-arg]]
[(->> conformed-arg (s/unform ::binding-form) unscrew-vec-unform)
arg-key]))
(into {}))))
process-arg-pred
(fn process-arg-pred [{:keys [name args body]}]
(let [bindings (if-let [anon-arg (some-> args :args first second)]
(assoc arg-binding-map :as anon-arg)
arg-binding-map)]
(remove nil? `(fn ~name [~bindings] ~body))))
processed-args
(if-not argspec-def
`(s/cat)
(let [wrapped-params (->> argspec-def
:args
(map extract-spec)
(interleave (map first named-conformed-args))
(cons `s/cat))]
(if-let [args-such-that (:args-such-that argspec-def)]
(->> args-such-that
:preds
(map process-arg-pred)
(list* `s/and wrapped-params))
wrapped-params)))
process-ret-pred
(fn process-ret-pred [{:keys [name args body]}]
(let [anon-arg (some-> args :args first second)
ret-sym (gensym "ret__")
bindings [{(if multi-arity-args?
['_ arg-binding-map]
arg-binding-map) :args
ret-sym :ret}]
processed-body (if anon-arg
(walk/postwalk-replace {anon-arg ret-sym} body)
body)]
(remove nil? `(fn ~name ~bindings ~processed-body))))
fn-spec
(when fn-such-that
(let [processed-ret-preds (map process-ret-pred (:preds fn-such-that))]
(if (next processed-ret-preds)
(cons `s/and processed-ret-preds)
(first processed-ret-preds))))
final-fspec
(concat (when anon-fspec? [`s/fspec])
[:args processed-args]
[:ret (extract-spec retspec)]
(when fn-spec [:fn fn-spec])
(when gen-fn [:gen gen-fn]))]
(if nilable? `(s/nilable ~final-fspec) final-fspec)))))
TODO make sure we check whether the variadic bodies are legit
Can not have more than one
Can not have one with more regular args than the variadic one
(let [get-fspecs (fn [fn-body]
(let [[param-count variadic] (-> fn-body :args count-args)
gspec (or (:gspec fn-body)
(s/conform ::gspec
(vec (concat (repeat param-count 'any?)
(when (> variadic 0)
`[(s/* any?)])
'[=> any?]))))]
[(->> (if (> variadic 0) "n" param-count)
(str "arity-")
keyword)
(gspec->fspec* (:args fn-body) gspec false true false)]))
get-spec-part (fn [part spec]
(->> spec
(drop-while (complement #{part}))
second))]
(defn- generate-fspec-body [fn-bodies]
(case (key fn-bodies)
:arity-1
(when-let [gspec (-> fn-bodies val :gspec)]
(gspec->fspec* (-> fn-bodies val :args) gspec false false false))
:arity-n
(when (some :gspec (val fn-bodies))
(let [fspecs (map get-fspecs (val fn-bodies))
arg-specs (mapcat (fn [[arity spec]]
[arity (or (get-spec-part :args spec) `empty?)])
fspecs)
fn-param (gensym "p1__")
multi-ret-specs (when (->> fspecs
(map #(get-spec-part :ret (second %)))
distinct
count
(not= 1))
(mapcat (fn [[arity spec]]
[arity `(s/valid? ~(get-spec-part :ret spec)
(:ret ~fn-param))])
fspecs))
get-fn-clause (partial get-spec-part :fn)
fn-specs (when (->> fspecs (map second) (some get-fn-clause))
(mapcat (fn [[arity spec]]
[arity (if-let [fn-spec (get-fn-clause spec)]
`(s/valid? ~fn-spec ~fn-param)
true)])
fspecs))
NOTE : destructure args and ret in the arg vec
multi-ret-clause (when multi-ret-specs
`(fn ~'valid-multi-arity-ret? [~fn-param]
(case (-> ~fn-param :args key)
~@multi-ret-specs)))
multi-fn-clause (when fn-specs
`(fn ~'valid-multi-arity-fn? [~fn-param]
(case (-> ~fn-param :args key)
~@fn-specs)))]
(concat [:args `(s/or ~@arg-specs)]
(when-not multi-ret-clause
[:ret (get-spec-part :ret (-> fspecs first second))])
(when (or multi-ret-clause multi-fn-clause)
[:fn (if multi-fn-clause
(if multi-ret-clause
`(s/and ~multi-ret-clause ~multi-fn-clause)
multi-fn-clause)
multi-ret-clause)])))))))
(def ^:private spec-op->type
(let [map-prot "cljs.core.IMap"
coll-prot "cljs.core.ICollection"
seqable-prot "(cljs.core.ISeqable|string)"]
{'number? "number"
'integer? "number"
'int? "number"
'nat-int? "number"
'pos-int? "number"
'neg-int? "number"
'float? "number"
'double? "number"
'int-in "number"
'double-in "number"
'string? "string"
'boolean? "boolean"
'keys map-prot
'map-of map-prot
'map? map-prot
'merge map-prot
'set? "cljs.core.ISet"
'vector? "cljs.core.IVector"
'tuple "cljs.core.IVector"
'seq? "cljs.core.ISeq"
'seqable? seqable-prot
'associative? "cljs.core.IAssociative"
'atom? "cljs.core.IAtom"
'coll-of coll-prot
'every coll-prot
'keyword? "cljs.core.Keyword"
'ifn? "cljs.core.IFn"
'fn? "Function"}))
(declare get-gspec-type)
(defn- get-type [recursive-call conformed-spec-elem]
(let [[spec-type spec-def] conformed-spec-elem
spec-op
(case spec-type
:list (let [op (-> spec-def first name symbol)]
(cond
(#{'nilable '?} op) (concat (->> spec-def
second
(s/conform ::spec-elem)
(get-type true))
[::nilable])
(#{'* '+} op) (concat (->> spec-def
second
(s/conform ::spec-elem)
(get-type true))
[::variadic])
TODO
(#{'coll-of 'every} op) [(or (->> spec-def
(drop-while (complement #{:kind}))
second)
op)]
:else [op]))
:gspec (let [gspec-def (val spec-def)]
(if (= (key spec-def) :nilable-gspec)
[(get-gspec-type (:gspec gspec-def)) ::nilable]
[(get-gspec-type gspec-def)]))
:pred-sym [spec-def]
[nil])]
(if recursive-call
spec-op
(if-let [js-type (spec-op->type (first spec-op))]
(let [modifiers (set (rest spec-op))]
(as-> js-type t
(str (if (::nilable modifiers) "?" "!") t)
(str (when (::variadic modifiers) "...") t)))
"*"))))
(defn- get-gspec-type [conformed-gspec]
(let [argspec-def (:args conformed-gspec)
args-jstype (if-not argspec-def
""
(->> (-> conformed-gspec :args :args)
(map (partial get-type false))
(string/join ", ")))
ret-jstype (get-type false (:ret conformed-gspec))]
(str "function(" args-jstype "): " ret-jstype)))
(defn- generate-type-annotations [env conformed-bs]
(when (cljs-env? env)
(case (key conformed-bs)
:arity-1 (when-let [gspec (-> conformed-bs val :gspec)]
{:jsdoc [(str "@type {" (get-gspec-type gspec) "}")]})
:arity-n nil #_(when-let [ret-types (as-> (val conformed-bs) x
(map #(get-type false (-> % :gspec :ret)) x)
(distinct x)
(when (not-any? #{"*" "?"} x) x))]
{:jsdoc [(str "@return {" (string/join "|" ret-types) "}")]}))))
(defn- merge-config [metadata]
(s/assert ::ghostwheel-config
(->> (merge (u/get-base-config)
(meta *ns*)
metadata)
(filter #(= (-> % key namespace) (name `ghostwheel.core)))
(into {}))))
(defn- get-quoted-qualified-fn-name [fn-name]
`(quote ~(symbol (str (.-name *ns*)) (str fn-name))))
(defn- trace-threading-macros [forms trace]
(if (< trace 4)
forms
(let [threading-macros-mappings
{'-> 'ghostwheel.threading-macros/*->
'->> 'ghostwheel.threading-macros/*->>
'as-> 'ghostwheel.threading-macros/*as->
'cond-> 'ghostwheel.threading-macros/*cond->
'cond->> 'ghostwheel.threading-macros/*cond->>
'some-> 'ghostwheel.threading-macros/*some->
'some->> 'ghostwheel.threading-macros/*some->>}]
(cond->> (walk/postwalk-replace threading-macros-mappings forms)
Make sure we do n't trace threading macros in anon - fns
when anon - fns themselves are n't traced
(< trace 5)
(walk/postwalk
#(if (and (list? %)
(#{'fn 'fn*} (first %)))
(walk/postwalk-replace (map-invert threading-macros-mappings) %)
%))))))
(defn- clairvoyant-trace [forms trace color env]
(let [clairvoyant 'clairvoyant.core/trace-forms
tracer 'ghostwheel.tracer/tracer
exclude (case trace
2 '#{'fn 'fn* 'let}
3 '#{'fn 'fn*}
4 '#{'fn 'fn*}
nil)
inline-trace? (fn [form]
(and (seq? form)
(symbol? (first form))
(let [sym (first form)
qualified-sym
(if (cljs-env? env)
(:name (ana-api/resolve env sym))
Clojure yet – check this when it does
#?(:clj (name (resolve sym))))]
(contains? #{'ghostwheel.core/|> 'ghostwheel.core/tr} qualified-sym))))
forms (walk/postwalk
#(if (inline-trace? %) (second %) %)
forms)]
(comment
#?(:clj (if cljs?
(when-not (and (find-ns (symbol (namespace clairvoyant)))
(find-ns (symbol (namespace tracer))))
(throw (Exception. "Can't find tracing namespaces. Either add `gnl/ghostwheel-tracer` artifact and `(:require [ghostwheel.tracer])`, or disable tracing in order to compile.")))
(throw (Exception. "Tracing is not yet implemented for Clojure.")))))
(if (< trace 2)
forms
`(~clairvoyant
{:enabled true
:tracer (~tracer
:color "#fff"
:background ~color
:expand ~(cond (= trace 6) '#{:bindings 'let 'defn 'defn- 'fn 'fn*}
(>= trace 3) '#{:bindings 'let 'defn 'defn-}
:else '#{'defn 'defn-}))
:exclude ~exclude}
~forms))))
(defn- generate-fdef
[forms]
(let [{[type fn-name] :name bs :bs} (s/conform ::>fdef-args forms)]
(case type
:sym (let [quoted-qualified-fn-name (get-quoted-qualified-fn-name fn-name)
{:keys [::instrument ::outstrument]} (merge-config (meta fn-name))
instrumentation (cond outstrument `(ost/instrument ~quoted-qualified-fn-name)
instrument `(st/instrument ~quoted-qualified-fn-name)
:else nil)
fdef `(s/fdef ~fn-name ~@(generate-fspec-body bs))]
(if instrumentation
`(do ~fdef ~instrumentation)
fdef))
:key `(s/def ~fn-name (s/fspec ~@(generate-fspec-body bs))))))
(defn- process-defn-body
[cfg fspec args+gspec+body]
(let [{:keys [env fn-name traced-fn-name trace color unexpected-fx]} cfg
{:keys [args body]} args+gspec+body
[prepost orig-body-forms] (case (key body)
:prepost+body [(-> body val :prepost)
(-> body val :body)]
:body [nil (val body)])
process-arg (fn [[arg-type arg]]
(as-> arg arg
(case arg-type
:sym [arg-type arg]
:seq [arg-type (update arg :as #(or % {:as :as :sym (gensym "arg_")}))]
:map [arg-type (update arg :as #(or % (gensym "arg_")))])))
extract-arg (fn [[arg-type arg]]
(case arg-type
:sym arg
:seq (get-in arg [:as :sym])
:map (:as arg)
nil))
unform-arg #(->> % (s/unform ::binding-form) unscrew-vec-unform)
reg-args (->> args :args (map process-arg))
var-arg (some-> args :varargs :form process-arg)
arg-list (vec (concat (map unform-arg reg-args)
(when var-arg ['& (unform-arg var-arg)])))
body-forms (if (and fspec (every? nil? orig-body-forms))
TODO error handling when specs too fancy for stub auto - generation
[`(apply (-> ~fspec s/gen gen/generate)
~@(map extract-arg reg-args) ~(extract-arg var-arg))]
(cond unexpected-fx
[`(throw (~(if (cljs-env? env) 'js/Error. 'Exception.)
~(str "Calling function `"
fn-name
"` which has unexpected side effects.")))]
(= trace :dispatch)
[`(if *global-trace-allowed?*
(apply ~traced-fn-name
~@(map extract-arg reg-args)
~(extract-arg var-arg))
(do ~@orig-body-forms))]
(= trace 1)
`[(do
(l/pr-clog ~(str (list fn-name arg-list))
nil
{::r/background ~color})
~@orig-body-forms)]
(>= trace 4)
(trace-threading-macros orig-body-forms trace)
:else
orig-body-forms))]
(remove nil? `(~arg-list ~prepost ~@body-forms))))
(defn- generate-defn
[forms private env]
(let [cljs? (cljs-env? env)
conformed-gdefn (s/conform ::>defn-args forms)
fn-bodies (:bs conformed-gdefn)
empty-bodies (every? empty?
(case (key fn-bodies)
:arity-1 (list (-> fn-bodies val :body val))
:arity-n (->> fn-bodies
val
(map :body)
(map val))))
arity (key fn-bodies)
fn-name (:name conformed-gdefn)
quoted-qualified-fn-name
(get-quoted-qualified-fn-name fn-name)
traced-fn-name (gensym (str fn-name "__"))
docstring (:docstring conformed-gdefn)
meta-map (merge (:meta conformed-gdefn)
(generate-type-annotations env fn-bodies)
{::ghostwheel true})
config (merge-config (merge (meta fn-name) meta-map))
color (resolve-trace-color (::trace-color config))
{:keys [::defn-macro ::instrument ::outstrument ::trace ::check]} config
defn-sym (cond defn-macro (with-meta (symbol defn-macro) {:private private})
private 'defn-
:else 'defn)
trace (if (cljs-env? env)
(cond empty-bodies 0
(true? trace) 4
:else trace)
fdef-body (generate-fspec-body fn-bodies)
fdef (when fdef-body `(s/fdef ~fn-name ~@fdef-body))
instrumentation (when (not empty-bodies)
(cond outstrument `(ost/instrument ~quoted-qualified-fn-name)
instrument `(st/instrument ~quoted-qualified-fn-name)
:else nil))
individual-arity-fspecs
(map (fn [{:keys [args gspec]}]
(when gspec
(gspec->fspec* args gspec true false false)))
(val fn-bodies))
[unexpected-fx generated-test] (when (and check (not empty-bodies))
(let [fspecs (case arity
:arity-1 [(when fdef-body `(s/fspec ~@fdef-body))]
:arity-n individual-arity-fspecs)]
(generate-test fn-name fspecs fn-bodies config cljs?)))
process-fn-bodies (fn [trace]
(let [process-cfg {:env env
:fn-name fn-name
:traced-fn-name traced-fn-name
:trace trace
:color color
:unexpected-fx unexpected-fx}]
(case arity
:arity-1 (->> fn-bodies val (process-defn-body process-cfg `(s/fspec ~@fdef-body)))
:arity-n (map (partial process-defn-body process-cfg)
individual-arity-fspecs
(val fn-bodies)))))
main-defn (remove nil? `(~defn-sym
~fn-name
~docstring
~meta-map
~@(process-fn-bodies (if (> trace 0) :dispatch 0))))
traced-defn (when (> trace 0)
(let [traced-defn (remove nil? `(~defn-sym
~traced-fn-name
~@(process-fn-bodies trace)))]
(if (= trace 1)
traced-defn
(clairvoyant-trace traced-defn trace color env))))]
`(do ~fdef ~traced-defn ~main-defn ~instrumentation ~generated-test)))
(defn after-check-async [done]
(let [success @r/*all-tests-successful]
(when success (doseq [f @*after-check-callbacks] (f)))
(reset! r/*all-tests-successful true)
(reset! *after-check-callbacks [])
(when success (done))))
(defn- generate-coverage-check [env nspace]
(let [cljs? (cljs-env? env)
{:keys [::check-coverage ::check]} (merge (u/get-base-config)
(if cljs?
(:meta (ana-api/find-ns nspace))
#?(:clj (meta nspace))))
get-intern-meta (comp meta (if cljs? key val))
all-checked-fns (when check-coverage
(some->> (if cljs? (ana-api/ns-interns nspace) #?(:clj (ns-interns nspace)))
(filter #(if cljs? (-> % val :fn-var) #?(:clj (t/function? (key %)))))
(remove #(-> % key str (string/ends-with? test-suffix)))
(remove #(-> % get-intern-meta ::check-coverage false?))))
plain-defns (when check-coverage
(some->> all-checked-fns
(remove #(-> % get-intern-meta ::ghostwheel))
(map (comp str key))
vec))
unchecked-defns (when check-coverage
(some->> all-checked-fns
(filter #(-> % get-intern-meta ::ghostwheel))
(filter #(-> % get-intern-meta ::check false?))
(map (comp str key))
vec))]
`(do
~(when (not check)
`(do
(l/group ~(str "WARNING: "
"`::g/check` disabled for "
nspace
(::r/incomplete-coverage r/snippets))
~r/warning-style)
(l/group-end)))
~(when (not-empty plain-defns)
`(do
(l/group ~(str "WARNING: "
"Plain `defn` functions detected in "
nspace
(::r/incomplete-coverage r/snippets))
~r/warning-style)
(l/log (mapv symbol ~plain-defns))
(l/log-bold "=> Use `>defn` instead.")
(l/group-end)))
~(when (not-empty unchecked-defns)
`(do
(l/group ~(str "WARNING: "
"`::g/check` disabled for some functions in "
nspace
(::r/incomplete-coverage r/snippets))
~r/warning-style)
(l/log (mapv symbol ~unchecked-defns))
(l/group-end))))))
(defn- generate-check [env targets]
(let [base-config
(u/get-base-config)
cljs?
(cljs-env? env)
{:keys [::extrument ::report-output]}
base-config
conformed-targets
(let [conformed-targets (s/conform ::check-targets targets)]
(if (= (key conformed-targets) :multi)
(val conformed-targets)
[(val conformed-targets)]))
processed-targets
(mapcat (fn [[type target]]
(if (not= type :regex)
[[type (:sym target)]]
(for [ns (if cljs? (ana-api/all-ns) #?(:clj (all-ns)))
:when (re-matches target (str (if cljs? ns #?(:clj (ns-name ns)))))]
[:ns ns])))
conformed-targets)
errors
(->> (for [target processed-targets
:let [[type sym] target]]
(case type
:fn (let [fn-data (if cljs? (ana-api/resolve env sym) #?(:clj (resolve sym)))
metadata (if cljs? (:meta fn-data) #?(:clj (meta fn-data)))
{:keys [::check-coverage ::check]}
(merge (u/get-base-config)
(meta (:ns fn-data))
metadata)]
(cond (not fn-data)
(str "Cannot resolve `" (str sym) "`")
(not (if cljs? (:fn-var fn-data) #?(:clj (t/function? sym))))
(str "`" sym "` is not a function.")
(not (::ghostwheel metadata))
(str "`" sym "` is not a Ghostwheel function => Use `>defn` to define it.")
(not check)
(str "Checking disabled for `" sym "` => Set `{:ghostwheel.core/check true}` to enable.")
:else
nil))
:ns (let [ns-data (if cljs? (ana-api/find-ns sym) #?(:clj sym))
metadata (if cljs? (:meta ns-data) #?(:clj (meta ns-data)))
{:keys [::check]} (merge base-config metadata)]
(cond (not ns-data)
(str "Cannot resolve `" (str sym) "`")
(not check)
(str "Checking disabled for `" sym "` => Set `{:ghostwheel.core/check true}` to enable.")
:else
nil))))
(remove nil?))]
(if (not-empty errors)
(u/gen-exception env (str "\n" (string/join "\n" errors)))
`(when *global-check-allowed?*
(binding [*global-trace-allowed?* false
l/*report-output* ~(if cljs? report-output :repl)]
(do
~@(remove nil?
`[~(when extrument
`(st/instrument (quote ~extrument)))
~@(for [target processed-targets
:let [[type sym] target]]
(case type
:fn `(binding [t/report r/report]
(~(symbol (str sym test-suffix))))
:ns `(binding [t/report r/report]
(t/run-tests (quote ~sym)))))
~@(->> (for [target processed-targets
:let [[type sym] target]
:when (= type :ns)]
(generate-coverage-check env sym))
(remove nil?))
~(when extrument
`(st/unstrument (quote ~extrument)))])))))))
(defn- generate-after-check [callbacks]
(let [{:keys [::check]}
(merge (u/get-base-config)
(meta *ns*))]
TODO implement for clj
(when (and check (seq callbacks))
`(swap! *after-check-callbacks (comp vec concat) ~(vec callbacks)))))
(defn- generate-traced-expr
[expr env]
(if (and (seq? expr)
(or (contains? l/ops-with-bindings (first expr))
(contains? threading-macro-syms (first expr))))
(let [cfg (merge-config (meta expr))
color (resolve-trace-color (::trace-color cfg))
trace (let [trace (::trace cfg)]
(if (= trace 0) 5 trace))]
(cond-> (trace-threading-macros expr trace)
REVIEW : Clairvoyant does n't work on Clojure yet
(cljs-env? env) (clairvoyant-trace trace color env)))
`(l/clog ~expr)))
(s/def ::>defn-args
(s/cat :name simple-symbol?
:docstring (s/? string?)
:meta (s/? map?)
:bs (s/alt :arity-1 ::args+gspec+body
:arity-n (s/+ (s/and seq? ::args+gspec+body))))))
(s/fdef >defn :args ::>defn-args)
(defmacro >defn
"Like defn, but requires a (nilable) gspec definition and generates
additional `s/fdef`, generative tests, instrumentation code, an
fspec-based stub, and/or tracing code, depending on the configuration
metadata and the existence of a valid gspec and non-nil body."
{:arglists '([name doc-string? attr-map? [params*] gspec prepost-map? body?]
[name doc-string? attr-map? ([params*] gspec prepost-map? body?) + attr-map?])}
[& forms]
(if (u/get-env-config)
(cond-> (remove nil? (generate-defn forms false &env))
(cljs-env? &env) clj->cljs)
(clean-defn 'defn forms)))
(s/fdef >defn- :args ::>defn-args)
NOTE : lots of duplication - refactor this to set / pass ^:private differently and call >
(defmacro >defn-
"Like defn-, but requires a (nilable) gspec definition and generates
additional `s/fdef`, generative tests, instrumentation code, an
fspec-based stub, and/or tracing code, depending on the configuration
metadata and the existence of a valid gspec and non-nil body."
{:arglists '([name doc-string? attr-map? [params*] gspec prepost-map? body?]
[name doc-string? attr-map? ([params*] gspec prepost-map? body?) + attr-map?])}
[& forms]
(if (u/get-env-config)
(cond-> (remove nil? (generate-defn forms true &env))
(cljs-env? &env) clj->cljs)
(clean-defn 'defn- forms)))
(defmacro after-check
"Takes a number of 0-arity functions to run
after all checks are completed successfully.
Meant to be used in a hot-reloading environment by putting it at the bottom
of a `(g/check)`-ed namespace and calling `ghostwheel.core/after-check-async`
correctly in the build system post-reload hooks."
[& callbacks]
(when (u/get-env-config)
(cond-> (generate-after-check callbacks)
(cljs-env? &env) (clj->cljs false))))
(s/def ::check-target
(s/or :fn (s/and seq?
(s/cat :quote #{'quote}
:sym (s/and symbol?
#(let [s (str %)]
(or (string/includes? s "/")
(not (string/includes? s ".")))))))
:ns (s/and seq? (s/cat :quote #{'quote} :sym symbol?))
:regex #?(:clj #(instance? java.util.regex.Pattern %)
:cljs regexp?)))
(s/def ::check-targets
(s/or :single ::check-target
:multi (s/spec (s/+ ::check-target))))
(s/fdef check
:args (s/spec (s/? ::check-targets)))
(defmacro check
"Runs Ghostwheel checks on the given namespaces and/or functions.
Checks the current namespace if called without arguments."
{:arglists '([]
[ns-regex-or-quoted-ns-or-fn]
[[ns-regex-or-quoted-ns-or-fn+]])}
([]
`(check (quote ~(.-name *ns*))))
([things]
(if (u/get-env-config)
(cond-> (generate-check &env things)
(cljs-env? &env) (clj->cljs false))
(str "Ghostwheel disabled => "
(if (cljs-env? &env)
"Add `:external-config {:ghostwheel {}}` to your compiler options to enable."
"Start the REPL with the `-Dghostwheel.enabled=true` JVM system property to enable.")))))
(s/def ::>fdef-args
(s/cat :name (s/or :sym symbol? :key qualified-keyword?)
:bs (s/alt :arity-1 ::args+gspec+body
:arity-n (s/+ (s/and seq? ::args+gspec+body))))))
(s/fdef >fdef :args ::>fdef-args)
(defmacro >fdef
"Defines an fspec using gspec syntax – pretty much a `>defn` without the body.
`name` can be a symbol or a qualified keyword, depending on whether the
fspec is meant to be registered as a top-level fspec (=> s/fdef fn-sym
...) or used in other specs (=> s/def ::spec-keyword (s/fspec ...)).
When defining global fspecs, instrumentation can be directly enabled by
setting the `^::g/instrument` or `^::g/outstrument` metadata on the symbol."
{:arglists '([name [params*] gspec]
[name ([params*] gspec) +])}
[& forms]
(when (u/get-env-config)
(cond-> (remove nil? (generate-fdef forms))
(cljs-env? &env) clj->cljs)))
(defmacro |>
"Traces or logs+returns the wrapped expression, depending on its type"
[expr]
(if (u/get-env-config)
(cond-> (generate-traced-expr expr &env)
(cljs-env? &env) clj->cljs)
expr))
(defmacro tr "Alias for |>" [expr] `(|> ~expr))
|
55a481b0e3440431918c1823011de4964308ac0d9ea15c49c4bec401dd6338c5
|
bjpop/haskell-mpi
|
PingPongFactorial.hs
|
# LANGUAGE ScopedTypeVariables #
.
Two processes calculate the factorial of the input .
Note : this is not a fast , nor sensible way to compute factorials .
It is merely intended to be used to demonstrate point - to - point
communications .
Ping Pong Factorial.
Two processes calculate the factorial of the input.
Note: this is not a fast, nor sensible way to compute factorials.
It is merely intended to be used to demonstrate point-to-point
communications.
-}
module Main where
import Control.Monad (when)
import Control.Parallel.MPI.Simple
import Control.Applicative ((<$>))
import Data.Char (isDigit)
type Msg = Either (Integer, Integer, Integer) Integer
zero, one :: Rank
zero = 0
one = 1
main :: IO ()
main = mpiWorld $ \size rank -> do
when (size == 2) $ do
when (rank == zero) $ do
n <- getNumber
send commWorld one unitTag (Left (n, 0, 1) :: Msg)
result <- factorial $ switch rank
when (rank == zero) $ print result
factorial :: Rank -> IO Integer
factorial rank = do
(msg :: Msg) <- fst <$> recv commWorld rank unitTag
case msg of
Right answer -> return answer
Left (n, count, acc)
| count == n -> do
send commWorld rank unitTag (Right acc :: Msg)
return acc
| otherwise -> do
let nextCount = count + 1
send commWorld rank unitTag (Left (n, nextCount, nextCount * acc) :: Msg)
factorial rank
switch :: Rank -> Rank
switch rank
| rank == zero = one
| otherwise = zero
getNumber :: IO Integer
getNumber = do
line <- getLine
if all isDigit line
then return $ read line
else return 0
| null |
https://raw.githubusercontent.com/bjpop/haskell-mpi/1a4e6f0ed20c7b0760344640f1ba5f2141e61719/test/examples/simple/PingPongFactorial.hs
|
haskell
|
# LANGUAGE ScopedTypeVariables #
.
Two processes calculate the factorial of the input .
Note : this is not a fast , nor sensible way to compute factorials .
It is merely intended to be used to demonstrate point - to - point
communications .
Ping Pong Factorial.
Two processes calculate the factorial of the input.
Note: this is not a fast, nor sensible way to compute factorials.
It is merely intended to be used to demonstrate point-to-point
communications.
-}
module Main where
import Control.Monad (when)
import Control.Parallel.MPI.Simple
import Control.Applicative ((<$>))
import Data.Char (isDigit)
type Msg = Either (Integer, Integer, Integer) Integer
zero, one :: Rank
zero = 0
one = 1
main :: IO ()
main = mpiWorld $ \size rank -> do
when (size == 2) $ do
when (rank == zero) $ do
n <- getNumber
send commWorld one unitTag (Left (n, 0, 1) :: Msg)
result <- factorial $ switch rank
when (rank == zero) $ print result
factorial :: Rank -> IO Integer
factorial rank = do
(msg :: Msg) <- fst <$> recv commWorld rank unitTag
case msg of
Right answer -> return answer
Left (n, count, acc)
| count == n -> do
send commWorld rank unitTag (Right acc :: Msg)
return acc
| otherwise -> do
let nextCount = count + 1
send commWorld rank unitTag (Left (n, nextCount, nextCount * acc) :: Msg)
factorial rank
switch :: Rank -> Rank
switch rank
| rank == zero = one
| otherwise = zero
getNumber :: IO Integer
getNumber = do
line <- getLine
if all isDigit line
then return $ read line
else return 0
|
|
8a8198e25439f61bfa721649afaa7daf073268db6e2f3a189c3cb66697c91038
|
agda/agda2hs
|
Name.hs
|
module Agda2Hs.Compile.Name where
import Control.Arrow ( (>>>) )
import Control.Monad
import Data.List ( intercalate, isPrefixOf )
import qualified Language.Haskell.Exts as Hs
import Agda.Compiler.Backend hiding ( topLevelModuleName )
import Agda.Compiler.Common ( topLevelModuleName )
import Agda.Syntax.Common
import Agda.TypeChecking.Pretty
import Agda.TypeChecking.Records ( isRecordConstructor )
import Agda.Utils.Maybe ( whenJust, fromMaybe )
import Agda.Utils.Pretty ( prettyShow )
import qualified Agda.Utils.Pretty as P ( Pretty(pretty) )
import Agda2Hs.Compile.Types
import Agda2Hs.Compile.Utils
import Agda2Hs.HsUtils
isSpecialName :: QName -> Maybe (Hs.QName (), Maybe Import)
isSpecialName = prettyShow >>> \ case
"Agda.Builtin.Nat.Nat" -> withImport "Numeric.Natural" $ unqual "Natural"
"Agda.Builtin.Int.Int" -> noImport $ unqual "Integer"
"Agda.Builtin.Word.Word64" -> noImport $ unqual "Word"
"Agda.Builtin.Float.Float" -> noImport $ unqual "Double"
"Agda.Builtin.Bool.Bool.false" -> noImport $ unqual "False"
"Agda.Builtin.Bool.Bool.true" -> noImport $ unqual "True"
"Agda.Builtin.List.List" -> noImport $ special Hs.ListCon
"Agda.Builtin.List.List._∷_" -> noImport $ special Hs.Cons
"Agda.Builtin.List.List.[]" -> noImport $ special Hs.ListCon
"Agda.Builtin.Unit.⊤" -> noImport $ special Hs.UnitCon
"Agda.Builtin.Unit.tt" -> noImport $ special Hs.UnitCon
"Haskell.Prim._∘_" -> noImport $ unqual "_._"
"Haskell.Prim.seq" -> noImport $ unqual "seq"
"Haskell.Prim._$!_" -> noImport $ unqual "_$!_"
_ -> Nothing
where
noImport x = Just (x, Nothing)
withImport mod x = Just (x, Just (Import (Hs.ModuleName () mod) Nothing (unQual x)))
unqual n = Hs.UnQual () $ hsName n
special c = Hs.Special () $ c ()
compileName :: Applicative m => Name -> m (Hs.Name ())
compileName n = hsName . show <$> pretty (nameConcrete n)
compileQName :: QName -> C (Hs.QName ())
compileQName f
| Just (x, mimp) <- isSpecialName f = do
whenJust mimp tellImport
return x
| otherwise = do
reportSDoc "agda2hs.name" 25 $ text $ "compiling name: " ++ prettyShow f
parent <- parentName f
f <- isRecordConstructor f >>= \ case
Just (r, Record{ recNamedCon = False }) -> return r -- Use the record name if no named constructor
_ -> return f
hf <- compileName (qnameName f)
mod <- compileModuleName $ qnameModule $ fromMaybe f parent
par <- traverse (compileName . qnameName) parent
unless (skipImport mod) $ tellImport (Import mod par hf)
-- TODO: this prints all names UNQUALIFIED. For names from
-- qualified imports, we need to add the proper qualification in
the code .
return $ Hs.UnQual () hf
where
skipImport mod =
"Agda.Builtin" `isPrefixOf` Hs.prettyPrint mod ||
"Haskell.Prim" `isPrefixOf` Hs.prettyPrint mod ||
"Haskell.Prelude" `isPrefixOf` Hs.prettyPrint mod
parentName :: QName -> C (Maybe QName)
parentName q = (theDef <$> getConstInfo q) >>= \case
Constructor { conData = dt } -> return $ Just dt
Function { funProjection = Right (Projection { projProper = Just{} , projFromType = rt }) }
-> return $ Just $ unArg rt
_ -> return Nothing
compileModuleName :: Monad m => ModuleName -> m (Hs.ModuleName ())
compileModuleName m = do
ns <- traverse (pretty . nameConcrete) (mnameToList m)
return $ Hs.ModuleName () $ intercalate "." $ map show ns
| null |
https://raw.githubusercontent.com/agda/agda2hs/037b8b8980254ff110733ff205e7d60e412287e3/src/Agda2Hs/Compile/Name.hs
|
haskell
|
Use the record name if no named constructor
TODO: this prints all names UNQUALIFIED. For names from
qualified imports, we need to add the proper qualification in
|
module Agda2Hs.Compile.Name where
import Control.Arrow ( (>>>) )
import Control.Monad
import Data.List ( intercalate, isPrefixOf )
import qualified Language.Haskell.Exts as Hs
import Agda.Compiler.Backend hiding ( topLevelModuleName )
import Agda.Compiler.Common ( topLevelModuleName )
import Agda.Syntax.Common
import Agda.TypeChecking.Pretty
import Agda.TypeChecking.Records ( isRecordConstructor )
import Agda.Utils.Maybe ( whenJust, fromMaybe )
import Agda.Utils.Pretty ( prettyShow )
import qualified Agda.Utils.Pretty as P ( Pretty(pretty) )
import Agda2Hs.Compile.Types
import Agda2Hs.Compile.Utils
import Agda2Hs.HsUtils
isSpecialName :: QName -> Maybe (Hs.QName (), Maybe Import)
isSpecialName = prettyShow >>> \ case
"Agda.Builtin.Nat.Nat" -> withImport "Numeric.Natural" $ unqual "Natural"
"Agda.Builtin.Int.Int" -> noImport $ unqual "Integer"
"Agda.Builtin.Word.Word64" -> noImport $ unqual "Word"
"Agda.Builtin.Float.Float" -> noImport $ unqual "Double"
"Agda.Builtin.Bool.Bool.false" -> noImport $ unqual "False"
"Agda.Builtin.Bool.Bool.true" -> noImport $ unqual "True"
"Agda.Builtin.List.List" -> noImport $ special Hs.ListCon
"Agda.Builtin.List.List._∷_" -> noImport $ special Hs.Cons
"Agda.Builtin.List.List.[]" -> noImport $ special Hs.ListCon
"Agda.Builtin.Unit.⊤" -> noImport $ special Hs.UnitCon
"Agda.Builtin.Unit.tt" -> noImport $ special Hs.UnitCon
"Haskell.Prim._∘_" -> noImport $ unqual "_._"
"Haskell.Prim.seq" -> noImport $ unqual "seq"
"Haskell.Prim._$!_" -> noImport $ unqual "_$!_"
_ -> Nothing
where
noImport x = Just (x, Nothing)
withImport mod x = Just (x, Just (Import (Hs.ModuleName () mod) Nothing (unQual x)))
unqual n = Hs.UnQual () $ hsName n
special c = Hs.Special () $ c ()
compileName :: Applicative m => Name -> m (Hs.Name ())
compileName n = hsName . show <$> pretty (nameConcrete n)
compileQName :: QName -> C (Hs.QName ())
compileQName f
| Just (x, mimp) <- isSpecialName f = do
whenJust mimp tellImport
return x
| otherwise = do
reportSDoc "agda2hs.name" 25 $ text $ "compiling name: " ++ prettyShow f
parent <- parentName f
f <- isRecordConstructor f >>= \ case
_ -> return f
hf <- compileName (qnameName f)
mod <- compileModuleName $ qnameModule $ fromMaybe f parent
par <- traverse (compileName . qnameName) parent
unless (skipImport mod) $ tellImport (Import mod par hf)
the code .
return $ Hs.UnQual () hf
where
skipImport mod =
"Agda.Builtin" `isPrefixOf` Hs.prettyPrint mod ||
"Haskell.Prim" `isPrefixOf` Hs.prettyPrint mod ||
"Haskell.Prelude" `isPrefixOf` Hs.prettyPrint mod
parentName :: QName -> C (Maybe QName)
parentName q = (theDef <$> getConstInfo q) >>= \case
Constructor { conData = dt } -> return $ Just dt
Function { funProjection = Right (Projection { projProper = Just{} , projFromType = rt }) }
-> return $ Just $ unArg rt
_ -> return Nothing
compileModuleName :: Monad m => ModuleName -> m (Hs.ModuleName ())
compileModuleName m = do
ns <- traverse (pretty . nameConcrete) (mnameToList m)
return $ Hs.ModuleName () $ intercalate "." $ map show ns
|
b62db0105f42c0ca2d9888e54f9f46179ab837de7f1d45ffa6128f4d4fbe0dea
|
binghe/PCL
|
bench.lisp
|
;;;-*- Mode: Lisp; Syntax: Common-lisp; Package: user -*-
(in-package :bench :use '(:lisp :pcl))
;;;Here are a few homebrew benchmarks for testing out Lisp performance.
BENCH - THIS - LISP : benchmarks for common lisp .
BENCH - THIS - CLOS : benchmarks for CLOS .
BENCH - FLAVORS : ditto for Symbolics flavors .
BE SURE TO CHANGE THE PACKAGE DEFINITION TO GET THE CLOS + LISP YOU WANT TO TEST .
;;;
Each benchmark is reported as operations per second . Without - interrupts is used ,
;;; so the scheduler isn't supposed to get in the way. Accuracy is generally
between one and five percent .
;;;
;;;Elapsed time is measured using get-internal-run-time. Because the accuracy of
;;; this number is fairly crude, it is important to use a large number of
;;; iterations to get an accurate benchmark. The function median-time may
;;; complain to you if you didn't pick enough iterations.
;;;
July 1992 . Watch out ! In some cases the instruction being timed will be
;;; optimized away by a clever compiler. Beware of benchmarks that are
;;; nearly as fast as *speed-of-empty-loop*.
;;;
Thanks to for much of this code .
;;;
;;;
#+Genera
(eval-when (compile load eval)
(import '(clos-internals::allocate-instance)))
(proclaim '(optimize (speed 3) (safety 1) (space 0) #+lucid (compilation-speed 0)))
;;;*********************************************************************
(defvar *min-time* (/ 500 (float internal-time-units-per-second))
"At least 2 orders of magnitude larger than our time resolution.")
(defmacro elapsed-time (form)
"Returns (1) the result of form and (2) the time (seconds) it takes to evaluate form."
;; Note that this function is completely portable.
(let ((start-time (gensym)) (end-time (gensym)))
`(let ((,start-time (get-internal-run-time)))
(values ,form
(let ((,end-time (get-internal-run-time)))
(/ (abs (- ,end-time ,start-time))
,(float internal-time-units-per-second)))))))
(defmacro without-interruption (&body forms)
#+genera `(scl:without-interrupts ,@forms)
#+lucid `(lcl::with-scheduling-inhibited ,@forms)
#+allegro `(excl:without-interrupts ,@forms)
#+(and (not genera) (not lucid) (not allegro)) `(progn ,@forms))
(defmacro median-time (form &optional (I 5))
"Return the median time it takes to evaluate form."
;; I: number of samples to take.
`(without-interruption
(let ((results nil))
(dotimes (ignore ,I)
(multiple-value-bind (ignore time) (elapsed-time ,form)
(declare (ignore ignore))
(if (< time *min-time*)
(format t "~% Warning. Evaluating ~S took only ~S seconds.~
~% You should probably use more iterations." ',form time))
(push time results)))
(nth ,(truncate I 2) (sort results #'<)))))
#+debug
(defun test () (median-time (sleep 1.0)))
;;;*********************************************************************
;;;OPERATIONS-PER-SECOND actually does the work of computing a benchmark. The amount
;;; of time it takes to execute the form N times is recorded, minus the time it
;;; takes to execute the empty loop. OP/S = N/time. This quantity is recomputed
five times and the median value is returned . Variance in the numbers increases
;;; when memory is being allocated (cons, make-instance, etc).
(defmacro repeat (form N)
;; Minimal loop
(let ((count (gensym)) (result (gensym)))
`(let ((,count ,N) ,result)
(loop
;; If you don't use the setq, the compiler may decide that since the
;; result is ignored, FORM can be "compiled out" of the loop.
(setq ,result ,form)
(if (zerop (decf ,count)) (return ,result))))))
(defun nempty (N)
"The empty loop."
(repeat nil N))
(defun empty-speed (N) (median-time (nempty N)))
(defun compute-empty-iterations (&optional (default 1000000))
(format t "~%Computing speed of empty loop...")
(let ((time nil))
(loop
(setq time (empty-speed default))
(if (< time *min-time*) (setq default (* default 10)) (return)))
(format t "done.")
default))
(defvar *empty-iterations*)
(defvar *speed-of-empty-loop*)
(eval-when (load eval)
(setq *empty-iterations* (compute-empty-iterations))
(setq *speed-of-empty-loop* (/ (empty-speed *empty-iterations*)
(float *empty-iterations*))))
(defmacro operations-per-second (form N &optional (I 5))
"Return the number of times FORM can evaluate in one second."
`(let ((time (median-time (repeat ,form ,N) ,I)))
(/ (float ,N) (- time (* *speed-of-empty-loop* N)))))
(defmacro bench (pretty-name name N &optional (stream t))
`(format ,stream "~%~A: ~30T~S" ,pretty-name (,name ,N)))
;;;****************************************************************************
BENCH - THIS - LISP
(defun Nmult (N)
(let ((a 2.1))
(operations-per-second (* a a) N)))
(defun Nadd (N)
(let ((a 2.1))
(operations-per-second (+ a a) N)))
(defun square (x) (* x x))
(defun funcall-1 (N)
;; inlined
(let ((x 2.1))
(operations-per-second (funcall #'(lambda (a) (* a a)) x) N)))
(defun f1 (n) n)
(defun funcall-2 (N)
(let ((f #'f1)
(x 2.1))
(operations-per-second (funcall f x) N)))
(defun funcall-3 (N)
(let ((x 2.1))
(operations-per-second (f1 x) N)))
(defun funcall-4 (N)
(let ((x 2.1))
(operations-per-second (funcall #'square x) N)))
(defun funcall-5 (N)
(let ((x 2.1)
(f #'square))
(let ((g #'(lambda (x)
(operations-per-second (funcall f x) N))))
(funcall g x))))
(defun Nsetf (N)
(let ((array (make-array 15)))
(operations-per-second (setf (aref array 5) t) N)))
(defun Nsymeval (N) (operations-per-second (eval T) N))
(defun Repeatuations (N) (operations-per-second (eval '(* 2.1 2.1)) N))
(defun n-cons (N) (let ((a 1)) (operations-per-second (cons a a) N)))
(defvar *object* t)
(Defun nspecial (N) (operations-per-second (null *object*) N))
(defun nlexical (N)
(let ((o t))
(operations-per-second (null o) N)))
(defun nfree (N)
(let ((o t))
(let ((g #'(lambda ()
#+genera (declare (sys:downward-function))
(operations-per-second (null o) N))))
(funcall g))))
(defun nfree2 (N)
(let ((o t))
(let ((g #'(lambda ()
(let ((f #'(lambda ()
#+genera (declare (sys:downward-function))
(operations-per-second (null o) N))))
(funcall f)))))
(funcall g))))
(defun ncompilations (N)
(let ((lambda-expression
'(lambda (bar) (let ((baz t)) (if baz (cons bar nil))))))
(operations-per-second (compile 'bob lambda-expression) N)))
(defun bench-this-lisp ()
(let ((N (/ *empty-iterations* 10)))
(bench "(* 2.1 2.1)" nmult N)
(bench "(+ 2.1 2.1)" nadd N)
(bench "funcall & (* 2.1 2.1)" funcall-3 N)
(bench "special reference" nspecial *empty-iterations*)
(bench "lexical reference" nlexical *empty-iterations*)
;; (bench "ivar reference" n-ivar-ref N)
(bench "(setf (aref array 5) t)" nsetf N)
(bench "(funcall lexical-f x)" funcall-2 N)
(bench "(f x)" funcall-3 N)
( Bench " ( eval t ) " nsymeval 10000 )
( bench " ( eval ' ( * 2.1 2.1 ) ) " repeatuations 10000 )
( bench " ( cons 1 2 ) " n - cons 100000 )
( bench " compile simple function " ncompilations 50 )
))
;(bench-this-lisp)
;;;**************************************************************
#+genera
(progn
(scl:defflavor bar (a b) ()
:initable-instance-variables
:writable-instance-variables)
(scl:defflavor frob (c) (bar)
:initable-instance-variables
:writable-instance-variables)
(scl:defmethod (hop bar) ()
a)
(scl:defmethod (set-hop bar) (n)
(setq a n))
(scl:defmethod (nohop bar) ()
5)
(defun n-ivar-ref (N)
(let ((i (scl:make-instance 'bar :a 0 :b 0)))
(ivar-ref i N)))
(scl:defmethod (ivar-ref bar) (N)
(operations-per-second b N))
(defun Ninstances (N) (operations-per-second (flavor:make-instance 'bar) N))
(defun n-svref (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (scl:symbol-value-in-instance instance 'a) N)))
(defun n-hop (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (hop instance) n)))
(defun n-gf (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (nohop instance) n)))
(defun n-set-hop (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (set-hop instance) n)))
(defun n-type-of (N)
(let ((instance (flavor:make-instance 'bar)))
(operations-per-second (flavor::%instance-flavor instance) N)))
(defun n-bar-b (N)
(let ((instance (flavor:make-instance 'bar :a 0 :b 0)))
(operations-per-second (bar-b instance) N)))
(defun n-frob-bar-b (N)
(let ((instance (flavor:make-instance 'frob :a 0 :b 0)))
(operations-per-second (bar-b instance) N)))
(defun bench-flavors ()
(bench "flavor:make-instance (2 slots)" ninstances 5000)
(bench "flavor:symbol-value-in-instance" n-svref 100000)
(bench "1 method, 1 dispatch" n-gf 100000)
(bench "slot symbol in method (access)" n-hop 100000)
(bench "slot symbol in method (modify)" n-hop 100000)
(bench "slot accessor bar" n-bar-b 100000)
(bench "slot accessor frob" n-frob-bar-b 100000)
(bench "instance-flavor" n-type-of 500000))
) ; end of #+genera
;;;**************************************************************
BENCH - THIS - CLOS
( evolved from tests of Symbolics CLOS )
(defmethod strange ((x t)) t) ; default method
(defmethod area ((x number)) 'green) ; builtin class
(defclass point
()
((x :initform 0 :accessor x :initarg :x)
(y :initform 0 :accessor y :initarg :y)))
(defmethod color ((thing point)) 'red)
(defmethod address ((thing point)) 'boston)
(defmethod area ((thing point)) 0)
(defmethod move-to ((p1 point) (p2 point)) 0)
(defmethod x-offset ((thing point))
(with-slots (x y) thing x))
(defmethod set-x-offset ((thing point) new-x)
(with-slots (x y) thing (setq x new-x)))
(defclass box
(point)
((width :initform 10 :accessor width :initarg :width)
(height :initform 10 :accessor height :initarg :height)))
(defmethod area ((thing box)) 0)
(defmethod move-to ((box box) (point point)) 0)
(defmethod address :around ((thing box)) (call-next-method))
(defvar p (make-instance 'point))
(defvar b (make-instance 'box))
(defun n-strange (N) (operations-per-second (strange 5) N))
(defun n-accesses (N)
(let ((instance p))
(operations-per-second (x instance) N)))
(defun n-color (N)
(let ((instance p))
(operations-per-second (color instance) n)))
(defun n-call-next-method (N)
(let ((instance b))
(operations-per-second (address instance) n)))
(defun n-area-1 (N)
(let ((instance p))
(operations-per-second (area instance) n)))
(defun n-area-2 (N)
(operations-per-second (area 5) n))
(defun n-move-1 (N)
(let ((instance p))
(operations-per-second (move-to instance instance) n)))
(defun n-move-2 (N)
(let ((x p) (y b))
(operations-per-second (move-to x y) n)))
(defun n-off (N)
(let ((instance p))
(operations-per-second (x-offset instance) n)))
(defun n-setoff (N)
(let ((instance p))
(operations-per-second (set-x-offset instance 500) n)))
(defun n-slot-value (N)
(let ((instance p))
(operations-per-second (slot-value instance 'x) n)))
(defun n-class-of-1 (N)
(let ((instance p))
(operations-per-second (class-of instance) n)))
(defun n-class-of-2 (N)
(operations-per-second (class-of 5) n))
(defun n-alloc (N)
(let ((c (find-class 'point)))
(operations-per-second (allocate-instance c) n)))
(defun n-make (N)
(operations-per-second (make-instance 'point) n))
(defun n-make-initargs (N)
;; Much slower than n-make!
(operations-per-second (make-instance 'point :x 0 :y 5) n))
(defun n-make-variable-initargs (N)
;; Much slower than n-make!
(let ((x 0)
(y 5))
(operations-per-second (make-instance 'point :x x :y y) n)))
(pcl::expanding-make-instance-top-level
(defun n-make1 (N)
(operations-per-second (make-instance 'point) n))
(defun n-make-initargs1 (N)
;; Much slower than n-make!
(operations-per-second (make-instance 'point :x 0 :y 5) n))
(defun n-make-variable-initargs1 (N)
;; Much slower than n-make!
(let ((x 0)
(y 5))
(operations-per-second (make-instance 'point :x x :y y) n)))
)
(pcl::precompile-random-code-segments)
(defun bench-this-clos ()
(let ((N (/ *empty-iterations* 10)))
(bench "1 default method" n-strange N)
(bench "1 dispatch, 1 method" n-color N)
(bench "1 dispatch, :around + primary" n-call-next-method N)
(bench "1 dispatch, 3 methods, instance" n-area-1 N)
(bench "1 dispatch, 3 methods, noninstance" n-area-2 N)
(bench "2 dispatch, 2 methods" n-move-1 N)
(bench "slot reader method" n-accesses N)
(bench "with-slots (1 access)" n-off N)
(bench "with-slots (1 modify)" n-setoff N)
(bench "naked slot-value" n-slot-value N)
(bench "class-of instance" n-class-of-1 N)
(bench "class-of noninstance" n-class-of-2 N)
(bench "allocate-instance (2 slots)" n-alloc
#+pcl 5000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 slots)" n-make
#+pcl 5000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 constant initargs)" n-make-initargs
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 variable initargs)" n-make-variable-initargs
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 slots)" n-make1
#+pcl 5000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 constant initargs)" n-make-initargs1
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 variable initargs)" n-make-variable-initargs1
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)) )
;(bench-this-clos)
| null |
https://raw.githubusercontent.com/binghe/PCL/7021c061c5eef1466e563c4abb664ab468ee0d80/bench/bench.lisp
|
lisp
|
-*- Mode: Lisp; Syntax: Common-lisp; Package: user -*-
Here are a few homebrew benchmarks for testing out Lisp performance.
so the scheduler isn't supposed to get in the way. Accuracy is generally
Elapsed time is measured using get-internal-run-time. Because the accuracy of
this number is fairly crude, it is important to use a large number of
iterations to get an accurate benchmark. The function median-time may
complain to you if you didn't pick enough iterations.
optimized away by a clever compiler. Beware of benchmarks that are
nearly as fast as *speed-of-empty-loop*.
*********************************************************************
Note that this function is completely portable.
I: number of samples to take.
*********************************************************************
OPERATIONS-PER-SECOND actually does the work of computing a benchmark. The amount
of time it takes to execute the form N times is recorded, minus the time it
takes to execute the empty loop. OP/S = N/time. This quantity is recomputed
when memory is being allocated (cons, make-instance, etc).
Minimal loop
If you don't use the setq, the compiler may decide that since the
result is ignored, FORM can be "compiled out" of the loop.
****************************************************************************
inlined
(bench "ivar reference" n-ivar-ref N)
(bench-this-lisp)
**************************************************************
end of #+genera
**************************************************************
default method
builtin class
Much slower than n-make!
Much slower than n-make!
Much slower than n-make!
Much slower than n-make!
(bench-this-clos)
|
(in-package :bench :use '(:lisp :pcl))
BENCH - THIS - LISP : benchmarks for common lisp .
BENCH - THIS - CLOS : benchmarks for CLOS .
BENCH - FLAVORS : ditto for Symbolics flavors .
BE SURE TO CHANGE THE PACKAGE DEFINITION TO GET THE CLOS + LISP YOU WANT TO TEST .
Each benchmark is reported as operations per second . Without - interrupts is used ,
between one and five percent .
July 1992 . Watch out ! In some cases the instruction being timed will be
Thanks to for much of this code .
#+Genera
(eval-when (compile load eval)
(import '(clos-internals::allocate-instance)))
(proclaim '(optimize (speed 3) (safety 1) (space 0) #+lucid (compilation-speed 0)))
(defvar *min-time* (/ 500 (float internal-time-units-per-second))
"At least 2 orders of magnitude larger than our time resolution.")
(defmacro elapsed-time (form)
"Returns (1) the result of form and (2) the time (seconds) it takes to evaluate form."
(let ((start-time (gensym)) (end-time (gensym)))
`(let ((,start-time (get-internal-run-time)))
(values ,form
(let ((,end-time (get-internal-run-time)))
(/ (abs (- ,end-time ,start-time))
,(float internal-time-units-per-second)))))))
(defmacro without-interruption (&body forms)
#+genera `(scl:without-interrupts ,@forms)
#+lucid `(lcl::with-scheduling-inhibited ,@forms)
#+allegro `(excl:without-interrupts ,@forms)
#+(and (not genera) (not lucid) (not allegro)) `(progn ,@forms))
(defmacro median-time (form &optional (I 5))
"Return the median time it takes to evaluate form."
`(without-interruption
(let ((results nil))
(dotimes (ignore ,I)
(multiple-value-bind (ignore time) (elapsed-time ,form)
(declare (ignore ignore))
(if (< time *min-time*)
(format t "~% Warning. Evaluating ~S took only ~S seconds.~
~% You should probably use more iterations." ',form time))
(push time results)))
(nth ,(truncate I 2) (sort results #'<)))))
#+debug
(defun test () (median-time (sleep 1.0)))
five times and the median value is returned . Variance in the numbers increases
(defmacro repeat (form N)
(let ((count (gensym)) (result (gensym)))
`(let ((,count ,N) ,result)
(loop
(setq ,result ,form)
(if (zerop (decf ,count)) (return ,result))))))
(defun nempty (N)
"The empty loop."
(repeat nil N))
(defun empty-speed (N) (median-time (nempty N)))
(defun compute-empty-iterations (&optional (default 1000000))
(format t "~%Computing speed of empty loop...")
(let ((time nil))
(loop
(setq time (empty-speed default))
(if (< time *min-time*) (setq default (* default 10)) (return)))
(format t "done.")
default))
(defvar *empty-iterations*)
(defvar *speed-of-empty-loop*)
(eval-when (load eval)
(setq *empty-iterations* (compute-empty-iterations))
(setq *speed-of-empty-loop* (/ (empty-speed *empty-iterations*)
(float *empty-iterations*))))
(defmacro operations-per-second (form N &optional (I 5))
"Return the number of times FORM can evaluate in one second."
`(let ((time (median-time (repeat ,form ,N) ,I)))
(/ (float ,N) (- time (* *speed-of-empty-loop* N)))))
(defmacro bench (pretty-name name N &optional (stream t))
`(format ,stream "~%~A: ~30T~S" ,pretty-name (,name ,N)))
BENCH - THIS - LISP
(defun Nmult (N)
(let ((a 2.1))
(operations-per-second (* a a) N)))
(defun Nadd (N)
(let ((a 2.1))
(operations-per-second (+ a a) N)))
(defun square (x) (* x x))
(defun funcall-1 (N)
(let ((x 2.1))
(operations-per-second (funcall #'(lambda (a) (* a a)) x) N)))
(defun f1 (n) n)
(defun funcall-2 (N)
(let ((f #'f1)
(x 2.1))
(operations-per-second (funcall f x) N)))
(defun funcall-3 (N)
(let ((x 2.1))
(operations-per-second (f1 x) N)))
(defun funcall-4 (N)
(let ((x 2.1))
(operations-per-second (funcall #'square x) N)))
(defun funcall-5 (N)
(let ((x 2.1)
(f #'square))
(let ((g #'(lambda (x)
(operations-per-second (funcall f x) N))))
(funcall g x))))
(defun Nsetf (N)
(let ((array (make-array 15)))
(operations-per-second (setf (aref array 5) t) N)))
(defun Nsymeval (N) (operations-per-second (eval T) N))
(defun Repeatuations (N) (operations-per-second (eval '(* 2.1 2.1)) N))
(defun n-cons (N) (let ((a 1)) (operations-per-second (cons a a) N)))
(defvar *object* t)
(Defun nspecial (N) (operations-per-second (null *object*) N))
(defun nlexical (N)
(let ((o t))
(operations-per-second (null o) N)))
(defun nfree (N)
(let ((o t))
(let ((g #'(lambda ()
#+genera (declare (sys:downward-function))
(operations-per-second (null o) N))))
(funcall g))))
(defun nfree2 (N)
(let ((o t))
(let ((g #'(lambda ()
(let ((f #'(lambda ()
#+genera (declare (sys:downward-function))
(operations-per-second (null o) N))))
(funcall f)))))
(funcall g))))
(defun ncompilations (N)
(let ((lambda-expression
'(lambda (bar) (let ((baz t)) (if baz (cons bar nil))))))
(operations-per-second (compile 'bob lambda-expression) N)))
(defun bench-this-lisp ()
(let ((N (/ *empty-iterations* 10)))
(bench "(* 2.1 2.1)" nmult N)
(bench "(+ 2.1 2.1)" nadd N)
(bench "funcall & (* 2.1 2.1)" funcall-3 N)
(bench "special reference" nspecial *empty-iterations*)
(bench "lexical reference" nlexical *empty-iterations*)
(bench "(setf (aref array 5) t)" nsetf N)
(bench "(funcall lexical-f x)" funcall-2 N)
(bench "(f x)" funcall-3 N)
( Bench " ( eval t ) " nsymeval 10000 )
( bench " ( eval ' ( * 2.1 2.1 ) ) " repeatuations 10000 )
( bench " ( cons 1 2 ) " n - cons 100000 )
( bench " compile simple function " ncompilations 50 )
))
#+genera
(progn
(scl:defflavor bar (a b) ()
:initable-instance-variables
:writable-instance-variables)
(scl:defflavor frob (c) (bar)
:initable-instance-variables
:writable-instance-variables)
(scl:defmethod (hop bar) ()
a)
(scl:defmethod (set-hop bar) (n)
(setq a n))
(scl:defmethod (nohop bar) ()
5)
(defun n-ivar-ref (N)
(let ((i (scl:make-instance 'bar :a 0 :b 0)))
(ivar-ref i N)))
(scl:defmethod (ivar-ref bar) (N)
(operations-per-second b N))
(defun Ninstances (N) (operations-per-second (flavor:make-instance 'bar) N))
(defun n-svref (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (scl:symbol-value-in-instance instance 'a) N)))
(defun n-hop (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (hop instance) n)))
(defun n-gf (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (nohop instance) n)))
(defun n-set-hop (N)
(let ((instance (flavor:make-instance 'bar :a 1)))
(operations-per-second (set-hop instance) n)))
(defun n-type-of (N)
(let ((instance (flavor:make-instance 'bar)))
(operations-per-second (flavor::%instance-flavor instance) N)))
(defun n-bar-b (N)
(let ((instance (flavor:make-instance 'bar :a 0 :b 0)))
(operations-per-second (bar-b instance) N)))
(defun n-frob-bar-b (N)
(let ((instance (flavor:make-instance 'frob :a 0 :b 0)))
(operations-per-second (bar-b instance) N)))
(defun bench-flavors ()
(bench "flavor:make-instance (2 slots)" ninstances 5000)
(bench "flavor:symbol-value-in-instance" n-svref 100000)
(bench "1 method, 1 dispatch" n-gf 100000)
(bench "slot symbol in method (access)" n-hop 100000)
(bench "slot symbol in method (modify)" n-hop 100000)
(bench "slot accessor bar" n-bar-b 100000)
(bench "slot accessor frob" n-frob-bar-b 100000)
(bench "instance-flavor" n-type-of 500000))
BENCH - THIS - CLOS
( evolved from tests of Symbolics CLOS )
(defclass point
()
((x :initform 0 :accessor x :initarg :x)
(y :initform 0 :accessor y :initarg :y)))
(defmethod color ((thing point)) 'red)
(defmethod address ((thing point)) 'boston)
(defmethod area ((thing point)) 0)
(defmethod move-to ((p1 point) (p2 point)) 0)
(defmethod x-offset ((thing point))
(with-slots (x y) thing x))
(defmethod set-x-offset ((thing point) new-x)
(with-slots (x y) thing (setq x new-x)))
(defclass box
(point)
((width :initform 10 :accessor width :initarg :width)
(height :initform 10 :accessor height :initarg :height)))
(defmethod area ((thing box)) 0)
(defmethod move-to ((box box) (point point)) 0)
(defmethod address :around ((thing box)) (call-next-method))
(defvar p (make-instance 'point))
(defvar b (make-instance 'box))
(defun n-strange (N) (operations-per-second (strange 5) N))
(defun n-accesses (N)
(let ((instance p))
(operations-per-second (x instance) N)))
(defun n-color (N)
(let ((instance p))
(operations-per-second (color instance) n)))
(defun n-call-next-method (N)
(let ((instance b))
(operations-per-second (address instance) n)))
(defun n-area-1 (N)
(let ((instance p))
(operations-per-second (area instance) n)))
(defun n-area-2 (N)
(operations-per-second (area 5) n))
(defun n-move-1 (N)
(let ((instance p))
(operations-per-second (move-to instance instance) n)))
(defun n-move-2 (N)
(let ((x p) (y b))
(operations-per-second (move-to x y) n)))
(defun n-off (N)
(let ((instance p))
(operations-per-second (x-offset instance) n)))
(defun n-setoff (N)
(let ((instance p))
(operations-per-second (set-x-offset instance 500) n)))
(defun n-slot-value (N)
(let ((instance p))
(operations-per-second (slot-value instance 'x) n)))
(defun n-class-of-1 (N)
(let ((instance p))
(operations-per-second (class-of instance) n)))
(defun n-class-of-2 (N)
(operations-per-second (class-of 5) n))
(defun n-alloc (N)
(let ((c (find-class 'point)))
(operations-per-second (allocate-instance c) n)))
(defun n-make (N)
(operations-per-second (make-instance 'point) n))
(defun n-make-initargs (N)
(operations-per-second (make-instance 'point :x 0 :y 5) n))
(defun n-make-variable-initargs (N)
(let ((x 0)
(y 5))
(operations-per-second (make-instance 'point :x x :y y) n)))
(pcl::expanding-make-instance-top-level
(defun n-make1 (N)
(operations-per-second (make-instance 'point) n))
(defun n-make-initargs1 (N)
(operations-per-second (make-instance 'point :x 0 :y 5) n))
(defun n-make-variable-initargs1 (N)
(let ((x 0)
(y 5))
(operations-per-second (make-instance 'point :x x :y y) n)))
)
(pcl::precompile-random-code-segments)
(defun bench-this-clos ()
(let ((N (/ *empty-iterations* 10)))
(bench "1 default method" n-strange N)
(bench "1 dispatch, 1 method" n-color N)
(bench "1 dispatch, :around + primary" n-call-next-method N)
(bench "1 dispatch, 3 methods, instance" n-area-1 N)
(bench "1 dispatch, 3 methods, noninstance" n-area-2 N)
(bench "2 dispatch, 2 methods" n-move-1 N)
(bench "slot reader method" n-accesses N)
(bench "with-slots (1 access)" n-off N)
(bench "with-slots (1 modify)" n-setoff N)
(bench "naked slot-value" n-slot-value N)
(bench "class-of instance" n-class-of-1 N)
(bench "class-of noninstance" n-class-of-2 N)
(bench "allocate-instance (2 slots)" n-alloc
#+pcl 5000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 slots)" n-make
#+pcl 5000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 constant initargs)" n-make-initargs
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 variable initargs)" n-make-variable-initargs
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 slots)" n-make1
#+pcl 5000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 constant initargs)" n-make-initargs1
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)
(bench "make-instance (2 variable initargs)" n-make-variable-initargs1
#+pcl 1000
#+allegro 100000
#+(and Genera (not pcl)) 100000
#+(and Lucid (not pcl)) 10000)) )
|
788002ecdb5d8373a7f1f9fb63510e0b8dfed6c23d48594fecea55e4b182199b
|
hiratara/Haskell-Nyumon-Sample
|
chap02-samples-2-6-2-case.hs
|
x = False :: Bool
main = print $ case x of True -> "x is True"
False -> "x is False"
| null |
https://raw.githubusercontent.com/hiratara/Haskell-Nyumon-Sample/ac52b741e3b96722f6fc104cfa84078e39f7a241/chap02-samples/chap02-samples-2-6-2-case.hs
|
haskell
|
x = False :: Bool
main = print $ case x of True -> "x is True"
False -> "x is False"
|
|
1fff063bfd8bc53db38024dc1fa90ba0384b2b44ca7ddd80965e28abd3d676fa
|
rbkmoney/cds
|
cds_card_validation_tests_SUITE.erl
|
-module(cds_card_validation_tests_SUITE).
-include_lib("damsel/include/dmsl_cds_thrift.hrl").
-export([all/0]).
-export([groups/0]).
-export([full_card_data_validation/1]).
-export([payment_system_detection/1]).
%%
%%
%% tests descriptions
%%
-define(AUTH_CVV(CVV), #{auth_data => #{cvv => CVV}}).
-type config() :: term().
-spec all() -> [{group, atom()}].
all() ->
[
{group, card_data_validation}
].
-spec groups() -> [{atom(), list(), [atom()]}].
groups() ->
[
{card_data_validation, [parallel], [
full_card_data_validation,
payment_system_detection
]}
].
%%
%% tests
%%
-spec full_card_data_validation(config()) -> _.
full_card_data_validation(_C) ->
MC = #{
cardnumber => <<"5321301234567892">>,
exp_date => {12, 3000},
cardholder => <<"Benedict Wizardcock">>
},
{ok, #{
payment_system := mastercard,
iin := <<"532130">>,
last_digits := <<"7892">>
}} = cds_card_data:get_card_info(MC),
MIR = #{
cardnumber => <<"2204301234567891">>,
exp_date => {12, 3000},
cardholder => <<"Benedict Wizardcock">>
},
{ok, #{
payment_system := nspkmir,
iin := <<"22043012">>,
last_digits := <<"91">>
}} = cds_card_data:get_card_info(MIR),
{ok, #{
payment_system := mastercard,
iin := <<"532130">>,
last_digits := <<"7892">>
}} = cds_card_data:get_card_info(MC),
ok.
-spec payment_system_detection(config()) -> _.
payment_system_detection(_C) ->
[
{ok, #{payment_system := Target}} = cds_card_data:get_card_info(Sample)
|| {Target, Sample} <- get_card_data_samples()
].
%%
%% helpers
%%
get_card_data_samples() ->
Samples = [
{amex, <<"378282246310005">>},
{amex, <<"371449635398431">>},
{amex, <<"378734493671000">>},
{dinersclub, <<"30569309025904">>},
{dinersclub, <<"38520000023237">>},
{dinersclub, <<"36213154429663">>},
{discover, <<"6011111111111117">>},
{discover, <<"6011000990139424">>},
{jcb, <<"3530111333300000">>},
{jcb, <<"3566002020360505">>},
{mastercard, <<"5555555555554444">>},
{mastercard, <<"5105105105105100">>},
{visa, <<"4716219619821724">>},
{visa, <<"4929221444411666">>},
{visa, <<"4929003096554179">>},
{visaelectron, <<"4508085628009599">>},
{visaelectron, <<"4508964269455370">>},
{visaelectron, <<"4026524202025897">>},
{unionpay, <<"6279227608204863">>},
{unionpay, <<"6238464198841867">>},
{unionpay, <<"6263242460178483">>},
{dankort, <<"5019717010103742">>},
{nspkmir, <<"2202243736741990">>},
{nspkmir, <<"2200330595609485549">>},
{forbrugsforeningen, <<"6007220000000004">>}
],
[
begin
{
Target,
#{cardnumber => CN}
}
end
|| {Target, CN} <- Samples
].
| null |
https://raw.githubusercontent.com/rbkmoney/cds/6e6541c99d34b0633775f0c5304f5008e6b2aaf3/apps/cds/test/cds_card_validation_tests_SUITE.erl
|
erlang
|
tests descriptions
tests
helpers
|
-module(cds_card_validation_tests_SUITE).
-include_lib("damsel/include/dmsl_cds_thrift.hrl").
-export([all/0]).
-export([groups/0]).
-export([full_card_data_validation/1]).
-export([payment_system_detection/1]).
-define(AUTH_CVV(CVV), #{auth_data => #{cvv => CVV}}).
-type config() :: term().
-spec all() -> [{group, atom()}].
all() ->
[
{group, card_data_validation}
].
-spec groups() -> [{atom(), list(), [atom()]}].
groups() ->
[
{card_data_validation, [parallel], [
full_card_data_validation,
payment_system_detection
]}
].
-spec full_card_data_validation(config()) -> _.
full_card_data_validation(_C) ->
MC = #{
cardnumber => <<"5321301234567892">>,
exp_date => {12, 3000},
cardholder => <<"Benedict Wizardcock">>
},
{ok, #{
payment_system := mastercard,
iin := <<"532130">>,
last_digits := <<"7892">>
}} = cds_card_data:get_card_info(MC),
MIR = #{
cardnumber => <<"2204301234567891">>,
exp_date => {12, 3000},
cardholder => <<"Benedict Wizardcock">>
},
{ok, #{
payment_system := nspkmir,
iin := <<"22043012">>,
last_digits := <<"91">>
}} = cds_card_data:get_card_info(MIR),
{ok, #{
payment_system := mastercard,
iin := <<"532130">>,
last_digits := <<"7892">>
}} = cds_card_data:get_card_info(MC),
ok.
-spec payment_system_detection(config()) -> _.
payment_system_detection(_C) ->
[
{ok, #{payment_system := Target}} = cds_card_data:get_card_info(Sample)
|| {Target, Sample} <- get_card_data_samples()
].
get_card_data_samples() ->
Samples = [
{amex, <<"378282246310005">>},
{amex, <<"371449635398431">>},
{amex, <<"378734493671000">>},
{dinersclub, <<"30569309025904">>},
{dinersclub, <<"38520000023237">>},
{dinersclub, <<"36213154429663">>},
{discover, <<"6011111111111117">>},
{discover, <<"6011000990139424">>},
{jcb, <<"3530111333300000">>},
{jcb, <<"3566002020360505">>},
{mastercard, <<"5555555555554444">>},
{mastercard, <<"5105105105105100">>},
{visa, <<"4716219619821724">>},
{visa, <<"4929221444411666">>},
{visa, <<"4929003096554179">>},
{visaelectron, <<"4508085628009599">>},
{visaelectron, <<"4508964269455370">>},
{visaelectron, <<"4026524202025897">>},
{unionpay, <<"6279227608204863">>},
{unionpay, <<"6238464198841867">>},
{unionpay, <<"6263242460178483">>},
{dankort, <<"5019717010103742">>},
{nspkmir, <<"2202243736741990">>},
{nspkmir, <<"2200330595609485549">>},
{forbrugsforeningen, <<"6007220000000004">>}
],
[
begin
{
Target,
#{cardnumber => CN}
}
end
|| {Target, CN} <- Samples
].
|
19c7c57ec30e7ed30f74d82117536a9edae77d5a3ed2fed1f7daef293f4606b9
|
ndmitchell/shake
|
Demo.hs
|
-- | Demo tutorial, accessed with --demo
module Development.Shake.Internal.Demo(demo) where
import Development.Shake.Internal.Paths
import Development.Shake.Command
import Control.Exception.Extra
import Control.Monad
import Data.List.Extra
import Data.Maybe
import System.Directory
import System.Exit
import System.FilePath
import General.Extra
import Development.Shake.FilePath(exe)
import System.IO
import System.Info.Extra
demo :: Bool -> IO ()
demo auto = do
hSetBuffering stdout NoBuffering
putStrLn $ "% Welcome to the Shake v" ++ shakeVersionString ++ " demo mode!"
putStr "% Detecting machine configuration... "
hasManual <- hasManualData
ghc <- isJust <$> findExecutable "ghc"
(gcc, gccPath) <- findGcc
shakeLib <- wrap $ fmap (not . null . words . fromStdout) (cmd ("ghc-pkg list --simple-output shake" :: String))
ninja <- findExecutable "ninja"
putStrLn "done\n"
let path = if isWindows then "%PATH%" else "$PATH"
require ghc $ "% You don't have 'ghc' on your " ++ path ++ ", which is required to run the demo."
require gcc $ "% You don't have 'gcc' on your " ++ path ++ ", which is required to run the demo."
require shakeLib "% You don't have the 'shake' library installed with GHC, which is required to run the demo."
require hasManual "% You don't have the Shake data files installed, which are required to run the demo."
empty <- all (all (== '.')) <$> getDirectoryContents "."
dir <- if empty then getCurrentDirectory else do
home <- getHomeDirectory
dir <- getDirectoryContents home
pure $ home </> head (map ("shake-demo" ++) ("":map show [2..]) \\ dir)
putStrLn "% The Shake demo uses an empty directory, OK to use:"
putStrLn $ "% " ++ dir
b <- yesNo auto
require b "% Please create an empty directory to run the demo from, then run 'shake --demo' again."
putStr "% Copying files... "
copyManualData dir
unless isWindows $ do
p <- getPermissions $ dir </> "build.sh"
setPermissions (dir </> "build.sh") p{executable=True}
putStrLn "done"
let pause = do
putStr "% Press ENTER to continue: "
if auto then putLine "" else getLine
let execute x = do
putStrLn $ "% RUNNING: " ++ x
cmd (Cwd dir) (AddPath [] (maybeToList gccPath)) Shell x :: IO ()
let build = if isWindows then "build" else "./build.sh"
putStrLn "\n% [1/5] Building an example project with Shake."
pause
putStrLn $ "% RUNNING: cd " ++ dir
execute build
putStrLn "\n% [2/5] Running the produced example."
pause
execute $ "_build" </> "run" <.> exe
putStrLn "\n% [3/5] Rebuilding an example project with Shake (nothing should change)."
pause
execute build
putStrLn "\n% [4/5] Cleaning the build."
pause
execute $ build ++ " clean"
putStrLn "\n% [5/5] Rebuilding with 2 threads and profiling."
pause
execute $ build ++ " -j2 --report --report=-"
putStrLn "\n% See the profiling summary above, or look at the HTML profile report in"
putStrLn $ "% " ++ dir </> "report.html"
putStrLn "\n% Demo complete - all the examples can be run from:"
putStrLn $ "% " ++ dir
putStrLn "% For more info see "
when (isJust ninja) $ do
putStrLn "\n% PS. Shake can also execute Ninja build files"
putStrLn "% For more info see "
-- | Require the user to press @y@ before continuing.
yesNo :: Bool -> IO Bool
yesNo auto = do
putStr "% [Y/N] (then ENTER): "
x <- if auto then putLine "y" else lower <$> getLine
if "y" `isPrefixOf` x then
pure True
else if "n" `isPrefixOf` x then
pure False
else
yesNo auto
putLine :: String -> IO String
putLine x = putStrLn x >> pure x
-- | Replace exceptions with 'False'.
wrap :: IO Bool -> IO Bool
wrap act = act `catch_` const (pure False)
-- | Require a condition to be true, or exit with a message.
require :: Bool -> String -> IO ()
require b msg = unless b $ putStrLn msg >> exitFailure
| null |
https://raw.githubusercontent.com/ndmitchell/shake/99c5a7a4dc1d5a069b13ed5c1bc8e4bc7f13f4a6/src/Development/Shake/Internal/Demo.hs
|
haskell
|
| Demo tutorial, accessed with --demo
| Require the user to press @y@ before continuing.
| Replace exceptions with 'False'.
| Require a condition to be true, or exit with a message.
|
module Development.Shake.Internal.Demo(demo) where
import Development.Shake.Internal.Paths
import Development.Shake.Command
import Control.Exception.Extra
import Control.Monad
import Data.List.Extra
import Data.Maybe
import System.Directory
import System.Exit
import System.FilePath
import General.Extra
import Development.Shake.FilePath(exe)
import System.IO
import System.Info.Extra
demo :: Bool -> IO ()
demo auto = do
hSetBuffering stdout NoBuffering
putStrLn $ "% Welcome to the Shake v" ++ shakeVersionString ++ " demo mode!"
putStr "% Detecting machine configuration... "
hasManual <- hasManualData
ghc <- isJust <$> findExecutable "ghc"
(gcc, gccPath) <- findGcc
shakeLib <- wrap $ fmap (not . null . words . fromStdout) (cmd ("ghc-pkg list --simple-output shake" :: String))
ninja <- findExecutable "ninja"
putStrLn "done\n"
let path = if isWindows then "%PATH%" else "$PATH"
require ghc $ "% You don't have 'ghc' on your " ++ path ++ ", which is required to run the demo."
require gcc $ "% You don't have 'gcc' on your " ++ path ++ ", which is required to run the demo."
require shakeLib "% You don't have the 'shake' library installed with GHC, which is required to run the demo."
require hasManual "% You don't have the Shake data files installed, which are required to run the demo."
empty <- all (all (== '.')) <$> getDirectoryContents "."
dir <- if empty then getCurrentDirectory else do
home <- getHomeDirectory
dir <- getDirectoryContents home
pure $ home </> head (map ("shake-demo" ++) ("":map show [2..]) \\ dir)
putStrLn "% The Shake demo uses an empty directory, OK to use:"
putStrLn $ "% " ++ dir
b <- yesNo auto
require b "% Please create an empty directory to run the demo from, then run 'shake --demo' again."
putStr "% Copying files... "
copyManualData dir
unless isWindows $ do
p <- getPermissions $ dir </> "build.sh"
setPermissions (dir </> "build.sh") p{executable=True}
putStrLn "done"
let pause = do
putStr "% Press ENTER to continue: "
if auto then putLine "" else getLine
let execute x = do
putStrLn $ "% RUNNING: " ++ x
cmd (Cwd dir) (AddPath [] (maybeToList gccPath)) Shell x :: IO ()
let build = if isWindows then "build" else "./build.sh"
putStrLn "\n% [1/5] Building an example project with Shake."
pause
putStrLn $ "% RUNNING: cd " ++ dir
execute build
putStrLn "\n% [2/5] Running the produced example."
pause
execute $ "_build" </> "run" <.> exe
putStrLn "\n% [3/5] Rebuilding an example project with Shake (nothing should change)."
pause
execute build
putStrLn "\n% [4/5] Cleaning the build."
pause
execute $ build ++ " clean"
putStrLn "\n% [5/5] Rebuilding with 2 threads and profiling."
pause
execute $ build ++ " -j2 --report --report=-"
putStrLn "\n% See the profiling summary above, or look at the HTML profile report in"
putStrLn $ "% " ++ dir </> "report.html"
putStrLn "\n% Demo complete - all the examples can be run from:"
putStrLn $ "% " ++ dir
putStrLn "% For more info see "
when (isJust ninja) $ do
putStrLn "\n% PS. Shake can also execute Ninja build files"
putStrLn "% For more info see "
yesNo :: Bool -> IO Bool
yesNo auto = do
putStr "% [Y/N] (then ENTER): "
x <- if auto then putLine "y" else lower <$> getLine
if "y" `isPrefixOf` x then
pure True
else if "n" `isPrefixOf` x then
pure False
else
yesNo auto
putLine :: String -> IO String
putLine x = putStrLn x >> pure x
wrap :: IO Bool -> IO Bool
wrap act = act `catch_` const (pure False)
require :: Bool -> String -> IO ()
require b msg = unless b $ putStrLn msg >> exitFailure
|
804970a37f7907fb073b0e9414fe3dc6e1ba6d706616c38857c957acf33eab7b
|
exercism/ocaml
|
example.ml
|
open Base
let is_empty = String.for_all ~f:Char.is_whitespace
let is_shouting s =
String.exists ~f:Char.is_alpha s &&
String.for_all ~f:(fun c -> not (Char.is_alpha c) || Char.is_uppercase c) s
let is_question s = Char.(s.[String.length s - 1] = '?')
let response_for s =
let s = String.strip s in
match s with
| s when is_empty s -> "Fine. Be that way!"
| s when is_shouting s -> if is_question s then "Calm down, I know what I'm doing!" else "Whoa, chill out!"
| s when is_question s -> "Sure."
| _ -> "Whatever."
| null |
https://raw.githubusercontent.com/exercism/ocaml/914e58d48e58a96fe7635fe4b06cc103af4ed683/exercises/practice/bob/.meta/example.ml
|
ocaml
|
open Base
let is_empty = String.for_all ~f:Char.is_whitespace
let is_shouting s =
String.exists ~f:Char.is_alpha s &&
String.for_all ~f:(fun c -> not (Char.is_alpha c) || Char.is_uppercase c) s
let is_question s = Char.(s.[String.length s - 1] = '?')
let response_for s =
let s = String.strip s in
match s with
| s when is_empty s -> "Fine. Be that way!"
| s when is_shouting s -> if is_question s then "Calm down, I know what I'm doing!" else "Whoa, chill out!"
| s when is_question s -> "Sure."
| _ -> "Whatever."
|
|
2aadb30a439324eacb81f9c7f5167e048bf40b6f0b2a653236265c1cddef93cb
|
ucsd-progsys/nate
|
lambda.mli
|
(***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : lambda.mli , v 1.43 2007/02/09 13:31:15 doligez Exp $
(* The "lambda" intermediate code *)
open Asttypes
type primitive =
Pidentity
| Pignore
(* Globals *)
| Pgetglobal of Ident.t
| Psetglobal of Ident.t
(* Operations on heap blocks *)
| Pmakeblock of int * mutable_flag
| Pfield of int
| Psetfield of int * bool
| Pfloatfield of int
| Psetfloatfield of int
| Pduprecord of Types.record_representation * int
(* External call *)
| Pccall of Primitive.description
(* Exceptions *)
| Praise
Boolean operations
| Psequand | Psequor | Pnot
Integer operations
| Pnegint | Paddint | Psubint | Pmulint | Pdivint | Pmodint
| Pandint | Porint | Pxorint
| Plslint | Plsrint | Pasrint
| Pintcomp of comparison
| Poffsetint of int
| Poffsetref of int
(* Float operations *)
| Pintoffloat | Pfloatofint
| Pnegfloat | Pabsfloat
| Paddfloat | Psubfloat | Pmulfloat | Pdivfloat
| Pfloatcomp of comparison
(* String operations *)
| Pstringlength | Pstringrefu | Pstringsetu | Pstringrefs | Pstringsets
(* Array operations *)
| Pmakearray of array_kind
| Parraylength of array_kind
| Parrayrefu of array_kind
| Parraysetu of array_kind
| Parrayrefs of array_kind
| Parraysets of array_kind
(* Test if the argument is a block or an immediate integer *)
| Pisint
(* Test if the (integer) argument is outside an interval *)
| Pisout
Bitvect operations
| Pbittest
Operations on boxed integers ( Nativeint.t , Int32.t , Int64.t )
| Pbintofint of boxed_integer
| Pintofbint of boxed_integer
| Pcvtbint of boxed_integer (*source*) * boxed_integer (*destination*)
| Pnegbint of boxed_integer
| Paddbint of boxed_integer
| Psubbint of boxed_integer
| Pmulbint of boxed_integer
| Pdivbint of boxed_integer
| Pmodbint of boxed_integer
| Pandbint of boxed_integer
| Porbint of boxed_integer
| Pxorbint of boxed_integer
| Plslbint of boxed_integer
| Plsrbint of boxed_integer
| Pasrbint of boxed_integer
| Pbintcomp of boxed_integer * comparison
(* Operations on big arrays *)
| Pbigarrayref of int * bigarray_kind * bigarray_layout
| Pbigarrayset of int * bigarray_kind * bigarray_layout
and comparison =
Ceq | Cneq | Clt | Cgt | Cle | Cge
and array_kind =
Pgenarray | Paddrarray | Pintarray | Pfloatarray
and boxed_integer =
Pnativeint | Pint32 | Pint64
and bigarray_kind =
Pbigarray_unknown
| Pbigarray_float32 | Pbigarray_float64
| Pbigarray_sint8 | Pbigarray_uint8
| Pbigarray_sint16 | Pbigarray_uint16
| Pbigarray_int32 | Pbigarray_int64
| Pbigarray_caml_int | Pbigarray_native_int
| Pbigarray_complex32 | Pbigarray_complex64
and bigarray_layout =
Pbigarray_unknown_layout
| Pbigarray_c_layout
| Pbigarray_fortran_layout
type structured_constant =
Const_base of constant
| Const_pointer of int
| Const_block of int * structured_constant list
| Const_float_array of string list
| Const_immstring of string
type function_kind = Curried | Tupled
type let_kind = Strict | Alias | StrictOpt | Variable
Meaning of kinds for let x = e in e ' :
Strict : e may have side - effets ; always evaluate e first
( If e is a simple expression , e.g. a variable or constant ,
we may still substitute e'[x / e ] . )
Alias : e is pure , we can substitute e'[x / e ] if x has 0 or 1 occurrences
in e '
StrictOpt : e does not have side - effects , but depend on the store ;
we can discard e if x does not appear in e '
Variable : the variable x is assigned later in e '
Strict: e may have side-effets; always evaluate e first
(If e is a simple expression, e.g. a variable or constant,
we may still substitute e'[x/e].)
Alias: e is pure, we can substitute e'[x/e] if x has 0 or 1 occurrences
in e'
StrictOpt: e does not have side-effects, but depend on the store;
we can discard e if x does not appear in e'
Variable: the variable x is assigned later in e' *)
type meth_kind = Self | Public | Cached
type shared_code = (int * int) list (* stack size -> code label *)
type lambda =
Lvar of Ident.t
| Lconst of structured_constant
| Lapply of lambda * lambda list
| Lfunction of function_kind * Ident.t list * lambda
| Llet of let_kind * Ident.t * lambda * lambda
| Lletrec of (Ident.t * lambda) list * lambda
| Lprim of primitive * lambda list
| Lswitch of lambda * lambda_switch
| Lstaticraise of int * lambda list
| Lstaticcatch of lambda * (int * Ident.t list) * lambda
| Ltrywith of lambda * Ident.t * lambda
| Lifthenelse of lambda * lambda * lambda
| Lsequence of lambda * lambda
| Lwhile of lambda * lambda
| Lfor of Ident.t * lambda * lambda * direction_flag * lambda
| Lassign of Ident.t * lambda
| Lsend of meth_kind * lambda * lambda * lambda list
| Levent of lambda * lambda_event
| Lifused of Ident.t * lambda
and lambda_switch =
{ sw_numconsts: int; (* Number of integer cases *)
Integer cases
sw_numblocks: int; (* Number of tag block cases *)
sw_blocks: (int * lambda) list; (* Tag block cases *)
sw_failaction : lambda option} (* Action to take if failure *)
and lambda_event =
{ lev_loc: Location.t;
lev_kind: lambda_event_kind;
lev_repr: int ref option;
lev_env: Env.summary }
and lambda_event_kind =
Lev_before
| Lev_after of Types.type_expr
| Lev_function
val same: lambda -> lambda -> bool
val const_unit: structured_constant
val lambda_unit: lambda
val name_lambda: lambda -> (Ident.t -> lambda) -> lambda
val name_lambda_list: lambda list -> (lambda list -> lambda) -> lambda
val is_guarded: lambda -> bool
val patch_guarded : lambda -> lambda -> lambda
val iter: (lambda -> unit) -> lambda -> unit
module IdentSet: Set.S with type elt = Ident.t
val free_variables: lambda -> IdentSet.t
val free_methods: lambda -> IdentSet.t
val transl_path: Path.t -> lambda
val make_sequence: ('a -> lambda) -> 'a list -> lambda
val subst_lambda: lambda Ident.tbl -> lambda -> lambda
val bind : let_kind -> Ident.t -> lambda -> lambda -> lambda
val commute_comparison : comparison -> comparison
val negate_comparison : comparison -> comparison
(***********************)
(* For static failures *)
(***********************)
(* Get a new static failure ident *)
val next_raise_count : unit -> int
val staticfail : lambda (* Anticipated static failure *)
(* Check anticipated failure, substitute its final value *)
val is_guarded: lambda -> bool
val patch_guarded : lambda -> lambda -> lambda
| null |
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/bytecomp/lambda.mli
|
ocaml
|
*********************************************************************
Objective Caml
*********************************************************************
The "lambda" intermediate code
Globals
Operations on heap blocks
External call
Exceptions
Float operations
String operations
Array operations
Test if the argument is a block or an immediate integer
Test if the (integer) argument is outside an interval
source
destination
Operations on big arrays
stack size -> code label
Number of integer cases
Number of tag block cases
Tag block cases
Action to take if failure
*********************
For static failures
*********************
Get a new static failure ident
Anticipated static failure
Check anticipated failure, substitute its final value
|
, projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : lambda.mli , v 1.43 2007/02/09 13:31:15 doligez Exp $
open Asttypes
type primitive =
Pidentity
| Pignore
| Pgetglobal of Ident.t
| Psetglobal of Ident.t
| Pmakeblock of int * mutable_flag
| Pfield of int
| Psetfield of int * bool
| Pfloatfield of int
| Psetfloatfield of int
| Pduprecord of Types.record_representation * int
| Pccall of Primitive.description
| Praise
Boolean operations
| Psequand | Psequor | Pnot
Integer operations
| Pnegint | Paddint | Psubint | Pmulint | Pdivint | Pmodint
| Pandint | Porint | Pxorint
| Plslint | Plsrint | Pasrint
| Pintcomp of comparison
| Poffsetint of int
| Poffsetref of int
| Pintoffloat | Pfloatofint
| Pnegfloat | Pabsfloat
| Paddfloat | Psubfloat | Pmulfloat | Pdivfloat
| Pfloatcomp of comparison
| Pstringlength | Pstringrefu | Pstringsetu | Pstringrefs | Pstringsets
| Pmakearray of array_kind
| Parraylength of array_kind
| Parrayrefu of array_kind
| Parraysetu of array_kind
| Parrayrefs of array_kind
| Parraysets of array_kind
| Pisint
| Pisout
Bitvect operations
| Pbittest
Operations on boxed integers ( Nativeint.t , Int32.t , Int64.t )
| Pbintofint of boxed_integer
| Pintofbint of boxed_integer
| Pnegbint of boxed_integer
| Paddbint of boxed_integer
| Psubbint of boxed_integer
| Pmulbint of boxed_integer
| Pdivbint of boxed_integer
| Pmodbint of boxed_integer
| Pandbint of boxed_integer
| Porbint of boxed_integer
| Pxorbint of boxed_integer
| Plslbint of boxed_integer
| Plsrbint of boxed_integer
| Pasrbint of boxed_integer
| Pbintcomp of boxed_integer * comparison
| Pbigarrayref of int * bigarray_kind * bigarray_layout
| Pbigarrayset of int * bigarray_kind * bigarray_layout
and comparison =
Ceq | Cneq | Clt | Cgt | Cle | Cge
and array_kind =
Pgenarray | Paddrarray | Pintarray | Pfloatarray
and boxed_integer =
Pnativeint | Pint32 | Pint64
and bigarray_kind =
Pbigarray_unknown
| Pbigarray_float32 | Pbigarray_float64
| Pbigarray_sint8 | Pbigarray_uint8
| Pbigarray_sint16 | Pbigarray_uint16
| Pbigarray_int32 | Pbigarray_int64
| Pbigarray_caml_int | Pbigarray_native_int
| Pbigarray_complex32 | Pbigarray_complex64
and bigarray_layout =
Pbigarray_unknown_layout
| Pbigarray_c_layout
| Pbigarray_fortran_layout
type structured_constant =
Const_base of constant
| Const_pointer of int
| Const_block of int * structured_constant list
| Const_float_array of string list
| Const_immstring of string
type function_kind = Curried | Tupled
type let_kind = Strict | Alias | StrictOpt | Variable
Meaning of kinds for let x = e in e ' :
Strict : e may have side - effets ; always evaluate e first
( If e is a simple expression , e.g. a variable or constant ,
we may still substitute e'[x / e ] . )
Alias : e is pure , we can substitute e'[x / e ] if x has 0 or 1 occurrences
in e '
StrictOpt : e does not have side - effects , but depend on the store ;
we can discard e if x does not appear in e '
Variable : the variable x is assigned later in e '
Strict: e may have side-effets; always evaluate e first
(If e is a simple expression, e.g. a variable or constant,
we may still substitute e'[x/e].)
Alias: e is pure, we can substitute e'[x/e] if x has 0 or 1 occurrences
in e'
StrictOpt: e does not have side-effects, but depend on the store;
we can discard e if x does not appear in e'
Variable: the variable x is assigned later in e' *)
type meth_kind = Self | Public | Cached
type lambda =
Lvar of Ident.t
| Lconst of structured_constant
| Lapply of lambda * lambda list
| Lfunction of function_kind * Ident.t list * lambda
| Llet of let_kind * Ident.t * lambda * lambda
| Lletrec of (Ident.t * lambda) list * lambda
| Lprim of primitive * lambda list
| Lswitch of lambda * lambda_switch
| Lstaticraise of int * lambda list
| Lstaticcatch of lambda * (int * Ident.t list) * lambda
| Ltrywith of lambda * Ident.t * lambda
| Lifthenelse of lambda * lambda * lambda
| Lsequence of lambda * lambda
| Lwhile of lambda * lambda
| Lfor of Ident.t * lambda * lambda * direction_flag * lambda
| Lassign of Ident.t * lambda
| Lsend of meth_kind * lambda * lambda * lambda list
| Levent of lambda * lambda_event
| Lifused of Ident.t * lambda
and lambda_switch =
Integer cases
and lambda_event =
{ lev_loc: Location.t;
lev_kind: lambda_event_kind;
lev_repr: int ref option;
lev_env: Env.summary }
and lambda_event_kind =
Lev_before
| Lev_after of Types.type_expr
| Lev_function
val same: lambda -> lambda -> bool
val const_unit: structured_constant
val lambda_unit: lambda
val name_lambda: lambda -> (Ident.t -> lambda) -> lambda
val name_lambda_list: lambda list -> (lambda list -> lambda) -> lambda
val is_guarded: lambda -> bool
val patch_guarded : lambda -> lambda -> lambda
val iter: (lambda -> unit) -> lambda -> unit
module IdentSet: Set.S with type elt = Ident.t
val free_variables: lambda -> IdentSet.t
val free_methods: lambda -> IdentSet.t
val transl_path: Path.t -> lambda
val make_sequence: ('a -> lambda) -> 'a list -> lambda
val subst_lambda: lambda Ident.tbl -> lambda -> lambda
val bind : let_kind -> Ident.t -> lambda -> lambda -> lambda
val commute_comparison : comparison -> comparison
val negate_comparison : comparison -> comparison
val next_raise_count : unit -> int
val is_guarded: lambda -> bool
val patch_guarded : lambda -> lambda -> lambda
|
9f8d27caff094a56a29eeb76172dc664812110e007ceea2280978542e1a9fbfc
|
jyh/metaprl
|
nuprl_prog_1.ml
|
extends Ma_num_thy_1
open Dtactic
define unfold_switch : "switch"[]{'"t";'"b"} <-->
('"b" '"t")
define unfold_switch_case : "switch_case"[]{'"v";'"case";'"cont"} <-->
"lambda"[]{"x"."ifthenelse"[]{"beq_int"[]{'"x";'"v"};'"case";('"cont" '"x")}}
define unfold_switch_default : "switch_default"[]{'"body"} <-->
"lambda"[]{"x".'"body"}
define unfold_switch_done : "switch_done"[]{} <-->
"lambda"[]{"x"."!undefined"[]{}}
define unfold_case : "case"[]{'"value";'"body"} <-->
(('"body" '"value") '"value")
define unfold_case_default : "case_default"[]{'"body"} <-->
"lambda"[]{"value"."lambda"[]{"value".'"body"}}
define unfold_case_pair : "case_pair"[]{"x", "y".'"body"['"x";'"y"]} <-->
"lambda"[]{"value"."lambda"[]{"cont"."spread"[]{'"value";"x", "y".'"body"['"x";'"y"]}}}
define unfold_case_inl : "case_inl"[]{"x".'"body"['"x"];'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."decide"[]{'"value";"x".'"body"['"x"];"_".(('"cont" '"contvalue") '"contvalue")}}}
define unfold_case_inr : "case_inr"[]{"x".'"body"['"x"];'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."decide"[]{'"value";"_".(('"cont" '"contvalue") '"contvalue");"x".'"body"['"x"]}}}
define unfold_case_cons : "case_cons"[]{"x", "y".'"body"['"x";'"y"];'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."list_ind"[]{'"value";(('"cont" '"contvalue") '"contvalue");"hd", "tl", "f".'"body"['"hd";'"tl"]}}}
define unfold_case_nil : "case_nil"[]{'"body";'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."list_ind"[]{'"value";'"body";"hd", "tl", "f".(('"cont" '"contvalue") '"contvalue")}}}
define unfold_case_it : "case_it"[]{'"body"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue".'"body"}}
(**** display forms ****)
dform nuprl_switch_df : except_mode[src] :: "switch"[]{'"t";'"b"} =
`"" pushm[0:n] `"Switch(" slot{'"t"} `")" sbreak[""," "] `"" slot{'"b"} `""
popm `""
dform nuprl_switch_case_df : except_mode[src] :: "switch_case"[]{'"v";'"case";'"cont"} =
`"Case " slot{'"v"} `" => " pushm[0:n] `"" slot{'"case"} `"" popm `""
sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_switch_default_df : except_mode[src] :: "switch_default"[]{'"body"} =
`"Default => " pushm[0:n] `"" slot{'"body"} `"" popm `"" sbreak[""," "]
`"EndSwitch"
dform nuprl_switch_done_df : except_mode[src] :: "switch_done"[]{} =
`"EndSwitch"
dform nuprl_case_df : except_mode[src] :: "case"[]{'"value";'"body"} =
`"" pushm[0:n] `"Case(" slot{'"value"} `")" sbreak[""," "] `"" slot{'"body"} `""
popm `""
dform nuprl_case_default_df : except_mode[src] :: "case_default"[]{'"body"} =
`"" szone `"" pushm[4:n] `"Default =>" sbreak[""," "] `"" slot{'"body"} `""
popm `"" ezone `""
dform nuprl_case_pair_df : except_mode[src] :: "case_pair"[]{"x", "y".'"body"} =
`"" pushm[4:n] `"<" slot{'"x"} `"," slot{'"y"} `"> =>" sbreak[""," "] `""
slot{'"body"} `"" popm `""
dform nuprl_case_inl_df : except_mode[src] :: "case_inl"[]{"x".'"body";'"cont"} =
`"" pushm[4:n] `"inl(" slot{'"x"} `") =>" sbreak[""," "] `"" slot{'"body"} `""
popm `"" sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_inr_df : except_mode[src] :: "case_inr"[]{"x".'"body";'"cont"} =
`"" pushm[4:n] `"inr(" slot{'"x"} `") =>" sbreak[""," "] `"" slot{'"body"} `""
popm `"" sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_cons_df : except_mode[src] :: "case_cons"[]{"x", "y".'"body";'"cont"} =
`"" pushm[4:n] `"" slot{'"x"} `"::" slot{'"y"} `" =>" sbreak[""," "] `""
slot{'"body"} `"" popm `"" sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_nil_df : except_mode[src] :: "case_nil"[]{'"body";'"cont"} =
`"" pushm[4:n] `"[] =>" sbreak[""," "] `"" slot{'"body"} `"" popm `""
sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_it_df : except_mode[src] :: "case_it"[]{'"body"} =
`"" pushm[4:n] `"" cdot `" =>" sbreak[""," "] `"" slot{'"body"} `"" popm `""
| null |
https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/mesa/nuprl_prog_1.ml
|
ocaml
|
*** display forms ***
|
extends Ma_num_thy_1
open Dtactic
define unfold_switch : "switch"[]{'"t";'"b"} <-->
('"b" '"t")
define unfold_switch_case : "switch_case"[]{'"v";'"case";'"cont"} <-->
"lambda"[]{"x"."ifthenelse"[]{"beq_int"[]{'"x";'"v"};'"case";('"cont" '"x")}}
define unfold_switch_default : "switch_default"[]{'"body"} <-->
"lambda"[]{"x".'"body"}
define unfold_switch_done : "switch_done"[]{} <-->
"lambda"[]{"x"."!undefined"[]{}}
define unfold_case : "case"[]{'"value";'"body"} <-->
(('"body" '"value") '"value")
define unfold_case_default : "case_default"[]{'"body"} <-->
"lambda"[]{"value"."lambda"[]{"value".'"body"}}
define unfold_case_pair : "case_pair"[]{"x", "y".'"body"['"x";'"y"]} <-->
"lambda"[]{"value"."lambda"[]{"cont"."spread"[]{'"value";"x", "y".'"body"['"x";'"y"]}}}
define unfold_case_inl : "case_inl"[]{"x".'"body"['"x"];'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."decide"[]{'"value";"x".'"body"['"x"];"_".(('"cont" '"contvalue") '"contvalue")}}}
define unfold_case_inr : "case_inr"[]{"x".'"body"['"x"];'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."decide"[]{'"value";"_".(('"cont" '"contvalue") '"contvalue");"x".'"body"['"x"]}}}
define unfold_case_cons : "case_cons"[]{"x", "y".'"body"['"x";'"y"];'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."list_ind"[]{'"value";(('"cont" '"contvalue") '"contvalue");"hd", "tl", "f".'"body"['"hd";'"tl"]}}}
define unfold_case_nil : "case_nil"[]{'"body";'"cont"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue"."list_ind"[]{'"value";'"body";"hd", "tl", "f".(('"cont" '"contvalue") '"contvalue")}}}
define unfold_case_it : "case_it"[]{'"body"} <-->
"lambda"[]{"value"."lambda"[]{"contvalue".'"body"}}
dform nuprl_switch_df : except_mode[src] :: "switch"[]{'"t";'"b"} =
`"" pushm[0:n] `"Switch(" slot{'"t"} `")" sbreak[""," "] `"" slot{'"b"} `""
popm `""
dform nuprl_switch_case_df : except_mode[src] :: "switch_case"[]{'"v";'"case";'"cont"} =
`"Case " slot{'"v"} `" => " pushm[0:n] `"" slot{'"case"} `"" popm `""
sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_switch_default_df : except_mode[src] :: "switch_default"[]{'"body"} =
`"Default => " pushm[0:n] `"" slot{'"body"} `"" popm `"" sbreak[""," "]
`"EndSwitch"
dform nuprl_switch_done_df : except_mode[src] :: "switch_done"[]{} =
`"EndSwitch"
dform nuprl_case_df : except_mode[src] :: "case"[]{'"value";'"body"} =
`"" pushm[0:n] `"Case(" slot{'"value"} `")" sbreak[""," "] `"" slot{'"body"} `""
popm `""
dform nuprl_case_default_df : except_mode[src] :: "case_default"[]{'"body"} =
`"" szone `"" pushm[4:n] `"Default =>" sbreak[""," "] `"" slot{'"body"} `""
popm `"" ezone `""
dform nuprl_case_pair_df : except_mode[src] :: "case_pair"[]{"x", "y".'"body"} =
`"" pushm[4:n] `"<" slot{'"x"} `"," slot{'"y"} `"> =>" sbreak[""," "] `""
slot{'"body"} `"" popm `""
dform nuprl_case_inl_df : except_mode[src] :: "case_inl"[]{"x".'"body";'"cont"} =
`"" pushm[4:n] `"inl(" slot{'"x"} `") =>" sbreak[""," "] `"" slot{'"body"} `""
popm `"" sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_inr_df : except_mode[src] :: "case_inr"[]{"x".'"body";'"cont"} =
`"" pushm[4:n] `"inr(" slot{'"x"} `") =>" sbreak[""," "] `"" slot{'"body"} `""
popm `"" sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_cons_df : except_mode[src] :: "case_cons"[]{"x", "y".'"body";'"cont"} =
`"" pushm[4:n] `"" slot{'"x"} `"::" slot{'"y"} `" =>" sbreak[""," "] `""
slot{'"body"} `"" popm `"" sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_nil_df : except_mode[src] :: "case_nil"[]{'"body";'"cont"} =
`"" pushm[4:n] `"[] =>" sbreak[""," "] `"" slot{'"body"} `"" popm `""
sbreak[""," "] `"" slot{'"cont"} `""
dform nuprl_case_it_df : except_mode[src] :: "case_it"[]{'"body"} =
`"" pushm[4:n] `"" cdot `" =>" sbreak[""," "] `"" slot{'"body"} `"" popm `""
|
b124840061473212a438d6b647674b9daa9af02375bd6a94f4023db1692bd93d
|
ddmcdonald/sparser
|
Note on what happens when Sparser loads.lisp
|
(in-package :sparser)
Notes on what happens when you load Sparser
Version 10/6/15
The proper way to load the Sparser system is to use the Lisp load
function to load the file load-nlp.lisp at the top of the directory
tree. The key part of this file is the selection of a 'script'
and starting the load process by loading the script file.
The purpose of the script file is to provide a place to predefine
parameters or define one or more parameters that can act as
flags to indicate that you are using Sparser under that setting.
At present, the set of scripts and setting flags is burned into
the options in load-nlp.lisp and later in init/everything.lisp.
The set up is very stylized, as described here, so it should
be possible to carry out these steps programmatically, but
that is for the future.
The default is simply to load the everything file and take the
default settings, effectively loading the entire system. At the
time this is writen (10/6/15) that is very likely to result
in an incoherent runtime system.
Once the specializing script is determined, what happens next is
goverened by the the operations and setting orchestrated by the
code in the file init/everything.lisp, which you will see is
aptly named.
Much of the early portino of that file is concerned with settings
for running with alternative Lisps and determining various file
locations. That is followed by a section of parameterizing the
loading process and what to do or not do at the end, such as
saving an image or loading the grammar. This code dates to the
early 1990 when Sparser was a commercially licensed system so you
will see setting which don't apply today.
The next major operation is to setup the preloader, load/fasl-or-newest,
whose purpose is
(a) to load setting about the lisp being used
(sparser::load/fasl-or-newest
cl-user::identify-the-lisp-&-specialize-preload)
(b) Setup the logical definitions of the location of the modules of
the grammar
(sparser::load/fasl-or-newest
cl-user::module-location-definitions)
As well as ome ancilary files that they use, and the the master
definitions of the grammar modules.
(sparser::lload "loaders;grammar modules")
Note the "logical filename" syntax there with the ";". Much of the
twists and turns in the loader code is concerned with moving back
and forth between the logical form of a filename and the form that
it takes on the OS we are using.
The next set of switch settings governs some of the details of
what is or isn't loaded, and sets out the master set of alternative
configurations, such as *c3* or *big-mechanism*. These are consulted
in a call to cond that determines and loads the corresponding
configuration of grammar modules to incude given that setting.
At that point we load the master loader with loads the rest of
the files of code. The function the-master-loader is at the top of
that file to make it easily to use meta-. with
The master load file calls load-the-grammar when it is just about
done with the system code. After that is loads the files in the
worspace directory of the current version (init/versions/v4/workspace/*).
At that point we are back with the code in everything.lisp. Right now
we dont' have a setup defined for saving Sparser as an image (though
we need to), so do here what would alternatively have been done
when a saved image wakes up.
(1) We load the load-time configuration file (v4/config/load.lisp),
which establishes the size of the major resources.
(2) we load lauch-time configuration file (config/launch.lisp).
It consists of a set of function definitions. Notably this is
where all the user-level workspace files are loaded. That is every
liap file in init/workspaces/. The switch setting that goes with
the configuration is also applied, e.g. for *c3* vs. *big-mechanism*.
The function postprocess-grammar-indexes provides useful set of
statistics besides doin what it's name implies. It is called as
the very last operation in load-the-grammar but could be called
later if desired.
| null |
https://raw.githubusercontent.com/ddmcdonald/sparser/304bd02d0cf7337ca25c8f1d44b1d7912759460f/Sparser/documentation/notes/Note%20on%20what%20happens%20when%20Sparser%20loads.lisp
|
lisp
|
(in-package :sparser)
Notes on what happens when you load Sparser
Version 10/6/15
The proper way to load the Sparser system is to use the Lisp load
function to load the file load-nlp.lisp at the top of the directory
tree. The key part of this file is the selection of a 'script'
and starting the load process by loading the script file.
The purpose of the script file is to provide a place to predefine
parameters or define one or more parameters that can act as
flags to indicate that you are using Sparser under that setting.
At present, the set of scripts and setting flags is burned into
the options in load-nlp.lisp and later in init/everything.lisp.
The set up is very stylized, as described here, so it should
be possible to carry out these steps programmatically, but
that is for the future.
The default is simply to load the everything file and take the
default settings, effectively loading the entire system. At the
time this is writen (10/6/15) that is very likely to result
in an incoherent runtime system.
Once the specializing script is determined, what happens next is
goverened by the the operations and setting orchestrated by the
code in the file init/everything.lisp, which you will see is
aptly named.
Much of the early portino of that file is concerned with settings
for running with alternative Lisps and determining various file
locations. That is followed by a section of parameterizing the
loading process and what to do or not do at the end, such as
saving an image or loading the grammar. This code dates to the
early 1990 when Sparser was a commercially licensed system so you
will see setting which don't apply today.
The next major operation is to setup the preloader, load/fasl-or-newest,
whose purpose is
(a) to load setting about the lisp being used
(sparser::load/fasl-or-newest
cl-user::identify-the-lisp-&-specialize-preload)
(b) Setup the logical definitions of the location of the modules of
the grammar
(sparser::load/fasl-or-newest
cl-user::module-location-definitions)
As well as ome ancilary files that they use, and the the master
definitions of the grammar modules.
(sparser::lload "loaders;grammar modules")
Note the "logical filename" syntax there with the ";". Much of the
twists and turns in the loader code is concerned with moving back
and forth between the logical form of a filename and the form that
it takes on the OS we are using.
The next set of switch settings governs some of the details of
what is or isn't loaded, and sets out the master set of alternative
configurations, such as *c3* or *big-mechanism*. These are consulted
in a call to cond that determines and loads the corresponding
configuration of grammar modules to incude given that setting.
At that point we load the master loader with loads the rest of
the files of code. The function the-master-loader is at the top of
that file to make it easily to use meta-. with
The master load file calls load-the-grammar when it is just about
done with the system code. After that is loads the files in the
worspace directory of the current version (init/versions/v4/workspace/*).
At that point we are back with the code in everything.lisp. Right now
we dont' have a setup defined for saving Sparser as an image (though
we need to), so do here what would alternatively have been done
when a saved image wakes up.
(1) We load the load-time configuration file (v4/config/load.lisp),
which establishes the size of the major resources.
(2) we load lauch-time configuration file (config/launch.lisp).
It consists of a set of function definitions. Notably this is
where all the user-level workspace files are loaded. That is every
liap file in init/workspaces/. The switch setting that goes with
the configuration is also applied, e.g. for *c3* vs. *big-mechanism*.
The function postprocess-grammar-indexes provides useful set of
statistics besides doin what it's name implies. It is called as
the very last operation in load-the-grammar but could be called
later if desired.
|
|
fcdfdc580febfa6a02bf78dd14e58e133edd6418c90f41c767cac43b10866c75
|
pouriya/cfg
|
cfg_keeper_SUITE.erl
|
%% Auto-generated by -Jahanbakhsh/estuff
%% -----------------------------------------------------------------------------
-module(cfg_keeper_SUITE).
-author('').
%% -----------------------------------------------------------------------------
%% Exports:
%% ct callbacks:
-export([init_per_suite/1
,end_per_suite/1
,all/0
,init_per_testcase/2
,end_per_testcase/2]).
%% Testcases:
-export(['1'/1
,'2'/1
,'3'/1
,'4'/1
,'5'/1
,'6'/1
,'7'/1
,'8'/1
,'9'/1]).
%% -----------------------------------------------------------------------------
Records & Macros & Includes :
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
%% -----------------------------------------------------------------------------
%% ct callbacks:
all() ->
ToInteger =
fun
({Func, 1}) ->
try
erlang:list_to_integer(erlang:atom_to_list(Func))
catch
_:_ ->
0
end;
(_) -> % Arity > 1 | Arity == 0
0
end,
% contains 0 for other functions:
Ints = [ToInteger(X) || X <- ?MODULE:module_info(exports)],
1 , 2 , ...
PosInts = lists:sort([Int || Int <- Ints, Int > 0]),
% '1', '2', ...
[erlang:list_to_atom(erlang:integer_to_list(X)) || X <- PosInts].
init_per_suite(Cfg) ->
application:start(sasl),
Cfg.
end_per_suite(Cfg) ->
application:stop(sasl),
Cfg.
init_per_testcase(_TestCase, Cfg) ->
Cfg.
end_per_testcase(_TestCase, _Cfg) ->
ok.
%% -----------------------------------------------------------------------------
%% Test cases:
'1'(_) ->
% init:
?assertMatch(ok, cfg:init({test, ok})),
?assertMatch({error, {init_config_keeper, #{k := v}}}, cfg:init({test, {error, #{k => v}}})),
?assertMatch({error, {init_config_keeper, #{returned_value := unknown}}}, cfg:init({test, unknown})),
?assertMatch({error, {init_config_keeper, #{exception := oops}}}, cfg:init({test, {exception, oops}})),
ok.
'2'(_) ->
% set/2:
?assertMatch(ok, cfg:set({test, fun(X) -> X end}, ok)),
?assertMatch({error, {set_config, #{k := v}}}, cfg:set({test, fun(X) -> X end}, {error, #{k => v}})),
?assertMatch({error, {set_config, #{returned_value := unknown}}}, cfg:set({test, fun(X) -> X end}, unknown)),
?assertMatch({error, {set_config, #{exception := oops}}}, cfg:set({test, fun(X) -> erlang:error(X) end}, oops)),
ok.
'3'(_) ->
set/3 :
?assertMatch(ok, cfg:set({test, fun(X, _) -> X end}, ok, undef)),
?assertMatch({error, {set_config, #{k := v}}}, cfg:set({test, fun(X, _) -> X end}, {error, #{k => v}}, undef)),
?assertMatch({error, {set_config, #{returned_value := unknown}}}, cfg:set({test, fun(X, _) -> X end}, unknown, undef)),
?assertMatch({error, {set_config, #{exception := oops}}}, cfg:set({test, fun(X, _) -> erlang:error(X) end}, oops, undef)),
ok.
'4'(_) ->
% get/1:
?assertMatch({ok, []}, cfg:get({test, {ok, []}})),
?assertMatch({error, {get_config, #{k := v}}}, cfg:get({test, {error, #{k => v}}})),
?assertMatch({error, {get_config, #{returned_value := unknown}}}, cfg:get({test, unknown})),
?assertMatch({error, {get_config, #{exception := oops}}}, cfg:get({test, {exception, oops}})),
ok.
'5'(_) ->
get/2 :
?assertMatch({ok, value}, cfg:get({test, fun(X) -> X end}, {ok, value})),
?assertMatch(not_found, cfg:get({test, fun(X) -> X end}, not_found)),
?assertMatch({error, {get_config, #{k := v}}}, cfg:get({test, fun(X) -> X end}, {error, #{k => v}})),
?assertMatch({error, {get_config, #{returned_value := unknown}}}, cfg:get({test, fun(X) -> X end}, unknown)),
?assertMatch({error, {get_config, #{exception := oops}}}, cfg:get({test, fun(X) -> erlang:error(X) end}, oops)),
ok.
'6'(_) ->
% get/3:
?assertMatch({ok, value}, cfg:get({test, fun(X) -> X end}, {ok, value}, default)),
?assertMatch({ok, default}, cfg:get({test, fun(X) -> X end}, not_found, default)),
ok.
'7'(_) ->
% delete/2:
?assertMatch(ok, cfg:delete({test, fun(X) -> X end}, ok)),
?assertMatch({error, {delete_config, #{k := v}}}, cfg:delete({test, fun(X) -> X end}, {error, #{k => v}})),
?assertMatch({error, {delete_config, #{returned_value := unknown}}}, cfg:delete({test, fun(X) -> X end}, unknown)),
?assertMatch({error, {delete_config, #{exception := oops}}}, cfg:delete({test, fun(X) -> erlang:error(X) end}, oops)),
ok.
'8'(_) ->
% delete/1:
?assertMatch(ok, cfg:delete({test, ok})),
?assertMatch({error, {delete_config, #{k := v}}}, cfg:delete({test, {error, #{k => v}}})),
?assertMatch({error, {delete_config, #{returned_value := unknown}}}, cfg:delete({test, unknown})),
?assertMatch({error, {delete_config, #{exception := oops}}}, cfg:delete({test, {exception, oops}})),
ok.
'9'(_) ->
_ = cfg_keeper:module(env),
_ = cfg_keeper:module(ets),
ok.
| null |
https://raw.githubusercontent.com/pouriya/cfg/b03eb73549e2fa11b88f91db73f700d7e6ef4617/test/cfg_keeper_SUITE.erl
|
erlang
|
Auto-generated by -Jahanbakhsh/estuff
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Exports:
ct callbacks:
Testcases:
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
ct callbacks:
Arity > 1 | Arity == 0
contains 0 for other functions:
'1', '2', ...
-----------------------------------------------------------------------------
Test cases:
init:
set/2:
get/1:
get/3:
delete/2:
delete/1:
|
-module(cfg_keeper_SUITE).
-author('').
-export([init_per_suite/1
,end_per_suite/1
,all/0
,init_per_testcase/2
,end_per_testcase/2]).
-export(['1'/1
,'2'/1
,'3'/1
,'4'/1
,'5'/1
,'6'/1
,'7'/1
,'8'/1
,'9'/1]).
Records & Macros & Includes :
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
all() ->
ToInteger =
fun
({Func, 1}) ->
try
erlang:list_to_integer(erlang:atom_to_list(Func))
catch
_:_ ->
0
end;
0
end,
Ints = [ToInteger(X) || X <- ?MODULE:module_info(exports)],
1 , 2 , ...
PosInts = lists:sort([Int || Int <- Ints, Int > 0]),
[erlang:list_to_atom(erlang:integer_to_list(X)) || X <- PosInts].
init_per_suite(Cfg) ->
application:start(sasl),
Cfg.
end_per_suite(Cfg) ->
application:stop(sasl),
Cfg.
init_per_testcase(_TestCase, Cfg) ->
Cfg.
end_per_testcase(_TestCase, _Cfg) ->
ok.
'1'(_) ->
?assertMatch(ok, cfg:init({test, ok})),
?assertMatch({error, {init_config_keeper, #{k := v}}}, cfg:init({test, {error, #{k => v}}})),
?assertMatch({error, {init_config_keeper, #{returned_value := unknown}}}, cfg:init({test, unknown})),
?assertMatch({error, {init_config_keeper, #{exception := oops}}}, cfg:init({test, {exception, oops}})),
ok.
'2'(_) ->
?assertMatch(ok, cfg:set({test, fun(X) -> X end}, ok)),
?assertMatch({error, {set_config, #{k := v}}}, cfg:set({test, fun(X) -> X end}, {error, #{k => v}})),
?assertMatch({error, {set_config, #{returned_value := unknown}}}, cfg:set({test, fun(X) -> X end}, unknown)),
?assertMatch({error, {set_config, #{exception := oops}}}, cfg:set({test, fun(X) -> erlang:error(X) end}, oops)),
ok.
'3'(_) ->
set/3 :
?assertMatch(ok, cfg:set({test, fun(X, _) -> X end}, ok, undef)),
?assertMatch({error, {set_config, #{k := v}}}, cfg:set({test, fun(X, _) -> X end}, {error, #{k => v}}, undef)),
?assertMatch({error, {set_config, #{returned_value := unknown}}}, cfg:set({test, fun(X, _) -> X end}, unknown, undef)),
?assertMatch({error, {set_config, #{exception := oops}}}, cfg:set({test, fun(X, _) -> erlang:error(X) end}, oops, undef)),
ok.
'4'(_) ->
?assertMatch({ok, []}, cfg:get({test, {ok, []}})),
?assertMatch({error, {get_config, #{k := v}}}, cfg:get({test, {error, #{k => v}}})),
?assertMatch({error, {get_config, #{returned_value := unknown}}}, cfg:get({test, unknown})),
?assertMatch({error, {get_config, #{exception := oops}}}, cfg:get({test, {exception, oops}})),
ok.
'5'(_) ->
get/2 :
?assertMatch({ok, value}, cfg:get({test, fun(X) -> X end}, {ok, value})),
?assertMatch(not_found, cfg:get({test, fun(X) -> X end}, not_found)),
?assertMatch({error, {get_config, #{k := v}}}, cfg:get({test, fun(X) -> X end}, {error, #{k => v}})),
?assertMatch({error, {get_config, #{returned_value := unknown}}}, cfg:get({test, fun(X) -> X end}, unknown)),
?assertMatch({error, {get_config, #{exception := oops}}}, cfg:get({test, fun(X) -> erlang:error(X) end}, oops)),
ok.
'6'(_) ->
?assertMatch({ok, value}, cfg:get({test, fun(X) -> X end}, {ok, value}, default)),
?assertMatch({ok, default}, cfg:get({test, fun(X) -> X end}, not_found, default)),
ok.
'7'(_) ->
?assertMatch(ok, cfg:delete({test, fun(X) -> X end}, ok)),
?assertMatch({error, {delete_config, #{k := v}}}, cfg:delete({test, fun(X) -> X end}, {error, #{k => v}})),
?assertMatch({error, {delete_config, #{returned_value := unknown}}}, cfg:delete({test, fun(X) -> X end}, unknown)),
?assertMatch({error, {delete_config, #{exception := oops}}}, cfg:delete({test, fun(X) -> erlang:error(X) end}, oops)),
ok.
'8'(_) ->
?assertMatch(ok, cfg:delete({test, ok})),
?assertMatch({error, {delete_config, #{k := v}}}, cfg:delete({test, {error, #{k => v}}})),
?assertMatch({error, {delete_config, #{returned_value := unknown}}}, cfg:delete({test, unknown})),
?assertMatch({error, {delete_config, #{exception := oops}}}, cfg:delete({test, {exception, oops}})),
ok.
'9'(_) ->
_ = cfg_keeper:module(env),
_ = cfg_keeper:module(ets),
ok.
|
7cc080bc50592b3f3e4909feebf10fe2db8f678e3173f820e44dba850458c873
|
azimut/shiny
|
3.lisp
|
(in-package :shiny)
;; Trying the ideas on the song
;;
;;
(freverb-toggle 1)
(freverb :roomsize .6d0 :damp .1d0 :level .9d0 :width 10d0)
sine 80 - 8
(fp 2 101 0)
(fp 10 14)
(fp 10 0 0)
(try-sounds (quant 4) 10 10 4)
;; !!
;; slow down and speed up chord rhythm and bar length
(let ((o (new palindrome :of '(.75 .6 .5 .45) :elide t)))
(defun f (time)
(let ((offset (next o))
(mychord (make-chord 55 70 4 *phrygian*)))
(pa time mychord offset '(60 60 55 50) 10 (list offset
offset
offset
(+ offset (pick .1 .2))))
(p (+ time (* 2 offset)) mychord (rcosr 35 5 1/2) offset 3)
(p (+ time (* 3 offset)) (first mychord) 40 (* offset 2) 2)
(aat (+ time (* 4 offset)) #'f it))))
(defun f ())
(f (quant 4))
(fp 11 116 8)
(fp 1 0)
(fp 2 0)
(fp 3 0)
(fp 4 0)
(fp 5 69)
(defun f ())
(defun f (time chan)
(let* ((c (make-chord 65 80 5 *phrygian*))
(s (second c))
(ss (make-chord-fixed s 3 *phrygian*))
)
(pa time (reverse c) .2 60 chan '(.2 .2 .2 .2 1))
;; a problem with a bass here is that it might not change from the previous
;; bass, a heap like structure would help. Also it won't matter that much if
;; the bass doesn't chant through the composition...i think
(p (+ time 1.2) (transpose ss -12) 25 1.5 (1+ chan)))
(aat (+ time 2.5) #'f it chan))
(f (quant 4) 1)
(f (quant 4) 3)
;; <3
;; alternate between:
;; - a descending arpeggio
- the same descending arpeggion but with the first note an interval below
;; add some "melody" by playing a random part of the chord
(defun ff ())
(defun ff (time)
(let* ((pc (ov-pc-scale :lydian))
(mychord (make-chord 55 70 4 pc))
(r (reverse mychord))
(rr (append (list (pc-relative (first r) -1 pc))
(subseq r 1 4))))
(if (odds .5)
(pa time r .25 '(65 55 50 50) 5 .25)
(pa time r '(0 .5 .5 .5) '(65 55 50 50) 5 .5))
(pa (+ 1 time) rr .25 50 6 .25)
(if (odds .5)
(pa (+ 2 time) r .25 '(65 50 50 50) 7 .25)
(pa (+ 2 time) rr '(0 .5 .5 .5) '(65 50 50 50) 7 .5))
(if (odds .1)
(p (+ time 1) (pick-random-list mychord 3) (rcosr 45 5 1/2) 3 2)
(progn
(p (+ time 1) (first mychord) (rcosr 45 5 1/2) 2 2)
(p (+ time 3) (pick (list (second mychord) (third mychord))
(first mychord))
(rcosr 45 5 1/2) 1 2)))
(pa (+ 3 time) rr .25 50 8 .25)
(aat (+ time 4) #'ff it)))
;;;;
(fg .5)
(let (;;(i (make-cycle '(i vi iii vii)))
(i (make-cycle '(iv v iii vi)))
;;(i (make-cycle '(iv^7 v7 iii7 vi7)))
)
(defun ff (time)
( pc ( ov - pc - scale : lydian ) )
( mychord ( make - chord 55 75 4 pc ) )
(pc (pc-diatonic 0 'major (next i)))
(lchord 4) ;; !
(larp (/ 1 lchord))
(mychord (make-chord 55 75 lchord pc))
;; (mychord (mapcar (lambda (x) (pc-relative x -7 pc)) mychord))
(r (reverse mychord))
( r ( mapcar ( lambda ( x ) ( pc - relative x 2 pc ) ) r ) )
;;(r (mapcar (lambda (x) (pc-relative x -100 pc)) r))
(rr (append (list (pc-relative (first r) -1 pc))
(subseq r 1 lchord))))
( if ( odds 1 )
;; (pa time
;; r
; ; ( pick )
;; ;;(pick r (reverse (mapcar (lambda (x) (pc-relative x +1 pc)) mychord)))
larp ' ( 65 55 50 50 ) 5 larp )
( pa time r ' ( 0 .5 .5 .5 ) ' ( 65 55 50 50 ) 5 .5 ) )
(pa (+ 1 time) rr larp 50 6 larp)
( if ( odds 1 )
( ( + 2 time )
;; r
;; ;;(pick r rr)
;; ;;(pick r (mapcar (lambda (x) (pc-relative x +1 pc)) mychord))
larp ' ( 65 50 50 50 ) 7 larp )
( ( + 2 time ) rr ' ( 0 .5 .5 .5 ) ' ( 65 50 50 50 ) 7 .5 ) )
( pa ( + time 1.5 ) ( repeat 2 ( list ( + ( pick 0 12 ) ( ) ) ) ) .5 ( pick 40 55 ) 11 .3 )
( pa ( + time 2.5 ) ( repeat 2 ( list ( + ( pick 0 12 ) ( ) ) ) ) .5 ( pick 40 55 ) 11 .3 )
(if (odds 1)
(p (+ time 1) (pick-random-list mychord 2) (rcosr 35 5 1/2) 3 10)
(progn
(p (+ time 1) (first mychord) (rcosr 40 5 1/2) 2 2)
(p (+ time 3) (pick (list (second mychord) (+ -12 (third mychord)))
(first mychord))
(rcosr 40 5 1/2) 1 2)))
(pa (+ 3 time) rr larp 50 8 larp)
(aat (+ time 4) #'ff it))))
;;;;;; -----------------
(fp 13 35)
(fp 10 49)
(fp 2 0)
(fp 11 6)
(defun ff ())
(ff (quant 4))
(fpress 2 0)
(fp 2 49)
(fp 10 49)
(fg 1.0)
(fp 2 52)
( fp 2 80 )
( fp 5 80 )
;; Majora
(loop for x from 5 upto 8 do (fp x 41))
Megadrive
(fp 5 12 0)
(fp 6 12 0)
(fp 7 12 0)
(fp 8 12 0)
(freverb-toggle 0)
(fp 8 44 0)
(p (quant 4) 60 60 1 8)
(pa (quant 4) '(60 62 64) .2 60 1 .2)
(fg .9)
(f (quant 4))
(fg .3)
(fp 1 52 0)
(fp 1 0)
(fp 3 49)
(fpitch 1 1000)
;; normal
(freverb :roomsize .2d0)
;; eerie
(freverb :roomsize .6d0 :damp .1d0 :level .9d0 :width 5d0)
(freset)
(pa (now) '(60 62 64) .5 60 0)
(off-with-the-notes)
| null |
https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/compositions/inlovewithaghost/3.lisp
|
lisp
|
Trying the ideas on the song
!!
slow down and speed up chord rhythm and bar length
a problem with a bass here is that it might not change from the previous
bass, a heap like structure would help. Also it won't matter that much if
the bass doesn't chant through the composition...i think
<3
alternate between:
- a descending arpeggio
add some "melody" by playing a random part of the chord
(i (make-cycle '(i vi iii vii)))
(i (make-cycle '(iv^7 v7 iii7 vi7)))
!
(mychord (mapcar (lambda (x) (pc-relative x -7 pc)) mychord))
(r (mapcar (lambda (x) (pc-relative x -100 pc)) r))
(pa time
r
; ( pick )
;;(pick r (reverse (mapcar (lambda (x) (pc-relative x +1 pc)) mychord)))
r
;;(pick r rr)
;;(pick r (mapcar (lambda (x) (pc-relative x +1 pc)) mychord))
-----------------
Majora
normal
eerie
|
(in-package :shiny)
(freverb-toggle 1)
(freverb :roomsize .6d0 :damp .1d0 :level .9d0 :width 10d0)
sine 80 - 8
(fp 2 101 0)
(fp 10 14)
(fp 10 0 0)
(try-sounds (quant 4) 10 10 4)
(let ((o (new palindrome :of '(.75 .6 .5 .45) :elide t)))
(defun f (time)
(let ((offset (next o))
(mychord (make-chord 55 70 4 *phrygian*)))
(pa time mychord offset '(60 60 55 50) 10 (list offset
offset
offset
(+ offset (pick .1 .2))))
(p (+ time (* 2 offset)) mychord (rcosr 35 5 1/2) offset 3)
(p (+ time (* 3 offset)) (first mychord) 40 (* offset 2) 2)
(aat (+ time (* 4 offset)) #'f it))))
(defun f ())
(f (quant 4))
(fp 11 116 8)
(fp 1 0)
(fp 2 0)
(fp 3 0)
(fp 4 0)
(fp 5 69)
(defun f ())
(defun f (time chan)
(let* ((c (make-chord 65 80 5 *phrygian*))
(s (second c))
(ss (make-chord-fixed s 3 *phrygian*))
)
(pa time (reverse c) .2 60 chan '(.2 .2 .2 .2 1))
(p (+ time 1.2) (transpose ss -12) 25 1.5 (1+ chan)))
(aat (+ time 2.5) #'f it chan))
(f (quant 4) 1)
(f (quant 4) 3)
- the same descending arpeggion but with the first note an interval below
(defun ff ())
(defun ff (time)
(let* ((pc (ov-pc-scale :lydian))
(mychord (make-chord 55 70 4 pc))
(r (reverse mychord))
(rr (append (list (pc-relative (first r) -1 pc))
(subseq r 1 4))))
(if (odds .5)
(pa time r .25 '(65 55 50 50) 5 .25)
(pa time r '(0 .5 .5 .5) '(65 55 50 50) 5 .5))
(pa (+ 1 time) rr .25 50 6 .25)
(if (odds .5)
(pa (+ 2 time) r .25 '(65 50 50 50) 7 .25)
(pa (+ 2 time) rr '(0 .5 .5 .5) '(65 50 50 50) 7 .5))
(if (odds .1)
(p (+ time 1) (pick-random-list mychord 3) (rcosr 45 5 1/2) 3 2)
(progn
(p (+ time 1) (first mychord) (rcosr 45 5 1/2) 2 2)
(p (+ time 3) (pick (list (second mychord) (third mychord))
(first mychord))
(rcosr 45 5 1/2) 1 2)))
(pa (+ 3 time) rr .25 50 8 .25)
(aat (+ time 4) #'ff it)))
(fg .5)
(i (make-cycle '(iv v iii vi)))
)
(defun ff (time)
( pc ( ov - pc - scale : lydian ) )
( mychord ( make - chord 55 75 4 pc ) )
(pc (pc-diatonic 0 'major (next i)))
(larp (/ 1 lchord))
(mychord (make-chord 55 75 lchord pc))
(r (reverse mychord))
( r ( mapcar ( lambda ( x ) ( pc - relative x 2 pc ) ) r ) )
(rr (append (list (pc-relative (first r) -1 pc))
(subseq r 1 lchord))))
( if ( odds 1 )
larp ' ( 65 55 50 50 ) 5 larp )
( pa time r ' ( 0 .5 .5 .5 ) ' ( 65 55 50 50 ) 5 .5 ) )
(pa (+ 1 time) rr larp 50 6 larp)
( if ( odds 1 )
( ( + 2 time )
larp ' ( 65 50 50 50 ) 7 larp )
( ( + 2 time ) rr ' ( 0 .5 .5 .5 ) ' ( 65 50 50 50 ) 7 .5 ) )
( pa ( + time 1.5 ) ( repeat 2 ( list ( + ( pick 0 12 ) ( ) ) ) ) .5 ( pick 40 55 ) 11 .3 )
( pa ( + time 2.5 ) ( repeat 2 ( list ( + ( pick 0 12 ) ( ) ) ) ) .5 ( pick 40 55 ) 11 .3 )
(if (odds 1)
(p (+ time 1) (pick-random-list mychord 2) (rcosr 35 5 1/2) 3 10)
(progn
(p (+ time 1) (first mychord) (rcosr 40 5 1/2) 2 2)
(p (+ time 3) (pick (list (second mychord) (+ -12 (third mychord)))
(first mychord))
(rcosr 40 5 1/2) 1 2)))
(pa (+ 3 time) rr larp 50 8 larp)
(aat (+ time 4) #'ff it))))
(fp 13 35)
(fp 10 49)
(fp 2 0)
(fp 11 6)
(defun ff ())
(ff (quant 4))
(fpress 2 0)
(fp 2 49)
(fp 10 49)
(fg 1.0)
(fp 2 52)
( fp 2 80 )
( fp 5 80 )
(loop for x from 5 upto 8 do (fp x 41))
Megadrive
(fp 5 12 0)
(fp 6 12 0)
(fp 7 12 0)
(fp 8 12 0)
(freverb-toggle 0)
(fp 8 44 0)
(p (quant 4) 60 60 1 8)
(pa (quant 4) '(60 62 64) .2 60 1 .2)
(fg .9)
(f (quant 4))
(fg .3)
(fp 1 52 0)
(fp 1 0)
(fp 3 49)
(fpitch 1 1000)
(freverb :roomsize .2d0)
(freverb :roomsize .6d0 :damp .1d0 :level .9d0 :width 5d0)
(freset)
(pa (now) '(60 62 64) .5 60 0)
(off-with-the-notes)
|
1a40d40758dc0a22f24590a4c25acd8656af1eb3a8e5bf75e617ce28f0ea1dbc
|
orx/ocaml-orx
|
tutorial_09_scrolling.ml
|
Adaptation of the scrolling tutorial from
This example is a direct adaptation of the 09_Scrolling.c tutorial from
module State = struct
type t = Orx.Camera.t
let state : t option ref = ref None
let get () = Option.get !state
end
let update (clock_info : Orx.Clock.Info.t) =
let camera = State.get () in
Orx.Config.push_section "Tutorial";
let scroll_speed = Orx.Config.get_vector "ScrollSpeed" in
Orx.Config.pop_section ();
let scroll_speed =
Orx.Vector.mulf scroll_speed (Orx.Clock.Info.get_dt clock_info)
in
let move_x =
if Orx.Input.is_active "CameraRight" then
Orx.Vector.get_x scroll_speed
else if Orx.Input.is_active "CameraLeft" then
-.Orx.Vector.get_x scroll_speed
else
0.0
in
let move_y =
if Orx.Input.is_active "CameraUp" then
-.Orx.Vector.get_y scroll_speed
else if Orx.Input.is_active "CameraDown" then
Orx.Vector.get_y scroll_speed
else
0.0
in
let move_z =
if Orx.Input.is_active "CameraZoomIn" then
Orx.Vector.get_z scroll_speed
else if Orx.Input.is_active "CameraZoomOut" then
-.Orx.Vector.get_z scroll_speed
else
0.0
in
let move = Orx.Vector.make ~x:move_x ~y:move_y ~z:move_z in
let camera_position = Orx.Camera.get_position camera in
Orx.Camera.set_position camera (Orx.Vector.add camera_position move)
let init () =
(* Print out a hint to the user about what's to come *)
let get_name (binding : string) : string =
let (type_, id, mode) = Orx.Input.get_binding binding 0 |> Result.get_ok in
Orx.Input.get_binding_name type_ id mode
in
Orx.Log.log
("@.- '%s', '%s', '%s' & '%s' will move the camera@."
^^ "- '%s' & '%s' will zoom in/out@."
^^ "* The scrolling and auto-scaling of objects is data-driven, no code \
required@."
^^ "* The sky background will follow the camera (parent/child frame \
relation)"
)
(get_name "CameraUp") (get_name "CameraLeft") (get_name "CameraDown")
(get_name "CameraRight") (get_name "CameraZoomIn") (get_name "CameraZoomOut");
let viewport = Orx.Viewport.create_from_config_exn "Viewport" in
let camera = Orx.Viewport.get_camera viewport |> Option.get in
State.state := Some camera;
let clock = Orx.Clock.get_core () in
Orx.Clock.register clock update;
let _scene : Orx.Object.t = Orx.Object.create_from_config_exn "Scene" in
Ok ()
let run () =
if Orx.Input.is_active "Quit" then
Orx.Status.error
else
Orx.Status.ok
let () =
Orx.Main.start ~config_dir:"examples/tutorial/data" ~init ~run "09_Scrolling"
| null |
https://raw.githubusercontent.com/orx/ocaml-orx/b1cf7d0efb958c72fbb9568905c81242593ff19d/examples/tutorial/tutorial_09_scrolling.ml
|
ocaml
|
Print out a hint to the user about what's to come
|
Adaptation of the scrolling tutorial from
This example is a direct adaptation of the 09_Scrolling.c tutorial from
module State = struct
type t = Orx.Camera.t
let state : t option ref = ref None
let get () = Option.get !state
end
let update (clock_info : Orx.Clock.Info.t) =
let camera = State.get () in
Orx.Config.push_section "Tutorial";
let scroll_speed = Orx.Config.get_vector "ScrollSpeed" in
Orx.Config.pop_section ();
let scroll_speed =
Orx.Vector.mulf scroll_speed (Orx.Clock.Info.get_dt clock_info)
in
let move_x =
if Orx.Input.is_active "CameraRight" then
Orx.Vector.get_x scroll_speed
else if Orx.Input.is_active "CameraLeft" then
-.Orx.Vector.get_x scroll_speed
else
0.0
in
let move_y =
if Orx.Input.is_active "CameraUp" then
-.Orx.Vector.get_y scroll_speed
else if Orx.Input.is_active "CameraDown" then
Orx.Vector.get_y scroll_speed
else
0.0
in
let move_z =
if Orx.Input.is_active "CameraZoomIn" then
Orx.Vector.get_z scroll_speed
else if Orx.Input.is_active "CameraZoomOut" then
-.Orx.Vector.get_z scroll_speed
else
0.0
in
let move = Orx.Vector.make ~x:move_x ~y:move_y ~z:move_z in
let camera_position = Orx.Camera.get_position camera in
Orx.Camera.set_position camera (Orx.Vector.add camera_position move)
let init () =
let get_name (binding : string) : string =
let (type_, id, mode) = Orx.Input.get_binding binding 0 |> Result.get_ok in
Orx.Input.get_binding_name type_ id mode
in
Orx.Log.log
("@.- '%s', '%s', '%s' & '%s' will move the camera@."
^^ "- '%s' & '%s' will zoom in/out@."
^^ "* The scrolling and auto-scaling of objects is data-driven, no code \
required@."
^^ "* The sky background will follow the camera (parent/child frame \
relation)"
)
(get_name "CameraUp") (get_name "CameraLeft") (get_name "CameraDown")
(get_name "CameraRight") (get_name "CameraZoomIn") (get_name "CameraZoomOut");
let viewport = Orx.Viewport.create_from_config_exn "Viewport" in
let camera = Orx.Viewport.get_camera viewport |> Option.get in
State.state := Some camera;
let clock = Orx.Clock.get_core () in
Orx.Clock.register clock update;
let _scene : Orx.Object.t = Orx.Object.create_from_config_exn "Scene" in
Ok ()
let run () =
if Orx.Input.is_active "Quit" then
Orx.Status.error
else
Orx.Status.ok
let () =
Orx.Main.start ~config_dir:"examples/tutorial/data" ~init ~run "09_Scrolling"
|
9879891fd4e770bcfdcb7c9da340db56e0e689b0dc5dbc5b132c13b4a7d47c3d
|
theodormoroianu/SecondYearCourses
|
lab5.hs
|
import Numeric.Natural
logistic :: Num a => a -> a -> Natural -> a
logistic rate start = f
where
f 0 = start
f n = rate * f (n - 1) * (1 - f (n - 1))
logistic0 :: Fractional a => Natural -> a
logistic0 = logistic 3.741 0.00079
ex1 :: Natural
ex1 = undefined
ex20 :: Fractional a => [a]
ex20 = [1, logistic0 ex1, 3]
ex21 :: Fractional a => a
ex21 = head ex20
ex22 :: Fractional a => a
ex22 = ex20 !! 2
ex23 :: Fractional a => [a]
ex23 = drop 2 ex20
ex24 :: Fractional a => [a]
ex24 = tail ex20
ex31 :: Natural -> Bool
ex31 x = x < 7 || logistic0 (ex1 + x) > 2
ex32 :: Natural -> Bool
ex32 x = logistic0 (ex1 + x) > 2 || x < 7
ex33 :: Bool
ex33 = ex31 5
ex34 :: Bool
ex34 = ex31 7
ex35 :: Bool
ex35 = ex32 5
ex36 :: Bool
ex36 = ex32 7
semn :: [Integer] -> String
semn = undefined
semnFold :: [Integer] -> String
semnFold = foldr op unit
where
unit = undefined
op = undefined
matrice :: Num a => [[a]]
matrice = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
corect :: [[a]] -> Bool
corect = undefined
el :: [[a]] -> Int -> Int -> a
el = undefined
transforma :: [[a]] -> [(a, Int, Int)]
transforma = undefined
| null |
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/99185b0e97119135e7301c2c7be0f07ae7258006/Haskell/l/lab5/lab5.hs
|
haskell
|
import Numeric.Natural
logistic :: Num a => a -> a -> Natural -> a
logistic rate start = f
where
f 0 = start
f n = rate * f (n - 1) * (1 - f (n - 1))
logistic0 :: Fractional a => Natural -> a
logistic0 = logistic 3.741 0.00079
ex1 :: Natural
ex1 = undefined
ex20 :: Fractional a => [a]
ex20 = [1, logistic0 ex1, 3]
ex21 :: Fractional a => a
ex21 = head ex20
ex22 :: Fractional a => a
ex22 = ex20 !! 2
ex23 :: Fractional a => [a]
ex23 = drop 2 ex20
ex24 :: Fractional a => [a]
ex24 = tail ex20
ex31 :: Natural -> Bool
ex31 x = x < 7 || logistic0 (ex1 + x) > 2
ex32 :: Natural -> Bool
ex32 x = logistic0 (ex1 + x) > 2 || x < 7
ex33 :: Bool
ex33 = ex31 5
ex34 :: Bool
ex34 = ex31 7
ex35 :: Bool
ex35 = ex32 5
ex36 :: Bool
ex36 = ex32 7
semn :: [Integer] -> String
semn = undefined
semnFold :: [Integer] -> String
semnFold = foldr op unit
where
unit = undefined
op = undefined
matrice :: Num a => [[a]]
matrice = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
corect :: [[a]] -> Bool
corect = undefined
el :: [[a]] -> Int -> Int -> a
el = undefined
transforma :: [[a]] -> [(a, Int, Int)]
transforma = undefined
|
|
6ce5f239dd64672b087373db9dd74d87a3511fd0dcee11efce0adc014c6ebb0d
|
eugeneia/athens
|
suite.lisp
|
;;; integrated testing including derived patterns
;;;
INCOMPATIBILITY NOTE : ` fail ' no longer effective by default : it is now exported
;;; separately from :trivia.fail to avoid the common conflict against fiveam.
;;; Also, :trivia.next and :trivia.skip exports `next' (conflicts with
` iterate : next ' ) and ` skip ' , respectively . all 3 macros have the same meaning .
;;;
INCOMPATIBILITY NOTE : ` match ' no longer expanded in 1 - pass through
;;; `macroexpand': some tests are now replaced with eval
(defpackage :trivia.test
(:use :closer-common-lisp :fiveam
:trivia.level2
:trivia.level1
:trivia.next
:trivia.level2.impl))
(in-package :trivia.test)
;; for debugging purpose
( setf * trace - dispatching * t )
(def-suite :trivia)
(in-suite :trivia)
;;; Pattern matching
(defmacro is-match (arg &body pattern)
`(is-true (locally
(declare (optimize (safety 3) (debug 3) (speed 0)))
(match ,arg (,@pattern t)))
,(format nil "~<pattern ~a did not match against arg ~s~:@>" (list pattern arg))))
(defmacro is-not-match (arg &body pattern)
`(is-false (locally
(declare (optimize (safety 3) (debug 3) (speed 0)))
(match ,arg (,@pattern t)))
,(format nil "~<pattern ~a matched against arg ~s~:@>" (list pattern arg))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass person ()
((name :initarg :name :reader name)
(age :initarg :age)))
(defun age (a b c)
(format t "this function is meaningless ~a ~a ~a" a b c))
(defstruct (point (:predicate point-p))
x y)
(defmethod make-load-form ((o point) &optional environment)
(make-load-form-saving-slots o
:slot-names '(x y)
:environment environment))
(defstruct (point3 (:include point))
z)
(defmethod make-load-form ((o point3) &optional environment)
(make-load-form-saving-slots o
:slot-names '(x y z)
:environment environment))
(declaim (inline x))
(defun x (a b c)
(format t "this function is meaningless ~a ~a ~a" a b c))
(declaim (notinline x)))
(test (constant-pattern :compile-at :definition-time)
;; integer
(is-match 1 1)
;; t
(is-match t t)
;; nil
(is-match nil nil)
;; keyword
(is-match :foo :foo)
;; float
(is-match 3.14 3.14)
(is-not-match 0.999 1)
;; string
(is-match "foo" "foo")
;; complex
(is-match '(1 t 3.14 :foo "foo") '(1 t 3.14 :foo "foo"))
quoted conses should not expand to patterns ( issue # 86 )
#+(or)
(is (eql 3 (match '(1 2 3) ('(1 _ a) a))))
(is-not-match '(1 2 3) '(1 _ a))
(is (eql 3 (match #(1 2 3) (#(1 _ a) a))))
;; ensure these are compared by char-wise eql
(is-match "aaa" "aaa")
(is-not-match "aaa" "AAA")
(is-match #S(POINT :x "A" :y "B")
#S(POINT :x "A" :y "B"))
(is-not-match #S(POINT :x "A" :y "B")
#S(POINT :x "a" :y "b"))
;; check if INCLUDEd slots are direct slots
(is-match #S(POINT3 :x "A" :y "B" :z "C")
#S(POINT3 :x "A" :y "B" :z "C"))
(is-not-match #S(POINT3 :x "A" :y "B" :z "C")
#S(POINT3 :x "a" :y "b" :z "c")))
(test variable-pattern
;; simple bind
(is (eql 1 (match 1 (x x))))
;; anonymous bind
(is-match 1 _)
;; complex bind
(is (eql 6
(match '(1 2 3)
((list x y z) (+ x y z))))))
(test place-pattern
;; level 0
(let ((z 1))
(match z ((place x) (incf x)))
(is (eql 2 z)))
level 1
(let ((z (cons 1 2)))
(match z
((cons (place x) y)
(incf x)
(incf y)))
(is (equal (cons 2 2) z)))
level 2
(let ((z (list (vector 1))))
(match z
((list (vector (place x)))
(incf x)))
(is (equalp (list (vector 2)) z))))
(test predicatep
(is (null (predicatep 'point)))
(is (eq 'point-p (predicate-p 'point))))
(test constructor-pattern
;; cons
(is-match (cons 1 2) (cons 1 2)))
there is a magical error on ECL only on travis .
(test assoc
(is-match '((1 . 2)) (assoc 1 2))
(is-match '((1 . 2) (3 . 4)) (assoc 3 4))
;; NOTE: incompatibility --- this is not an association list, according to CLHS
( is - match ' ( 1 ( 2 . 3 ) ) ( assoc 2 3 ) )
;; NOTE: old incompatibility --- superceded by the following
#+old
(signals type-error
(match '(1 (2 . 3)) ((assoc 2 3) t)))
;; NOTE: new incompatibility --- when it is not an assoc list, do not match.
(is-not-match '(1 (2 . 3)) (assoc 2 3))
issue # 54
(is-not-match '(1) (assoc :foo val)) ; should not signal error
(signals type-error
(match '((:foo 1))
((assoc :foo val :test (lambda (x y) (declare (ignorable x y)) (error 'type-error)))
val)))
(signals type-error
(match '((:foo 1))
((assoc :foo val :key (lambda (x) (declare (ignorable x)) (error 'type-error)))
val)))
(let ((counter 0))
(is-false
(handler-bind ((type-error #'continue))
(match '((:foo 1) (:bar 1))
((assoc :baz val :key (lambda (x)
(declare (ignorable x))
(restart-case (error 'type-error)
(continue ()
(incf counter)
(print :continue!)))
x))
val))))
(is (= 2 counter)))
NOTE : incompatibility --- first argument to assoc should be quoted or constant
( is - match ' ( ( a . 1 ) ) ( assoc a 1 ) )
(is-match '((a . 1)) (assoc 'a 1))
(is-not-match 1 (assoc 1 2))
(is-not-match '((1 . 2)) (assoc 3 4))
(is-not-match '((1 . 2) (3 . 4)) (assoc 3 5))
issue # 52
(is-match '((:foo . 1)) (assoc :foo val))
(is-not-match '((foo . 2)) (assoc :foo val))
(is-not-match '(("foo" . 3)) (assoc :foo val))
(is-not-match '((0 . 4)) (assoc :foo val))
(is-not-match '(1) (assoc :foo val))
(is-not-match '((1 . 2) 2) (assoc :foo val))
;; NOTE: incompatibility --- keyword arguments to assoc is evaluated
( is - match ' ( ( " a " . 1 ) ) ( assoc " A " 1 : test string - equal ) )
(is-match '(("a" . 1)) (assoc "A" 1 :test #'string-equal)))
(test property
(is-match '(:a 1) (property :a 1))
(is-match '(:a 1 :b 2) (property :a 1))
;; NOTE: depends on SAFETY setting, it may signal type-error
( is - match ' (: a 1 2 ) ( property : a 1 ) )
(is-match '(1 2 :b 3) (property :b 3))
NOTE : incompatibility --- first argument to property should be quoted or constant
( is - match ' ( a 1 ) ( property a 1 ) )
(is-match '(a 1) (property 'a 1))
(is-not-match 1 (property :a 1))
(is-not-match '(:a 1) (property :b 1))
(is-not-match '(:a 1 :b 2) (property :b 3)))
(test property-default-foundp
(is (= 3 (match '(:a 1 :b 2)
((property :c c 3)
c))))
(is-false (match '(:a 1 :b 2)
((property :c c 3 foundp)
foundp)))
(is (= 2 (match '(:a 1 :b 2)
((property :b b 3)
b))))
(is-true (match '(:a 1 :b 2)
((property :b b 3 foundp)
foundp))))
(test vector
(is-match (vector 1 2) (vector 1 2))
(match (vector 1 2)
;; soft vector pattern
((vector* 1 2 a) (is (eq a nil)))))
(test simple-vector
(is-match (vector 1 2) (simple-vector 1 2)))
(test class
(let ((person (make-instance 'person :name "Bob" :age 31)))
(is (equal '("Bob" 31)
(match person
((person name age) (list name age)))))
(is-match person (person))
(is-match person (person (name "Bob") (age 31)))
(is-match person (person (name "Bob")))
(is-match person (person (age 31)))
(is-not-match person (person (name "Alice")))
(is-not-match person (person (age 49)))
(is-not-match 1 (person))))
(test make-instance
(let ((person (make-instance 'person :name "Bob" :age 31)))
(is-match person (person :name "Bob" :age 31))
(is-not-match person (person :name "Bob" :age 49))))
(test structure
(let ((point (make-point :x 1 :y 2)))
(is (equal '(1 2)
(match point
((point- x y) (list x y)))))
(is-match point (point))
(is-match point (point (x 1) (y 2)))
(is-match point (point (x 1)))
(is-match point (point (y 2)))
(is-not-match point (point (x 2)))
(is-not-match 1 (point-))
(is-match point (point-))
(is-match point (point- (x 1) (y 2)))
(is-match point (point- (x 1)))
(is-match point (point- (y 2)))
(is-not-match point (point- (x 2)))
(is-not-match 1 (point-))))
(test structure-make-instance
(let ((point (make-point :x 1 :y 2)))
(is-match point (point- :x 1 :y 2))
(is-not-match point (point- :x 2 :y 2))))
(test list
(is-match '() (list))
(is-match '(1 2 3) (list 1 2 3))
(is-not-match '() (list _))
(is-not-match 5 (list _)))
(test list*
(is-match '() (list* _))
(is-match '(1 2 3) (list* 1 2 (list 3)))
(is-match '(1 2 3) (list* _))
guicho271828 --- this is incorrect , should match because ( list * 5 ) = = 5
( is - not - match 5 ( list * _ ) )
(is-match 5 (list* _)))
(test alist
(is-match '((1 . 2) (2 . 3) (3 . 4)) (alist (3 . 4) (1 . 2))))
(test plist
(is-match '(:a 1 :b 2 :c 3) (plist :c 3 :a 1)))
(test satisfies
(is-match 1 (satisfies numberp))
(is-not-match 1 (satisfies stringp)))
(test eq-family
(is-match :foo (eq :foo))
(is-match 1 (eql 1))
(is-match "foo" (equal "foo"))
(is-match #(1) (equalp #(1))))
(test type
(is-match 1 (type number))
(is-match "foo" (type string))
(is-match :foo (type (eql :foo)))
(is-match 1 (type (or string number)))
(is-not-match 1 (type (not t))))
(test guard-pattern
(is-match 1 (guard _ t))
(is-not-match 1 (guard _ nil))
(is-match 1 (guard 1 t))
(is-not-match 1 (guard 1 nil))
(is-not-match 1 (guard 2 t))
(is-match 1 (guard x (eql x 1))))
(test lift
(is-match 1 (and x (guard y (eql x y))))
(is-match 1 (and (guard x (eql x y)) y)) ;; forward-referencing guard
(is-not-match 1 (and x (guard 2 (eql x 1))))
(is-not-match 1 (and x (guard y (not (eql x y)))))
(is-match '(1 1) (list x (guard y (eql x y))))
(is-match '(1 1) (list (guard x (oddp x)) (guard y (eql x y)))))
(test lift1
(is-not-match '(1 2) (list (guard x (oddp x)) (guard y (eql x y))))
(is-match '(1 (1)) (list x (guard (list (guard y (eql x y))) (eql x 1))))
(is-not-match '(1 (1)) (list x (guard (list (guard y (eql x y))) (eql x 2))))
(is-match 1 (or (list x) (guard x (oddp x))))
(is-match '(1) (or (list x) (guard x (oddp x))))
(is-not-match 1 (or (list x) (guard x (evenp x)))))
(test lift2
(is-match '(1) (list (or (list x) (guard x (oddp x)))))
(is-not-match '(1) (or (list (or (list x) (guard x (evenp x))))
(list (guard x (eql x 2)))))
(is-match '(2) (or (list (or (list x) (guard x (evenp x))))
(list (guard x (eql x 2)))))
(is-match (list 2 2) (list (or (guard x (eql x 1))
(guard x (eql x 2)))
(or (guard y (eql y 1))
(guard y (eql y 2)))))
(is-match 2 (or (guard x (eql x 1))
(guard x (eql x 2))))
(is-match 5 (or (guard x (eql x 1))
(or (guard x (eql x 2))
(or (guard x (eql x 3))
(or (guard x (eql x 4))
(guard x (eql x 5)))))))
(is-match '(((1)))
(list (or (guard x (eql x 1))
(list (or (guard x (eql x 1))
(list (or (guard x (eql x 1))
(list)))))))))
(test not-pattern
(is-match 1 (not 2))
(is-not-match 1 (not 1))
;; double negation
(is-not-match 1 (not (not (not 1))))
(is-match 1 (not (not (not (not 1)))))
;; complex
(is-match 1 (not (guard it (consp it))))
;; variables in not pattern should not be bound
(is (equal 1
(let ((it 1))
(match 2
((not (guard it (eql it 3))) it)
(_ :fail))))))
(test or-pattern
(is-not-match 1 (or))
(is-match 1 (or 1))
(is-match 1 (or 1 1))
(is-match 1 (or 1 2))
(is-match 1 (or 2 1))
(is-not-match 1 (or 2 3))
(is-match 1 (or _))
(is-match 1 (or _ _))
(is-match 1 (or 2 (or 1)))
(is-match 1 (or (or 1)))
(is-not-match 1 (or (or (not 1))))
;; unshared variables
(is (equal '(nil nil)
(match 1 ((or 1 (list x) y) (list x y)))))
(is (equal '(nil 2)
(match 2 ((or 1 (list x) y) (list x y)))))
(is (equal '(1 nil)
(match '(1) ((or 1 (list x) y) (list x y))))))
(test and-pattern
(is-match 1 (and))
(is-match 1 (and 1))
(is-match 1 (and 1 1))
(is-not-match 1 (and 1 2))
(is-match 1 (and _))
(is-match 1 (and _ _))
(is-match 1 (and 1 (and 1)))
(is-match 1 (and (and 1)))
(is (eql 1 (match 1 ((and 1 x) x))))
(is-not-match 1 (and (and (not 1))))
(is-match 1 (and (type number) (type integer)))
;; complex
(is-true (match 1
((and 1 2) nil)
(1 t)
(2 nil)))
(is (eql 1
(match (list 1 2)
((list (and 1 x) 2) x))))
(is-true (match (list 1 2 3)
((list (and 1 2 3 4 5) 2))
((list (and 1 (type number)) 3 3))
((list (and 1 (type number)) 2 3) t)))
(is-true (match (list 2 2)
((list (and 2 (type number)) 3))
((list (and 2 (type number)) 2 3))
((list (and 1 (type number)) 2))
((list (and 2 (type number)) 2) t))))
(test match
;; empty
(is-false (match 1))
;; values
(is (equal '(1 2 3)
(multiple-value-list (match 1 (1 (values 1 2 3))))))
;; mixture
(is-true (match (cons 1 2)
((cons 2 1) 2)
(_ t)
((cons 1 2) nil)))
;; linear pattern
(signals error
(eval
'(match (cons 1 2)
((cons x x) t))))
(signals error
(eval
'(match (list 1 (list 2 3))
((list x (list y x)) t))))
(signals error
(eval
'(match (list 1 (list 2 3))
((list x (list y y)) t))))
(signals error
(eval
'(match 1
((and x x) t))))
(is-match 1 (and _ _))
(is-match 1 (or _ _))
;; declarations
(is-true (match 1
(1 (declare (ignore)) t)))
;; when is not supported
#+nil
(is-true (match 1
(1 when t (declare (ignore)) t)))
(is-true (match 1
((guard 1 t) (declare (ignore)) t)))
;; syntax sugar
#+nil
(is-true (match 1 (_ when t t)))
#+nil
(is-true (match 1 (_ unless nil t))))
(test multiple-value-match
(is (eql 2
(multiple-value-match (values 1 2)
((2) 1)
((1 y) y))))
;; linear pattern
(signals error
(eval
'(multiple-value-match (values 1 2)
((x x) t))))
(is-true (multiple-value-match 1
((_ _) t))))
(test ematch
(is-true (ematch 1 (1 t)))
(signals match-error
(ematch 1 (2 t)))
;; only once
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (ematch (f) (0 t))
(match-error (e)
(first (match-error-values e)))))))))
there is a magical error only on CMU on .
(test multiple-value-ematch
(signals match-error
(multiple-value-ematch (values 1 2)
((2 1) t)))
;; only once
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (multiple-value-ematch (values (f)) ((0) t))
(match-error (e)
(first (match-error-values e)))))))))
(test cmatch
(is-true (cmatch 1 (1 t)))
(is-false (handler-bind ((match-error #'continue))
(cmatch 1 (2 t))))
;; only once
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (cmatch (f) (0 t))
(match-error (e)
(first (match-error-values e)))))))))
(test multiple-value-cmatch
(is-false (handler-bind ((match-error #'continue))
(multiple-value-cmatch (values 1 2)
((2 1) t))))
;; only once
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (multiple-value-cmatch (values (f)) ((0) t))
(match-error (e)
(first (match-error-values e)))))))))
;;; Regression tests
(test issue39
(is (eql 0
(match '(0) ((list x) x))))
(is (eql 0
(match '(0) ((list (and x (guard it (numberp it)))) x)))))
This is from , but no description is given and it 's not clear why
;; this should not be allowed.
#+nil
(test issue38
(signals error
(eval '(match 1 ((or (place x) (place x)))))))
(test issue31
(is (equal '(2 1 (3 4))
(match '(1 2 3 4)
((or (list* (and (type symbol) x) y z)
(list* y x z))
(list x y z))))))
(test issue68
(is (equal '(:b 1)
(match 1
((guard x (equal x 2)) (list :a x))
(x (list :b x))))))
(defun signal-error ()
(error 'error))
(defun will-fail ()
(match 1
((not 2)
(signal-error))))
(test issue101
(signals error (will-fail)))
there is a magical error on CMU only on .
(test issue105
(is-match '(1) (list* (or 1 2) _)))
(defun ^2 (x) (* x x))
(test access
(is-match '(2) (list (access #'^2 4))))
(test match*
(match* ((list 2) (list 3) (list 5))
(((list x) (list y) (list (guard z (= z (+ x y)))))
(is (= 5 z)))
(_ (fail))))
(test defun-match*
(defun-match* myfunc (x y)
((1 2) 3)
((4 5) 6)
((_ _) nil))
(is (= 3 (myfunc 1 2)))
(is (= 6 (myfunc 4 5)))
(is-false (myfunc 7 8)))
(test next
;; optima:fail --> trivia:next : it causes symbol conflict with fiveam
;; and not convenient but note that it you :use trivia.fail package, it
;; exports 'trivia:fail, same functionality as in optima
(is-false (match 1 (1 (next))))
(is-true (match 1
(1 (next))
(1 t)))
(is-true (match 1
(1 (next))
(1 t)
(_ nil)))
(is (eql 1
(match (cons 1 2)
((cons x y)
(if (eql x 1)
(next)
y))
((cons x 2)
x))))
(is-true (multiple-value-match (values 1 2)
((1 2) (next))
((_ _) t)))
(is-true (ematch 1
(1 (next))
(_ t)))
(signals match-error
(ematch 1
(1 (next))
(1 (next))))
(signals match-error
(multiple-value-ematch (values 1 2)
((1 2) (next))))
(is-true (match 1 (_ (next)) (_ t)))
(signals match-error
(ematch 1
this should be match2 , since
(1 (next))
(1 (next)) ;; <<--- this `next' jumps to the
))
(1 ;; <<--- next matching clause here
(next))))
(let ((x `(match2 1 (1 (next)))))
(signals ERROR ;; not necessarily PROGRAM-ERROR
using ` next ' in the last clause of match2
(eval x))))
(test hash-table
(match (make-hash-table)
((hash-table count) (is (= count 0)))))
(test and-wildcard-bug
;; unintended unwinding by "wildcard" condition
(is-true
(match 3
((guard1 it t it (and (type number) a _))
(eq a 3)))))
(test issue-23
(is-match '(shader foo :fragment "")
(guard (list shader name type value)
(string-equal (symbol-name shader) "shader"))))
on clisp , fixnum is not recognized as an instance of built - in - class
#-clisp
(progn
(defgeneric plus (a b))
(defmethod plus ((a fixnum) (b fixnum))
(+ a b))
(test issue-24
(is-match #'plus
(generic-function))
(match #'plus
((generic-function
methods
method-combination
lambda-list
argument-precedence-order)
(is (= 1 (length methods)))
(is-true method-combination)
(is (= 2 (length lambda-list)))
(is (equal '(a b) argument-precedence-order)))))
)
(test issue-51
;; otherwise == _
(signals unbound-variable
(eval
'(match :anything0
(otherwise
otherwise))))
(is-match :anything1 otherwise)
(is-match (list :anything2 :anything2)
(list otherwise otherwise))
(is-match (list :anything3 :anything4)
(list otherwise otherwise))
(is-match (list :anything5 :anything6)
(list a b))
;; this is explicitly allowed.
(is-true
(match (list :anything7 :anything7)
(otherwise t)
(_ (error "should not match")))))
| null |
https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/trivia-20180711-git/test/suite.lisp
|
lisp
|
integrated testing including derived patterns
separately from :trivia.fail to avoid the common conflict against fiveam.
Also, :trivia.next and :trivia.skip exports `next' (conflicts with
`macroexpand': some tests are now replaced with eval
for debugging purpose
Pattern matching
integer
t
nil
keyword
float
string
complex
ensure these are compared by char-wise eql
check if INCLUDEd slots are direct slots
simple bind
anonymous bind
complex bind
level 0
cons
NOTE: incompatibility --- this is not an association list, according to CLHS
NOTE: old incompatibility --- superceded by the following
NOTE: new incompatibility --- when it is not an assoc list, do not match.
should not signal error
NOTE: incompatibility --- keyword arguments to assoc is evaluated
NOTE: depends on SAFETY setting, it may signal type-error
soft vector pattern
forward-referencing guard
double negation
complex
variables in not pattern should not be bound
unshared variables
complex
empty
values
mixture
linear pattern
declarations
when is not supported
syntax sugar
linear pattern
only once
only once
only once
only once
Regression tests
this should not be allowed.
optima:fail --> trivia:next : it causes symbol conflict with fiveam
and not convenient but note that it you :use trivia.fail package, it
exports 'trivia:fail, same functionality as in optima
<<--- this `next' jumps to the
<<--- next matching clause here
not necessarily PROGRAM-ERROR
unintended unwinding by "wildcard" condition
otherwise == _
this is explicitly allowed.
|
INCOMPATIBILITY NOTE : ` fail ' no longer effective by default : it is now exported
` iterate : next ' ) and ` skip ' , respectively . all 3 macros have the same meaning .
INCOMPATIBILITY NOTE : ` match ' no longer expanded in 1 - pass through
(defpackage :trivia.test
(:use :closer-common-lisp :fiveam
:trivia.level2
:trivia.level1
:trivia.next
:trivia.level2.impl))
(in-package :trivia.test)
( setf * trace - dispatching * t )
(def-suite :trivia)
(in-suite :trivia)
(defmacro is-match (arg &body pattern)
`(is-true (locally
(declare (optimize (safety 3) (debug 3) (speed 0)))
(match ,arg (,@pattern t)))
,(format nil "~<pattern ~a did not match against arg ~s~:@>" (list pattern arg))))
(defmacro is-not-match (arg &body pattern)
`(is-false (locally
(declare (optimize (safety 3) (debug 3) (speed 0)))
(match ,arg (,@pattern t)))
,(format nil "~<pattern ~a matched against arg ~s~:@>" (list pattern arg))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass person ()
((name :initarg :name :reader name)
(age :initarg :age)))
(defun age (a b c)
(format t "this function is meaningless ~a ~a ~a" a b c))
(defstruct (point (:predicate point-p))
x y)
(defmethod make-load-form ((o point) &optional environment)
(make-load-form-saving-slots o
:slot-names '(x y)
:environment environment))
(defstruct (point3 (:include point))
z)
(defmethod make-load-form ((o point3) &optional environment)
(make-load-form-saving-slots o
:slot-names '(x y z)
:environment environment))
(declaim (inline x))
(defun x (a b c)
(format t "this function is meaningless ~a ~a ~a" a b c))
(declaim (notinline x)))
(test (constant-pattern :compile-at :definition-time)
(is-match 1 1)
(is-match t t)
(is-match nil nil)
(is-match :foo :foo)
(is-match 3.14 3.14)
(is-not-match 0.999 1)
(is-match "foo" "foo")
(is-match '(1 t 3.14 :foo "foo") '(1 t 3.14 :foo "foo"))
quoted conses should not expand to patterns ( issue # 86 )
#+(or)
(is (eql 3 (match '(1 2 3) ('(1 _ a) a))))
(is-not-match '(1 2 3) '(1 _ a))
(is (eql 3 (match #(1 2 3) (#(1 _ a) a))))
(is-match "aaa" "aaa")
(is-not-match "aaa" "AAA")
(is-match #S(POINT :x "A" :y "B")
#S(POINT :x "A" :y "B"))
(is-not-match #S(POINT :x "A" :y "B")
#S(POINT :x "a" :y "b"))
(is-match #S(POINT3 :x "A" :y "B" :z "C")
#S(POINT3 :x "A" :y "B" :z "C"))
(is-not-match #S(POINT3 :x "A" :y "B" :z "C")
#S(POINT3 :x "a" :y "b" :z "c")))
(test variable-pattern
(is (eql 1 (match 1 (x x))))
(is-match 1 _)
(is (eql 6
(match '(1 2 3)
((list x y z) (+ x y z))))))
(test place-pattern
(let ((z 1))
(match z ((place x) (incf x)))
(is (eql 2 z)))
level 1
(let ((z (cons 1 2)))
(match z
((cons (place x) y)
(incf x)
(incf y)))
(is (equal (cons 2 2) z)))
level 2
(let ((z (list (vector 1))))
(match z
((list (vector (place x)))
(incf x)))
(is (equalp (list (vector 2)) z))))
(test predicatep
(is (null (predicatep 'point)))
(is (eq 'point-p (predicate-p 'point))))
(test constructor-pattern
(is-match (cons 1 2) (cons 1 2)))
there is a magical error on ECL only on travis .
(test assoc
(is-match '((1 . 2)) (assoc 1 2))
(is-match '((1 . 2) (3 . 4)) (assoc 3 4))
( is - match ' ( 1 ( 2 . 3 ) ) ( assoc 2 3 ) )
#+old
(signals type-error
(match '(1 (2 . 3)) ((assoc 2 3) t)))
(is-not-match '(1 (2 . 3)) (assoc 2 3))
issue # 54
(signals type-error
(match '((:foo 1))
((assoc :foo val :test (lambda (x y) (declare (ignorable x y)) (error 'type-error)))
val)))
(signals type-error
(match '((:foo 1))
((assoc :foo val :key (lambda (x) (declare (ignorable x)) (error 'type-error)))
val)))
(let ((counter 0))
(is-false
(handler-bind ((type-error #'continue))
(match '((:foo 1) (:bar 1))
((assoc :baz val :key (lambda (x)
(declare (ignorable x))
(restart-case (error 'type-error)
(continue ()
(incf counter)
(print :continue!)))
x))
val))))
(is (= 2 counter)))
NOTE : incompatibility --- first argument to assoc should be quoted or constant
( is - match ' ( ( a . 1 ) ) ( assoc a 1 ) )
(is-match '((a . 1)) (assoc 'a 1))
(is-not-match 1 (assoc 1 2))
(is-not-match '((1 . 2)) (assoc 3 4))
(is-not-match '((1 . 2) (3 . 4)) (assoc 3 5))
issue # 52
(is-match '((:foo . 1)) (assoc :foo val))
(is-not-match '((foo . 2)) (assoc :foo val))
(is-not-match '(("foo" . 3)) (assoc :foo val))
(is-not-match '((0 . 4)) (assoc :foo val))
(is-not-match '(1) (assoc :foo val))
(is-not-match '((1 . 2) 2) (assoc :foo val))
( is - match ' ( ( " a " . 1 ) ) ( assoc " A " 1 : test string - equal ) )
(is-match '(("a" . 1)) (assoc "A" 1 :test #'string-equal)))
(test property
(is-match '(:a 1) (property :a 1))
(is-match '(:a 1 :b 2) (property :a 1))
( is - match ' (: a 1 2 ) ( property : a 1 ) )
(is-match '(1 2 :b 3) (property :b 3))
NOTE : incompatibility --- first argument to property should be quoted or constant
( is - match ' ( a 1 ) ( property a 1 ) )
(is-match '(a 1) (property 'a 1))
(is-not-match 1 (property :a 1))
(is-not-match '(:a 1) (property :b 1))
(is-not-match '(:a 1 :b 2) (property :b 3)))
(test property-default-foundp
(is (= 3 (match '(:a 1 :b 2)
((property :c c 3)
c))))
(is-false (match '(:a 1 :b 2)
((property :c c 3 foundp)
foundp)))
(is (= 2 (match '(:a 1 :b 2)
((property :b b 3)
b))))
(is-true (match '(:a 1 :b 2)
((property :b b 3 foundp)
foundp))))
(test vector
(is-match (vector 1 2) (vector 1 2))
(match (vector 1 2)
((vector* 1 2 a) (is (eq a nil)))))
(test simple-vector
(is-match (vector 1 2) (simple-vector 1 2)))
(test class
(let ((person (make-instance 'person :name "Bob" :age 31)))
(is (equal '("Bob" 31)
(match person
((person name age) (list name age)))))
(is-match person (person))
(is-match person (person (name "Bob") (age 31)))
(is-match person (person (name "Bob")))
(is-match person (person (age 31)))
(is-not-match person (person (name "Alice")))
(is-not-match person (person (age 49)))
(is-not-match 1 (person))))
(test make-instance
(let ((person (make-instance 'person :name "Bob" :age 31)))
(is-match person (person :name "Bob" :age 31))
(is-not-match person (person :name "Bob" :age 49))))
(test structure
(let ((point (make-point :x 1 :y 2)))
(is (equal '(1 2)
(match point
((point- x y) (list x y)))))
(is-match point (point))
(is-match point (point (x 1) (y 2)))
(is-match point (point (x 1)))
(is-match point (point (y 2)))
(is-not-match point (point (x 2)))
(is-not-match 1 (point-))
(is-match point (point-))
(is-match point (point- (x 1) (y 2)))
(is-match point (point- (x 1)))
(is-match point (point- (y 2)))
(is-not-match point (point- (x 2)))
(is-not-match 1 (point-))))
(test structure-make-instance
(let ((point (make-point :x 1 :y 2)))
(is-match point (point- :x 1 :y 2))
(is-not-match point (point- :x 2 :y 2))))
(test list
(is-match '() (list))
(is-match '(1 2 3) (list 1 2 3))
(is-not-match '() (list _))
(is-not-match 5 (list _)))
(test list*
(is-match '() (list* _))
(is-match '(1 2 3) (list* 1 2 (list 3)))
(is-match '(1 2 3) (list* _))
guicho271828 --- this is incorrect , should match because ( list * 5 ) = = 5
( is - not - match 5 ( list * _ ) )
(is-match 5 (list* _)))
(test alist
(is-match '((1 . 2) (2 . 3) (3 . 4)) (alist (3 . 4) (1 . 2))))
(test plist
(is-match '(:a 1 :b 2 :c 3) (plist :c 3 :a 1)))
(test satisfies
(is-match 1 (satisfies numberp))
(is-not-match 1 (satisfies stringp)))
(test eq-family
(is-match :foo (eq :foo))
(is-match 1 (eql 1))
(is-match "foo" (equal "foo"))
(is-match #(1) (equalp #(1))))
(test type
(is-match 1 (type number))
(is-match "foo" (type string))
(is-match :foo (type (eql :foo)))
(is-match 1 (type (or string number)))
(is-not-match 1 (type (not t))))
(test guard-pattern
(is-match 1 (guard _ t))
(is-not-match 1 (guard _ nil))
(is-match 1 (guard 1 t))
(is-not-match 1 (guard 1 nil))
(is-not-match 1 (guard 2 t))
(is-match 1 (guard x (eql x 1))))
(test lift
(is-match 1 (and x (guard y (eql x y))))
(is-not-match 1 (and x (guard 2 (eql x 1))))
(is-not-match 1 (and x (guard y (not (eql x y)))))
(is-match '(1 1) (list x (guard y (eql x y))))
(is-match '(1 1) (list (guard x (oddp x)) (guard y (eql x y)))))
(test lift1
(is-not-match '(1 2) (list (guard x (oddp x)) (guard y (eql x y))))
(is-match '(1 (1)) (list x (guard (list (guard y (eql x y))) (eql x 1))))
(is-not-match '(1 (1)) (list x (guard (list (guard y (eql x y))) (eql x 2))))
(is-match 1 (or (list x) (guard x (oddp x))))
(is-match '(1) (or (list x) (guard x (oddp x))))
(is-not-match 1 (or (list x) (guard x (evenp x)))))
(test lift2
(is-match '(1) (list (or (list x) (guard x (oddp x)))))
(is-not-match '(1) (or (list (or (list x) (guard x (evenp x))))
(list (guard x (eql x 2)))))
(is-match '(2) (or (list (or (list x) (guard x (evenp x))))
(list (guard x (eql x 2)))))
(is-match (list 2 2) (list (or (guard x (eql x 1))
(guard x (eql x 2)))
(or (guard y (eql y 1))
(guard y (eql y 2)))))
(is-match 2 (or (guard x (eql x 1))
(guard x (eql x 2))))
(is-match 5 (or (guard x (eql x 1))
(or (guard x (eql x 2))
(or (guard x (eql x 3))
(or (guard x (eql x 4))
(guard x (eql x 5)))))))
(is-match '(((1)))
(list (or (guard x (eql x 1))
(list (or (guard x (eql x 1))
(list (or (guard x (eql x 1))
(list)))))))))
(test not-pattern
(is-match 1 (not 2))
(is-not-match 1 (not 1))
(is-not-match 1 (not (not (not 1))))
(is-match 1 (not (not (not (not 1)))))
(is-match 1 (not (guard it (consp it))))
(is (equal 1
(let ((it 1))
(match 2
((not (guard it (eql it 3))) it)
(_ :fail))))))
(test or-pattern
(is-not-match 1 (or))
(is-match 1 (or 1))
(is-match 1 (or 1 1))
(is-match 1 (or 1 2))
(is-match 1 (or 2 1))
(is-not-match 1 (or 2 3))
(is-match 1 (or _))
(is-match 1 (or _ _))
(is-match 1 (or 2 (or 1)))
(is-match 1 (or (or 1)))
(is-not-match 1 (or (or (not 1))))
(is (equal '(nil nil)
(match 1 ((or 1 (list x) y) (list x y)))))
(is (equal '(nil 2)
(match 2 ((or 1 (list x) y) (list x y)))))
(is (equal '(1 nil)
(match '(1) ((or 1 (list x) y) (list x y))))))
(test and-pattern
(is-match 1 (and))
(is-match 1 (and 1))
(is-match 1 (and 1 1))
(is-not-match 1 (and 1 2))
(is-match 1 (and _))
(is-match 1 (and _ _))
(is-match 1 (and 1 (and 1)))
(is-match 1 (and (and 1)))
(is (eql 1 (match 1 ((and 1 x) x))))
(is-not-match 1 (and (and (not 1))))
(is-match 1 (and (type number) (type integer)))
(is-true (match 1
((and 1 2) nil)
(1 t)
(2 nil)))
(is (eql 1
(match (list 1 2)
((list (and 1 x) 2) x))))
(is-true (match (list 1 2 3)
((list (and 1 2 3 4 5) 2))
((list (and 1 (type number)) 3 3))
((list (and 1 (type number)) 2 3) t)))
(is-true (match (list 2 2)
((list (and 2 (type number)) 3))
((list (and 2 (type number)) 2 3))
((list (and 1 (type number)) 2))
((list (and 2 (type number)) 2) t))))
(test match
(is-false (match 1))
(is (equal '(1 2 3)
(multiple-value-list (match 1 (1 (values 1 2 3))))))
(is-true (match (cons 1 2)
((cons 2 1) 2)
(_ t)
((cons 1 2) nil)))
(signals error
(eval
'(match (cons 1 2)
((cons x x) t))))
(signals error
(eval
'(match (list 1 (list 2 3))
((list x (list y x)) t))))
(signals error
(eval
'(match (list 1 (list 2 3))
((list x (list y y)) t))))
(signals error
(eval
'(match 1
((and x x) t))))
(is-match 1 (and _ _))
(is-match 1 (or _ _))
(is-true (match 1
(1 (declare (ignore)) t)))
#+nil
(is-true (match 1
(1 when t (declare (ignore)) t)))
(is-true (match 1
((guard 1 t) (declare (ignore)) t)))
#+nil
(is-true (match 1 (_ when t t)))
#+nil
(is-true (match 1 (_ unless nil t))))
(test multiple-value-match
(is (eql 2
(multiple-value-match (values 1 2)
((2) 1)
((1 y) y))))
(signals error
(eval
'(multiple-value-match (values 1 2)
((x x) t))))
(is-true (multiple-value-match 1
((_ _) t))))
(test ematch
(is-true (ematch 1 (1 t)))
(signals match-error
(ematch 1 (2 t)))
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (ematch (f) (0 t))
(match-error (e)
(first (match-error-values e)))))))))
there is a magical error only on CMU on .
(test multiple-value-ematch
(signals match-error
(multiple-value-ematch (values 1 2)
((2 1) t)))
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (multiple-value-ematch (values (f)) ((0) t))
(match-error (e)
(first (match-error-values e)))))))))
(test cmatch
(is-true (cmatch 1 (1 t)))
(is-false (handler-bind ((match-error #'continue))
(cmatch 1 (2 t))))
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (cmatch (f) (0 t))
(match-error (e)
(first (match-error-values e)))))))))
(test multiple-value-cmatch
(is-false (handler-bind ((match-error #'continue))
(multiple-value-cmatch (values 1 2)
((2 1) t))))
(let ((count 0))
(flet ((f () (incf count)))
(is (eql 1
(handler-case (multiple-value-cmatch (values (f)) ((0) t))
(match-error (e)
(first (match-error-values e)))))))))
(test issue39
(is (eql 0
(match '(0) ((list x) x))))
(is (eql 0
(match '(0) ((list (and x (guard it (numberp it)))) x)))))
This is from , but no description is given and it 's not clear why
#+nil
(test issue38
(signals error
(eval '(match 1 ((or (place x) (place x)))))))
(test issue31
(is (equal '(2 1 (3 4))
(match '(1 2 3 4)
((or (list* (and (type symbol) x) y z)
(list* y x z))
(list x y z))))))
(test issue68
(is (equal '(:b 1)
(match 1
((guard x (equal x 2)) (list :a x))
(x (list :b x))))))
(defun signal-error ()
(error 'error))
(defun will-fail ()
(match 1
((not 2)
(signal-error))))
(test issue101
(signals error (will-fail)))
there is a magical error on CMU only on .
(test issue105
(is-match '(1) (list* (or 1 2) _)))
(defun ^2 (x) (* x x))
(test access
(is-match '(2) (list (access #'^2 4))))
(test match*
(match* ((list 2) (list 3) (list 5))
(((list x) (list y) (list (guard z (= z (+ x y)))))
(is (= 5 z)))
(_ (fail))))
(test defun-match*
(defun-match* myfunc (x y)
((1 2) 3)
((4 5) 6)
((_ _) nil))
(is (= 3 (myfunc 1 2)))
(is (= 6 (myfunc 4 5)))
(is-false (myfunc 7 8)))
(test next
(is-false (match 1 (1 (next))))
(is-true (match 1
(1 (next))
(1 t)))
(is-true (match 1
(1 (next))
(1 t)
(_ nil)))
(is (eql 1
(match (cons 1 2)
((cons x y)
(if (eql x 1)
(next)
y))
((cons x 2)
x))))
(is-true (multiple-value-match (values 1 2)
((1 2) (next))
((_ _) t)))
(is-true (ematch 1
(1 (next))
(_ t)))
(signals match-error
(ematch 1
(1 (next))
(1 (next))))
(signals match-error
(multiple-value-ematch (values 1 2)
((1 2) (next))))
(is-true (match 1 (_ (next)) (_ t)))
(signals match-error
(ematch 1
this should be match2 , since
(1 (next))
))
(next))))
(let ((x `(match2 1 (1 (next)))))
using ` next ' in the last clause of match2
(eval x))))
(test hash-table
(match (make-hash-table)
((hash-table count) (is (= count 0)))))
(test and-wildcard-bug
(is-true
(match 3
((guard1 it t it (and (type number) a _))
(eq a 3)))))
(test issue-23
(is-match '(shader foo :fragment "")
(guard (list shader name type value)
(string-equal (symbol-name shader) "shader"))))
on clisp , fixnum is not recognized as an instance of built - in - class
#-clisp
(progn
(defgeneric plus (a b))
(defmethod plus ((a fixnum) (b fixnum))
(+ a b))
(test issue-24
(is-match #'plus
(generic-function))
(match #'plus
((generic-function
methods
method-combination
lambda-list
argument-precedence-order)
(is (= 1 (length methods)))
(is-true method-combination)
(is (= 2 (length lambda-list)))
(is (equal '(a b) argument-precedence-order)))))
)
(test issue-51
(signals unbound-variable
(eval
'(match :anything0
(otherwise
otherwise))))
(is-match :anything1 otherwise)
(is-match (list :anything2 :anything2)
(list otherwise otherwise))
(is-match (list :anything3 :anything4)
(list otherwise otherwise))
(is-match (list :anything5 :anything6)
(list a b))
(is-true
(match (list :anything7 :anything7)
(otherwise t)
(_ (error "should not match")))))
|
5bfb5327451d1bae40b004439d8b6edcae9fa3c53bf23079eb58043d5481e615
|
boris-ci/boris
|
EitherT.hs
|
# LANGUAGE NoImplicitPrelude #
module Boris.Prelude.EitherT (
EitherT
, Except.ExceptT
, newEitherT
, runEitherT
, eitherT
, mapEitherT
, bimapEitherT
, firstEitherT
, secondEitherT
, left
, hoistEither
, bracketEitherT'
) where
import Control.Monad.Catch (MonadMask (..), SomeException (..), throwM, catchAll)
import Control.Applicative (Applicative (..))
import Control.Monad (Monad (..), (>>=), liftM)
import qualified Control.Monad.Trans.Except as Except
import Data.Either (Either (..), either)
import Data.Function ((.), ($), id, const)
import Data.Functor (Functor (..))
type EitherT =
Except.ExceptT
newEitherT :: f (Either e a) -> EitherT e f a
newEitherT =
Except.ExceptT
runEitherT :: EitherT e f a -> f (Either e a)
runEitherT =
Except.runExceptT
eitherT :: Monad m => (x -> m b) -> (a -> m b) -> EitherT x m a -> m b
eitherT f g m =
runEitherT m >>= either f g
left :: Applicative f => e -> EitherT e f a
left =
newEitherT . pure . Left
mapEitherT :: (m (Either x a) -> n (Either y b)) -> EitherT x m a -> EitherT y n b
mapEitherT f =
newEitherT . f . runEitherT
bimapEitherT :: Functor m => (x -> y) -> (a -> b) -> EitherT x m a -> EitherT y m b
bimapEitherT f g =
mapEitherT (fmap (either (Left . f) (Right . g)))
firstEitherT :: Functor m => (x -> y) -> EitherT x m a -> EitherT y m a
firstEitherT f =
bimapEitherT f id
secondEitherT :: Functor m => (a -> b) -> EitherT x m a -> EitherT x m b
secondEitherT f =
bimapEitherT id f
hoistEither :: Monad m => Either x a -> EitherT x m a
hoistEither =
newEitherT . return
bracketEitherT' :: MonadMask m => EitherT e m a -> (a -> EitherT e m c) -> (a -> EitherT e m b) -> EitherT e m b
bracketEitherT' acquire release run =
newEitherT $ bracketF
(runEitherT acquire)
(\r -> case r of
Left _ ->
-- Acquire failed, we have nothing to release
return . Right $ ()
Right r' ->
-- Acquire succeeded, we need to try and release
runEitherT (release r') >>= \x -> return $ case x of
Left err -> Left (Left err)
Right _ -> Right ())
(\r -> case r of
Left err ->
-- Acquire failed, we have nothing to run
return . Left $ err
Right r' ->
-- Acquire succeeded, we can do some work
runEitherT (run r'))
data BracketResult a =
BracketOk a
| BracketFailedFinalizerOk SomeException
| BracketFailedFinalizerError a
-- Bracket where you care about the output of the finalizer. If the finalizer fails
-- with a value level fail, it will return the result of the finalizer.
:
-- - Left indicates a value level fail.
-- - Right indicates that the finalizer has a value level success, and its results can be ignored.
--
bracketF :: MonadMask m => m a -> (a -> m (Either b c)) -> (a -> m b) -> m b
bracketF a f g =
mask $ \restore -> do
a' <- a
x <- restore (BracketOk `liftM` g a') `catchAll`
(\ex -> either BracketFailedFinalizerError (const $ BracketFailedFinalizerOk ex) `liftM` f a')
case x of
BracketFailedFinalizerOk ex ->
throwM ex
BracketFailedFinalizerError b ->
return b
BracketOk b -> do
z <- f a'
return $ either id (const b) z
| null |
https://raw.githubusercontent.com/boris-ci/boris/c321187490afc889bf281442ac4ef9398b77b200/boris-core/src/Boris/Prelude/EitherT.hs
|
haskell
|
Acquire failed, we have nothing to release
Acquire succeeded, we need to try and release
Acquire failed, we have nothing to run
Acquire succeeded, we can do some work
Bracket where you care about the output of the finalizer. If the finalizer fails
with a value level fail, it will return the result of the finalizer.
- Left indicates a value level fail.
- Right indicates that the finalizer has a value level success, and its results can be ignored.
|
# LANGUAGE NoImplicitPrelude #
module Boris.Prelude.EitherT (
EitherT
, Except.ExceptT
, newEitherT
, runEitherT
, eitherT
, mapEitherT
, bimapEitherT
, firstEitherT
, secondEitherT
, left
, hoistEither
, bracketEitherT'
) where
import Control.Monad.Catch (MonadMask (..), SomeException (..), throwM, catchAll)
import Control.Applicative (Applicative (..))
import Control.Monad (Monad (..), (>>=), liftM)
import qualified Control.Monad.Trans.Except as Except
import Data.Either (Either (..), either)
import Data.Function ((.), ($), id, const)
import Data.Functor (Functor (..))
type EitherT =
Except.ExceptT
newEitherT :: f (Either e a) -> EitherT e f a
newEitherT =
Except.ExceptT
runEitherT :: EitherT e f a -> f (Either e a)
runEitherT =
Except.runExceptT
eitherT :: Monad m => (x -> m b) -> (a -> m b) -> EitherT x m a -> m b
eitherT f g m =
runEitherT m >>= either f g
left :: Applicative f => e -> EitherT e f a
left =
newEitherT . pure . Left
mapEitherT :: (m (Either x a) -> n (Either y b)) -> EitherT x m a -> EitherT y n b
mapEitherT f =
newEitherT . f . runEitherT
bimapEitherT :: Functor m => (x -> y) -> (a -> b) -> EitherT x m a -> EitherT y m b
bimapEitherT f g =
mapEitherT (fmap (either (Left . f) (Right . g)))
firstEitherT :: Functor m => (x -> y) -> EitherT x m a -> EitherT y m a
firstEitherT f =
bimapEitherT f id
secondEitherT :: Functor m => (a -> b) -> EitherT x m a -> EitherT x m b
secondEitherT f =
bimapEitherT id f
hoistEither :: Monad m => Either x a -> EitherT x m a
hoistEither =
newEitherT . return
bracketEitherT' :: MonadMask m => EitherT e m a -> (a -> EitherT e m c) -> (a -> EitherT e m b) -> EitherT e m b
bracketEitherT' acquire release run =
newEitherT $ bracketF
(runEitherT acquire)
(\r -> case r of
Left _ ->
return . Right $ ()
Right r' ->
runEitherT (release r') >>= \x -> return $ case x of
Left err -> Left (Left err)
Right _ -> Right ())
(\r -> case r of
Left err ->
return . Left $ err
Right r' ->
runEitherT (run r'))
data BracketResult a =
BracketOk a
| BracketFailedFinalizerOk SomeException
| BracketFailedFinalizerError a
:
bracketF :: MonadMask m => m a -> (a -> m (Either b c)) -> (a -> m b) -> m b
bracketF a f g =
mask $ \restore -> do
a' <- a
x <- restore (BracketOk `liftM` g a') `catchAll`
(\ex -> either BracketFailedFinalizerError (const $ BracketFailedFinalizerOk ex) `liftM` f a')
case x of
BracketFailedFinalizerOk ex ->
throwM ex
BracketFailedFinalizerError b ->
return b
BracketOk b -> do
z <- f a'
return $ either id (const b) z
|
c3c11a67f04ca06820f9bf79df7fc26a92e26a79496f7513f130addb146533c0
|
coq/coq
|
fl.ml
|
(************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
module Error = struct
exception CannotFindMeta of string * string
exception CannotParseMetaFile of string * string
exception DeclaredMLModuleNotFound of string * string * string
exception MetaLacksFieldForPackage of string * string * string
let no_meta f package = raise @@ CannotFindMeta (f, package)
let cannot_parse_meta_file file msg = raise @@ CannotParseMetaFile (file,msg)
let declare_in_META f s m = raise @@ DeclaredMLModuleNotFound (f, s, m)
let meta_file_lacks_field meta_file package field = raise @@ MetaLacksFieldForPackage (meta_file, package, field)
let _ = CErrors.register_handler @@ function
| CannotFindMeta (f, package) ->
Some Pp.(str "in file" ++ spc () ++ str f ++ str "," ++ spc ()
++ str "could not find META." ++ str package ++ str ".")
| CannotParseMetaFile (file, msg) ->
Some Pp.(str "META file \"" ++ str file ++ str "\":" ++ spc ()
++ str "Syntax error:" ++ spc () ++ str msg)
| DeclaredMLModuleNotFound (f, s, m) ->
Some Pp.(str "in file " ++ str f ++ str "," ++ spc() ++ str "declared ML module" ++ spc ()
++ str s ++ spc () ++ str "has not been found in" ++ spc () ++ str m ++ str ".")
| MetaLacksFieldForPackage (meta_file, package, field) ->
Some Pp.(str "META file \"" ++ str meta_file ++ str "\"" ++ spc () ++ str "lacks field" ++ spc ()
++ str field ++ spc () ++ str "for package" ++ spc () ++ str package ++ str ".")
| _ -> None
end
Platform build is doing something weird with META , hence we parse
when finding , but at some point we should find , then parse .
when finding, but at some point we should find, then parse. *)
let parse_META meta_file package =
try
let ic = open_in meta_file in
let m = Fl_metascanner.parse ic in
close_in ic;
Some m
with
(* This should not be necessary, but there's a problem in the platform build *)
| Sys_error _msg -> None
(* findlib >= 1.9.3 uses its own Error exception, so we can't catch
it without bumping our version requirements. TODO pass the message on once we bump. *)
| _ -> Error.cannot_parse_meta_file package ""
let rec find_parsable_META meta_files package =
match meta_files with
| [] ->
(try
let meta_file = Findlib.package_meta_file package in
Option.map (fun meta -> meta_file, meta) (parse_META meta_file package)
with Fl_package_base.No_such_package _ -> None)
| meta_file :: ms ->
if String.equal (Filename.extension meta_file) ("." ^ package)
then Option.map (fun meta -> meta_file, meta) (parse_META meta_file package)
else find_parsable_META ms package
let rec find_plugin_field_opt fld = function
| [] ->
None
| { Fl_metascanner.def_var; def_value; _ } :: rest ->
if String.equal def_var fld
then Some def_value
else find_plugin_field_opt fld rest
let find_plugin_field fld def pkgs =
Option.default def (find_plugin_field_opt fld pkgs)
let rec find_plugin meta_file plugin_name path p { Fl_metascanner.pkg_defs ; pkg_children } =
match p with
| [] -> path, pkg_defs
| p :: ps ->
let c =
match CList.assoc_f_opt String.equal p pkg_children with
| None -> Error.declare_in_META meta_file (String.concat "." plugin_name) meta_file
| Some c -> c
in
let path = path @ [find_plugin_field "directory" "." c.Fl_metascanner.pkg_defs] in
find_plugin meta_file plugin_name path ps c
let findlib_resolve ~meta_files ~file ~package ~plugin_name =
match find_parsable_META meta_files package with
| None -> Error.no_meta file package
| Some (meta_file, meta) ->
(* let meta = parse_META meta_file package in *)
let path = [find_plugin_field "directory" "." meta.Fl_metascanner.pkg_defs] in
let path, plug = find_plugin meta_file plugin_name path plugin_name meta in
let cmxs_file =
match find_plugin_field_opt "plugin" plug with
| None ->
Error.meta_file_lacks_field meta_file package "plugin"
| Some res_file ->
String.concat "/" path ^ "/" ^ Filename.chop_extension res_file
in
meta_file, cmxs_file
| null |
https://raw.githubusercontent.com/coq/coq/c4587fa780c885fda25a38a2f16e84dc9011f9bd/tools/coqdep/lib/fl.ml
|
ocaml
|
**********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
This should not be necessary, but there's a problem in the platform build
findlib >= 1.9.3 uses its own Error exception, so we can't catch
it without bumping our version requirements. TODO pass the message on once we bump.
let meta = parse_META meta_file package in
|
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
module Error = struct
exception CannotFindMeta of string * string
exception CannotParseMetaFile of string * string
exception DeclaredMLModuleNotFound of string * string * string
exception MetaLacksFieldForPackage of string * string * string
let no_meta f package = raise @@ CannotFindMeta (f, package)
let cannot_parse_meta_file file msg = raise @@ CannotParseMetaFile (file,msg)
let declare_in_META f s m = raise @@ DeclaredMLModuleNotFound (f, s, m)
let meta_file_lacks_field meta_file package field = raise @@ MetaLacksFieldForPackage (meta_file, package, field)
let _ = CErrors.register_handler @@ function
| CannotFindMeta (f, package) ->
Some Pp.(str "in file" ++ spc () ++ str f ++ str "," ++ spc ()
++ str "could not find META." ++ str package ++ str ".")
| CannotParseMetaFile (file, msg) ->
Some Pp.(str "META file \"" ++ str file ++ str "\":" ++ spc ()
++ str "Syntax error:" ++ spc () ++ str msg)
| DeclaredMLModuleNotFound (f, s, m) ->
Some Pp.(str "in file " ++ str f ++ str "," ++ spc() ++ str "declared ML module" ++ spc ()
++ str s ++ spc () ++ str "has not been found in" ++ spc () ++ str m ++ str ".")
| MetaLacksFieldForPackage (meta_file, package, field) ->
Some Pp.(str "META file \"" ++ str meta_file ++ str "\"" ++ spc () ++ str "lacks field" ++ spc ()
++ str field ++ spc () ++ str "for package" ++ spc () ++ str package ++ str ".")
| _ -> None
end
Platform build is doing something weird with META , hence we parse
when finding , but at some point we should find , then parse .
when finding, but at some point we should find, then parse. *)
let parse_META meta_file package =
try
let ic = open_in meta_file in
let m = Fl_metascanner.parse ic in
close_in ic;
Some m
with
| Sys_error _msg -> None
| _ -> Error.cannot_parse_meta_file package ""
let rec find_parsable_META meta_files package =
match meta_files with
| [] ->
(try
let meta_file = Findlib.package_meta_file package in
Option.map (fun meta -> meta_file, meta) (parse_META meta_file package)
with Fl_package_base.No_such_package _ -> None)
| meta_file :: ms ->
if String.equal (Filename.extension meta_file) ("." ^ package)
then Option.map (fun meta -> meta_file, meta) (parse_META meta_file package)
else find_parsable_META ms package
let rec find_plugin_field_opt fld = function
| [] ->
None
| { Fl_metascanner.def_var; def_value; _ } :: rest ->
if String.equal def_var fld
then Some def_value
else find_plugin_field_opt fld rest
let find_plugin_field fld def pkgs =
Option.default def (find_plugin_field_opt fld pkgs)
let rec find_plugin meta_file plugin_name path p { Fl_metascanner.pkg_defs ; pkg_children } =
match p with
| [] -> path, pkg_defs
| p :: ps ->
let c =
match CList.assoc_f_opt String.equal p pkg_children with
| None -> Error.declare_in_META meta_file (String.concat "." plugin_name) meta_file
| Some c -> c
in
let path = path @ [find_plugin_field "directory" "." c.Fl_metascanner.pkg_defs] in
find_plugin meta_file plugin_name path ps c
let findlib_resolve ~meta_files ~file ~package ~plugin_name =
match find_parsable_META meta_files package with
| None -> Error.no_meta file package
| Some (meta_file, meta) ->
let path = [find_plugin_field "directory" "." meta.Fl_metascanner.pkg_defs] in
let path, plug = find_plugin meta_file plugin_name path plugin_name meta in
let cmxs_file =
match find_plugin_field_opt "plugin" plug with
| None ->
Error.meta_file_lacks_field meta_file package "plugin"
| Some res_file ->
String.concat "/" path ^ "/" ^ Filename.chop_extension res_file
in
meta_file, cmxs_file
|
904a03d7f88b986631609c3ec3ffa125362a58de5e94aa2cdca977981e6ed631
|
hio/erlang-record_info
|
test.erl
|
% ----------------------------------------------------------------------------
% test.
% ----------------------------------------------------------------------------
-module(test).
-export([main/0]).
-export([test/0]).
-include("test.hrl").
-include("record_info.hrl").
-import(record_info, [record_to_proplist/2]).
-import(record_info, [proplist_to_record/3]).
-export_record_info([rec]).
-export_record_info([rec2]).
-record(rec, {
a = 1 :: integer(),
b = 2 :: integer()
}).
-record(rec_private, {
a = 1 :: integer()
}).
-spec main() -> ok.
main() ->
test(),
init:stop(),
ok.
-spec test() -> ok.
test() ->
plan(12),
R1 = #rec{a = 3, b = 4},
disp(1, R1, {rec, 3, 4}),
R2 = record_to_proplist(R1, ?MODULE),
disp(2, R2, [{a,3}, {b,4}]),
R3 = proplist_to_record(R2, rec, ?MODULE),
disp(3, R3, {rec, 3, 4}),
R4 = proplist_to_record([], rec, ?MODULE),
disp(4, R4, {rec,1,2}),
R5 = fun()-> try
% non key-value element.
BadElem = list_to_tuple([a,b,c]),
proplist_to_record([BadElem], rec, ?MODULE)
catch
C:R -> {C,R}
end end(),
disp(5, R5, {error,{badarg,{a,b,c}}}),
R6 = #rec2{aaa = 4},
disp(6, R6, {rec2,4,1234}),
R7 = record_to_proplist(R6, ?MODULE),
disp(7, R7, [{aaa,4},{bbb,1234}]),
R8 = proplist_to_record([], rec2, ?MODULE),
disp(8, R8, {rec2,undefined,1234}),
R9 = lists:sort(record_info:record_list(?MODULE)),
disp(9, R9, [rec, rec2]),
R10 = #rec_private { a = 10 },
disp(10, R10, #rec_private{ a = 10 }),
R11 = (fun() -> try
record_to_proplist(R10, ?MODULE)
catch
C:R -> {C,R}
end end)(),
disp(11, R11, {error,function_clause}),
R12 = (fun() -> try
proplist_to_record([], rec_private, ?MODULE)
catch
C:R -> {C,R}
end end)(),
disp(12, R12, {error,function_clause}),
ok.
plan(N) ->
io:format("1..~p~n", [N]),
ok.
disp(N, Got, Expected) ->
Eq = Got == Expected,
Result = case Eq of
true -> "ok";
false -> "not ok"
end,
ExpectedStr = io_lib:format("~p", [Expected]),
io:format("~s ~p # expects ~s~n", [Result, N, ExpectedStr]),
case Eq of
true ->
ok;
false ->
GotStr = io_lib:format("~p", [Got]),
io:format("# got ~s~n", [GotStr])
end,
Eq.
% ----------------------------------------------------------------------------
% End of File.
% ----------------------------------------------------------------------------
| null |
https://raw.githubusercontent.com/hio/erlang-record_info/0e8dd70a2b4c206296792875ed8d433337ce7b17/t/test.erl
|
erlang
|
----------------------------------------------------------------------------
test.
----------------------------------------------------------------------------
non key-value element.
----------------------------------------------------------------------------
End of File.
----------------------------------------------------------------------------
|
-module(test).
-export([main/0]).
-export([test/0]).
-include("test.hrl").
-include("record_info.hrl").
-import(record_info, [record_to_proplist/2]).
-import(record_info, [proplist_to_record/3]).
-export_record_info([rec]).
-export_record_info([rec2]).
-record(rec, {
a = 1 :: integer(),
b = 2 :: integer()
}).
-record(rec_private, {
a = 1 :: integer()
}).
-spec main() -> ok.
main() ->
test(),
init:stop(),
ok.
-spec test() -> ok.
test() ->
plan(12),
R1 = #rec{a = 3, b = 4},
disp(1, R1, {rec, 3, 4}),
R2 = record_to_proplist(R1, ?MODULE),
disp(2, R2, [{a,3}, {b,4}]),
R3 = proplist_to_record(R2, rec, ?MODULE),
disp(3, R3, {rec, 3, 4}),
R4 = proplist_to_record([], rec, ?MODULE),
disp(4, R4, {rec,1,2}),
R5 = fun()-> try
BadElem = list_to_tuple([a,b,c]),
proplist_to_record([BadElem], rec, ?MODULE)
catch
C:R -> {C,R}
end end(),
disp(5, R5, {error,{badarg,{a,b,c}}}),
R6 = #rec2{aaa = 4},
disp(6, R6, {rec2,4,1234}),
R7 = record_to_proplist(R6, ?MODULE),
disp(7, R7, [{aaa,4},{bbb,1234}]),
R8 = proplist_to_record([], rec2, ?MODULE),
disp(8, R8, {rec2,undefined,1234}),
R9 = lists:sort(record_info:record_list(?MODULE)),
disp(9, R9, [rec, rec2]),
R10 = #rec_private { a = 10 },
disp(10, R10, #rec_private{ a = 10 }),
R11 = (fun() -> try
record_to_proplist(R10, ?MODULE)
catch
C:R -> {C,R}
end end)(),
disp(11, R11, {error,function_clause}),
R12 = (fun() -> try
proplist_to_record([], rec_private, ?MODULE)
catch
C:R -> {C,R}
end end)(),
disp(12, R12, {error,function_clause}),
ok.
plan(N) ->
io:format("1..~p~n", [N]),
ok.
disp(N, Got, Expected) ->
Eq = Got == Expected,
Result = case Eq of
true -> "ok";
false -> "not ok"
end,
ExpectedStr = io_lib:format("~p", [Expected]),
io:format("~s ~p # expects ~s~n", [Result, N, ExpectedStr]),
case Eq of
true ->
ok;
false ->
GotStr = io_lib:format("~p", [Got]),
io:format("# got ~s~n", [GotStr])
end,
Eq.
|
d4eeb136a7c5cfa3507524a7c8c7f526421eb8b8556a095348c00e6043687149
|
dfinity-side-projects/winter
|
LEB128.hs
|
# LANGUAGE BinaryLiterals #
# LANGUAGE TypeApplications #
module Wasm.Binary.LEB128 where
import Control.Monad
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits
import Data.Bool
import Data.Int
import Text.Printf
getULEB128 :: (Bits a, Integral a) => Int -> Get a
getULEB128 budget
| budget <= 0 = fail $ printf "getULEB128: invalid budget: %d" budget
| otherwise = do
byte <- getWord8
let overflow =
budget < 7 && byte .&. 0b01111111 >= shiftL 0b00000001 budget
when overflow $ fail "getULEB128: integer overflow"
if not $ testBit byte 7
then return $ fromIntegral byte
else do
residue <- getULEB128 $ budget - 7
let value = fromIntegral $ byte .&. 0b01111111
return $ value .|. shiftL residue 7
putULEB128 :: (Bits a, Integral a) => a -> Put
putULEB128 value = if value < 0b10000000
then putWord8 $ fromIntegral value
else do
putWord8 $ 0b01111111 .&. fromIntegral value + 0b10000000
putULEB128 $ shiftR value 7
getSLEB128 :: (Bits a, Integral a) => Int -> Get a
getSLEB128 budget
| budget <= 0 = fail $ printf "getSLEB128: invalid budget: %d" budget
| otherwise = do
byte <- getWord8
let mask = shiftL 0b11111111 (budget - 1) .&. 0b01111111
let overflow =
budget < 7 && byte .&. mask /= 0b00000000 && byte .&. mask /= mask
when overflow $ fail "getSLEB128: integer overflow"
if not $ testBit byte 7
then return $ coerce $ shiftL byte 1 .&. 0b10000000 .|. byte
else do
residue <- getSLEB128 $ budget - 7
let value = fromIntegral $ byte .&. 0b01111111
return $ value .|. shiftL residue 7
where coerce = fromIntegral @Int8 . fromIntegral
putSLEB128 :: (Bits a, Integral a) => a -> Put
putSLEB128 value = go value
where
negative = value < 0
nonnegative = not negative
mask = bool complement id nonnegative 0b00000000
go residue = do
let byte = fromIntegral $ residue .&. 0b01111111
let residue' = shiftR residue 7
if residue' /= mask
then do
putWord8 $ byte .|. 0b10000000
go residue'
else do
let signed = testBit byte 6
let unsigned = not signed
if unsigned && nonnegative || signed && negative
then putWord8 byte
else do
putWord8 $ byte .|. 0b10000000
putWord8 $ fromIntegral mask .&. 0b01111111
| null |
https://raw.githubusercontent.com/dfinity-side-projects/winter/2cc31576fe029d85c37d21fc9ea4902c5c64b5a9/src/Wasm/Binary/LEB128.hs
|
haskell
|
# LANGUAGE BinaryLiterals #
# LANGUAGE TypeApplications #
module Wasm.Binary.LEB128 where
import Control.Monad
import Data.Binary.Get
import Data.Binary.Put
import Data.Bits
import Data.Bool
import Data.Int
import Text.Printf
getULEB128 :: (Bits a, Integral a) => Int -> Get a
getULEB128 budget
| budget <= 0 = fail $ printf "getULEB128: invalid budget: %d" budget
| otherwise = do
byte <- getWord8
let overflow =
budget < 7 && byte .&. 0b01111111 >= shiftL 0b00000001 budget
when overflow $ fail "getULEB128: integer overflow"
if not $ testBit byte 7
then return $ fromIntegral byte
else do
residue <- getULEB128 $ budget - 7
let value = fromIntegral $ byte .&. 0b01111111
return $ value .|. shiftL residue 7
putULEB128 :: (Bits a, Integral a) => a -> Put
putULEB128 value = if value < 0b10000000
then putWord8 $ fromIntegral value
else do
putWord8 $ 0b01111111 .&. fromIntegral value + 0b10000000
putULEB128 $ shiftR value 7
getSLEB128 :: (Bits a, Integral a) => Int -> Get a
getSLEB128 budget
| budget <= 0 = fail $ printf "getSLEB128: invalid budget: %d" budget
| otherwise = do
byte <- getWord8
let mask = shiftL 0b11111111 (budget - 1) .&. 0b01111111
let overflow =
budget < 7 && byte .&. mask /= 0b00000000 && byte .&. mask /= mask
when overflow $ fail "getSLEB128: integer overflow"
if not $ testBit byte 7
then return $ coerce $ shiftL byte 1 .&. 0b10000000 .|. byte
else do
residue <- getSLEB128 $ budget - 7
let value = fromIntegral $ byte .&. 0b01111111
return $ value .|. shiftL residue 7
where coerce = fromIntegral @Int8 . fromIntegral
putSLEB128 :: (Bits a, Integral a) => a -> Put
putSLEB128 value = go value
where
negative = value < 0
nonnegative = not negative
mask = bool complement id nonnegative 0b00000000
go residue = do
let byte = fromIntegral $ residue .&. 0b01111111
let residue' = shiftR residue 7
if residue' /= mask
then do
putWord8 $ byte .|. 0b10000000
go residue'
else do
let signed = testBit byte 6
let unsigned = not signed
if unsigned && nonnegative || signed && negative
then putWord8 byte
else do
putWord8 $ byte .|. 0b10000000
putWord8 $ fromIntegral mask .&. 0b01111111
|
|
261280ab3921bb9fae78a8b510dc3edba6e4686812149d2b53b8723f7ec95553
|
m4b/rdr
|
ElfProgramHeader.ml
|
type program_header32 =
{
p_type: int [@size 4];
p_offset: int [@size 4];
p_vaddr: int [@size 4];
p_paddr: int [@size 4];
p_filesz: int [@size 4];
p_memsz: int [@size 4];
p_flags: int [@size 4];
p_align: int [@size 4];
}
let sizeof_program_header32 = 8 * 4
64 bit
type program_header =
{
p_type: int [@size 4];
p_flags: int [@size 4];
p_offset: int [@size 8];
p_vaddr: int [@size 8];
p_paddr: int [@size 8];
p_filesz: int [@size 8];
p_memsz: int [@size 8];
p_align: int [@size 8];
}
let sizeof_program_header = 56 (* bytes *)
type t = program_header list
type t32 = program_header32 list
(* p type *)
Program header table entry unused
Loadable program segment
let kPT_DYNAMIC = 2 (* Dynamic linking information *)
Program interpreter
let kPT_NOTE = 4 (* Auxiliary information *)
let kPT_SHLIB = 5 (* Reserved *)
let kPT_PHDR = 6 (* Entry for header table itself *)
let kPT_TLS = 7 (* Thread-local storage segment *)
let kPT_NUM = 8 (* Number of defined types *)
let kPT_LOOS = 0x60000000 (* Start of OS-specific *)
GCC .eh_frame_hdr segment
let kPT_GNU_STACK = 0x6474e551 (* Indicates stack executability *)
let kPT_GNU_RELRO = 0x6474e552 (* Read-only after relocation *)
let kPT_PAX_FLAGS = 0x65041580 (* pax security header, _not_ in ELF header *)
let kPT_LOSUNW = 0x6ffffffa
Sun Specific segment
Stack segment
let kPT_HISUNW = 0x6fffffff
let kPT_HIOS = 0x6fffffff (* End of OS-specific *)
let kPT_LOPROC = 0x70000000 (* Start of processor-specific *)
let kPT_HIPROC = 0x7fffffff (* End of processor-specific *)
let kPT_MIPS_REGINFO = 0x70000000 (* Register usage information *)
let kPT_MIPS_RTPROC = 0x70000001 (* Runtime procedure table. *)
let kPT_MIPS_OPTIONS = 0x70000002
let kPT_HP_TLS = (kPT_LOOS + 0x0)
let kPT_HP_CORE_NONE = (kPT_LOOS + 0x1)
let kPT_HP_CORE_VERSION = (kPT_LOOS + 0x2)
let kPT_HP_CORE_KERNEL = (kPT_LOOS + 0x3)
let kPT_HP_CORE_COMM = (kPT_LOOS + 0x4)
let kPT_HP_CORE_PROC = (kPT_LOOS + 0x5)
let kPT_HP_CORE_LOADABLE = (kPT_LOOS + 0x6)
let kPT_HP_CORE_STACK = (kPT_LOOS + 0x7)
let kPT_HP_CORE_SHM = (kPT_LOOS + 0x8)
let kPT_HP_CORE_MMF = (kPT_LOOS + 0x9)
let kPT_HP_PARALLEL = (kPT_LOOS + 0x10)
let kPT_HP_FASTBIND = (kPT_LOOS + 0x11)
let kPT_HP_OPT_ANNOT = (kPT_LOOS + 0x12)
let kPT_HP_HSL_ANNOT = (kPT_LOOS + 0x13)
let kPT_HP_STACK = (kPT_LOOS + 0x14)
we do n't care about this , and it aliases anyway
let kPT_PARISC_ARCHEXT = 0x70000000
let kPT_PARISC_UNWIND = 0x70000001
let kPT_PARISC_ARCHEXT = 0x70000000
let kPT_PARISC_UNWIND = 0x70000001
*)
let kPPC64_OPT_TLS = 1
let kPPC64_OPT_MULTI_TOC = 2
ARM unwind segment .
let kPT_IA_64_ARCHEXT = (kPT_LOPROC + 0) (* arch extension bits *)
let kPT_IA_64_UNWIND = (kPT_LOPROC + 1) (* ia64 unwind bits *)
let kPT_IA_64_HP_OPT_ANOT = (kPT_LOOS + 0x12)
let kPT_IA_64_HP_HSL_ANOT = (kPT_LOOS + 0x13)
let kPT_IA_64_HP_STACK = (kPT_LOOS + 0x14)
let get_program_header32 binary offset :program_header32 =
let p_type,o = Binary.u32o binary offset in (* &i *)
let p_offset,o = Binary.u32o binary o in
let p_vaddr,o = Binary.u32o binary o in
let p_paddr,o = Binary.u32o binary o in
let p_filesz,o = Binary.u32o binary o in
let p_memsz,o = Binary.u32o binary o in
let p_flags,o = Binary.u32o binary o in
let p_align,_ = Binary.u32o binary o in
{
p_type;
p_offset;
p_vaddr;
p_paddr;
p_filesz;
p_memsz;
p_flags;
p_align;
}
let get_program_header binary offset =
let p_type,o = Binary.u32o binary offset in
let p_flags,o = Binary.u32o binary o in
let p_offset,o = Binary.u64o binary o in
let p_vaddr,o = Binary.u64o binary o in
let p_paddr,o = Binary.u64o binary o in
let p_filesz,o = Binary.u64o binary o in
let p_memsz,o = Binary.u64o binary o in
let p_align,_ = Binary.u64o binary o in
{
p_type;
1 = x 2 = w 4 = r
p_offset;
p_vaddr;
p_paddr;
p_filesz;
p_memsz;
p_align;
}
let ptype_to_string ptype =
match ptype with
| 0 -> "PT_NULL"
| 1 -> "PT_LOAD"
| 2 -> "PT_DYNAMIC"
| 3 -> "PT_INTERP"
| 4 -> "PT_NOTE"
| 5 -> "PT_SHLIB"
| 6 -> "PT_PHDR"
| 7 -> "PT_TLS"
| 8 -> "PT_NUM"
| 0x60000000 - > " PT_LOOS "
| 0x6474e550 -> "PT_GNU_EH_FRAME"
| 0x6474e551 -> "PT_GNU_STACK"
| 0x6474e552 -> "PT_GNU_RELRO"
| 0x65041580 -> "PT_PAX_FLAGS"
(* | 0x6ffffffa -> "PT_LOSUNW" *)
| 0x6ffffffa -> "PT_SUNWBSS"
| 0x6ffffffb -> "PT_SUNWSTACK"
| 0x6fffffff - > " PT_HIOS "
| pt when pt = kPT_MIPS_REGINFO -> "PT_MIPS_REGINFO"
| pt when pt = kPT_MIPS_RTPROC -> "PT_MIPS_RTPROC"
| pt when pt = kPT_MIPS_OPTIONS -> "PT_MIPS_OPTIONS"
| pt when pt = kPT_HP_TLS -> "PT_HP_TLS"
| pt when pt = kPT_HP_CORE_NONE -> "PT_HP_CORE_NONE"
| pt when pt = kPT_HP_CORE_VERSION -> "PT_HP_CORE_VERSION"
| pt when pt = kPT_HP_CORE_KERNEL -> "PT_HP_CORE_KERNEL"
| pt when pt = kPT_HP_CORE_COMM -> "PT_HP_CORE_COMM"
| pt when pt = kPT_HP_CORE_PROC -> "PT_HP_CORE_PROC"
| pt when pt = kPT_HP_CORE_LOADABLE -> "PT_HP_CORE_LOADABLE"
| pt when pt = kPT_HP_CORE_STACK -> "PT_HP_CORE_STACK"
| pt when pt = kPT_HP_CORE_SHM -> "PT_HP_CORE_SHM"
| pt when pt = kPT_HP_CORE_MMF -> "PT_HP_CORE_MMF"
| pt when pt = kPT_HP_PARALLEL -> "PT_HP_PARALLEL"
| pt when pt = kPT_HP_FASTBIND -> "PT_HP_FASTBIND"
(* PT_LOOS + 0x12 *)
| pt when pt = kPT_IA_64_HP_OPT_ANOT -> "PT_IA_64_HP_OPT_ANOT"
| pt when pt = kPT_IA_64_HP_HSL_ANOT -> "PT_IA_64_HP_HSL_ANOT"
| pt when pt = kPT_IA_64_HP_STACK -> "PT_IA_64_HP_STACK"
(* PT_LOOS + 0x14 *)
| pt when pt = kPT_HP_OPT_ANNOT -> "PT_HP_OPT_ANNOT"
| pt when pt = kPT_HP_HSL_ANNOT -> "PT_HP_HSL_ANNOT"
| pt when pt = kPT_HP_STACK -> "PT_HP_STACK"
| 0x70000000 - > " PT_LOPROC "
| pt when pt = kPT_ARM_EXIDX -> "PT_ARM_EXIDX"
| pt when pt = kPT_IA_64_ARCHEXT -> "PT_IA_64_ARCHEXT"
| pt when pt = kPT_IA_64_UNWIND -> "PT_IA_64_UNWIND"
| 0x7fffffff - > " PT_HIPROC "
| pt -> Printf.sprintf "PT_UNKNOWN 0x%x" pt
let flags_to_string flags =
match flags with
| 1 -> "X"
| 2 -> "W"
| 3 -> "W+X"
| 4 -> "R"
| 5 -> "R+X"
| 6 -> "RW"
| 7 -> "RW+X"
| f -> Printf.sprintf "FLAG 0x%x" f
let is_empty phs = phs = []
let program_header_to_string ph =
Printf.sprintf "%-12s %-4s offset: 0x%04x vaddr: 0x%08x paddr: 0x%08x filesz: 0x%04x memsz: 0x%04x align: %d"
(ptype_to_string ph.p_type)
6 r / w 5 r / x
ph.p_offset
ph.p_vaddr
ph.p_paddr
ph.p_filesz
ph.p_memsz
ph.p_align
let print_program_headers phs =
Printf.printf "Program Headers (%d):\n" @@ List.length phs;
List.iteri (fun i ph -> Printf.printf "%s\n" @@ program_header_to_string ph) phs
let get_program_headers32 binary phoff phentsize phnum :t32 =
let rec loop count offset acc =
if (count >= phnum) then
List.rev acc
else
let ph = get_program_header32 binary offset in
loop (count + 1) (offset + phentsize) (ph::acc)
in loop 0 phoff []
let get_program_headers binary phoff phentsize phnum =
let rec loop count offset acc =
if (count >= phnum) then
List.rev acc
else
let ph = get_program_header binary offset in
loop (count + 1) (offset + phentsize) (ph::acc)
in loop 0 phoff []
let get_header32 (ph:int) (phs:t32) =
try Some (List.find (fun (elem:program_header32) -> (elem.p_type = ph)) phs)
with _ -> None
let get_main_program_header32 phs = get_header32 kPT_PHDR phs
let get_interpreter_header32 phs = get_header32 kPT_INTERP phs
let get_dynamic_program_header32 phs = get_header32 kPT_DYNAMIC phs
let get_interpreter32 binary phs =
match get_interpreter_header32 phs with
| Some ph ->
Binary.string binary ~max:ph.p_filesz ph.p_offset
| None -> ""
let get_header ph phs =
try Some (List.find (fun elem -> (elem.p_type = ph)) phs)
with _ -> None
let get_main_program_header phs = get_header kPT_PHDR phs
let get_interpreter_header phs = get_header kPT_INTERP phs
let get_dynamic_program_header phs = get_header kPT_DYNAMIC phs
let get_interpreter binary phs =
match get_interpreter_header phs with
| Some ph ->
Binary.string binary ~max:ph.p_filesz ph.p_offset
| None -> ""
TODO : move this to separate module , or replace the PEUtils similar functionality with a simple find_offset function
type slide_sector = {start_sector: int; end_sector: int; slide: int;}
let is_in_sector offset sector =
(* should this be offset <= sector.end_sector ? *)
offset >= sector.start_sector && offset < sector.end_sector
let is_contained_in s1 s2 =
s1.start_sector >= s2.start_sector
&& s1.end_sector <= s2.end_sector
let join s1 s2 =
let start_sector = min s1.start_sector s2.start_sector in
let end_sector = max s1.end_sector s2.end_sector in
assert (s1.slide = s2.slide);
let slide = s1.slide in
{start_sector; end_sector; slide}
let print_slide_sector sector =
Printf.printf "0x%x: 0x%x - 0x%x\n"
sector.slide sector.start_sector sector.end_sector
let print_slide_sectors sectors =
List.iter (fun el -> print_slide_sector el) sectors
(* checks to see if the slides are equal; will this hold uniformly? *)
module SlideSet =
Set.Make(
struct type t = slide_sector
let compare =
(fun a b -> Pervasives.compare a.slide b.slide)
end)
module Map =
Map.Make(struct
type t = int
let compare = compare
end)
(* finds the vaddr masks *)
let get_slide_sectors phs =
let map =
List.fold_left
(fun acc ph ->
let slide = ph.p_vaddr - ph.p_offset in
if (slide <> 0) then
let start_sector = ph.p_vaddr in
let end_sector = start_sector + ph.p_filesz in (* this might need to be ph.p_memsz *)
let s1 = {start_sector; end_sector; slide} in
if (Map.mem slide acc) then
let s2 = Map.find slide acc in
if (is_contained_in s1 s2) then
acc
else
Map.add slide (join s1 s2) acc
else
Map.add slide s1 acc
else
acc
) Map.empty phs
in
Map.fold (fun k v acc -> v::acc) map []
(* checks if the offset is in the slide sector,
and adjusts using the sectors slide if so *)
let adjust sectors offset =
List.fold_left (fun acc sector ->
if (is_in_sector offset sector) then
offset - sector.slide
else
acc) offset sectors
let set_program_header bytes ph offset =
Binary.set_uint bytes ph.p_type 4 offset
|> Binary.set_uint bytes ph.p_flags 4
|> Binary.set_uint bytes ph.p_offset 8
|> Binary.set_uint bytes ph.p_vaddr 8
|> Binary.set_uint bytes ph.p_paddr 8
|> Binary.set_uint bytes ph.p_filesz 8
|> Binary.set_uint bytes ph.p_memsz 8
|> Binary.set_uint bytes ph.p_align 8
let program_header_to_bytes ph =
let b = Bytes.create sizeof_program_header in
ignore @@ set_program_header b ph 0;
b
let set bytes phs offset =
(* fold over the list, accumulating the offset,
and return the final offset *)
List.fold_left (fun acc ph -> set_program_header bytes ph acc) offset phs
let to_bytes phs =
let b = Bytes.create ((List.length phs) * sizeof_program_header) in
ignore @@ set b phs 0;
b
(* TODO: test to_bytes and set *)
let get_p_type p_type =
match p_type with
| 0 - > 1 - > PT_LOAD
| 2 - > PT_DYNAMIC
| 3 - > PT_INTERP
| 4 - >
| 5 - > PT_SHLIB
| 6 - > PT_PHDR
| 7 - > PT_TLS
| 8 - > PT_NUM
| 0x60000000 - > kPT_LOOS
| 0x6474e550 - > PT_GNU_EH_FRAME
| 0x6474e551 - > PT_GNU_STACK
| 0x6474e552 - > PT_GNU_RELRO
| 0x6ffffffa - > PT_LOSUNW
| 0x6ffffffa - > PT_SUNWBSS
| 0x6ffffffb - > PT_SUNWSTACK
| 0x6fffffff - > PT_HISUNW
| 0x6fffffff - > PT_HIOS
| 0x70000000 - > PT_LOPROC
| 0x7fffffff - > PT_HIPROC
let get_p_type p_type =
match p_type with
| 0 -> PT_NULL
| 1 -> PT_LOAD
| 2 -> PT_DYNAMIC
| 3 -> PT_INTERP
| 4 -> PT_NOTE
| 5 -> PT_SHLIB
| 6 -> PT_PHDR
| 7 -> PT_TLS
| 8 -> PT_NUM
| 0x60000000 -> kPT_LOOS
| 0x6474e550 -> PT_GNU_EH_FRAME
| 0x6474e551 -> PT_GNU_STACK
| 0x6474e552 -> PT_GNU_RELRO
| 0x6ffffffa -> PT_LOSUNW
| 0x6ffffffa -> PT_SUNWBSS
| 0x6ffffffb -> PT_SUNWSTACK
| 0x6fffffff -> PT_HISUNW
| 0x6fffffff -> PT_HIOS
| 0x70000000 -> PT_LOPROC
| 0x7fffffff -> PT_HIPROC
*)
| null |
https://raw.githubusercontent.com/m4b/rdr/2bf1f73fc317cd74f8c7cacd542889df729bd003/lib/elf/ElfProgramHeader.ml
|
ocaml
|
bytes
p type
Dynamic linking information
Auxiliary information
Reserved
Entry for header table itself
Thread-local storage segment
Number of defined types
Start of OS-specific
Indicates stack executability
Read-only after relocation
pax security header, _not_ in ELF header
End of OS-specific
Start of processor-specific
End of processor-specific
Register usage information
Runtime procedure table.
arch extension bits
ia64 unwind bits
&i
| 0x6ffffffa -> "PT_LOSUNW"
PT_LOOS + 0x12
PT_LOOS + 0x14
should this be offset <= sector.end_sector ?
checks to see if the slides are equal; will this hold uniformly?
finds the vaddr masks
this might need to be ph.p_memsz
checks if the offset is in the slide sector,
and adjusts using the sectors slide if so
fold over the list, accumulating the offset,
and return the final offset
TODO: test to_bytes and set
|
type program_header32 =
{
p_type: int [@size 4];
p_offset: int [@size 4];
p_vaddr: int [@size 4];
p_paddr: int [@size 4];
p_filesz: int [@size 4];
p_memsz: int [@size 4];
p_flags: int [@size 4];
p_align: int [@size 4];
}
let sizeof_program_header32 = 8 * 4
64 bit
type program_header =
{
p_type: int [@size 4];
p_flags: int [@size 4];
p_offset: int [@size 8];
p_vaddr: int [@size 8];
p_paddr: int [@size 8];
p_filesz: int [@size 8];
p_memsz: int [@size 8];
p_align: int [@size 8];
}
type t = program_header list
type t32 = program_header32 list
Program header table entry unused
Loadable program segment
Program interpreter
GCC .eh_frame_hdr segment
let kPT_LOSUNW = 0x6ffffffa
Sun Specific segment
Stack segment
let kPT_HISUNW = 0x6fffffff
let kPT_MIPS_OPTIONS = 0x70000002
let kPT_HP_TLS = (kPT_LOOS + 0x0)
let kPT_HP_CORE_NONE = (kPT_LOOS + 0x1)
let kPT_HP_CORE_VERSION = (kPT_LOOS + 0x2)
let kPT_HP_CORE_KERNEL = (kPT_LOOS + 0x3)
let kPT_HP_CORE_COMM = (kPT_LOOS + 0x4)
let kPT_HP_CORE_PROC = (kPT_LOOS + 0x5)
let kPT_HP_CORE_LOADABLE = (kPT_LOOS + 0x6)
let kPT_HP_CORE_STACK = (kPT_LOOS + 0x7)
let kPT_HP_CORE_SHM = (kPT_LOOS + 0x8)
let kPT_HP_CORE_MMF = (kPT_LOOS + 0x9)
let kPT_HP_PARALLEL = (kPT_LOOS + 0x10)
let kPT_HP_FASTBIND = (kPT_LOOS + 0x11)
let kPT_HP_OPT_ANNOT = (kPT_LOOS + 0x12)
let kPT_HP_HSL_ANNOT = (kPT_LOOS + 0x13)
let kPT_HP_STACK = (kPT_LOOS + 0x14)
we do n't care about this , and it aliases anyway
let kPT_PARISC_ARCHEXT = 0x70000000
let kPT_PARISC_UNWIND = 0x70000001
let kPT_PARISC_ARCHEXT = 0x70000000
let kPT_PARISC_UNWIND = 0x70000001
*)
let kPPC64_OPT_TLS = 1
let kPPC64_OPT_MULTI_TOC = 2
ARM unwind segment .
let kPT_IA_64_HP_OPT_ANOT = (kPT_LOOS + 0x12)
let kPT_IA_64_HP_HSL_ANOT = (kPT_LOOS + 0x13)
let kPT_IA_64_HP_STACK = (kPT_LOOS + 0x14)
let get_program_header32 binary offset :program_header32 =
let p_offset,o = Binary.u32o binary o in
let p_vaddr,o = Binary.u32o binary o in
let p_paddr,o = Binary.u32o binary o in
let p_filesz,o = Binary.u32o binary o in
let p_memsz,o = Binary.u32o binary o in
let p_flags,o = Binary.u32o binary o in
let p_align,_ = Binary.u32o binary o in
{
p_type;
p_offset;
p_vaddr;
p_paddr;
p_filesz;
p_memsz;
p_flags;
p_align;
}
let get_program_header binary offset =
let p_type,o = Binary.u32o binary offset in
let p_flags,o = Binary.u32o binary o in
let p_offset,o = Binary.u64o binary o in
let p_vaddr,o = Binary.u64o binary o in
let p_paddr,o = Binary.u64o binary o in
let p_filesz,o = Binary.u64o binary o in
let p_memsz,o = Binary.u64o binary o in
let p_align,_ = Binary.u64o binary o in
{
p_type;
1 = x 2 = w 4 = r
p_offset;
p_vaddr;
p_paddr;
p_filesz;
p_memsz;
p_align;
}
let ptype_to_string ptype =
match ptype with
| 0 -> "PT_NULL"
| 1 -> "PT_LOAD"
| 2 -> "PT_DYNAMIC"
| 3 -> "PT_INTERP"
| 4 -> "PT_NOTE"
| 5 -> "PT_SHLIB"
| 6 -> "PT_PHDR"
| 7 -> "PT_TLS"
| 8 -> "PT_NUM"
| 0x60000000 - > " PT_LOOS "
| 0x6474e550 -> "PT_GNU_EH_FRAME"
| 0x6474e551 -> "PT_GNU_STACK"
| 0x6474e552 -> "PT_GNU_RELRO"
| 0x65041580 -> "PT_PAX_FLAGS"
| 0x6ffffffa -> "PT_SUNWBSS"
| 0x6ffffffb -> "PT_SUNWSTACK"
| 0x6fffffff - > " PT_HIOS "
| pt when pt = kPT_MIPS_REGINFO -> "PT_MIPS_REGINFO"
| pt when pt = kPT_MIPS_RTPROC -> "PT_MIPS_RTPROC"
| pt when pt = kPT_MIPS_OPTIONS -> "PT_MIPS_OPTIONS"
| pt when pt = kPT_HP_TLS -> "PT_HP_TLS"
| pt when pt = kPT_HP_CORE_NONE -> "PT_HP_CORE_NONE"
| pt when pt = kPT_HP_CORE_VERSION -> "PT_HP_CORE_VERSION"
| pt when pt = kPT_HP_CORE_KERNEL -> "PT_HP_CORE_KERNEL"
| pt when pt = kPT_HP_CORE_COMM -> "PT_HP_CORE_COMM"
| pt when pt = kPT_HP_CORE_PROC -> "PT_HP_CORE_PROC"
| pt when pt = kPT_HP_CORE_LOADABLE -> "PT_HP_CORE_LOADABLE"
| pt when pt = kPT_HP_CORE_STACK -> "PT_HP_CORE_STACK"
| pt when pt = kPT_HP_CORE_SHM -> "PT_HP_CORE_SHM"
| pt when pt = kPT_HP_CORE_MMF -> "PT_HP_CORE_MMF"
| pt when pt = kPT_HP_PARALLEL -> "PT_HP_PARALLEL"
| pt when pt = kPT_HP_FASTBIND -> "PT_HP_FASTBIND"
| pt when pt = kPT_IA_64_HP_OPT_ANOT -> "PT_IA_64_HP_OPT_ANOT"
| pt when pt = kPT_IA_64_HP_HSL_ANOT -> "PT_IA_64_HP_HSL_ANOT"
| pt when pt = kPT_IA_64_HP_STACK -> "PT_IA_64_HP_STACK"
| pt when pt = kPT_HP_OPT_ANNOT -> "PT_HP_OPT_ANNOT"
| pt when pt = kPT_HP_HSL_ANNOT -> "PT_HP_HSL_ANNOT"
| pt when pt = kPT_HP_STACK -> "PT_HP_STACK"
| 0x70000000 - > " PT_LOPROC "
| pt when pt = kPT_ARM_EXIDX -> "PT_ARM_EXIDX"
| pt when pt = kPT_IA_64_ARCHEXT -> "PT_IA_64_ARCHEXT"
| pt when pt = kPT_IA_64_UNWIND -> "PT_IA_64_UNWIND"
| 0x7fffffff - > " PT_HIPROC "
| pt -> Printf.sprintf "PT_UNKNOWN 0x%x" pt
let flags_to_string flags =
match flags with
| 1 -> "X"
| 2 -> "W"
| 3 -> "W+X"
| 4 -> "R"
| 5 -> "R+X"
| 6 -> "RW"
| 7 -> "RW+X"
| f -> Printf.sprintf "FLAG 0x%x" f
let is_empty phs = phs = []
let program_header_to_string ph =
Printf.sprintf "%-12s %-4s offset: 0x%04x vaddr: 0x%08x paddr: 0x%08x filesz: 0x%04x memsz: 0x%04x align: %d"
(ptype_to_string ph.p_type)
6 r / w 5 r / x
ph.p_offset
ph.p_vaddr
ph.p_paddr
ph.p_filesz
ph.p_memsz
ph.p_align
let print_program_headers phs =
Printf.printf "Program Headers (%d):\n" @@ List.length phs;
List.iteri (fun i ph -> Printf.printf "%s\n" @@ program_header_to_string ph) phs
let get_program_headers32 binary phoff phentsize phnum :t32 =
let rec loop count offset acc =
if (count >= phnum) then
List.rev acc
else
let ph = get_program_header32 binary offset in
loop (count + 1) (offset + phentsize) (ph::acc)
in loop 0 phoff []
let get_program_headers binary phoff phentsize phnum =
let rec loop count offset acc =
if (count >= phnum) then
List.rev acc
else
let ph = get_program_header binary offset in
loop (count + 1) (offset + phentsize) (ph::acc)
in loop 0 phoff []
let get_header32 (ph:int) (phs:t32) =
try Some (List.find (fun (elem:program_header32) -> (elem.p_type = ph)) phs)
with _ -> None
let get_main_program_header32 phs = get_header32 kPT_PHDR phs
let get_interpreter_header32 phs = get_header32 kPT_INTERP phs
let get_dynamic_program_header32 phs = get_header32 kPT_DYNAMIC phs
let get_interpreter32 binary phs =
match get_interpreter_header32 phs with
| Some ph ->
Binary.string binary ~max:ph.p_filesz ph.p_offset
| None -> ""
let get_header ph phs =
try Some (List.find (fun elem -> (elem.p_type = ph)) phs)
with _ -> None
let get_main_program_header phs = get_header kPT_PHDR phs
let get_interpreter_header phs = get_header kPT_INTERP phs
let get_dynamic_program_header phs = get_header kPT_DYNAMIC phs
let get_interpreter binary phs =
match get_interpreter_header phs with
| Some ph ->
Binary.string binary ~max:ph.p_filesz ph.p_offset
| None -> ""
TODO : move this to separate module , or replace the PEUtils similar functionality with a simple find_offset function
type slide_sector = {start_sector: int; end_sector: int; slide: int;}
let is_in_sector offset sector =
offset >= sector.start_sector && offset < sector.end_sector
let is_contained_in s1 s2 =
s1.start_sector >= s2.start_sector
&& s1.end_sector <= s2.end_sector
let join s1 s2 =
let start_sector = min s1.start_sector s2.start_sector in
let end_sector = max s1.end_sector s2.end_sector in
assert (s1.slide = s2.slide);
let slide = s1.slide in
{start_sector; end_sector; slide}
let print_slide_sector sector =
Printf.printf "0x%x: 0x%x - 0x%x\n"
sector.slide sector.start_sector sector.end_sector
let print_slide_sectors sectors =
List.iter (fun el -> print_slide_sector el) sectors
module SlideSet =
Set.Make(
struct type t = slide_sector
let compare =
(fun a b -> Pervasives.compare a.slide b.slide)
end)
module Map =
Map.Make(struct
type t = int
let compare = compare
end)
let get_slide_sectors phs =
let map =
List.fold_left
(fun acc ph ->
let slide = ph.p_vaddr - ph.p_offset in
if (slide <> 0) then
let start_sector = ph.p_vaddr in
let s1 = {start_sector; end_sector; slide} in
if (Map.mem slide acc) then
let s2 = Map.find slide acc in
if (is_contained_in s1 s2) then
acc
else
Map.add slide (join s1 s2) acc
else
Map.add slide s1 acc
else
acc
) Map.empty phs
in
Map.fold (fun k v acc -> v::acc) map []
let adjust sectors offset =
List.fold_left (fun acc sector ->
if (is_in_sector offset sector) then
offset - sector.slide
else
acc) offset sectors
let set_program_header bytes ph offset =
Binary.set_uint bytes ph.p_type 4 offset
|> Binary.set_uint bytes ph.p_flags 4
|> Binary.set_uint bytes ph.p_offset 8
|> Binary.set_uint bytes ph.p_vaddr 8
|> Binary.set_uint bytes ph.p_paddr 8
|> Binary.set_uint bytes ph.p_filesz 8
|> Binary.set_uint bytes ph.p_memsz 8
|> Binary.set_uint bytes ph.p_align 8
let program_header_to_bytes ph =
let b = Bytes.create sizeof_program_header in
ignore @@ set_program_header b ph 0;
b
let set bytes phs offset =
List.fold_left (fun acc ph -> set_program_header bytes ph acc) offset phs
let to_bytes phs =
let b = Bytes.create ((List.length phs) * sizeof_program_header) in
ignore @@ set b phs 0;
b
let get_p_type p_type =
match p_type with
| 0 - > 1 - > PT_LOAD
| 2 - > PT_DYNAMIC
| 3 - > PT_INTERP
| 4 - >
| 5 - > PT_SHLIB
| 6 - > PT_PHDR
| 7 - > PT_TLS
| 8 - > PT_NUM
| 0x60000000 - > kPT_LOOS
| 0x6474e550 - > PT_GNU_EH_FRAME
| 0x6474e551 - > PT_GNU_STACK
| 0x6474e552 - > PT_GNU_RELRO
| 0x6ffffffa - > PT_LOSUNW
| 0x6ffffffa - > PT_SUNWBSS
| 0x6ffffffb - > PT_SUNWSTACK
| 0x6fffffff - > PT_HISUNW
| 0x6fffffff - > PT_HIOS
| 0x70000000 - > PT_LOPROC
| 0x7fffffff - > PT_HIPROC
let get_p_type p_type =
match p_type with
| 0 -> PT_NULL
| 1 -> PT_LOAD
| 2 -> PT_DYNAMIC
| 3 -> PT_INTERP
| 4 -> PT_NOTE
| 5 -> PT_SHLIB
| 6 -> PT_PHDR
| 7 -> PT_TLS
| 8 -> PT_NUM
| 0x60000000 -> kPT_LOOS
| 0x6474e550 -> PT_GNU_EH_FRAME
| 0x6474e551 -> PT_GNU_STACK
| 0x6474e552 -> PT_GNU_RELRO
| 0x6ffffffa -> PT_LOSUNW
| 0x6ffffffa -> PT_SUNWBSS
| 0x6ffffffb -> PT_SUNWSTACK
| 0x6fffffff -> PT_HISUNW
| 0x6fffffff -> PT_HIOS
| 0x70000000 -> PT_LOPROC
| 0x7fffffff -> PT_HIPROC
*)
|
dc9b4156b221e8815177e4d4b6f1e9afda24e677324995e345b92f93e67cbcfa
|
wilkerlucio/multi-timer
|
core.cljs
|
(ns com.wsscode.multi-timer.core
(:require ["react" :as react]
[goog.object :as gobj]
[com.wsscode.multi-timer.ui :as ui]
[com.wsscode.multi-timer.rn-support :as support]
[com.wsscode.multi-timer.components.timer :as c.timer]
[fulcro.client :as fulcro]
[fulcro.client.mutations :as mutations]
[fulcro.client.primitives :as fp]))
(mutations/defmutation tick-clock [{::c.timer/keys [current-time]}]
(action [{:keys [state]}]
(swap! state assoc ::c.timer/current-time current-time))
(refresh [_] [::c.timer/current-time]))
(fp/defsc MultiTimer
[this {::keys [id recorder]}]
{:initial-state (fn [_] {::id (random-uuid)
::recorder (fp/get-initial-state c.timer/Recorder {})})
:ident [::id ::id]
:query [::id
{::recorder (fp/get-query c.timer/Recorder)}]}
(ui/view (clj->js {:style {:flex 1
:backgroundColor "#fff"
:alignItems "center"
:justifyContent "center"}})
(c.timer/recorder recorder)))
(def multi-timer (fp/factory MultiTimer))
(fp/defsc Root [_ {:keys [ui/root]}]
{:initial-state {:ui/root {}
::c.timer/current-time 100}
:query [{:ui/root (fp/get-query MultiTimer)} ::c.timer/current-time]}
(multi-timer root))
(defn tick-timer [reconciler]
(let [time (c.timer/time-now)]
(fp/compressible-transact! reconciler [`(tick-clock {::c.timer/current-time ~time})])
(js/requestAnimationFrame #(tick-timer reconciler))))
(defonce app
(atom
(fulcro/new-fulcro-client
:started-callback
(fn [app]
(js/setInterval
(fn []
(let [time (c.timer/time-now)]
(fp/compressible-transact! (:reconciler app) [`(tick-clock {::c.timer/current-time ~time})])))
500)
#_ (tick-timer (:reconciler app)))
:shared {::time-based (atom #{})}
:reconciler-options {:root-render support/root-render
:root-unmount support/root-unmount})))
(defonce RootNode (support/root-node! 1))
(defonce app-root (fp/factory RootNode))
(defn reload []
(swap! app fulcro/mount Root 1))
(defn rootelement []
(reload)
(app-root {}))
| null |
https://raw.githubusercontent.com/wilkerlucio/multi-timer/efd2c04dc7f25249368bdabadc2a76d54a9bb5f8/src/com/wsscode/multi_timer/core.cljs
|
clojure
|
(ns com.wsscode.multi-timer.core
(:require ["react" :as react]
[goog.object :as gobj]
[com.wsscode.multi-timer.ui :as ui]
[com.wsscode.multi-timer.rn-support :as support]
[com.wsscode.multi-timer.components.timer :as c.timer]
[fulcro.client :as fulcro]
[fulcro.client.mutations :as mutations]
[fulcro.client.primitives :as fp]))
(mutations/defmutation tick-clock [{::c.timer/keys [current-time]}]
(action [{:keys [state]}]
(swap! state assoc ::c.timer/current-time current-time))
(refresh [_] [::c.timer/current-time]))
(fp/defsc MultiTimer
[this {::keys [id recorder]}]
{:initial-state (fn [_] {::id (random-uuid)
::recorder (fp/get-initial-state c.timer/Recorder {})})
:ident [::id ::id]
:query [::id
{::recorder (fp/get-query c.timer/Recorder)}]}
(ui/view (clj->js {:style {:flex 1
:backgroundColor "#fff"
:alignItems "center"
:justifyContent "center"}})
(c.timer/recorder recorder)))
(def multi-timer (fp/factory MultiTimer))
(fp/defsc Root [_ {:keys [ui/root]}]
{:initial-state {:ui/root {}
::c.timer/current-time 100}
:query [{:ui/root (fp/get-query MultiTimer)} ::c.timer/current-time]}
(multi-timer root))
(defn tick-timer [reconciler]
(let [time (c.timer/time-now)]
(fp/compressible-transact! reconciler [`(tick-clock {::c.timer/current-time ~time})])
(js/requestAnimationFrame #(tick-timer reconciler))))
(defonce app
(atom
(fulcro/new-fulcro-client
:started-callback
(fn [app]
(js/setInterval
(fn []
(let [time (c.timer/time-now)]
(fp/compressible-transact! (:reconciler app) [`(tick-clock {::c.timer/current-time ~time})])))
500)
#_ (tick-timer (:reconciler app)))
:shared {::time-based (atom #{})}
:reconciler-options {:root-render support/root-render
:root-unmount support/root-unmount})))
(defonce RootNode (support/root-node! 1))
(defonce app-root (fp/factory RootNode))
(defn reload []
(swap! app fulcro/mount Root 1))
(defn rootelement []
(reload)
(app-root {}))
|
|
a81b7cf01112e633e35ac8646e714becab8d8b127de5cd1f510926d286bca658
|
effectfully-ou/sketches
|
IO.hs
|
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
module Mineunifier.IO where
import Mineunifier.Core
import Data.Proxy
import GHC.TypeLits
import Data.Type.Equality
class Parse source result
instance Parse "?" c
instance c ~~ 'X => Parse "x" c
instance c ~~ 'N (FromNat 0) => Parse "0" c
instance c ~~ 'N (FromNat 1) => Parse "1" c
instance c ~~ 'N (FromNat 2) => Parse "2" c
instance c ~~ 'N (FromNat 3) => Parse "3" c
instance c ~~ 'N (FromNat 4) => Parse "4" c
instance c ~~ 'N (FromNat 5) => Parse "5" c
instance c ~~ 'N (FromNat 6) => Parse "6" c
instance c ~~ 'N (FromNat 7) => Parse "7" c
instance c ~~ 'N (FromNat 8) => Parse "8" c
instance result ~~ '[] => Parse '[] result
instance (Parse s r, Parse ss' rs', rs ~~ (r ': rs')) => Parse (s ': ss') rs
class DisplayGamey a where
displayGamey :: String
instance DisplayGamey 'X where
displayGamey = "x"
instance KnownNat (ToNat m) => DisplayGamey ('N m) where
displayGamey = show . natVal $ Proxy @(ToNat m)
instance DisplayGamey '[] where
displayGamey = ""
instance (DisplayGamey el, DisplayGamey row) => DisplayGamey (el ': row :: [Cell]) where
displayGamey = displayGamey @el ++ " " ++ displayGamey @row
instance (DisplayGamey row, DisplayGamey rows) => DisplayGamey (row ': rows :: [[Cell]]) where
displayGamey = displayGamey @row ++ "\n" ++ displayGamey @rows
displayBoard :: forall input result. (Parse input result, DisplayGamey result) => String
displayBoard = displayGamey @result
-- >>> :set -XDataKinds
-- >>> :set -XTypeApplications
-- >>> putStrLn $ displayBoard @('[ ["1", "1", "0"], ["x", "1", "0"] ])
-- 1 1 0
-- x 1 0
-- >>> putStrLn $ displayBoard @('[ ["1", "1", "0"], ["?", "1", "0"] ])
-- <interactive>:546:13: error:
• Ambiguous type variable ‘ r0 ’ arising from a use of ‘ displayBoard ’
prevents the constraint ‘ ( DisplayGamey r0 ) ’ from being solved .
-- Probable fix: use a type annotation to specify what ‘r0’ should be.
-- These potential instances exist:
instance [ safe ] KnownNat ( ToNat m ) = > DisplayGamey ( ' N m )
-- -- Defined at /tmp/danteoGX7Hm.hs:41:10
-- instance [safe] DisplayGamey 'X
-- -- Defined at /tmp/danteoGX7Hm.hs:38:10
• In the second argument of ‘ ( $ ) ’ , namely
-- ‘displayBoard @('[["1", "1", "0"], ["?", "1", "0"]])’
-- In the expression:
putStrLn $ displayBoard @('[["1 " , " 1 " , " 0 " ] , [ " ? " , " 1 " , " 0 " ] ] )
-- In an equation for ‘it’:
-- it = putStrLn $ displayBoard @('[["1", "1", "0"], ["?", "1", "0"]])
| null |
https://raw.githubusercontent.com/effectfully-ou/sketches/4fe60f38961300ff96f7a0713161f650ea40f0e7/mineunifier/src/Mineunifier/IO.hs
|
haskell
|
>>> :set -XDataKinds
>>> :set -XTypeApplications
>>> putStrLn $ displayBoard @('[ ["1", "1", "0"], ["x", "1", "0"] ])
1 1 0
x 1 0
>>> putStrLn $ displayBoard @('[ ["1", "1", "0"], ["?", "1", "0"] ])
<interactive>:546:13: error:
Probable fix: use a type annotation to specify what ‘r0’ should be.
These potential instances exist:
-- Defined at /tmp/danteoGX7Hm.hs:41:10
instance [safe] DisplayGamey 'X
-- Defined at /tmp/danteoGX7Hm.hs:38:10
‘displayBoard @('[["1", "1", "0"], ["?", "1", "0"]])’
In the expression:
In an equation for ‘it’:
it = putStrLn $ displayBoard @('[["1", "1", "0"], ["?", "1", "0"]])
|
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
module Mineunifier.IO where
import Mineunifier.Core
import Data.Proxy
import GHC.TypeLits
import Data.Type.Equality
class Parse source result
instance Parse "?" c
instance c ~~ 'X => Parse "x" c
instance c ~~ 'N (FromNat 0) => Parse "0" c
instance c ~~ 'N (FromNat 1) => Parse "1" c
instance c ~~ 'N (FromNat 2) => Parse "2" c
instance c ~~ 'N (FromNat 3) => Parse "3" c
instance c ~~ 'N (FromNat 4) => Parse "4" c
instance c ~~ 'N (FromNat 5) => Parse "5" c
instance c ~~ 'N (FromNat 6) => Parse "6" c
instance c ~~ 'N (FromNat 7) => Parse "7" c
instance c ~~ 'N (FromNat 8) => Parse "8" c
instance result ~~ '[] => Parse '[] result
instance (Parse s r, Parse ss' rs', rs ~~ (r ': rs')) => Parse (s ': ss') rs
class DisplayGamey a where
displayGamey :: String
instance DisplayGamey 'X where
displayGamey = "x"
instance KnownNat (ToNat m) => DisplayGamey ('N m) where
displayGamey = show . natVal $ Proxy @(ToNat m)
instance DisplayGamey '[] where
displayGamey = ""
instance (DisplayGamey el, DisplayGamey row) => DisplayGamey (el ': row :: [Cell]) where
displayGamey = displayGamey @el ++ " " ++ displayGamey @row
instance (DisplayGamey row, DisplayGamey rows) => DisplayGamey (row ': rows :: [[Cell]]) where
displayGamey = displayGamey @row ++ "\n" ++ displayGamey @rows
displayBoard :: forall input result. (Parse input result, DisplayGamey result) => String
displayBoard = displayGamey @result
• Ambiguous type variable ‘ r0 ’ arising from a use of ‘ displayBoard ’
prevents the constraint ‘ ( DisplayGamey r0 ) ’ from being solved .
instance [ safe ] KnownNat ( ToNat m ) = > DisplayGamey ( ' N m )
• In the second argument of ‘ ( $ ) ’ , namely
putStrLn $ displayBoard @('[["1 " , " 1 " , " 0 " ] , [ " ? " , " 1 " , " 0 " ] ] )
|
6cbdc4ecc1a1e937fee655b292ceccb168e80d58ebaf11f6c73852dd24258899
|
incoherentsoftware/defect-process
|
Think.hs
|
module Player.Think
( thinkPlayer
) where
import Control.Monad (when)
import Control.Monad.State (execState, gets, modify)
import Data.Maybe (isNothing)
import qualified Data.Set as S
import AppEnv
import Attack
import Msg
import Player
import Player.BufferedInputState
import Player.Gun
import Player.Gun.Manager
import Player.LockOnAim
import Player.MovementSkill as MS
import Player.SecondarySkill as SS
import Player.SecondarySkill.Manager
import Player.Weapon as W
import Player.Weapon.Manager
import Util
import Window.InputState
invalidActionSoundPath = "event:/SFX Events/Level/pickup-item-cant-buy" :: FilePath
playerInteractMsgs :: InputState -> Player -> [Msg ThinkPlayerMsgsPhase]
playerInteractMsgs inputState player
| InteractAlias `aliasPressed` inputState = [mkMsg $ PlayerMsgInteract (_gold player)]
| otherwise = []
playerWeaponMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerWeaponMsgs player = concat <$> traverse thinkWeapon (zip [0..] weapons)
where
thinkWeapon :: (Int, Some Weapon) -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
thinkWeapon (i, Some wpn) = (W._think wpn) wpnThinkStatus player (_attack player) wpn
where
flags = _flags player
canAttack = and
[ not $ _gettingHit flags
, gunManagerCancelable $ _gunManager player
, playerMovementSkillCancelable player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
wpnAtkStatus
| canAttack = WeaponAttackReady
| otherwise = WeaponAttackNotReady
wpnThinkStatus
| i == 0 = WeaponThinkForeground wpnAtkStatus
| otherwise = WeaponThinkBackground
weapons = _weapons $ _weaponManager player
playerGunMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerGunMsgs player = thinkGunManager shootable player (_gunManager player)
where
flags = _flags player
canShoot = and
[ not $ _gettingHit flags
, playerMovementSkillCancelable player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
shootable
| canShoot = Shootable
| otherwise = NotShootable
playerMovementSkillMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerMovementSkillMsgs player = case _movementSkill player of
Nothing -> return []
Just (Some movementSkill) ->
let
flags = _flags player
canUseSkill = and
[ not $ _gettingHit flags
, gunManagerCancelable $ _gunManager player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
in (MS._think movementSkill) canUseSkill player movementSkill
playerSecondarySkillMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerSecondarySkillMsgs player = thinkSecondarySkillManager canUseSkill player (_secondarySkillManager player)
where
flags = _flags player
canUseSkill = and
[ not $ _gettingHit flags
, gunManagerCancelable $ _gunManager player
, playerMovementSkillCancelable player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
playerInvalidActionUiMsgs :: InputState -> Player -> [Msg ThinkPlayerMsgsPhase]
playerInvalidActionUiMsgs inputState player =
let
isPressed = \alias input -> alias `aliasPressed` inputState || input `inPlayerInputBuffer` player
isSkillPressed = \slot -> isSecondarySkillPressed inputState slot || isSecondarySkillPressedBuffer player slot
mkMsgUiInvalidAction = \alias -> mkMsg $ UiMsgInvalidAction alias
mkMsgUiInvalidActionEx = \alias1 alias2 -> mkMsg $ UiMsgInvalidActionEx alias1 alias2
mkMsgClearInputBuffer = \input -> mkMsg $ PlayerMsgClearInputBuffer (S.singleton input)
weapons = _weapons $ _weaponManager player
guns = _guns $ _gunManager player
secondarySkillMgr = _secondarySkillManager player
in flip execState [] $ do
when (isPressed WeaponAlias WeaponInput && null weapons) $
modify ([mkMsgUiInvalidAction WeaponAlias, mkMsgClearInputBuffer WeaponInput] ++)
when (isPressed SwitchWeaponAlias SwitchWeaponInput && length weapons < 2) $
modify ([mkMsgUiInvalidAction SwitchWeaponAlias, mkMsgClearInputBuffer SwitchWeaponInput] ++)
when (isPressed ShootAlias ShootInput && null guns) $
modify ([mkMsgUiInvalidAction ShootAlias, mkMsgClearInputBuffer ShootInput] ++)
when (isPressed SwitchGunAlias SwitchGunInput && length guns < 2) $
modify ([mkMsgUiInvalidAction SwitchGunAlias, mkMsgClearInputBuffer SwitchGunInput] ++)
when (isPressed MovementSkillAlias MovementSkillInput && isNothing (_movementSkill player)) $
modify ([mkMsgUiInvalidAction MovementSkillAlias, mkMsgClearInputBuffer MovementSkillInput] ++)
when (isSkillPressed SecondarySkillNeutralSlot && isNothing (_neutralSlot secondarySkillMgr)) $
modify ([mkMsgUiInvalidAction SecondarySkillAlias, mkMsgClearInputBuffer SecondarySkillNeutralInput] ++)
when (isSkillPressed SecondarySkillUpSlot && isNothing (_upSlot secondarySkillMgr)) $
modify
( [mkMsgUiInvalidActionEx SecondarySkillAlias UpAlias, mkMsgClearInputBuffer SecondarySkillUpInput] ++
)
when (isSkillPressed SecondarySkillDownSlot && isNothing (_downSlot secondarySkillMgr)) $
modify
(
[ mkMsgUiInvalidActionEx SecondarySkillAlias DownAlias
, mkMsgClearInputBuffer SecondarySkillDownInput
] ++
)
unlessM (gets null) $
modify (mkMsg (AudioMsgPlaySoundCentered invalidActionSoundPath):)
thinkPlayer :: Player -> AppEnv ThinkPlayerMsgsPhase ()
thinkPlayer player
| isPlayerInSpawnAnim player = return ()
| isPlayerInDeathAnim player = return ()
| otherwise = do
inputState <- readInputState
moveSkillMsgs <- playerMovementSkillMsgs player
lockOnAimMsgs <- thinkPlayerLockOnAim player (_lockOnAim player)
secondarySkillMsgs <- playerSecondarySkillMsgs player
gunMsgs <- playerGunMsgs player
weaponMsgs <- playerWeaponMsgs player
weaponMgrMsgs <- thinkWeaponManager player (_weaponManager player)
let
attackMsgs = maybe [] thinkAttack (_attack player)
interactMsgs = playerInteractMsgs inputState player
invalidActionUiMsgs = playerInvalidActionUiMsgs inputState player
writeMsgs . concat $
[ moveSkillMsgs
, lockOnAimMsgs
, secondarySkillMsgs
, gunMsgs
, weaponMsgs
, weaponMgrMsgs
, attackMsgs
, interactMsgs
, invalidActionUiMsgs
]
| null |
https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Player/Think.hs
|
haskell
|
module Player.Think
( thinkPlayer
) where
import Control.Monad (when)
import Control.Monad.State (execState, gets, modify)
import Data.Maybe (isNothing)
import qualified Data.Set as S
import AppEnv
import Attack
import Msg
import Player
import Player.BufferedInputState
import Player.Gun
import Player.Gun.Manager
import Player.LockOnAim
import Player.MovementSkill as MS
import Player.SecondarySkill as SS
import Player.SecondarySkill.Manager
import Player.Weapon as W
import Player.Weapon.Manager
import Util
import Window.InputState
invalidActionSoundPath = "event:/SFX Events/Level/pickup-item-cant-buy" :: FilePath
playerInteractMsgs :: InputState -> Player -> [Msg ThinkPlayerMsgsPhase]
playerInteractMsgs inputState player
| InteractAlias `aliasPressed` inputState = [mkMsg $ PlayerMsgInteract (_gold player)]
| otherwise = []
playerWeaponMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerWeaponMsgs player = concat <$> traverse thinkWeapon (zip [0..] weapons)
where
thinkWeapon :: (Int, Some Weapon) -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
thinkWeapon (i, Some wpn) = (W._think wpn) wpnThinkStatus player (_attack player) wpn
where
flags = _flags player
canAttack = and
[ not $ _gettingHit flags
, gunManagerCancelable $ _gunManager player
, playerMovementSkillCancelable player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
wpnAtkStatus
| canAttack = WeaponAttackReady
| otherwise = WeaponAttackNotReady
wpnThinkStatus
| i == 0 = WeaponThinkForeground wpnAtkStatus
| otherwise = WeaponThinkBackground
weapons = _weapons $ _weaponManager player
playerGunMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerGunMsgs player = thinkGunManager shootable player (_gunManager player)
where
flags = _flags player
canShoot = and
[ not $ _gettingHit flags
, playerMovementSkillCancelable player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
shootable
| canShoot = Shootable
| otherwise = NotShootable
playerMovementSkillMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerMovementSkillMsgs player = case _movementSkill player of
Nothing -> return []
Just (Some movementSkill) ->
let
flags = _flags player
canUseSkill = and
[ not $ _gettingHit flags
, gunManagerCancelable $ _gunManager player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
in (MS._think movementSkill) canUseSkill player movementSkill
playerSecondarySkillMsgs :: Player -> AppEnv ThinkPlayerMsgsPhase [Msg ThinkPlayerMsgsPhase]
playerSecondarySkillMsgs player = thinkSecondarySkillManager canUseSkill player (_secondarySkillManager player)
where
flags = _flags player
canUseSkill = and
[ not $ _gettingHit flags
, gunManagerCancelable $ _gunManager player
, playerMovementSkillCancelable player
, playerAttackCancelable player
, not $ _onSpeedRail flags
]
playerInvalidActionUiMsgs :: InputState -> Player -> [Msg ThinkPlayerMsgsPhase]
playerInvalidActionUiMsgs inputState player =
let
isPressed = \alias input -> alias `aliasPressed` inputState || input `inPlayerInputBuffer` player
isSkillPressed = \slot -> isSecondarySkillPressed inputState slot || isSecondarySkillPressedBuffer player slot
mkMsgUiInvalidAction = \alias -> mkMsg $ UiMsgInvalidAction alias
mkMsgUiInvalidActionEx = \alias1 alias2 -> mkMsg $ UiMsgInvalidActionEx alias1 alias2
mkMsgClearInputBuffer = \input -> mkMsg $ PlayerMsgClearInputBuffer (S.singleton input)
weapons = _weapons $ _weaponManager player
guns = _guns $ _gunManager player
secondarySkillMgr = _secondarySkillManager player
in flip execState [] $ do
when (isPressed WeaponAlias WeaponInput && null weapons) $
modify ([mkMsgUiInvalidAction WeaponAlias, mkMsgClearInputBuffer WeaponInput] ++)
when (isPressed SwitchWeaponAlias SwitchWeaponInput && length weapons < 2) $
modify ([mkMsgUiInvalidAction SwitchWeaponAlias, mkMsgClearInputBuffer SwitchWeaponInput] ++)
when (isPressed ShootAlias ShootInput && null guns) $
modify ([mkMsgUiInvalidAction ShootAlias, mkMsgClearInputBuffer ShootInput] ++)
when (isPressed SwitchGunAlias SwitchGunInput && length guns < 2) $
modify ([mkMsgUiInvalidAction SwitchGunAlias, mkMsgClearInputBuffer SwitchGunInput] ++)
when (isPressed MovementSkillAlias MovementSkillInput && isNothing (_movementSkill player)) $
modify ([mkMsgUiInvalidAction MovementSkillAlias, mkMsgClearInputBuffer MovementSkillInput] ++)
when (isSkillPressed SecondarySkillNeutralSlot && isNothing (_neutralSlot secondarySkillMgr)) $
modify ([mkMsgUiInvalidAction SecondarySkillAlias, mkMsgClearInputBuffer SecondarySkillNeutralInput] ++)
when (isSkillPressed SecondarySkillUpSlot && isNothing (_upSlot secondarySkillMgr)) $
modify
( [mkMsgUiInvalidActionEx SecondarySkillAlias UpAlias, mkMsgClearInputBuffer SecondarySkillUpInput] ++
)
when (isSkillPressed SecondarySkillDownSlot && isNothing (_downSlot secondarySkillMgr)) $
modify
(
[ mkMsgUiInvalidActionEx SecondarySkillAlias DownAlias
, mkMsgClearInputBuffer SecondarySkillDownInput
] ++
)
unlessM (gets null) $
modify (mkMsg (AudioMsgPlaySoundCentered invalidActionSoundPath):)
thinkPlayer :: Player -> AppEnv ThinkPlayerMsgsPhase ()
thinkPlayer player
| isPlayerInSpawnAnim player = return ()
| isPlayerInDeathAnim player = return ()
| otherwise = do
inputState <- readInputState
moveSkillMsgs <- playerMovementSkillMsgs player
lockOnAimMsgs <- thinkPlayerLockOnAim player (_lockOnAim player)
secondarySkillMsgs <- playerSecondarySkillMsgs player
gunMsgs <- playerGunMsgs player
weaponMsgs <- playerWeaponMsgs player
weaponMgrMsgs <- thinkWeaponManager player (_weaponManager player)
let
attackMsgs = maybe [] thinkAttack (_attack player)
interactMsgs = playerInteractMsgs inputState player
invalidActionUiMsgs = playerInvalidActionUiMsgs inputState player
writeMsgs . concat $
[ moveSkillMsgs
, lockOnAimMsgs
, secondarySkillMsgs
, gunMsgs
, weaponMsgs
, weaponMgrMsgs
, attackMsgs
, interactMsgs
, invalidActionUiMsgs
]
|
|
ae1de1b89d86b4660b61f94da6a150290c36c4e03c0d47f595f7a5a03b26842f
|
REPROSEC/dolev-yao-star
|
Vale_Lib_MapTree.ml
|
open Prims
type ('a, 'isule) is_cmp = unit
type ('a, 'b) tree =
| Empty
| Node of 'a * 'b * Prims.nat * ('a, 'b) tree * ('a, 'b) tree
let uu___is_Empty : 'a 'b . ('a, 'b) tree -> Prims.bool =
fun projectee -> match projectee with | Empty -> true | uu___ -> false
let uu___is_Node : 'a 'b . ('a, 'b) tree -> Prims.bool =
fun projectee ->
match projectee with | Node (_0, _1, _2, _3, _4) -> true | uu___ -> false
let __proj__Node__item___0 : 'a 'b . ('a, 'b) tree -> 'a =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _0
let __proj__Node__item___1 : 'a 'b . ('a, 'b) tree -> 'b =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _1
let __proj__Node__item___2 : 'a 'b . ('a, 'b) tree -> Prims.nat =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _2
let __proj__Node__item___3 : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _3
let __proj__Node__item___4 : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _4
let height : 'a 'b . ('a, 'b) tree -> Prims.nat =
fun t ->
match t with
| Empty -> Prims.int_zero
| Node (uu___, uu___1, h, uu___2, uu___3) -> h
let mkNode :
'a 'b . 'a -> 'b -> ('a, 'b) tree -> ('a, 'b) tree -> ('a, 'b) tree =
fun key ->
fun value ->
fun l ->
fun r ->
let hl = height l in
let hr = height r in
let h = if hl > hr then hl else hr in
Node (key, value, (h + Prims.int_one), l, r)
let rotate_l : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun t ->
match t with
| Node (kl, vl, uu___, l, Node (kr, vr, uu___1, lr, rr)) ->
mkNode kr vr (mkNode kl vl l lr) rr
| uu___ -> t
let rotate_r : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun t ->
match t with
| Node (kr, vr, uu___, Node (kl, vl, uu___1, ll, rl), r) ->
mkNode kl vl ll (mkNode kr vr rl r)
| uu___ -> t
let balance : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun t ->
match t with
| Node (uu___, uu___1, uu___2, l, r) ->
let hl = height l in
let hr = height r in
if hl >= (hr + (Prims.of_int (2)))
then rotate_r t
else if hr >= (hl + (Prims.of_int (2))) then rotate_l t else t
| uu___ -> t
let rec get :
'a 'b .
('a -> 'a -> Prims.bool) ->
('a, 'b) tree -> 'a -> 'b FStar_Pervasives_Native.option
=
fun is_le ->
fun t ->
fun key ->
match t with
| Empty -> FStar_Pervasives_Native.None
| Node (k, v, h, l, r) ->
if key = k
then FStar_Pervasives_Native.Some v
else if is_le key k then get is_le l key else get is_le r key
let rec put :
'a 'b .
('a -> 'a -> Prims.bool) -> ('a, 'b) tree -> 'a -> 'b -> ('a, 'b) tree
=
fun is_le ->
fun t ->
fun key ->
fun value ->
match t with
| Empty -> mkNode key value Empty Empty
| Node (k, v, uu___, l, r) ->
if key = k
then mkNode k value l r
else
if is_le key k
then balance (mkNode k v (put is_le l key value) r)
else balance (mkNode k v l (put is_le r key value))
let is_lt_option :
'a .
('a -> 'a -> Prims.bool) ->
'a FStar_Pervasives_Native.option ->
'a FStar_Pervasives_Native.option -> Prims.bool
=
fun is_le ->
fun x ->
fun y ->
match (x, y) with
| (FStar_Pervasives_Native.Some x1, FStar_Pervasives_Native.Some y1)
-> (is_le x1 y1) && (x1 <> y1)
| uu___ -> true
type ('a, 'b, 'isule, 't, 'lo, 'hi) inv = Obj.t
type ('a, 'b) map' =
| Map of ('a -> 'a -> Prims.bool) * ('a, 'b) tree * 'b * unit
let uu___is_Map : 'a 'b . ('a, 'b) map' -> Prims.bool = fun projectee -> true
let __proj__Map__item__is_le :
'a 'b . ('a, 'b) map' -> 'a -> 'a -> Prims.bool =
fun projectee ->
match projectee with | Map (is_le, t, default_v, invs) -> is_le
let __proj__Map__item__t : 'a 'b . ('a, 'b) map' -> ('a, 'b) tree =
fun projectee ->
match projectee with | Map (is_le, t, default_v, invs) -> t
let __proj__Map__item__default_v : 'a 'b . ('a, 'b) map' -> 'b =
fun projectee ->
match projectee with | Map (is_le, t, default_v, invs) -> default_v
type ('a, 'b) map = ('a, 'b) map'
let const : 'a 'b . ('a -> 'a -> Prims.bool) -> 'b -> ('a, 'b) map =
fun is_le -> fun d -> Map (is_le, Empty, d, ())
let sel : 'a 'b . ('a, 'b) map -> 'a -> 'b =
fun uu___ ->
fun key ->
match uu___ with
| Map (is_le, t, d, uu___1) ->
(match get is_le t key with
| FStar_Pervasives_Native.Some v -> v
| FStar_Pervasives_Native.None -> d)
let upd : 'a 'b . ('a, 'b) map -> 'a -> 'b -> ('a, 'b) map =
fun uu___ ->
fun key ->
fun value ->
match uu___ with
| Map (is_le, t, d, uu___1) ->
let t' = put is_le t key value in Map (is_le, t', d, ())
| null |
https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Vale_Lib_MapTree.ml
|
ocaml
|
open Prims
type ('a, 'isule) is_cmp = unit
type ('a, 'b) tree =
| Empty
| Node of 'a * 'b * Prims.nat * ('a, 'b) tree * ('a, 'b) tree
let uu___is_Empty : 'a 'b . ('a, 'b) tree -> Prims.bool =
fun projectee -> match projectee with | Empty -> true | uu___ -> false
let uu___is_Node : 'a 'b . ('a, 'b) tree -> Prims.bool =
fun projectee ->
match projectee with | Node (_0, _1, _2, _3, _4) -> true | uu___ -> false
let __proj__Node__item___0 : 'a 'b . ('a, 'b) tree -> 'a =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _0
let __proj__Node__item___1 : 'a 'b . ('a, 'b) tree -> 'b =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _1
let __proj__Node__item___2 : 'a 'b . ('a, 'b) tree -> Prims.nat =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _2
let __proj__Node__item___3 : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _3
let __proj__Node__item___4 : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun projectee -> match projectee with | Node (_0, _1, _2, _3, _4) -> _4
let height : 'a 'b . ('a, 'b) tree -> Prims.nat =
fun t ->
match t with
| Empty -> Prims.int_zero
| Node (uu___, uu___1, h, uu___2, uu___3) -> h
let mkNode :
'a 'b . 'a -> 'b -> ('a, 'b) tree -> ('a, 'b) tree -> ('a, 'b) tree =
fun key ->
fun value ->
fun l ->
fun r ->
let hl = height l in
let hr = height r in
let h = if hl > hr then hl else hr in
Node (key, value, (h + Prims.int_one), l, r)
let rotate_l : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun t ->
match t with
| Node (kl, vl, uu___, l, Node (kr, vr, uu___1, lr, rr)) ->
mkNode kr vr (mkNode kl vl l lr) rr
| uu___ -> t
let rotate_r : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun t ->
match t with
| Node (kr, vr, uu___, Node (kl, vl, uu___1, ll, rl), r) ->
mkNode kl vl ll (mkNode kr vr rl r)
| uu___ -> t
let balance : 'a 'b . ('a, 'b) tree -> ('a, 'b) tree =
fun t ->
match t with
| Node (uu___, uu___1, uu___2, l, r) ->
let hl = height l in
let hr = height r in
if hl >= (hr + (Prims.of_int (2)))
then rotate_r t
else if hr >= (hl + (Prims.of_int (2))) then rotate_l t else t
| uu___ -> t
let rec get :
'a 'b .
('a -> 'a -> Prims.bool) ->
('a, 'b) tree -> 'a -> 'b FStar_Pervasives_Native.option
=
fun is_le ->
fun t ->
fun key ->
match t with
| Empty -> FStar_Pervasives_Native.None
| Node (k, v, h, l, r) ->
if key = k
then FStar_Pervasives_Native.Some v
else if is_le key k then get is_le l key else get is_le r key
let rec put :
'a 'b .
('a -> 'a -> Prims.bool) -> ('a, 'b) tree -> 'a -> 'b -> ('a, 'b) tree
=
fun is_le ->
fun t ->
fun key ->
fun value ->
match t with
| Empty -> mkNode key value Empty Empty
| Node (k, v, uu___, l, r) ->
if key = k
then mkNode k value l r
else
if is_le key k
then balance (mkNode k v (put is_le l key value) r)
else balance (mkNode k v l (put is_le r key value))
let is_lt_option :
'a .
('a -> 'a -> Prims.bool) ->
'a FStar_Pervasives_Native.option ->
'a FStar_Pervasives_Native.option -> Prims.bool
=
fun is_le ->
fun x ->
fun y ->
match (x, y) with
| (FStar_Pervasives_Native.Some x1, FStar_Pervasives_Native.Some y1)
-> (is_le x1 y1) && (x1 <> y1)
| uu___ -> true
type ('a, 'b, 'isule, 't, 'lo, 'hi) inv = Obj.t
type ('a, 'b) map' =
| Map of ('a -> 'a -> Prims.bool) * ('a, 'b) tree * 'b * unit
let uu___is_Map : 'a 'b . ('a, 'b) map' -> Prims.bool = fun projectee -> true
let __proj__Map__item__is_le :
'a 'b . ('a, 'b) map' -> 'a -> 'a -> Prims.bool =
fun projectee ->
match projectee with | Map (is_le, t, default_v, invs) -> is_le
let __proj__Map__item__t : 'a 'b . ('a, 'b) map' -> ('a, 'b) tree =
fun projectee ->
match projectee with | Map (is_le, t, default_v, invs) -> t
let __proj__Map__item__default_v : 'a 'b . ('a, 'b) map' -> 'b =
fun projectee ->
match projectee with | Map (is_le, t, default_v, invs) -> default_v
type ('a, 'b) map = ('a, 'b) map'
let const : 'a 'b . ('a -> 'a -> Prims.bool) -> 'b -> ('a, 'b) map =
fun is_le -> fun d -> Map (is_le, Empty, d, ())
let sel : 'a 'b . ('a, 'b) map -> 'a -> 'b =
fun uu___ ->
fun key ->
match uu___ with
| Map (is_le, t, d, uu___1) ->
(match get is_le t key with
| FStar_Pervasives_Native.Some v -> v
| FStar_Pervasives_Native.None -> d)
let upd : 'a 'b . ('a, 'b) map -> 'a -> 'b -> ('a, 'b) map =
fun uu___ ->
fun key ->
fun value ->
match uu___ with
| Map (is_le, t, d, uu___1) ->
let t' = put is_le t key value in Map (is_le, t', d, ())
|
|
a8939abd0eac489b78ccb5297d0a504dba00a26cce30b6c71943c4b505429414
|
sdiehl/elliptic-curve
|
SECP160K1.hs
|
module Data.Curve.Weierstrass.SECP160K1
( module Data.Curve.Weierstrass
, Point(..)
-- * SECP160K1 curve
, module Data.Curve.Weierstrass.SECP160K1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
-------------------------------------------------------------------------------
-- Types
-------------------------------------------------------------------------------
-- | SECP160K1 curve.
data SECP160K1
-- | Field of points of SECP160K1 curve.
type Fq = Prime Q
type Q = 0xfffffffffffffffffffffffffffffffeffffac73
-- | Field of coefficients of SECP160K1 curve.
type Fr = Prime R
type R = 0x100000000000000000001b8fa16dfab9aca16b6b3
SECP160K1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c SECP160K1 Fq Fr => WCurve c SECP160K1 Fq Fr where
a_ = const _a
{-# INLINABLE a_ #-}
b_ = const _b
# INLINABLE b _ #
h_ = const _h
{-# INLINABLE h_ #-}
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
-- | Affine SECP160K1 curve point.
type PA = WAPoint SECP160K1 Fq Fr
Affine SECP160K1 curve is a Weierstrass affine curve .
instance WACurve SECP160K1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
-- | Jacobian SECP160K1 point.
type PJ = WJPoint SECP160K1 Fq Fr
Jacobian SECP160K1 curve is a Weierstrass Jacobian curve .
instance WJCurve SECP160K1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
-- | Projective SECP160K1 point.
type PP = WPPoint SECP160K1 Fq Fr
Projective SECP160K1 curve is a Weierstrass projective curve .
instance WPCurve SECP160K1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
-------------------------------------------------------------------------------
-- Parameters
-------------------------------------------------------------------------------
-- | Coefficient @A@ of SECP160K1 curve.
_a :: Fq
_a = 0x0
# INLINABLE _ a #
| Coefficient @B@ of SECP160K1 curve .
_b :: Fq
_b = 0x7
{-# INLINABLE _b #-}
-- | Cofactor of SECP160K1 curve.
_h :: Natural
_h = 0x1
# INLINABLE _ h #
-- | Characteristic of SECP160K1 curve.
_q :: Natural
_q = 0xfffffffffffffffffffffffffffffffeffffac73
{-# INLINABLE _q #-}
-- | Order of SECP160K1 curve.
_r :: Natural
_r = 0x100000000000000000001b8fa16dfab9aca16b6b3
{-# INLINABLE _r #-}
-- | Coordinate @X@ of SECP160K1 curve.
_x :: Fq
_x = 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebb
{-# INLINABLE _x #-}
-- | Coordinate @Y@ of SECP160K1 curve.
_y :: Fq
_y = 0x938cf935318fdced6bc28286531733c3f03c4fee
{-# INLINABLE _y #-}
-- | Generator of affine SECP160K1 curve.
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian SECP160K1 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
-- | Generator of projective SECP160K1 curve.
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
| null |
https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Weierstrass/SECP160K1.hs
|
haskell
|
* SECP160K1 curve
-----------------------------------------------------------------------------
Types
-----------------------------------------------------------------------------
| SECP160K1 curve.
| Field of points of SECP160K1 curve.
| Field of coefficients of SECP160K1 curve.
# INLINABLE a_ #
# INLINABLE h_ #
| Affine SECP160K1 curve point.
| Jacobian SECP160K1 point.
| Projective SECP160K1 point.
-----------------------------------------------------------------------------
Parameters
-----------------------------------------------------------------------------
| Coefficient @A@ of SECP160K1 curve.
# INLINABLE _b #
| Cofactor of SECP160K1 curve.
| Characteristic of SECP160K1 curve.
# INLINABLE _q #
| Order of SECP160K1 curve.
# INLINABLE _r #
| Coordinate @X@ of SECP160K1 curve.
# INLINABLE _x #
| Coordinate @Y@ of SECP160K1 curve.
# INLINABLE _y #
| Generator of affine SECP160K1 curve.
| Generator of projective SECP160K1 curve.
|
module Data.Curve.Weierstrass.SECP160K1
( module Data.Curve.Weierstrass
, Point(..)
, module Data.Curve.Weierstrass.SECP160K1
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
data SECP160K1
type Fq = Prime Q
type Q = 0xfffffffffffffffffffffffffffffffeffffac73
type Fr = Prime R
type R = 0x100000000000000000001b8fa16dfab9aca16b6b3
SECP160K1 curve is a Weierstrass curve .
instance Curve 'Weierstrass c SECP160K1 Fq Fr => WCurve c SECP160K1 Fq Fr where
a_ = const _a
b_ = const _b
# INLINABLE b _ #
h_ = const _h
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
type PA = WAPoint SECP160K1 Fq Fr
Affine SECP160K1 curve is a Weierstrass affine curve .
instance WACurve SECP160K1 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
type PJ = WJPoint SECP160K1 Fq Fr
Jacobian SECP160K1 curve is a Weierstrass Jacobian curve .
instance WJCurve SECP160K1 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
type PP = WPPoint SECP160K1 Fq Fr
Projective SECP160K1 curve is a Weierstrass projective curve .
instance WPCurve SECP160K1 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
_a :: Fq
_a = 0x0
# INLINABLE _ a #
| Coefficient @B@ of SECP160K1 curve .
_b :: Fq
_b = 0x7
_h :: Natural
_h = 0x1
# INLINABLE _ h #
_q :: Natural
_q = 0xfffffffffffffffffffffffffffffffeffffac73
_r :: Natural
_r = 0x100000000000000000001b8fa16dfab9aca16b6b3
_x :: Fq
_x = 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebb
_y :: Fq
_y = 0x938cf935318fdced6bc28286531733c3f03c4fee
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian SECP160K1 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
|
cc16c856513c137d6bc9167997d0d0f15104a28d3e55987b73dbb2e9a20c039d
|
Eduap-com/WordMat
|
nregex.lisp
|
-*- Mode : Lisp ; Package : USER ; -*-
;;;
;;; This code was written by:
;;;
< >
National Science Center Foundation
Augusta , Georgia 30909
;;;
;;; If you modify this code, please comment your modifications
;;; clearly and inform the author of any improvements so they
;;; can be incorporated in future releases.
;;;
;;; nregex.lisp - My 4/8/92 attempt at a Lisp based regular expression
;;; parser.
;;;
;;; This regular expression parser operates by taking a
;;; regular expression and breaking it down into a list
;;; consisting of lisp expressions and flags. The list
;;; of lisp expressions is then taken in turned into a
;;; lambda expression that can be later applied to a
;;; string argument for parsing.
;;;
;;; First we create a copy of macros to help debug the beast
(eval-when #-gcl(:compile-toplevel :load-toplevel :execute)
#+gcl(load compile eval)
(defpackage :maxima-nregex
(:use :common-lisp)
(:export
Vars
#:*regex-debug* #:*regex-groups* #:*regex-groupings*
;; Functions
#:regex-compile
))
)
(in-package :maxima-nregex)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *regex-debug* nil) ; Set to nil for no debugging code
(defmacro info (message &rest args)
(if *regex-debug*
`(format *trace-output* ,message ,@args)))
;;;
;;; Declare the global variables for storing the paren index list.
;;;
(defvar *regex-groups* (make-array 10))
(defvar *regex-groupings* 0)
)
;;;
;;; Declare a simple interface for testing. You probably wouldn't want
;;; to use this interface unless you were just calling this once.
;;;
(defun regex (expression string)
"Usage: (regex <expression> <string)
This function will call regex-compile on the expression and then apply
the string to the returned lambda list."
(let ((findit (cond ((stringp expression)
(regex-compile expression))
((listp expression)
expression)))
(result nil))
(if (not (funcall (if (functionp findit)
findit
(eval `(function ,findit))) string))
(return-from regex nil))
(if (= *regex-groupings* 0)
(return-from regex t))
(dotimes (i *regex-groupings*)
(push (funcall 'subseq
string
(car (aref *regex-groups* i))
(cadr (aref *regex-groups* i)))
result))
(reverse result)))
;;;
;;; Declare some simple macros to make the code more readable.
;;;
(defvar *regex-special-chars* "?*+.()[]\\${}")
(defmacro add-exp (list)
"Add an item to the end of expression"
`(setf expression (append expression ,list)))
;;;
;;; Now for the main regex compiler routine.
;;;
(defun regex-compile (source &key (anchored nil) (case-sensitive t))
"Usage: (regex-compile <expression> [ :anchored (t/nil) ] [ :case-sensitive (t/nil) ])
This function take a regular expression (supplied as source) and
compiles this into a lambda list that a string argument can then
be applied to. It is also possible to compile this lambda list
for better performance or to save it as a named function for later
use"
(info "Now entering regex-compile with \"~A\"~%" source)
;;
This routine works in two parts .
The first pass take the regular expression and produces a list of
;; operators and lisp expressions for the entire regular expression.
The second pass takes this list and produces the lambda expression .
(let ((expression '()) ; holder for expressions
(group 1) ; Current group index
Stack of current group endings
(result nil) ; holder for built expression.
(fast-first nil)) ; holder for quick unanchored scan
;;
;; If the expression was an empty string then it alway
;; matches (so lets leave early)
;;
(if (= (length source) 0)
(return-from regex-compile
'(lambda (&rest args)
(declare (ignore args))
t)))
;;
If the first character is a caret then set the anchored
;; flags and remove if from the expression string.
;;
(cond ((eql (char source 0) #\^)
(setf source (subseq source 1))
(setf anchored t)))
;;
If the first sequence is . * then also set the anchored flags .
;; (This is purely for optimization, it will work without this).
;;
(if (>= (length source) 2)
(if (string= source ".*" :start1 0 :end1 2)
(setf anchored t)))
;;
Also , If this is not an anchored search and the first character is
;; a literal, then do a quick scan to see if it is even in the string.
;; If not then we can issue a quick nil,
;; otherwise we can start the search at the matching character to skip
;; the checks of the non-matching characters anyway.
;;
;; If I really wanted to speed up this section of code it would be
;; easy to recognize the case of a fairly long multi-character literal
and generate a Boyer - Moore search for the entire literal .
;;
I generate the code to do a loop because on CMU Lisp this is about
;; twice as fast a calling position.
;;
(if (and (not anchored)
(not (position (char source 0) *regex-special-chars*))
(not (and (> (length source) 1)
(position (char source 1) *regex-special-chars*))))
(setf fast-first `((if (not (do ((i start (+ i 1)))
((>= i length))
(if (,(if case-sensitive 'eql 'char-equal)
(char string i)
,(char source 0))
(return (setf start i)))))
(return-from final-return nil)))))
;;
Generate the very first expression to save the starting index
;; so that group 0 will be the entire string matched always
;;
(add-exp '((setf (aref *regex-groups* 0)
(list index nil))))
;;
;; Loop over each character in the regular expression building the
;; expression list as we go.
;;
(do ((eindex 0 (1+ eindex)))
((= eindex (length source)))
(let ((current (char source eindex)))
(info "Now processing character ~A index = ~A~%" current eindex)
(case current
((#\.)
;;
;; Generate code for a single wild character
;;
(add-exp '((if (>= index length)
(return-from compare nil)
(incf index)))))
((#\$)
;;
;; If this is the last character of the expression then
;; anchor the end of the expression, otherwise let it slide
;; as a standard character (even though it should be quoted).
;;
(if (= eindex (1- (length source)))
(add-exp '((if (not (= index length))
(return-from compare nil))))
(add-exp '((if (not (and (< index length)
(eql (char string index) #\$)))
(return-from compare nil)
(incf index))))))
((#\*)
(add-exp '(astrisk)))
((#\+)
(add-exp '(plus)))
((#\?)
(add-exp '(question)))
((#\()
;;
;; Start a grouping.
;;
(incf group)
(push group group-stack)
(add-exp `((setf (aref *regex-groups* ,(1- group))
(list index nil))))
(add-exp `(,group)))
((#\))
;;
;; End a grouping
;;
(let ((group (pop group-stack)))
(add-exp `((setf (cadr (aref *regex-groups* ,(1- group)))
index)))
(add-exp `(,(- group)))))
((#\[)
;;
;; Start of a range operation.
Generate a bit - vector that has one bit per possible character
;; and then on each character or range, set the possible bits.
;;
If the first character is carat then invert the set .
(let* ((invert (eql (char source (1+ eindex)) #\^))
(bitstring (make-array 256 :element-type 'bit
:initial-element
(if invert 1 0)))
(set-char (if invert 0 1)))
(if invert (incf eindex))
(do ((x (1+ eindex) (1+ x)))
((eql (char source x) #\]) (setf eindex x))
(info "Building range with character ~A~%" (char source x))
(cond ((and (eql (char source (1+ x)) #\-)
(not (eql (char source (+ x 2)) #\])))
(if (>= (char-code (char source x))
(char-code (char source (+ 2 x))))
(error (intl:gettext "regex: ranges must be in ascending order; found: \"~A-~A\"")
(char source x) (char source (+ 2 x))))
(do ((j (char-code (char source x)) (1+ j)))
((> j (char-code (char source (+ 2 x))))
(incf x 2))
(info "Setting bit for char ~A code ~A~%" (code-char j) j)
(setf (sbit bitstring j) set-char)))
(t
(cond ((not (eql (char source x) #\]))
(let ((char (char source x)))
;;
;; If the character is quoted then find out what
;; it should have been
;;
(if (eql (char source x) #\\ )
(let ((length))
(multiple-value-setq (char length)
(regex-quoted (subseq source x) invert))
(incf x length)))
(info "Setting bit for char ~A code ~A~%" char (char-code char))
(if (not (vectorp char))
(setf (sbit bitstring (char-code (char source x))) set-char)
(bit-ior bitstring char t))))))))
(add-exp `((let ((range ,bitstring))
(if (>= index length)
(return-from compare nil))
(if (= 1 (sbit range (char-code (char string index))))
(incf index)
(return-from compare nil)))))))
((#\\ )
;;
;; Intreprete the next character as a special, range, octal, group or
;; just the character itself.
;;
(let ((length)
(value))
(multiple-value-setq (value length)
(regex-quoted (subseq source (1+ eindex)) nil))
(cond ((listp value)
(add-exp value))
((characterp value)
(add-exp `((if (not (and (< index length)
(eql (char string index)
,value)))
(return-from compare nil)
(incf index)))))
((vectorp value)
(add-exp `((let ((range ,value))
(if (>= index length)
(return-from compare nil))
(if (= 1 (sbit range (char-code (char string index))))
(incf index)
(return-from compare nil)))))))
(incf eindex length)))
(t
;;
;; We have a literal character.
Scan to see how many we have and if it is more than one
generate a string= verses as single eql .
;;
(let* ((lit "")
(term (dotimes (litindex (- (length source) eindex) nil)
(let ((litchar (char source (+ eindex litindex))))
(if (position litchar *regex-special-chars*)
(return litchar)
(progn
(info "Now adding ~A index ~A to lit~%" litchar
litindex)
(setf lit (concatenate 'string lit
(string litchar)))))))))
(if (= (length lit) 1)
(add-exp `((if (not (and (< index length)
(,(if case-sensitive 'eql 'char-equal)
(char string index) ,current)))
(return-from compare nil)
(incf index))))
;;
;; If we have a multi-character literal then we must
;; check to see if the next character (if there is one)
;; is an astrisk or a plus. If so then we must not use this
;; character in the big literal.
(progn
(if (or (eql term #\*) (eql term #\+))
(setf lit (subseq lit 0 (1- (length lit)))))
(add-exp `((if (< length (+ index ,(length lit)))
(return-from compare nil))
(if (not (,(if case-sensitive 'string= 'string-equal)
string ,lit :start1 index
:end1 (+ index ,(length lit))))
(return-from compare nil)
(incf index ,(length lit)))))))
(incf eindex (1- (length lit))))))))
;;
;; Plug end of list to return t. If we made it this far then
;; We have matched!
(add-exp '((setf (cadr (aref *regex-groups* 0))
index)))
(add-exp '((return-from final-return t)))
;;
;;; (print expression)
;;
;; Now take the expression list and turn it into a lambda expression
;; replacing the special flags with lisp code.
;; For example: A BEGIN needs to be replace by an expression that
;; saves the current index, then evaluates everything till it gets to
;; the END then save the new index if it didn't fail.
;; On an ASTRISK I need to take the previous expression and wrap
;; it in a do that will evaluate the expression till an error
;; occurs and then another do that encompases the remainder of the
regular expression and iterates decrementing the index by one
;; of the matched expression sizes and then returns nil. After
;; the last expression insert a form that does a return t so that
;; if the entire nested sub-expression succeeds then the loop
;; is broken manually.
;;
(setf result (copy-tree nil))
;;
;; Reversing the current expression makes building up the
;; lambda list easier due to the nexting of expressions when
;; and astrisk has been encountered.
(setf expression (reverse expression))
(do ((elt 0 (1+ elt)))
((>= elt (length expression)))
(let ((piece (nth elt expression)))
;;
;; Now check for PLUS, if so then ditto the expression and then let the
;; ASTRISK below handle the rest.
;;
(cond ((eql piece 'plus)
(cond ((listp (nth (1+ elt) expression))
(setf result (append (list (nth (1+ elt) expression))
result)))
;;
;; duplicate the entire group
;; NOTE: This hasn't been implemented yet!!
(t
(format *standard-output* "`group' repeat hasn't been implemented yet~%")))))
(cond ((listp piece) ;Just append the list
(setf result (append (list piece) result)))
((eql piece 'question) ; Wrap it in a block that won't fail
(cond ((listp (nth (1+ elt) expression))
(setf result
(append `((progn (block compare
,(nth (1+ elt)
expression))
t))
result))
(incf elt))
;;
;; This is a QUESTION on an entire group which
;; hasn't been implemented yet!!!
;;
(t
(format *standard-output* "Optional groups not implemented yet~%"))))
((or (eql piece 'astrisk) ; Do the wild thing!
(eql piece 'plus))
(cond ((listp (nth (1+ elt) expression))
;;
;; This is a single character wild card so
;; do the simple form.
;;
(setf result
`((let ((oindex index))
(declare (fixnum oindex))
(block compare
(do ()
(nil)
,(nth (1+ elt) expression)))
(do ((start index (1- start)))
((< start oindex) nil)
(declare (fixnum start))
(let ((index start))
(declare (fixnum index))
(block compare
,@result))))))
(incf elt))
(t
;;
;; This is a subgroup repeated so I must build
;; the loop using several values.
;;
))
)
(t t)))) ; Just ignore everything else.
;;
;; Now wrap the result in a lambda list that can then be
;; invoked or compiled, however the user wishes.
;;
(if anchored
(setf result
`(lambda (string &key (start 0) (end (length string)))
(declare (string string)
(fixnum start end)
(ignorable start)
(optimize (speed 0) (compilation-speed 3)))
(setf *regex-groupings* ,group)
(block final-return
(block compare
(let ((index start)
(length end))
(declare (fixnum index length))
,@result)))))
(setf result
`(lambda (string &key (start 0) (end (length string)))
(declare (string string)
(fixnum start end)
(ignorable start)
(optimize (speed 0) (compilation-speed 3)))
(setf *regex-groupings* ,group)
(block final-return
(let ((length end))
(declare (fixnum length))
,@fast-first
(do ((marker start (1+ marker)))
((> marker end) nil)
(declare (fixnum marker))
(let ((index marker))
(declare (fixnum index))
(if (block compare
,@result)
(return t)))))))))))
;;;
;;; Define a function that will take a quoted character and return
;;; what the real character should be plus how much of the source
;;; string was used. If the result is a set of characters, return an
;;; array of bits indicating which characters should be set. If the
;;; expression is one of the sub-group matches return a
;;; list-expression that will provide the match.
;;;
(defun regex-quoted (char-string &optional (invert nil))
"Usage: (regex-quoted <char-string> &optional invert)
Returns either the quoted character or a simple bit vector of bits set for
the matching values"
(let ((first (char char-string 0))
(result (char char-string 0))
(used-length 1))
(cond ((eql first #\n)
(setf result #\newline))
((eql first #\c)
(setf result #\return))
((eql first #\t)
(setf result #\tab))
((eql first #\d)
(setf result #*0000000000000000000000000000000000000000000000001111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\D)
(setf result #*1111111111111111111111111111111111111111111111110000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\w)
(setf result #*0000000000000000000000000000000000000000000000001111111111000000011111111111111111111111111000010111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\W)
(setf result #*1111111111111111111111111111111111111111111111110000000000111111100000000000000000000000000111101000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\b)
(setf result #*0000000001000000000000000000000011000000000010100000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\B)
(setf result #*1111111110111111111111111111111100111111111101011111111111011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\s)
(setf result #*0000000001100000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\S)
(setf result #*1111111110011111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((and (>= (char-code first) (char-code #\0))
(<= (char-code first) (char-code #\9)))
(if (and (> (length char-string) 2)
(and (>= (char-code (char char-string 1)) (char-code #\0))
(<= (char-code (char char-string 1)) (char-code #\9))
(>= (char-code (char char-string 2)) (char-code #\0))
(<= (char-code (char char-string 2)) (char-code #\9))))
;;
;; It is a single character specified in octal
;;
(progn
(setf result (do ((x 0 (1+ x))
(return 0))
((= x 2) return)
(setf return (+ (* return 8)
(- (char-code (char char-string x))
(char-code #\0))))))
(setf used-length 3))
;;
;; We have a group number replacement.
;;
(let ((group (- (char-code first) (char-code #\0))))
(setf result `((let ((nstring (subseq string (car (aref *regex-groups* ,group))
(cadr (aref *regex-groups* ,group)))))
(if (< length (+ index (length nstring)))
(return-from compare nil))
(if (not (string= string nstring
:start1 index
:end1 (+ index (length nstring))))
(return-from compare nil)
(incf index (length nstring)))))))))
(t
(setf result first)))
(if (and (vectorp result) invert)
(bit-xor result #*1111111110011111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 t))
(values result used-length)))
| null |
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/src/nregex.lisp
|
lisp
|
Package : USER ; -*-
This code was written by:
If you modify this code, please comment your modifications
clearly and inform the author of any improvements so they
can be incorporated in future releases.
nregex.lisp - My 4/8/92 attempt at a Lisp based regular expression
parser.
This regular expression parser operates by taking a
regular expression and breaking it down into a list
consisting of lisp expressions and flags. The list
of lisp expressions is then taken in turned into a
lambda expression that can be later applied to a
string argument for parsing.
First we create a copy of macros to help debug the beast
Functions
Set to nil for no debugging code
Declare the global variables for storing the paren index list.
Declare a simple interface for testing. You probably wouldn't want
to use this interface unless you were just calling this once.
Declare some simple macros to make the code more readable.
Now for the main regex compiler routine.
operators and lisp expressions for the entire regular expression.
holder for expressions
Current group index
holder for built expression.
holder for quick unanchored scan
If the expression was an empty string then it alway
matches (so lets leave early)
flags and remove if from the expression string.
(This is purely for optimization, it will work without this).
a literal, then do a quick scan to see if it is even in the string.
If not then we can issue a quick nil,
otherwise we can start the search at the matching character to skip
the checks of the non-matching characters anyway.
If I really wanted to speed up this section of code it would be
easy to recognize the case of a fairly long multi-character literal
twice as fast a calling position.
so that group 0 will be the entire string matched always
Loop over each character in the regular expression building the
expression list as we go.
Generate code for a single wild character
If this is the last character of the expression then
anchor the end of the expression, otherwise let it slide
as a standard character (even though it should be quoted).
Start a grouping.
End a grouping
Start of a range operation.
and then on each character or range, set the possible bits.
If the character is quoted then find out what
it should have been
Intreprete the next character as a special, range, octal, group or
just the character itself.
We have a literal character.
If we have a multi-character literal then we must
check to see if the next character (if there is one)
is an astrisk or a plus. If so then we must not use this
character in the big literal.
Plug end of list to return t. If we made it this far then
We have matched!
(print expression)
Now take the expression list and turn it into a lambda expression
replacing the special flags with lisp code.
For example: A BEGIN needs to be replace by an expression that
saves the current index, then evaluates everything till it gets to
the END then save the new index if it didn't fail.
On an ASTRISK I need to take the previous expression and wrap
it in a do that will evaluate the expression till an error
occurs and then another do that encompases the remainder of the
of the matched expression sizes and then returns nil. After
the last expression insert a form that does a return t so that
if the entire nested sub-expression succeeds then the loop
is broken manually.
Reversing the current expression makes building up the
lambda list easier due to the nexting of expressions when
and astrisk has been encountered.
Now check for PLUS, if so then ditto the expression and then let the
ASTRISK below handle the rest.
duplicate the entire group
NOTE: This hasn't been implemented yet!!
Just append the list
Wrap it in a block that won't fail
This is a QUESTION on an entire group which
hasn't been implemented yet!!!
Do the wild thing!
This is a single character wild card so
do the simple form.
This is a subgroup repeated so I must build
the loop using several values.
Just ignore everything else.
Now wrap the result in a lambda list that can then be
invoked or compiled, however the user wishes.
Define a function that will take a quoted character and return
what the real character should be plus how much of the source
string was used. If the result is a set of characters, return an
array of bits indicating which characters should be set. If the
expression is one of the sub-group matches return a
list-expression that will provide the match.
It is a single character specified in octal
We have a group number replacement.
|
< >
National Science Center Foundation
Augusta , Georgia 30909
(eval-when #-gcl(:compile-toplevel :load-toplevel :execute)
#+gcl(load compile eval)
(defpackage :maxima-nregex
(:use :common-lisp)
(:export
Vars
#:*regex-debug* #:*regex-groups* #:*regex-groupings*
#:regex-compile
))
)
(in-package :maxima-nregex)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro info (message &rest args)
(if *regex-debug*
`(format *trace-output* ,message ,@args)))
(defvar *regex-groups* (make-array 10))
(defvar *regex-groupings* 0)
)
(defun regex (expression string)
"Usage: (regex <expression> <string)
This function will call regex-compile on the expression and then apply
the string to the returned lambda list."
(let ((findit (cond ((stringp expression)
(regex-compile expression))
((listp expression)
expression)))
(result nil))
(if (not (funcall (if (functionp findit)
findit
(eval `(function ,findit))) string))
(return-from regex nil))
(if (= *regex-groupings* 0)
(return-from regex t))
(dotimes (i *regex-groupings*)
(push (funcall 'subseq
string
(car (aref *regex-groups* i))
(cadr (aref *regex-groups* i)))
result))
(reverse result)))
(defvar *regex-special-chars* "?*+.()[]\\${}")
(defmacro add-exp (list)
"Add an item to the end of expression"
`(setf expression (append expression ,list)))
(defun regex-compile (source &key (anchored nil) (case-sensitive t))
"Usage: (regex-compile <expression> [ :anchored (t/nil) ] [ :case-sensitive (t/nil) ])
This function take a regular expression (supplied as source) and
compiles this into a lambda list that a string argument can then
be applied to. It is also possible to compile this lambda list
for better performance or to save it as a named function for later
use"
(info "Now entering regex-compile with \"~A\"~%" source)
This routine works in two parts .
The first pass take the regular expression and produces a list of
The second pass takes this list and produces the lambda expression .
Stack of current group endings
(if (= (length source) 0)
(return-from regex-compile
'(lambda (&rest args)
(declare (ignore args))
t)))
If the first character is a caret then set the anchored
(cond ((eql (char source 0) #\^)
(setf source (subseq source 1))
(setf anchored t)))
If the first sequence is . * then also set the anchored flags .
(if (>= (length source) 2)
(if (string= source ".*" :start1 0 :end1 2)
(setf anchored t)))
Also , If this is not an anchored search and the first character is
and generate a Boyer - Moore search for the entire literal .
I generate the code to do a loop because on CMU Lisp this is about
(if (and (not anchored)
(not (position (char source 0) *regex-special-chars*))
(not (and (> (length source) 1)
(position (char source 1) *regex-special-chars*))))
(setf fast-first `((if (not (do ((i start (+ i 1)))
((>= i length))
(if (,(if case-sensitive 'eql 'char-equal)
(char string i)
,(char source 0))
(return (setf start i)))))
(return-from final-return nil)))))
Generate the very first expression to save the starting index
(add-exp '((setf (aref *regex-groups* 0)
(list index nil))))
(do ((eindex 0 (1+ eindex)))
((= eindex (length source)))
(let ((current (char source eindex)))
(info "Now processing character ~A index = ~A~%" current eindex)
(case current
((#\.)
(add-exp '((if (>= index length)
(return-from compare nil)
(incf index)))))
((#\$)
(if (= eindex (1- (length source)))
(add-exp '((if (not (= index length))
(return-from compare nil))))
(add-exp '((if (not (and (< index length)
(eql (char string index) #\$)))
(return-from compare nil)
(incf index))))))
((#\*)
(add-exp '(astrisk)))
((#\+)
(add-exp '(plus)))
((#\?)
(add-exp '(question)))
((#\()
(incf group)
(push group group-stack)
(add-exp `((setf (aref *regex-groups* ,(1- group))
(list index nil))))
(add-exp `(,group)))
((#\))
(let ((group (pop group-stack)))
(add-exp `((setf (cadr (aref *regex-groups* ,(1- group)))
index)))
(add-exp `(,(- group)))))
((#\[)
Generate a bit - vector that has one bit per possible character
If the first character is carat then invert the set .
(let* ((invert (eql (char source (1+ eindex)) #\^))
(bitstring (make-array 256 :element-type 'bit
:initial-element
(if invert 1 0)))
(set-char (if invert 0 1)))
(if invert (incf eindex))
(do ((x (1+ eindex) (1+ x)))
((eql (char source x) #\]) (setf eindex x))
(info "Building range with character ~A~%" (char source x))
(cond ((and (eql (char source (1+ x)) #\-)
(not (eql (char source (+ x 2)) #\])))
(if (>= (char-code (char source x))
(char-code (char source (+ 2 x))))
(error (intl:gettext "regex: ranges must be in ascending order; found: \"~A-~A\"")
(char source x) (char source (+ 2 x))))
(do ((j (char-code (char source x)) (1+ j)))
((> j (char-code (char source (+ 2 x))))
(incf x 2))
(info "Setting bit for char ~A code ~A~%" (code-char j) j)
(setf (sbit bitstring j) set-char)))
(t
(cond ((not (eql (char source x) #\]))
(let ((char (char source x)))
(if (eql (char source x) #\\ )
(let ((length))
(multiple-value-setq (char length)
(regex-quoted (subseq source x) invert))
(incf x length)))
(info "Setting bit for char ~A code ~A~%" char (char-code char))
(if (not (vectorp char))
(setf (sbit bitstring (char-code (char source x))) set-char)
(bit-ior bitstring char t))))))))
(add-exp `((let ((range ,bitstring))
(if (>= index length)
(return-from compare nil))
(if (= 1 (sbit range (char-code (char string index))))
(incf index)
(return-from compare nil)))))))
((#\\ )
(let ((length)
(value))
(multiple-value-setq (value length)
(regex-quoted (subseq source (1+ eindex)) nil))
(cond ((listp value)
(add-exp value))
((characterp value)
(add-exp `((if (not (and (< index length)
(eql (char string index)
,value)))
(return-from compare nil)
(incf index)))))
((vectorp value)
(add-exp `((let ((range ,value))
(if (>= index length)
(return-from compare nil))
(if (= 1 (sbit range (char-code (char string index))))
(incf index)
(return-from compare nil)))))))
(incf eindex length)))
(t
Scan to see how many we have and if it is more than one
generate a string= verses as single eql .
(let* ((lit "")
(term (dotimes (litindex (- (length source) eindex) nil)
(let ((litchar (char source (+ eindex litindex))))
(if (position litchar *regex-special-chars*)
(return litchar)
(progn
(info "Now adding ~A index ~A to lit~%" litchar
litindex)
(setf lit (concatenate 'string lit
(string litchar)))))))))
(if (= (length lit) 1)
(add-exp `((if (not (and (< index length)
(,(if case-sensitive 'eql 'char-equal)
(char string index) ,current)))
(return-from compare nil)
(incf index))))
(progn
(if (or (eql term #\*) (eql term #\+))
(setf lit (subseq lit 0 (1- (length lit)))))
(add-exp `((if (< length (+ index ,(length lit)))
(return-from compare nil))
(if (not (,(if case-sensitive 'string= 'string-equal)
string ,lit :start1 index
:end1 (+ index ,(length lit))))
(return-from compare nil)
(incf index ,(length lit)))))))
(incf eindex (1- (length lit))))))))
(add-exp '((setf (cadr (aref *regex-groups* 0))
index)))
(add-exp '((return-from final-return t)))
regular expression and iterates decrementing the index by one
(setf result (copy-tree nil))
(setf expression (reverse expression))
(do ((elt 0 (1+ elt)))
((>= elt (length expression)))
(let ((piece (nth elt expression)))
(cond ((eql piece 'plus)
(cond ((listp (nth (1+ elt) expression))
(setf result (append (list (nth (1+ elt) expression))
result)))
(t
(format *standard-output* "`group' repeat hasn't been implemented yet~%")))))
(setf result (append (list piece) result)))
(cond ((listp (nth (1+ elt) expression))
(setf result
(append `((progn (block compare
,(nth (1+ elt)
expression))
t))
result))
(incf elt))
(t
(format *standard-output* "Optional groups not implemented yet~%"))))
(eql piece 'plus))
(cond ((listp (nth (1+ elt) expression))
(setf result
`((let ((oindex index))
(declare (fixnum oindex))
(block compare
(do ()
(nil)
,(nth (1+ elt) expression)))
(do ((start index (1- start)))
((< start oindex) nil)
(declare (fixnum start))
(let ((index start))
(declare (fixnum index))
(block compare
,@result))))))
(incf elt))
(t
))
)
(if anchored
(setf result
`(lambda (string &key (start 0) (end (length string)))
(declare (string string)
(fixnum start end)
(ignorable start)
(optimize (speed 0) (compilation-speed 3)))
(setf *regex-groupings* ,group)
(block final-return
(block compare
(let ((index start)
(length end))
(declare (fixnum index length))
,@result)))))
(setf result
`(lambda (string &key (start 0) (end (length string)))
(declare (string string)
(fixnum start end)
(ignorable start)
(optimize (speed 0) (compilation-speed 3)))
(setf *regex-groupings* ,group)
(block final-return
(let ((length end))
(declare (fixnum length))
,@fast-first
(do ((marker start (1+ marker)))
((> marker end) nil)
(declare (fixnum marker))
(let ((index marker))
(declare (fixnum index))
(if (block compare
,@result)
(return t)))))))))))
(defun regex-quoted (char-string &optional (invert nil))
"Usage: (regex-quoted <char-string> &optional invert)
Returns either the quoted character or a simple bit vector of bits set for
the matching values"
(let ((first (char char-string 0))
(result (char char-string 0))
(used-length 1))
(cond ((eql first #\n)
(setf result #\newline))
((eql first #\c)
(setf result #\return))
((eql first #\t)
(setf result #\tab))
((eql first #\d)
(setf result #*0000000000000000000000000000000000000000000000001111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\D)
(setf result #*1111111111111111111111111111111111111111111111110000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\w)
(setf result #*0000000000000000000000000000000000000000000000001111111111000000011111111111111111111111111000010111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\W)
(setf result #*1111111111111111111111111111111111111111111111110000000000111111100000000000000000000000000111101000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\b)
(setf result #*0000000001000000000000000000000011000000000010100000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\B)
(setf result #*1111111110111111111111111111111100111111111101011111111111011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((eql first #\s)
(setf result #*0000000001100000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
((eql first #\S)
(setf result #*1111111110011111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111))
((and (>= (char-code first) (char-code #\0))
(<= (char-code first) (char-code #\9)))
(if (and (> (length char-string) 2)
(and (>= (char-code (char char-string 1)) (char-code #\0))
(<= (char-code (char char-string 1)) (char-code #\9))
(>= (char-code (char char-string 2)) (char-code #\0))
(<= (char-code (char char-string 2)) (char-code #\9))))
(progn
(setf result (do ((x 0 (1+ x))
(return 0))
((= x 2) return)
(setf return (+ (* return 8)
(- (char-code (char char-string x))
(char-code #\0))))))
(setf used-length 3))
(let ((group (- (char-code first) (char-code #\0))))
(setf result `((let ((nstring (subseq string (car (aref *regex-groups* ,group))
(cadr (aref *regex-groups* ,group)))))
(if (< length (+ index (length nstring)))
(return-from compare nil))
(if (not (string= string nstring
:start1 index
:end1 (+ index (length nstring))))
(return-from compare nil)
(incf index (length nstring)))))))))
(t
(setf result first)))
(if (and (vectorp result) invert)
(bit-xor result #*1111111110011111111111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 t))
(values result used-length)))
|
745780b35aa55a90e42fdc7cc52991f63c8ba8b4c1cb7ceffd5c0ef0eab58835
|
basho/riak_kv
|
riak_kv_wm_object.erl
|
%% -------------------------------------------------------------------
%%
riak_kv_wm_object : Webmachine resource for KV object level operations .
%%
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
@doc Resource for serving objects over HTTP .
%%
%% URLs that begin with `/types' are necessary for the new bucket
types implementation in Riak 2.0 , those that begin with ` /buckets '
%% are for the default bucket type, and `/riak' is an old URL style,
%% also only works for the default bucket type.
%%
%% It is possible to reconfigure the `/riak' prefix but that seems to
%% be rarely if ever used.
%%
%% ```
%% POST /types/Type/buckets/Bucket/keys
%% POST /buckets/Bucket/keys
%% POST /riak/Bucket'''
%%
%% Allow the server to choose a key for the data.
%%
%% ```
%% GET /types/Type/buckets/Bucket/keys/Key
%% GET /buckets/Bucket/keys/Key
%% GET /riak/Bucket/Key'''
%%
Get the data stored in the named Bucket under the named Key .
%%
%% Content-type of the response will be taken from the
%% Content-type was used in the request that stored the data.
%%
%% Additional headers will include:
%% <ul>
%% <li>`X-Riak-Vclock': The vclock of the object</li>
%% <li>`Link': The links the object has</li>
< li>`Etag ' : The " vtag " metadata of the object</li >
%% <li>`Last-Modified': The last-modified time of the object</li>
%% <li>`Encoding': The value of the incoming Encoding header from
%% the request that stored the data.</li>
< li>`X - Riak - Meta- ' : Any headers prefixed by X - Riak - Meta- supplied
on PUT are returned verbatim</li >
%% </ul>
%%
Specifying the query param ` r = R ' , where ` R ' is an integer will
cause to use ` R ' as the r - value for the read request . A
default r - value of 2 will be used if none is specified .
%%
%% If the object is found to have siblings (only possible if the
bucket property ` allow_mult ' is true ) , then
Content - type will be ` text / plain ' ; ` Link ' , ` Etag ' , and ` Last - Modified '
%% headers will be omitted; and the body of the response will
%% be a list of the vtags of each sibling. To request a specific
sibling , include the query param ` vtag = V ' , where ` V ' is the vtag
%% of the sibling you want.
%%
%% ```
%% PUT /types/Type/buckets/Bucket/keys/Key
%% PUT /buckets/Bucket/keys/Key
PUT /riak / Bucket / Key '' '
%%
Store new data in the named Bucket under the named Key .
%%
%% A Content-type header *must* be included in the request. The
%% value of this header will be used in the response to subsequent
%% GET requests.
%%
%% The body of the request will be stored literally as the value
%% of the riak_object, and will be served literally as the body of
%% the response to subsequent GET requests.
%%
%% Include an X-Riak-Vclock header to modify data without creating
%% siblings.
%%
%% Include a Link header to set the links of the object.
%%
%% Include an Encoding header if you would like an Encoding header
%% to be included in the response to subsequent GET requests.
%%
Include custom metadata using headers prefixed with X - Riak - Meta- .
%% They will be returned verbatim on subsequent GET requests.
%%
Specifying the query param ` w = W ' , where W is an integer will
cause to use W as the w - value for the write request . A
default w - value of 2 will be used if none is specified .
%%
Specifying the query param ` dw = DW ' , where DW is an integer will
cause to use DW as the dw - value for the write request . A
default dw - value of 2 will be used if none is specified .
%%
Specifying the query param ` r = R ' , where R is an integer will
cause to use R as the r - value for the read request ( used
%% to determine whether or not the resource exists). A default
r - value of 2 will be used if none is specified .
%%
%% ```
%% POST /types/Type/buckets/Bucket/keys/Key
%% POST /buckets/Bucket/keys/Key
%% POST /riak/Bucket/Key'''
%%
%% Equivalent to `PUT /riak/Bucket/Key' (useful for clients that
do not support the PUT method ) .
%%
%% ```
%% DELETE /types/Type/buckets/Bucket/keys/Key (with bucket-type)
%% DELETE /buckets/Bucket/keys/Key (NEW)
%% DELETE /riak/Bucket/Key (OLD)'''
%%
Delete the data stored in the named Bucket under the named Key .
-module(riak_kv_wm_object).
%% webmachine resource exports
-export([
init/1,
service_available/2,
is_authorized/2,
forbidden/2,
allowed_methods/2,
allow_missing_post/2,
malformed_request/2,
resource_exists/2,
is_conflict/2,
last_modified/2,
generate_etag/2,
content_types_provided/2,
charsets_provided/2,
encodings_provided/2,
content_types_accepted/2,
post_is_create/2,
create_path/2,
process_post/2,
produce_doc_body/2,
accept_doc_body/2,
produce_sibling_message_body/2,
produce_multipart_body/2,
multiple_choices/2,
delete_resource/2
]).
-record(ctx, {api_version, %% integer() - Determine which version of the API to use.
bucket_type, %% binary() - Bucket type (from uri)
bucket, %% binary() - Bucket name (from uri)
key, %% binary() - Key (from uri)
client, %% riak_client() - the store client
r, %% integer() - r-value for reads
w, %% integer() - w-value for writes
dw, %% integer() - dw-value for writes
rw, %% integer() - rw-value for deletes
pr, %% integer() - number of primary nodes required in preflist on read
pw, %% integer() - number of primary nodes required in preflist on write
node_confirms,%% integer() - number of physically diverse nodes required in preflist on write
basic_quorum, %% boolean() - whether to use basic_quorum
boolean ( ) - whether to treat notfounds as successes
asis, %% boolean() - whether to send the put without modifying the vclock
sync_on_write,%% string() - sync on write behaviour to pass to backend
prefix, %% string() - prefix for resource uris
riak, %% local | {node(), atom()} - params for riak client
doc, %% {ok, riak_object()}|{error, term()} - the object found
vtag, %% string() - vtag the user asked for
bucketprops, %% proplist() - properties of the bucket
links, %% [link()] - links of the object
index_fields, %% [index_field()]
method, %% atom() - HTTP method for the request
timeout, %% integer() - passed-in timeout value in ms
security %% security context
}).
-ifdef(namespaced_types).
-type riak_kv_wm_object_dict() :: dict:dict().
-else.
-type riak_kv_wm_object_dict() :: dict().
-endif.
-include_lib("webmachine/include/webmachine.hrl").
-include("riak_kv_wm_raw.hrl").
-type context() :: #ctx{}.
-type request_data() :: #wm_reqdata{}.
-type validation_function() ::
fun((request_data(), context()) ->
{boolean()|{halt, pos_integer()}, request_data(), context()}).
-type link() :: {{Bucket::binary(), Key::binary()}, Tag::binary()}.
-define(DEFAULT_TIMEOUT, 60000).
-define(V1_BUCKET_REGEX, "/([^/]+)>; ?rel=\"([^\"]+)\"").
-define(V1_KEY_REGEX, "/([^/]+)/([^/]+)>; ?riaktag=\"([^\"]+)\"").
-define(V2_BUCKET_REGEX, "</buckets/([^/]+)>; ?rel=\"([^\"]+)\"").
-define(V2_KEY_REGEX,
"</buckets/([^/]+)/keys/([^/]+)>; ?riaktag=\"([^\"]+)\"").
-spec init(proplists:proplist()) -> {ok, context()}.
%% @doc Initialize this resource. This function extracts the
%% 'prefix' and 'riak' properties from the dispatch args.
init(Props) ->
{ok, #ctx{api_version=proplists:get_value(api_version, Props),
prefix=proplists:get_value(prefix, Props),
riak=proplists:get_value(riak, Props),
bucket_type=proplists:get_value(bucket_type, Props)}}.
-spec service_available(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Determine whether or not a connection to Riak
%% can be established. This function also takes this
%% opportunity to extract the 'bucket' and 'key' path
%% bindings from the dispatch, as well as any vtag
%% query parameter.
service_available(RD, Ctx0=#ctx{riak=RiakProps}) ->
Ctx = riak_kv_wm_utils:ensure_bucket_type(RD, Ctx0, #ctx.bucket_type),
ClientID = riak_kv_wm_utils:get_client_id(RD),
case riak_kv_wm_utils:get_riak_client(RiakProps, ClientID) of
{ok, C} ->
Bucket =
case wrq:path_info(bucket, RD) of
undefined ->
undefined;
B ->
list_to_binary(
riak_kv_wm_utils:maybe_decode_uri(RD, B))
end,
Key =
case wrq:path_info(key, RD) of
undefined ->
undefined;
K ->
list_to_binary(
riak_kv_wm_utils:maybe_decode_uri(RD, K))
end,
{true,
RD,
Ctx#ctx{
method=wrq:method(RD),
client=C,
bucket=Bucket,
key=Key,
vtag=wrq:get_qs_value(?Q_VTAG, RD)}};
Error ->
{false,
wrq:set_resp_body(
io_lib:format("Unable to connect to Riak: ~p~n", [Error]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
is_authorized(ReqData, Ctx) ->
case riak_api_web_security:is_authorized(ReqData) of
false ->
{"Basic realm=\"Riak\"", ReqData, Ctx};
{true, SecContext} ->
{true, ReqData, Ctx#ctx{security=SecContext}};
insecure ->
%% XXX 301 may be more appropriate here, but since the http and
%% https port are different and configurable, it is hard to figure
%% out the redirect URL to serve.
{{halt, 426}, wrq:append_to_resp_body(<<"Security is enabled and "
"Riak does not accept credentials over HTTP. Try HTTPS "
"instead.">>, ReqData), Ctx}
end.
-spec forbidden(#wm_reqdata{}, context()) -> term().
forbidden(RD, Ctx) ->
case riak_kv_wm_utils:is_forbidden(RD) of
true ->
{true, RD, Ctx};
false ->
validate(RD, Ctx)
end.
-spec validate(#wm_reqdata{}, context()) -> term().
validate(RD, Ctx=#ctx{security=undefined}) ->
validate_resource(
RD, Ctx, riak_kv_wm_utils:method_to_perm(Ctx#ctx.method));
validate(RD, Ctx=#ctx{security=Security}) ->
Perm = riak_kv_wm_utils:method_to_perm(Ctx#ctx.method),
Res = riak_core_security:check_permission({Perm,
{Ctx#ctx.bucket_type,
Ctx#ctx.bucket}},
Security),
maybe_validate_resource(Res, RD, Ctx, Perm).
-spec maybe_validate_resource(
term(), #wm_reqdata{}, context(), string()) -> term().
maybe_validate_resource({false, Error, _}, RD, Ctx, _Perm) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
{true, wrq:append_to_resp_body(
unicode:characters_to_binary(Error, utf8, utf8),
RD1), Ctx};
maybe_validate_resource({true, _}, RD, Ctx, Perm) ->
validate_resource(RD, Ctx, Perm).
-spec validate_resource(#wm_reqdata{}, context(), string()) -> term().
validate_resource(RD, Ctx, Perm) when Perm == "riak_kv.get" ->
Ensure the key is here , otherwise 404
%% we do this early as it used to be done in the
%% malformed check, so the rest of the resource
%% assumes that the key is present.
validate_doc(RD, Ctx);
validate_resource(RD, Ctx, _Perm) ->
Ensure the bucket type exists , otherwise 404 early .
validate_bucket_type(RD, Ctx).
%% @doc Detects whether fetching the requested object results in an
%% error.
validate_doc(RD, Ctx) ->
DocCtx = ensure_doc(Ctx),
case DocCtx#ctx.doc of
{error, Reason} ->
handle_common_error(Reason, RD, DocCtx);
_ ->
{false, RD, DocCtx}
end.
%% @doc Detects whether the requested object's bucket-type exists.
validate_bucket_type(RD, Ctx) ->
case riak_kv_wm_utils:bucket_type_exists(Ctx#ctx.bucket_type) of
true ->
{false, RD, Ctx};
false ->
handle_common_error(bucket_type_unknown, RD, Ctx)
end.
-spec allowed_methods(#wm_reqdata{}, context()) ->
{[atom()], #wm_reqdata{}, context()}.
%% @doc Get the list of methods this resource supports.
allowed_methods(RD, Ctx) ->
{['HEAD', 'GET', 'POST', 'PUT', 'DELETE'], RD, Ctx}.
-spec allow_missing_post(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
@doc Makes POST and PUT equivalent for creating new
%% bucket entries.
allow_missing_post(RD, Ctx) ->
{true, RD, Ctx}.
-spec malformed_request(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Determine whether query parameters, request headers,
%% and request body are badly-formed.
%% Body format is checked to be valid JSON, including
%% a "props" object for a bucket-PUT. Body format
%% is not tested for a key-level request (since the
%% body may be any content the client desires).
%% Query parameters r, w, dw, and rw are checked to
%% be valid integers. Their values are stored in
%% the context() at this time.
%% Link headers are checked for the form:
& lt;/Prefix / Bucket / Key> ; ; " , ...
%% The parsed links are stored in the context()
%% at this time.
malformed_request(RD, Ctx) when Ctx#ctx.method =:= 'POST'
orelse Ctx#ctx.method =:= 'PUT' ->
malformed_request([fun malformed_content_type/2,
fun malformed_timeout_param/2,
fun malformed_rw_params/2,
fun malformed_link_headers/2,
fun malformed_index_headers/2],
RD, Ctx);
malformed_request(RD, Ctx) ->
malformed_request([fun malformed_timeout_param/2,
fun malformed_rw_params/2], RD, Ctx).
@doc Given a list of 2 - arity funs , threads through the request data
%% and context, returning as soon as a single fun discovers a
%% malformed request or halts.
-spec malformed_request(
list(validation_function()), request_data(), context()) ->
{boolean() | {halt, pos_integer()}, request_data(), context()}.
malformed_request([], RD, Ctx) ->
{false, RD, Ctx};
malformed_request([H|T], RD, Ctx) ->
case H(RD, Ctx) of
{true, _, _} = Result -> Result;
{{halt,_}, _, _} = Halt -> Halt;
{false, RD1, Ctx1} ->
malformed_request(T, RD1, Ctx1)
end.
%% @doc Detects whether the Content-Type header is missing on
PUT / POST .
malformed_content_type(RD, Ctx) ->
case wrq:get_req_header("Content-Type", RD) of
undefined ->
{true, missing_content_type(RD), Ctx};
_ -> {false, RD, Ctx}
end.
-spec malformed_timeout_param(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Check that the timeout parameter is are a
%% string-encoded integer. Store the integer value
%% in context() if so.
malformed_timeout_param(RD, Ctx) ->
case wrq:get_qs_value("timeout", RD) of
undefined ->
{false, RD, Ctx};
TimeoutStr ->
try
Timeout = list_to_integer(TimeoutStr),
{false, RD, Ctx#ctx{timeout=Timeout}}
catch
_:_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("Bad timeout "
"value ~p~n",
[TimeoutStr]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end
end.
-spec malformed_rw_params(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Check that r, w, dw, and rw query parameters are
%% string-encoded integers. Store the integer values
%% in context() if so.
malformed_rw_params(RD, Ctx) ->
Res =
lists:foldl(fun malformed_rw_param/2,
{false, RD, Ctx},
[{#ctx.r, "r", "default"},
{#ctx.w, "w", "default"},
{#ctx.dw, "dw", "default"},
{#ctx.rw, "rw", "default"},
{#ctx.pw, "pw", "default"},
{#ctx.node_confirms, "node_confirms", "default"},
{#ctx.pr, "pr", "default"}]),
Res2 =
lists:foldl(fun malformed_custom_param/2,
Res,
[{#ctx.sync_on_write,
"sync_on_write",
"default",
[default, backend, one, all]}]),
lists:foldl(fun malformed_boolean_param/2,
Res2,
[{#ctx.basic_quorum, "basic_quorum", "default"},
{#ctx.notfound_ok, "notfound_ok", "default"},
{#ctx.asis, "asis", "false"}]).
-spec malformed_rw_param({Idx::integer(), Name::string(), Default::string()},
{boolean(), #wm_reqdata{}, context()}) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Check that a specific r, w, dw, or rw query param is a
%% string-encoded integer. Store its result in context() if it
is , or print an error message in # wm_reqdata { } if it is not .
malformed_rw_param({Idx, Name, Default}, {Result, RD, Ctx}) ->
case catch normalize_rw_param(wrq:get_qs_value(Name, Default, RD)) of
P when (is_atom(P) orelse is_integer(P)) ->
{Result, RD, setelement(Idx, Ctx, P)};
_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("~s query parameter must be an integer or "
"one of the following words: 'one', 'quorum' or 'all'~n",
[Name]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
-spec malformed_custom_param({Idx::integer(),
Name::string(),
Default::string(),
AllowedValues::[atom()]},
{boolean(), #wm_reqdata{}, context()}) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Check that a custom parameter is one of the AllowedValues
%% Store its result in context() if it is, or print an error message
in # wm_reqdata { } if it is not .
malformed_custom_param({Idx, Name, Default, AllowedValues}, {Result, RD, Ctx}) ->
AllowedValueTuples = [{V} || V <- AllowedValues],
Option=
lists:keyfind(
list_to_atom(
string:to_lower(
wrq:get_qs_value(Name, Default, RD))),
1,
AllowedValueTuples),
case Option of
false ->
ErrorText =
"~s query parameter must be one of the following words: ~p~n",
{true,
wrq:append_to_resp_body(
io_lib:format(ErrorText, [Name, AllowedValues]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx};
_ ->
{Value} = Option,
{Result, RD, setelement(Idx, Ctx, Value)}
end.
%% @doc Check that a specific query param is a
%% string-encoded boolean. Store its result in context() if it
is , or print an error message in # wm_reqdata { } if it is not .
malformed_boolean_param({Idx, Name, Default}, {Result, RD, Ctx}) ->
case string:to_lower(wrq:get_qs_value(Name, Default, RD)) of
"true" ->
{Result, RD, setelement(Idx, Ctx, true)};
"false" ->
{Result, RD, setelement(Idx, Ctx, false)};
"default" ->
{Result, RD, setelement(Idx, Ctx, default)};
_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("~s query parameter must be true or false~n",
[Name]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
normalize_rw_param("backend") -> backend;
normalize_rw_param("default") -> default;
normalize_rw_param("one") -> one;
normalize_rw_param("quorum") -> quorum;
normalize_rw_param("all") -> all;
normalize_rw_param(V) -> list_to_integer(V).
-spec malformed_link_headers(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Check that the Link header in the request() is valid.
%% Store the parsed links in context() if the header is valid,
or print an error in # wm_reqdata { } if it is not .
%% A link header should be of the form:
& lt;/Prefix / Bucket / Key> ; ; " , ...
malformed_link_headers(RD, Ctx) ->
case catch get_link_heads(RD, Ctx) of
Links when is_list(Links) ->
{false, RD, Ctx#ctx{links=Links}};
_Error when Ctx#ctx.api_version == 1->
{true,
wrq:append_to_resp_body(
io_lib:format("Invalid Link header. Links must be of the form~n"
"</~s/BUCKET/KEY>; riaktag=\"TAG\"~n",
[Ctx#ctx.prefix]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx};
_Error when Ctx#ctx.api_version == 2 ->
{true,
wrq:append_to_resp_body(
io_lib:format("Invalid Link header. Links must be of the form~n"
"</buckets/BUCKET/keys/KEY>; riaktag=\"TAG\"~n", []),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
-spec malformed_index_headers(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Check that the Index headers (HTTP headers prefixed with index_")
%% are valid. Store the parsed headers in context() if valid,
or print an error in # wm_reqdata { } if not .
%% An index field should be of the form "index_fieldname_type"
malformed_index_headers(RD, Ctx) ->
%% Get a list of index_headers...
IndexFields1 = extract_index_fields(RD),
Validate the fields . If validation passes , then the index
%% headers are correctly formed.
case riak_index:parse_fields(IndexFields1) of
{ok, IndexFields2} ->
{false, RD, Ctx#ctx { index_fields=IndexFields2 }};
{error, Reasons} ->
{true,
wrq:append_to_resp_body(
[riak_index:format_failure_reason(X) || X <- Reasons],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
-spec extract_index_fields(#wm_reqdata{}) -> proplists:proplist().
%% @doc Extract fields from headers prefixed by "x-riak-index-" in the
client 's PUT request , to be indexed at write time .
extract_index_fields(RD) ->
PrefixSize = length(?HEAD_INDEX_PREFIX),
{ok, RE} = re:compile(",\\s"),
F =
fun({K,V}, Acc) ->
KList = riak_kv_wm_utils:any_to_list(K),
case lists:prefix(?HEAD_INDEX_PREFIX, string:to_lower(KList)) of
true ->
%% Isolate the name of the index field.
IndexField =
list_to_binary(
element(2, lists:split(PrefixSize, KList))),
%% HACK ALERT: Split values on comma. The HTTP
%% spec allows for comma separated tokens
%% where the tokens can be quoted strings. We
%% don't currently support quoted strings.
%% (-sec14.html)
Values = re:split(V, RE, [{return, binary}]),
[{IndexField, X} || X <- Values] ++ Acc;
false ->
Acc
end
end,
lists:foldl(F, [], mochiweb_headers:to_list(wrq:req_headers(RD))).
-spec content_types_provided(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Producer::atom()}], #wm_reqdata{}, context()}.
%% @doc List the content types available for representing this resource.
%% The content-type for a key-level request is the content-type that
was used in the PUT request that stored the document in Riak .
content_types_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'PUT'; Method =:= 'POST' ->
{ContentType, _} = extract_content_type(RD),
{[{ContentType, produce_doc_body}], RD, Ctx};
content_types_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'DELETE' ->
{[{"text/html", to_html}], RD, Ctx};
content_types_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
we can assume DocCtx#ctx.doc is { ok , Doc } because of malformed_request
case select_doc(DocCtx) of
{MD, V} ->
{[{get_ctype(MD,V), produce_doc_body}], RD, DocCtx};
multiple_choices ->
{[{"text/plain", produce_sibling_message_body},
{"multipart/mixed", produce_multipart_body}], RD, DocCtx}
end.
-spec charsets_provided(#wm_reqdata{}, context()) ->
{no_charset|[{Charset::string(), Producer::function()}],
#wm_reqdata{}, context()}.
%% @doc List the charsets available for representing this resource.
%% The charset for a key-level request is the charset that was used
in the PUT request that stored the document in ( none if
no charset was specified at PUT - time ) .
charsets_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'PUT'; Method =:= 'POST' ->
case extract_content_type(RD) of
{_, undefined} ->
{no_charset, RD, Ctx};
{_, Charset} ->
{[{Charset, fun(X) -> X end}], RD, Ctx}
end;
charsets_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'DELETE' ->
{no_charset, RD, Ctx};
charsets_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_CHARSET, MD) of
{ok, CS} ->
{[{CS, fun(X) -> X end}], RD, DocCtx};
error ->
{no_charset, RD, DocCtx}
end;
multiple_choices ->
{no_charset, RD, DocCtx}
end;
{error, _} ->
{no_charset, RD, DocCtx}
end.
-spec encodings_provided(#wm_reqdata{}, context()) ->
{[{Encoding::string(), Producer::function()}], #wm_reqdata{}, context()}.
%% @doc List the encodings available for representing this resource.
%% The encoding for a key-level request is the encoding that was
used in the PUT request that stored the document in Riak , or
" identity " and " gzip " if no encoding was specified at PUT - time .
encodings_provided(RD, Ctx0) ->
DocCtx =
case Ctx0#ctx.method of
UpdM when UpdM =:= 'PUT'; UpdM =:= 'POST'; UpdM =:= 'DELETE' ->
Ctx0;
_ ->
ensure_doc(Ctx0)
end,
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_ENCODING, MD) of
{ok, Enc} ->
{[{Enc, fun(X) -> X end}], RD, DocCtx};
error ->
{riak_kv_wm_utils:default_encodings(), RD, DocCtx}
end;
multiple_choices ->
{riak_kv_wm_utils:default_encodings(), RD, DocCtx}
end;
_ ->
{riak_kv_wm_utils:default_encodings(), RD, DocCtx}
end.
-spec content_types_accepted(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Acceptor::atom()}],
#wm_reqdata{}, context()}.
%% @doc Get the list of content types this resource will accept.
%% Whatever content type is specified by the Content-Type header
of a key - level PUT request will be accepted by this resource .
%% (A key-level put *must* include a Content-Type header.)
content_types_accepted(RD, Ctx) ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
%% user must specify content type of the data
{[], RD, Ctx};
CType ->
Media = hd(string:tokens(CType, ";")),
case string:tokens(Media, "/") of
[_Type, _Subtype] ->
%% accept whatever the user says
{[{Media, accept_doc_body}], RD, Ctx};
_ ->
{[],
wrq:set_resp_header(
?HEAD_CTYPE,
"text/plain",
wrq:set_resp_body(
["\"", Media, "\""
" is not a valid media type"
" for the Content-type header.\n"],
RD)),
Ctx}
end
end.
-spec resource_exists(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Determine whether or not the requested item exists.
Documents exists if a read request to returns { ok , riak_object ( ) } ,
%% and either no vtag query parameter was specified, or the value of the
vtag param matches the vtag of some value of the object .
resource_exists(RD, Ctx0) ->
Method = Ctx0#ctx.method,
ToFetch =
case Method of
UpdM when UpdM =:= 'PUT'; UpdM =:= 'POST'; UpdM =:= 'DELETE' ->
conditional_headers_present(RD) == true;
_ ->
true
end,
case ToFetch of
true ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, Doc} ->
case DocCtx#ctx.vtag of
undefined ->
{true, RD, DocCtx};
Vtag ->
MDs = riak_object:get_metadatas(Doc),
{lists:any(
fun(M) ->
dict:fetch(?MD_VTAG, M) =:= Vtag
end,
MDs),
RD,
DocCtx#ctx{vtag=Vtag}}
end;
{error, _} ->
%% This should never actually be reached because all the
error conditions from ensure_doc are handled up in
%% malformed_request.
{false, RD, DocCtx}
end;
false ->
% Fake it - rather than fetch to see. If we're deleting we assume
it does exist , and if PUT / POST , assume it does n't
case Method of
'DELETE' ->
{true, RD, Ctx0};
_ ->
{false, RD, Ctx0}
end
end.
-spec is_conflict(request_data(), context()) ->
{boolean(), request_data(), context()}.
is_conflict(RD, Ctx) ->
case {Ctx#ctx.method, wrq:get_req_header(?HEAD_IF_NOT_MODIFIED, RD)} of
{_ , undefined} ->
{false, RD, Ctx};
{UpdM, NotModifiedClock} when UpdM =:= 'PUT'; UpdM =:= 'POST' ->
case Ctx#ctx.doc of
{ok, Obj} ->
InClock =
riak_object:decode_vclock(
base64:decode(NotModifiedClock)),
CurrentClock =
riak_object:vclock(Obj),
{not vclock:equal(InClock, CurrentClock), RD, Ctx};
_ ->
{true, RD, Ctx}
end;
_ ->
{false, RD, Ctx}
end.
-spec conditional_headers_present(request_data()) -> boolean().
conditional_headers_present(RD) ->
NoneMatch =
(wrq:get_req_header("If-None-Match", RD) =/= undefined),
Match =
(wrq:get_req_header("If-Match", RD) =/= undefined),
UnModifiedSince =
(wrq:get_req_header("If-Unmodified-Since", RD) =/= undefined),
NotModified =
(wrq:get_req_header(?HEAD_IF_NOT_MODIFIED, RD) =/= undefined),
(NoneMatch or Match or UnModifiedSince or NotModified).
-spec post_is_create(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc POST is considered a document-creation operation for bucket-level
requests ( this makes webmachine call create_path/2 , where the key
%% for the created document will be chosen).
post_is_create(RD, Ctx=#ctx{key=undefined}) ->
%% bucket-POST is create
{true, RD, Ctx};
post_is_create(RD, Ctx) ->
%% key-POST is not create
{false, RD, Ctx}.
-spec create_path(#wm_reqdata{}, context()) ->
{string(), #wm_reqdata{}, context()}.
%% @doc Choose the Key for the document created during a bucket-level POST.
%% This function also sets the Location header to generate a
201 Created response .
create_path(RD, Ctx=#ctx{prefix=P, bucket_type=T, bucket=B, api_version=V}) ->
K = riak_core_util:unique_id_62(),
{K,
wrq:set_resp_header("Location",
riak_kv_wm_utils:format_uri(T, B, K, P, V),
RD),
Ctx#ctx{key=list_to_binary(K)}}.
-spec process_post(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
%% @doc Pass-through for key-level requests to allow POST to function
as PUT for clients that do not support PUT .
process_post(RD, Ctx) -> accept_doc_body(RD, Ctx).
-spec accept_doc_body(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
@doc Store the data the client is PUTing in the document .
%% This function translates the headers and body of the HTTP request
into their final riak_object ( ) form , and executes the put .
accept_doc_body(
RD,
Ctx=#ctx{
bucket_type=T, bucket=B, key=K, client=C,
links=L,
index_fields=IF}) ->
Doc0 = riak_object:new(riak_kv_wm_utils:maybe_bucket_type(T,B), K, <<>>),
VclockDoc = riak_object:set_vclock(Doc0, decode_vclock_header(RD)),
{CType, Charset} = extract_content_type(RD),
UserMeta = extract_user_meta(RD),
CTypeMD = dict:store(?MD_CTYPE, CType, dict:new()),
CharsetMD =
if Charset /= undefined ->
dict:store(?MD_CHARSET, Charset, CTypeMD);
true ->
CTypeMD
end,
EncMD =
case wrq:get_req_header(?HEAD_ENCODING, RD) of
undefined -> CharsetMD;
E -> dict:store(?MD_ENCODING, E, CharsetMD)
end,
LinkMD = dict:store(?MD_LINKS, L, EncMD),
UserMetaMD = dict:store(?MD_USERMETA, UserMeta, LinkMD),
IndexMD = dict:store(?MD_INDEX, IF, UserMetaMD),
MDDoc = riak_object:update_metadata(VclockDoc, IndexMD),
Doc =
riak_object:update_value(
MDDoc, riak_kv_wm_utils:accept_value(CType, wrq:req_body(RD))),
Options0 =
case wrq:get_qs_value(?Q_RETURNBODY, RD) of
?Q_TRUE -> [returnbody];
_ -> []
end,
Options = make_options(Options0, Ctx),
NoneMatch = (wrq:get_req_header("If-None-Match", RD) =/= undefined),
Options2 = case riak_kv_util:consistent_object(B) and NoneMatch of
true ->
[{if_none_match, true}|Options];
false ->
Options
end,
case riak_client:put(Doc, Options2, C) of
{error, Reason} ->
handle_common_error(Reason, RD, Ctx);
ok ->
{true, RD, Ctx#ctx{doc={ok, Doc}}};
{ok, RObj} ->
DocCtx = Ctx#ctx{doc={ok, RObj}},
HasSiblings = (select_doc(DocCtx) == multiple_choices),
send_returnbody(RD, DocCtx, HasSiblings)
end.
%% Handle the no-sibling case. Just send the object.
send_returnbody(RD, DocCtx, _HasSiblings = false) ->
{Body, DocRD, DocCtx2} = produce_doc_body(RD, DocCtx),
{DocRD2, DocCtx3} = add_conditional_headers(DocRD, DocCtx2),
{true, wrq:append_to_response_body(Body, DocRD2), DocCtx3};
%% Handle the sibling case. Send either the sibling message body, or a
%% multipart body, depending on what the client accepts.
send_returnbody(RD, DocCtx, _HasSiblings = true) ->
AcceptHdr = wrq:get_req_header("Accept", RD),
PossibleTypes = ["multipart/mixed", "text/plain"],
case webmachine_util:choose_media_type(PossibleTypes, AcceptHdr) of
"multipart/mixed" ->
{Body, DocRD, DocCtx2} = produce_multipart_body(RD, DocCtx),
{DocRD2, DocCtx3} = add_conditional_headers(DocRD, DocCtx2),
{true, wrq:append_to_response_body(Body, DocRD2), DocCtx3};
_ ->
{Body, DocRD, DocCtx2} = produce_sibling_message_body(RD, DocCtx),
{DocRD2, DocCtx3} = add_conditional_headers(DocRD, DocCtx2),
{true, wrq:append_to_response_body(Body, DocRD2), DocCtx3}
end.
%% Add ETag and Last-Modified headers to responses that might not
%% necessarily include them, specifically when the client requests
returnbody on a PUT or POST .
add_conditional_headers(RD, Ctx) ->
{ETag, RD2, Ctx2} = generate_etag(RD, Ctx),
{LM, RD3, Ctx3} = last_modified(RD2, Ctx2),
RD4 =
wrq:set_resp_header(
"ETag", webmachine_util:quoted_string(ETag), RD3),
RD5 =
wrq:set_resp_header(
"Last-Modified",
httpd_util:rfc1123_date(
calendar:universal_time_to_local_time(LM)), RD4),
{RD5,Ctx3}.
-spec extract_content_type(#wm_reqdata{}) ->
{ContentType::string(), Charset::string()|undefined}.
@doc Interpret the Content - Type header in the client 's PUT request .
%% This function extracts the content type and charset for use
%% in subsequent GET requests.
extract_content_type(RD) ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
undefined;
RawCType ->
[CType|RawParams] = string:tokens(RawCType, "; "),
Params = [ list_to_tuple(string:tokens(P, "=")) || P <- RawParams],
{CType, proplists:get_value("charset", Params)}
end.
-spec extract_user_meta(#wm_reqdata{}) -> proplists:proplist().
@doc Extract headers prefixed by X - Riak - Meta- in the client 's PUT request
%% to be returned by subsequent GET requests.
extract_user_meta(RD) ->
lists:filter(fun({K,_V}) ->
lists:prefix(
?HEAD_USERMETA_PREFIX,
string:to_lower(riak_kv_wm_utils:any_to_list(K)))
end,
mochiweb_headers:to_list(wrq:req_headers(RD))).
-spec multiple_choices(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
%% @doc Determine whether a document has siblings. If the user has
%% specified a specific vtag, the document is considered not to
%% have sibling versions. This is a safe assumption, because
%% resource_exists will have filtered out requests earlier for
vtags that are invalid for this version of the document .
multiple_choices(RD, Ctx=#ctx{vtag=undefined, doc={ok, Doc}}) ->
%% user didn't specify a vtag, so there better not be siblings
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:value_count(Doc) of
1 -> {false, RD, Ctx};
_ -> {true, RD, Ctx}
end;
_ ->
%% just updated can't have multiple
{false, RD, Ctx}
end;
multiple_choices(RD, Ctx) ->
specific vtag was specified
if it 's a tombstone add the X - Riak - Deleted header
case select_doc(Ctx) of
{M, _} ->
case dict:find(?MD_DELETED, M) of
{ok, "true"} ->
{false,
wrq:set_resp_header(?HEAD_DELETED, "true", RD),
Ctx};
error ->
{false, RD, Ctx}
end;
multiple_choices ->
throw(
{unexpected_code_path,
?MODULE,
multiple_choices,
multiple_choices})
end.
-spec produce_doc_body(#wm_reqdata{}, context()) ->
{binary(), #wm_reqdata{}, context()}.
%% @doc Extract the value of the document, and place it in the
%% response body of the request. This function also adds the
Link , X - Riak - Meta- headers , and X - Riak - Index- headers to the
response . One link will point to the bucket , with the
%% property "rel=container". The rest of the links will be
%% constructed from the links of the document.
produce_doc_body(RD, Ctx) ->
Prefix = Ctx#ctx.prefix,
Bucket = Ctx#ctx.bucket,
APIVersion = Ctx#ctx.api_version,
case select_doc(Ctx) of
{MD, Doc} ->
%% Add links to response...
Links1 = case dict:find(?MD_LINKS, MD) of
{ok, L} -> L;
error -> []
end,
Links2 =
riak_kv_wm_utils:format_links(
[{Bucket, "up"}|Links1], Prefix, APIVersion),
LinkRD = wrq:merge_resp_headers(Links2, RD),
%% Add user metadata to response...
UserMetaRD = case dict:find(?MD_USERMETA, MD) of
{ok, UserMeta} ->
lists:foldl(
fun({K,V},Acc) ->
wrq:merge_resp_headers([{K,V}],Acc)
end,
LinkRD, UserMeta);
error -> LinkRD
end,
%% Add index metadata to response...
IndexRD =
case dict:find(?MD_INDEX, MD) of
{ok, IndexMeta} ->
lists:foldl(
fun({K,V}, Acc) ->
K1 = riak_kv_wm_utils:any_to_list(K),
V1 = riak_kv_wm_utils:any_to_list(V),
wrq:merge_resp_headers(
[{?HEAD_INDEX_PREFIX ++ K1, V1}], Acc)
end,
UserMetaRD, IndexMeta);
error ->
UserMetaRD
end,
{riak_kv_wm_utils:encode_value(Doc),
encode_vclock_header(IndexRD, Ctx), Ctx};
multiple_choices ->
throw(
{unexpected_code_path,
?MODULE,
produce_doc_body,
multiple_choices})
end.
-spec produce_sibling_message_body(#wm_reqdata{}, context()) ->
{iolist(), #wm_reqdata{}, context()}.
%% @doc Produce the text message informing the user that there are multiple
%% values for this document, and giving that user the vtags of those
values so they can get to them with the vtag query param .
produce_sibling_message_body(RD, Ctx=#ctx{doc={ok, Doc}}) ->
Vtags = [ dict:fetch(?MD_VTAG, M)
|| M <- riak_object:get_metadatas(Doc) ],
{[<<"Siblings:\n">>, [ [V,<<"\n">>] || V <- Vtags]],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain",
encode_vclock_header(RD, Ctx)),
Ctx}.
-spec produce_multipart_body(#wm_reqdata{}, context()) ->
{iolist(), #wm_reqdata{}, context()}.
%% @doc Produce a multipart body representation of an object with multiple
values ( siblings ) , each sibling being one part of the larger
%% document.
produce_multipart_body(RD, Ctx=#ctx{doc={ok, Doc}, bucket=B, prefix=P}) ->
APIVersion = Ctx#ctx.api_version,
Boundary = riak_core_util:unique_id_62(),
{[[["\r\n--",Boundary,"\r\n",
riak_kv_wm_utils:multipart_encode_body(P, B, Content, APIVersion)]
|| Content <- riak_object:get_contents(Doc)],
"\r\n--",Boundary,"--\r\n"],
wrq:set_resp_header(?HEAD_CTYPE,
"multipart/mixed; boundary="++Boundary,
encode_vclock_header(RD, Ctx)),
Ctx}.
-spec select_doc(context()) ->
{Metadata :: term(), Value :: term()}|multiple_choices.
%% @doc Selects the "proper" document:
%% - chooses update-value/metadata if update-value is set
- chooses only / if only one exists
- chooses val / given Vtag if multiple contents exist
%% (assumes a vtag has been specified)
select_doc(#ctx{doc={ok, Doc}, vtag=Vtag}) ->
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:get_contents(Doc) of
[Single] -> Single;
Mult ->
case lists:dropwhile(
fun({M,_}) ->
dict:fetch(?MD_VTAG, M) /= Vtag
end,
Mult) of
[Match|_] -> Match;
[] -> multiple_choices
end
end;
UpdateValue ->
{riak_object:get_update_metadata(Doc), UpdateValue}
end.
-spec encode_vclock_header(#wm_reqdata{}, context()) -> #wm_reqdata{}.
@doc Add the X - Riak - Vclock header to the response .
encode_vclock_header(RD, #ctx{doc={ok, Doc}}) ->
{Head, Val} = riak_object:vclock_header(Doc),
wrq:set_resp_header(Head, Val, RD);
encode_vclock_header(RD, #ctx{doc={error, {deleted, VClock}}}) ->
BinVClock = riak_object:encode_vclock(VClock),
wrq:set_resp_header(
?HEAD_VCLOCK, binary_to_list(base64:encode(BinVClock)), RD).
-spec decode_vclock_header(#wm_reqdata{}) -> vclock:vclock().
@doc Translate the X - Riak - Vclock header value from the request into
its Erlang representation . If no vclock header exists , a fresh
%% vclock is returned.
decode_vclock_header(RD) ->
case wrq:get_req_header(?HEAD_VCLOCK, RD) of
undefined -> vclock:fresh();
Head -> riak_object:decode_vclock(base64:decode(Head))
end.
-spec ensure_doc(context()) -> context().
%% @doc Ensure that the 'doc' field of the context() has been filled
%% with the result of a riak_client:get request. This is a
%% convenience for memoizing the result of a get so it can be
%% used in multiple places in this resource, without having to
%% worry about the order of executing of those places.
ensure_doc(Ctx=#ctx{doc=undefined, key=undefined}) ->
Ctx#ctx{doc={error, notfound}};
ensure_doc(Ctx=#ctx{doc=undefined, bucket_type=T, bucket=B, key=K, client=C,
basic_quorum=Quorum, notfound_ok=NotFoundOK}) ->
case riak_kv_wm_utils:bucket_type_exists(T) of
true ->
Options0 =
[deletedvclock,
{basic_quorum, Quorum},
{notfound_ok, NotFoundOK}],
Options = make_options(Options0, Ctx),
BT = riak_kv_wm_utils:maybe_bucket_type(T,B),
Ctx#ctx{doc=riak_client:get(BT, K, Options, C)};
false ->
Ctx#ctx{doc={error, bucket_type_unknown}}
end;
ensure_doc(Ctx) -> Ctx.
-spec delete_resource(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
%% @doc Delete the document specified.
delete_resource(RD, Ctx=#ctx{bucket_type=T, bucket=B, key=K, client=C}) ->
Options = make_options([], Ctx),
BT = riak_kv_wm_utils:maybe_bucket_type(T,B),
Result =
case wrq:get_req_header(?HEAD_VCLOCK, RD) of
undefined ->
riak_client:delete(BT, K, Options, C);
_ ->
VC = decode_vclock_header(RD),
riak_client:delete_vclock(BT, K, VC, Options, C)
end,
case Result of
ok ->
{true, RD, Ctx};
{error, Reason} ->
handle_common_error(Reason, RD, Ctx)
end.
-ifndef(old_hash).
md5(Bin) ->
crypto:hash(md5, Bin).
-else.
md5(Bin) ->
crypto:md5(Bin).
-endif.
-spec generate_etag(#wm_reqdata{}, context()) ->
{undefined|string(), #wm_reqdata{}, context()}.
%% @doc Get the etag for this resource.
%% Documents will have an etag equal to their vtag. For documents with
%% siblings when no vtag is specified, this will be an etag derived from
%% the vector clock.
generate_etag(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{dict:fetch(?MD_VTAG, MD), RD, Ctx};
multiple_choices ->
{ok, Doc} = Ctx#ctx.doc,
<<ETag:128/integer>> =
md5(term_to_binary(riak_object:vclock(Doc))),
{riak_core_util:integer_to_list(ETag, 62), RD, Ctx}
end.
-spec last_modified(#wm_reqdata{}, context()) ->
{undefined|calendar:datetime(), #wm_reqdata{}, context()}.
%% @doc Get the last-modified time for this resource.
%% Documents will have the last-modified time specified by the
%% riak_object.
%% For documents with siblings, this is the last-modified time of the
%% latest sibling.
last_modified(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{normalize_last_modified(MD),RD, Ctx};
multiple_choices ->
{ok, Doc} = Ctx#ctx.doc,
LMDates = [ normalize_last_modified(MD) ||
MD <- riak_object:get_metadatas(Doc) ],
{lists:max(LMDates), RD, Ctx}
end.
-spec normalize_last_modified(riak_kv_wm_object_dict()) -> calendar:datetime().
%% @doc Extract and convert the Last-Modified metadata into a normalized form
for use in the last_modified/2 callback .
normalize_last_modified(MD) ->
case dict:fetch(?MD_LASTMOD, MD) of
Now={_,_,_} ->
calendar:now_to_universal_time(Now);
Rfc1123 when is_list(Rfc1123) ->
httpd_util:convert_request_date(Rfc1123)
end.
-spec get_link_heads(#wm_reqdata{}, context()) -> [link()].
%% @doc Extract the list of links from the Link request header.
%% This function will die if an invalid link header format
%% is found.
get_link_heads(RD, Ctx) ->
APIVersion = Ctx#ctx.api_version,
Prefix = Ctx#ctx.prefix,
Bucket = Ctx#ctx.bucket,
%% Get a list of link headers...
LinkHeaders1 =
case wrq:get_req_header(?HEAD_LINK, RD) of
undefined -> [];
Heads -> string:tokens(Heads, ",")
end,
%% Decode the link headers. Throw an exception if we can't
%% properly parse any of the headers...
{BucketLinks, KeyLinks} =
case APIVersion of
1 ->
{ok, BucketRegex} =
re:compile("</" ++ Prefix ++ ?V1_BUCKET_REGEX),
{ok, KeyRegex} =
re:compile("</" ++ Prefix ++ ?V1_KEY_REGEX),
extract_links(LinkHeaders1, BucketRegex, KeyRegex);
@todo Handle links in API Version 3 ?
Two when Two >= 2 ->
{ok, BucketRegex} =
re:compile(?V2_BUCKET_REGEX),
{ok, KeyRegex} =
re:compile(?V2_KEY_REGEX),
extract_links(LinkHeaders1, BucketRegex, KeyRegex)
end,
Validate that the only bucket header is pointing to the parent
%% bucket...
IsValid = (BucketLinks == []) orelse (BucketLinks == [{Bucket, <<"up">>}]),
case IsValid of
true ->
KeyLinks;
false ->
throw({invalid_link_headers, LinkHeaders1})
end.
Run each LinkHeader string ( ) through the BucketRegex and
KeyRegex . Return { BucketLinks , KeyLinks } .
extract_links(LinkHeaders, BucketRegex, KeyRegex) ->
%% Run each regex against each string...
extract_links_1(LinkHeaders, BucketRegex, KeyRegex, [], []).
extract_links_1([LinkHeader|Rest], BucketRegex, KeyRegex, BucketAcc, KeyAcc) ->
case re:run(LinkHeader, BucketRegex, [{capture, all_but_first, list}]) of
{match, [Bucket, Tag]} ->
Bucket1 = list_to_binary(mochiweb_util:unquote(Bucket)),
Tag1 = list_to_binary(mochiweb_util:unquote(Tag)),
NewBucketAcc = [{Bucket1, Tag1}|BucketAcc],
extract_links_1(Rest, BucketRegex, KeyRegex, NewBucketAcc, KeyAcc);
nomatch ->
case re:run(LinkHeader, KeyRegex, [{capture, all_but_first, list}]) of
{match, [Bucket, Key, Tag]} ->
Bucket1 = list_to_binary(mochiweb_util:unquote(Bucket)),
Key1 = list_to_binary(mochiweb_util:unquote(Key)),
Tag1 = list_to_binary(mochiweb_util:unquote(Tag)),
NewKeyAcc = [{{Bucket1, Key1}, Tag1}|KeyAcc],
extract_links_1(Rest, BucketRegex, KeyRegex, BucketAcc, NewKeyAcc);
nomatch ->
throw({invalid_link_header, LinkHeader})
end
end;
extract_links_1([], _BucketRegex, _KeyRegex, BucketAcc, KeyAcc) ->
{BucketAcc, KeyAcc}.
-spec get_ctype(riak_kv_wm_object_dict(), term()) -> string().
%% @doc Work out the content type for this object - use the metadata if provided
get_ctype(MD,V) ->
case dict:find(?MD_CTYPE, MD) of
{ok, Ctype} ->
Ctype;
error when is_binary(V) ->
"application/octet-stream";
error ->
"application/x-erlang-binary"
end.
missing_content_type(RD) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
wrq:append_to_response_body(<<"Missing Content-Type request header">>, RD1).
send_precommit_error(RD, Reason) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
Error = if
Reason =:= undefined ->
list_to_binary([atom_to_binary(wrq:method(RD1), utf8),
<<" aborted by pre-commit hook.">>]);
true ->
Reason
end,
wrq:append_to_response_body(Error, RD1).
handle_common_error(Reason, RD, Ctx) ->
case {error, Reason} of
{error, precommit_fail} ->
{{halt, 403}, send_precommit_error(RD, undefined), Ctx};
{error, {precommit_fail, Message}} ->
{{halt, 403}, send_precommit_error(RD, Message), Ctx};
{error, too_many_fails} ->
{{halt, 503}, wrq:append_to_response_body("Too Many write failures"
" to satisfy W/DW\n", RD), Ctx};
{error, timeout} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("request timed out~n",[]),
RD)),
Ctx};
{error, notfound} ->
{{halt, 404},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("not found~n",[]),
RD)),
Ctx};
{error, bucket_type_unknown} ->
{{halt, 404},
wrq:set_resp_body(
io_lib:format("Unknown bucket type: ~s", [Ctx#ctx.bucket_type]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx};
{error, {deleted, _VClock}} ->
{{halt, 404},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:set_resp_header(?HEAD_DELETED, "true",
wrq:append_to_response_body(
io_lib:format("not found~n",[]),
encode_vclock_header(RD, Ctx)))),
Ctx};
{error, {n_val_violation, N}} ->
Msg = io_lib:format("Specified w/dw/pw/node_confirms values invalid for bucket"
" n value of ~p~n", [N]),
{{halt, 400}, wrq:append_to_response_body(Msg, RD), Ctx};
{error, {r_val_unsatisfied, Requested, Returned}} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("R-value unsatisfied: ~p/~p~n",
[Returned, Requested]),
RD)),
Ctx};
{error, {dw_val_unsatisfied, DW, NumDW}} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("DW-value unsatisfied: ~p/~p~n",
[NumDW, DW]),
RD)),
Ctx};
{error, {pr_val_unsatisfied, Requested, Returned}} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("PR-value unsatisfied: ~p/~p~n",
[Returned, Requested]),
RD)),
Ctx};
{error, {pw_val_unsatisfied, Requested, Returned}} ->
Msg = io_lib:format("PW-value unsatisfied: ~p/~p~n", [Returned,
Requested]),
{{halt, 503}, wrq:append_to_response_body(Msg, RD), Ctx};
{error, {node_confirms_val_unsatisfied, Requested, Returned}} ->
Msg = io_lib:format("node_confirms-value unsatisfied: ~p/~p~n", [Returned,
Requested]),
{{halt, 503}, wrq:append_to_response_body(Msg, RD), Ctx};
{error, failed} ->
{{halt, 412}, RD, Ctx};
{error, Err} ->
{{halt, 500},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("Error:~n~p~n",[Err]),
RD)),
Ctx}
end.
make_options(Prev, Ctx) ->
NewOpts0 = [{rw, Ctx#ctx.rw}, {r, Ctx#ctx.r}, {w, Ctx#ctx.w},
{pr, Ctx#ctx.pr}, {pw, Ctx#ctx.pw}, {dw, Ctx#ctx.dw},
{node_confirms, Ctx#ctx.node_confirms},
{sync_on_write, Ctx#ctx.sync_on_write},
{timeout, Ctx#ctx.timeout},
{asis, Ctx#ctx.asis}],
NewOpts = [ {Opt, Val} || {Opt, Val} <- NewOpts0,
Val /= undefined, Val /= default ],
Prev ++ NewOpts.
| null |
https://raw.githubusercontent.com/basho/riak_kv/e04bc998e2f48e083a875e290ca242f2d699830d/src/riak_kv_wm_object.erl
|
erlang
|
-------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
URLs that begin with `/types' are necessary for the new bucket
are for the default bucket type, and `/riak' is an old URL style,
also only works for the default bucket type.
It is possible to reconfigure the `/riak' prefix but that seems to
be rarely if ever used.
```
POST /types/Type/buckets/Bucket/keys
POST /buckets/Bucket/keys
POST /riak/Bucket'''
Allow the server to choose a key for the data.
```
GET /types/Type/buckets/Bucket/keys/Key
GET /buckets/Bucket/keys/Key
GET /riak/Bucket/Key'''
Content-type of the response will be taken from the
Content-type was used in the request that stored the data.
Additional headers will include:
<ul>
<li>`X-Riak-Vclock': The vclock of the object</li>
<li>`Link': The links the object has</li>
<li>`Last-Modified': The last-modified time of the object</li>
<li>`Encoding': The value of the incoming Encoding header from
the request that stored the data.</li>
</ul>
If the object is found to have siblings (only possible if the
headers will be omitted; and the body of the response will
be a list of the vtags of each sibling. To request a specific
of the sibling you want.
```
PUT /types/Type/buckets/Bucket/keys/Key
PUT /buckets/Bucket/keys/Key
A Content-type header *must* be included in the request. The
value of this header will be used in the response to subsequent
GET requests.
The body of the request will be stored literally as the value
of the riak_object, and will be served literally as the body of
the response to subsequent GET requests.
Include an X-Riak-Vclock header to modify data without creating
siblings.
Include a Link header to set the links of the object.
Include an Encoding header if you would like an Encoding header
to be included in the response to subsequent GET requests.
They will be returned verbatim on subsequent GET requests.
to determine whether or not the resource exists). A default
```
POST /types/Type/buckets/Bucket/keys/Key
POST /buckets/Bucket/keys/Key
POST /riak/Bucket/Key'''
Equivalent to `PUT /riak/Bucket/Key' (useful for clients that
```
DELETE /types/Type/buckets/Bucket/keys/Key (with bucket-type)
DELETE /buckets/Bucket/keys/Key (NEW)
DELETE /riak/Bucket/Key (OLD)'''
webmachine resource exports
integer() - Determine which version of the API to use.
binary() - Bucket type (from uri)
binary() - Bucket name (from uri)
binary() - Key (from uri)
riak_client() - the store client
integer() - r-value for reads
integer() - w-value for writes
integer() - dw-value for writes
integer() - rw-value for deletes
integer() - number of primary nodes required in preflist on read
integer() - number of primary nodes required in preflist on write
integer() - number of physically diverse nodes required in preflist on write
boolean() - whether to use basic_quorum
boolean() - whether to send the put without modifying the vclock
string() - sync on write behaviour to pass to backend
string() - prefix for resource uris
local | {node(), atom()} - params for riak client
{ok, riak_object()}|{error, term()} - the object found
string() - vtag the user asked for
proplist() - properties of the bucket
[link()] - links of the object
[index_field()]
atom() - HTTP method for the request
integer() - passed-in timeout value in ms
security context
@doc Initialize this resource. This function extracts the
'prefix' and 'riak' properties from the dispatch args.
can be established. This function also takes this
opportunity to extract the 'bucket' and 'key' path
bindings from the dispatch, as well as any vtag
query parameter.
XXX 301 may be more appropriate here, but since the http and
https port are different and configurable, it is hard to figure
out the redirect URL to serve.
we do this early as it used to be done in the
malformed check, so the rest of the resource
assumes that the key is present.
@doc Detects whether fetching the requested object results in an
error.
@doc Detects whether the requested object's bucket-type exists.
@doc Get the list of methods this resource supports.
bucket entries.
@doc Determine whether query parameters, request headers,
and request body are badly-formed.
Body format is checked to be valid JSON, including
a "props" object for a bucket-PUT. Body format
is not tested for a key-level request (since the
body may be any content the client desires).
Query parameters r, w, dw, and rw are checked to
be valid integers. Their values are stored in
the context() at this time.
Link headers are checked for the form:
The parsed links are stored in the context()
at this time.
and context, returning as soon as a single fun discovers a
malformed request or halts.
@doc Detects whether the Content-Type header is missing on
@doc Check that the timeout parameter is are a
string-encoded integer. Store the integer value
in context() if so.
@doc Check that r, w, dw, and rw query parameters are
string-encoded integers. Store the integer values
in context() if so.
@doc Check that a specific r, w, dw, or rw query param is a
string-encoded integer. Store its result in context() if it
Store its result in context() if it is, or print an error message
@doc Check that a specific query param is a
string-encoded boolean. Store its result in context() if it
@doc Check that the Link header in the request() is valid.
Store the parsed links in context() if the header is valid,
A link header should be of the form:
@doc Check that the Index headers (HTTP headers prefixed with index_")
are valid. Store the parsed headers in context() if valid,
An index field should be of the form "index_fieldname_type"
Get a list of index_headers...
headers are correctly formed.
@doc Extract fields from headers prefixed by "x-riak-index-" in the
Isolate the name of the index field.
HACK ALERT: Split values on comma. The HTTP
spec allows for comma separated tokens
where the tokens can be quoted strings. We
don't currently support quoted strings.
(-sec14.html)
@doc List the content types available for representing this resource.
The content-type for a key-level request is the content-type that
@doc List the charsets available for representing this resource.
The charset for a key-level request is the charset that was used
@doc List the encodings available for representing this resource.
The encoding for a key-level request is the encoding that was
@doc Get the list of content types this resource will accept.
Whatever content type is specified by the Content-Type header
(A key-level put *must* include a Content-Type header.)
user must specify content type of the data
accept whatever the user says
@doc Determine whether or not the requested item exists.
and either no vtag query parameter was specified, or the value of the
This should never actually be reached because all the
malformed_request.
Fake it - rather than fetch to see. If we're deleting we assume
@doc POST is considered a document-creation operation for bucket-level
for the created document will be chosen).
bucket-POST is create
key-POST is not create
@doc Choose the Key for the document created during a bucket-level POST.
This function also sets the Location header to generate a
@doc Pass-through for key-level requests to allow POST to function
This function translates the headers and body of the HTTP request
Handle the no-sibling case. Just send the object.
Handle the sibling case. Send either the sibling message body, or a
multipart body, depending on what the client accepts.
Add ETag and Last-Modified headers to responses that might not
necessarily include them, specifically when the client requests
This function extracts the content type and charset for use
in subsequent GET requests.
to be returned by subsequent GET requests.
@doc Determine whether a document has siblings. If the user has
specified a specific vtag, the document is considered not to
have sibling versions. This is a safe assumption, because
resource_exists will have filtered out requests earlier for
user didn't specify a vtag, so there better not be siblings
just updated can't have multiple
@doc Extract the value of the document, and place it in the
response body of the request. This function also adds the
property "rel=container". The rest of the links will be
constructed from the links of the document.
Add links to response...
Add user metadata to response...
Add index metadata to response...
@doc Produce the text message informing the user that there are multiple
values for this document, and giving that user the vtags of those
@doc Produce a multipart body representation of an object with multiple
document.
@doc Selects the "proper" document:
- chooses update-value/metadata if update-value is set
(assumes a vtag has been specified)
vclock is returned.
@doc Ensure that the 'doc' field of the context() has been filled
with the result of a riak_client:get request. This is a
convenience for memoizing the result of a get so it can be
used in multiple places in this resource, without having to
worry about the order of executing of those places.
@doc Delete the document specified.
@doc Get the etag for this resource.
Documents will have an etag equal to their vtag. For documents with
siblings when no vtag is specified, this will be an etag derived from
the vector clock.
@doc Get the last-modified time for this resource.
Documents will have the last-modified time specified by the
riak_object.
For documents with siblings, this is the last-modified time of the
latest sibling.
@doc Extract and convert the Last-Modified metadata into a normalized form
@doc Extract the list of links from the Link request header.
This function will die if an invalid link header format
is found.
Get a list of link headers...
Decode the link headers. Throw an exception if we can't
properly parse any of the headers...
bucket...
Run each regex against each string...
@doc Work out the content type for this object - use the metadata if provided
|
riak_kv_wm_object : Webmachine resource for KV object level operations .
Copyright ( c ) 2007 - 2013 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@doc Resource for serving objects over HTTP .
types implementation in Riak 2.0 , those that begin with ` /buckets '
Get the data stored in the named Bucket under the named Key .
< li>`Etag ' : The " vtag " metadata of the object</li >
< li>`X - Riak - Meta- ' : Any headers prefixed by X - Riak - Meta- supplied
on PUT are returned verbatim</li >
Specifying the query param ` r = R ' , where ` R ' is an integer will
cause to use ` R ' as the r - value for the read request . A
default r - value of 2 will be used if none is specified .
bucket property ` allow_mult ' is true ) , then
Content - type will be ` text / plain ' ; ` Link ' , ` Etag ' , and ` Last - Modified '
sibling , include the query param ` vtag = V ' , where ` V ' is the vtag
PUT /riak / Bucket / Key '' '
Store new data in the named Bucket under the named Key .
Include custom metadata using headers prefixed with X - Riak - Meta- .
Specifying the query param ` w = W ' , where W is an integer will
cause to use W as the w - value for the write request . A
default w - value of 2 will be used if none is specified .
Specifying the query param ` dw = DW ' , where DW is an integer will
cause to use DW as the dw - value for the write request . A
default dw - value of 2 will be used if none is specified .
Specifying the query param ` r = R ' , where R is an integer will
cause to use R as the r - value for the read request ( used
r - value of 2 will be used if none is specified .
do not support the PUT method ) .
Delete the data stored in the named Bucket under the named Key .
-module(riak_kv_wm_object).
-export([
init/1,
service_available/2,
is_authorized/2,
forbidden/2,
allowed_methods/2,
allow_missing_post/2,
malformed_request/2,
resource_exists/2,
is_conflict/2,
last_modified/2,
generate_etag/2,
content_types_provided/2,
charsets_provided/2,
encodings_provided/2,
content_types_accepted/2,
post_is_create/2,
create_path/2,
process_post/2,
produce_doc_body/2,
accept_doc_body/2,
produce_sibling_message_body/2,
produce_multipart_body/2,
multiple_choices/2,
delete_resource/2
]).
boolean ( ) - whether to treat notfounds as successes
}).
-ifdef(namespaced_types).
-type riak_kv_wm_object_dict() :: dict:dict().
-else.
-type riak_kv_wm_object_dict() :: dict().
-endif.
-include_lib("webmachine/include/webmachine.hrl").
-include("riak_kv_wm_raw.hrl").
-type context() :: #ctx{}.
-type request_data() :: #wm_reqdata{}.
-type validation_function() ::
fun((request_data(), context()) ->
{boolean()|{halt, pos_integer()}, request_data(), context()}).
-type link() :: {{Bucket::binary(), Key::binary()}, Tag::binary()}.
-define(DEFAULT_TIMEOUT, 60000).
-define(V1_BUCKET_REGEX, "/([^/]+)>; ?rel=\"([^\"]+)\"").
-define(V1_KEY_REGEX, "/([^/]+)/([^/]+)>; ?riaktag=\"([^\"]+)\"").
-define(V2_BUCKET_REGEX, "</buckets/([^/]+)>; ?rel=\"([^\"]+)\"").
-define(V2_KEY_REGEX,
"</buckets/([^/]+)/keys/([^/]+)>; ?riaktag=\"([^\"]+)\"").
-spec init(proplists:proplist()) -> {ok, context()}.
init(Props) ->
{ok, #ctx{api_version=proplists:get_value(api_version, Props),
prefix=proplists:get_value(prefix, Props),
riak=proplists:get_value(riak, Props),
bucket_type=proplists:get_value(bucket_type, Props)}}.
-spec service_available(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Determine whether or not a connection to Riak
service_available(RD, Ctx0=#ctx{riak=RiakProps}) ->
Ctx = riak_kv_wm_utils:ensure_bucket_type(RD, Ctx0, #ctx.bucket_type),
ClientID = riak_kv_wm_utils:get_client_id(RD),
case riak_kv_wm_utils:get_riak_client(RiakProps, ClientID) of
{ok, C} ->
Bucket =
case wrq:path_info(bucket, RD) of
undefined ->
undefined;
B ->
list_to_binary(
riak_kv_wm_utils:maybe_decode_uri(RD, B))
end,
Key =
case wrq:path_info(key, RD) of
undefined ->
undefined;
K ->
list_to_binary(
riak_kv_wm_utils:maybe_decode_uri(RD, K))
end,
{true,
RD,
Ctx#ctx{
method=wrq:method(RD),
client=C,
bucket=Bucket,
key=Key,
vtag=wrq:get_qs_value(?Q_VTAG, RD)}};
Error ->
{false,
wrq:set_resp_body(
io_lib:format("Unable to connect to Riak: ~p~n", [Error]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
is_authorized(ReqData, Ctx) ->
case riak_api_web_security:is_authorized(ReqData) of
false ->
{"Basic realm=\"Riak\"", ReqData, Ctx};
{true, SecContext} ->
{true, ReqData, Ctx#ctx{security=SecContext}};
insecure ->
{{halt, 426}, wrq:append_to_resp_body(<<"Security is enabled and "
"Riak does not accept credentials over HTTP. Try HTTPS "
"instead.">>, ReqData), Ctx}
end.
-spec forbidden(#wm_reqdata{}, context()) -> term().
forbidden(RD, Ctx) ->
case riak_kv_wm_utils:is_forbidden(RD) of
true ->
{true, RD, Ctx};
false ->
validate(RD, Ctx)
end.
-spec validate(#wm_reqdata{}, context()) -> term().
validate(RD, Ctx=#ctx{security=undefined}) ->
validate_resource(
RD, Ctx, riak_kv_wm_utils:method_to_perm(Ctx#ctx.method));
validate(RD, Ctx=#ctx{security=Security}) ->
Perm = riak_kv_wm_utils:method_to_perm(Ctx#ctx.method),
Res = riak_core_security:check_permission({Perm,
{Ctx#ctx.bucket_type,
Ctx#ctx.bucket}},
Security),
maybe_validate_resource(Res, RD, Ctx, Perm).
-spec maybe_validate_resource(
term(), #wm_reqdata{}, context(), string()) -> term().
maybe_validate_resource({false, Error, _}, RD, Ctx, _Perm) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
{true, wrq:append_to_resp_body(
unicode:characters_to_binary(Error, utf8, utf8),
RD1), Ctx};
maybe_validate_resource({true, _}, RD, Ctx, Perm) ->
validate_resource(RD, Ctx, Perm).
-spec validate_resource(#wm_reqdata{}, context(), string()) -> term().
validate_resource(RD, Ctx, Perm) when Perm == "riak_kv.get" ->
Ensure the key is here , otherwise 404
validate_doc(RD, Ctx);
validate_resource(RD, Ctx, _Perm) ->
Ensure the bucket type exists , otherwise 404 early .
validate_bucket_type(RD, Ctx).
validate_doc(RD, Ctx) ->
DocCtx = ensure_doc(Ctx),
case DocCtx#ctx.doc of
{error, Reason} ->
handle_common_error(Reason, RD, DocCtx);
_ ->
{false, RD, DocCtx}
end.
validate_bucket_type(RD, Ctx) ->
case riak_kv_wm_utils:bucket_type_exists(Ctx#ctx.bucket_type) of
true ->
{false, RD, Ctx};
false ->
handle_common_error(bucket_type_unknown, RD, Ctx)
end.
-spec allowed_methods(#wm_reqdata{}, context()) ->
{[atom()], #wm_reqdata{}, context()}.
allowed_methods(RD, Ctx) ->
{['HEAD', 'GET', 'POST', 'PUT', 'DELETE'], RD, Ctx}.
-spec allow_missing_post(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
@doc Makes POST and PUT equivalent for creating new
allow_missing_post(RD, Ctx) ->
{true, RD, Ctx}.
-spec malformed_request(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
& lt;/Prefix / Bucket / Key> ; ; " , ...
malformed_request(RD, Ctx) when Ctx#ctx.method =:= 'POST'
orelse Ctx#ctx.method =:= 'PUT' ->
malformed_request([fun malformed_content_type/2,
fun malformed_timeout_param/2,
fun malformed_rw_params/2,
fun malformed_link_headers/2,
fun malformed_index_headers/2],
RD, Ctx);
malformed_request(RD, Ctx) ->
malformed_request([fun malformed_timeout_param/2,
fun malformed_rw_params/2], RD, Ctx).
@doc Given a list of 2 - arity funs , threads through the request data
-spec malformed_request(
list(validation_function()), request_data(), context()) ->
{boolean() | {halt, pos_integer()}, request_data(), context()}.
malformed_request([], RD, Ctx) ->
{false, RD, Ctx};
malformed_request([H|T], RD, Ctx) ->
case H(RD, Ctx) of
{true, _, _} = Result -> Result;
{{halt,_}, _, _} = Halt -> Halt;
{false, RD1, Ctx1} ->
malformed_request(T, RD1, Ctx1)
end.
PUT / POST .
malformed_content_type(RD, Ctx) ->
case wrq:get_req_header("Content-Type", RD) of
undefined ->
{true, missing_content_type(RD), Ctx};
_ -> {false, RD, Ctx}
end.
-spec malformed_timeout_param(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
malformed_timeout_param(RD, Ctx) ->
case wrq:get_qs_value("timeout", RD) of
undefined ->
{false, RD, Ctx};
TimeoutStr ->
try
Timeout = list_to_integer(TimeoutStr),
{false, RD, Ctx#ctx{timeout=Timeout}}
catch
_:_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("Bad timeout "
"value ~p~n",
[TimeoutStr]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end
end.
-spec malformed_rw_params(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
malformed_rw_params(RD, Ctx) ->
Res =
lists:foldl(fun malformed_rw_param/2,
{false, RD, Ctx},
[{#ctx.r, "r", "default"},
{#ctx.w, "w", "default"},
{#ctx.dw, "dw", "default"},
{#ctx.rw, "rw", "default"},
{#ctx.pw, "pw", "default"},
{#ctx.node_confirms, "node_confirms", "default"},
{#ctx.pr, "pr", "default"}]),
Res2 =
lists:foldl(fun malformed_custom_param/2,
Res,
[{#ctx.sync_on_write,
"sync_on_write",
"default",
[default, backend, one, all]}]),
lists:foldl(fun malformed_boolean_param/2,
Res2,
[{#ctx.basic_quorum, "basic_quorum", "default"},
{#ctx.notfound_ok, "notfound_ok", "default"},
{#ctx.asis, "asis", "false"}]).
-spec malformed_rw_param({Idx::integer(), Name::string(), Default::string()},
{boolean(), #wm_reqdata{}, context()}) ->
{boolean(), #wm_reqdata{}, context()}.
is , or print an error message in # wm_reqdata { } if it is not .
malformed_rw_param({Idx, Name, Default}, {Result, RD, Ctx}) ->
case catch normalize_rw_param(wrq:get_qs_value(Name, Default, RD)) of
P when (is_atom(P) orelse is_integer(P)) ->
{Result, RD, setelement(Idx, Ctx, P)};
_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("~s query parameter must be an integer or "
"one of the following words: 'one', 'quorum' or 'all'~n",
[Name]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
-spec malformed_custom_param({Idx::integer(),
Name::string(),
Default::string(),
AllowedValues::[atom()]},
{boolean(), #wm_reqdata{}, context()}) ->
{boolean(), #wm_reqdata{}, context()}.
@doc Check that a custom parameter is one of the AllowedValues
in # wm_reqdata { } if it is not .
malformed_custom_param({Idx, Name, Default, AllowedValues}, {Result, RD, Ctx}) ->
AllowedValueTuples = [{V} || V <- AllowedValues],
Option=
lists:keyfind(
list_to_atom(
string:to_lower(
wrq:get_qs_value(Name, Default, RD))),
1,
AllowedValueTuples),
case Option of
false ->
ErrorText =
"~s query parameter must be one of the following words: ~p~n",
{true,
wrq:append_to_resp_body(
io_lib:format(ErrorText, [Name, AllowedValues]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx};
_ ->
{Value} = Option,
{Result, RD, setelement(Idx, Ctx, Value)}
end.
is , or print an error message in # wm_reqdata { } if it is not .
malformed_boolean_param({Idx, Name, Default}, {Result, RD, Ctx}) ->
case string:to_lower(wrq:get_qs_value(Name, Default, RD)) of
"true" ->
{Result, RD, setelement(Idx, Ctx, true)};
"false" ->
{Result, RD, setelement(Idx, Ctx, false)};
"default" ->
{Result, RD, setelement(Idx, Ctx, default)};
_ ->
{true,
wrq:append_to_resp_body(
io_lib:format("~s query parameter must be true or false~n",
[Name]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
normalize_rw_param("backend") -> backend;
normalize_rw_param("default") -> default;
normalize_rw_param("one") -> one;
normalize_rw_param("quorum") -> quorum;
normalize_rw_param("all") -> all;
normalize_rw_param(V) -> list_to_integer(V).
-spec malformed_link_headers(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
or print an error in # wm_reqdata { } if it is not .
& lt;/Prefix / Bucket / Key> ; ; " , ...
malformed_link_headers(RD, Ctx) ->
case catch get_link_heads(RD, Ctx) of
Links when is_list(Links) ->
{false, RD, Ctx#ctx{links=Links}};
_Error when Ctx#ctx.api_version == 1->
{true,
wrq:append_to_resp_body(
io_lib:format("Invalid Link header. Links must be of the form~n"
"</~s/BUCKET/KEY>; riaktag=\"TAG\"~n",
[Ctx#ctx.prefix]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx};
_Error when Ctx#ctx.api_version == 2 ->
{true,
wrq:append_to_resp_body(
io_lib:format("Invalid Link header. Links must be of the form~n"
"</buckets/BUCKET/keys/KEY>; riaktag=\"TAG\"~n", []),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
-spec malformed_index_headers(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
or print an error in # wm_reqdata { } if not .
malformed_index_headers(RD, Ctx) ->
IndexFields1 = extract_index_fields(RD),
Validate the fields . If validation passes , then the index
case riak_index:parse_fields(IndexFields1) of
{ok, IndexFields2} ->
{false, RD, Ctx#ctx { index_fields=IndexFields2 }};
{error, Reasons} ->
{true,
wrq:append_to_resp_body(
[riak_index:format_failure_reason(X) || X <- Reasons],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx}
end.
-spec extract_index_fields(#wm_reqdata{}) -> proplists:proplist().
client 's PUT request , to be indexed at write time .
extract_index_fields(RD) ->
PrefixSize = length(?HEAD_INDEX_PREFIX),
{ok, RE} = re:compile(",\\s"),
F =
fun({K,V}, Acc) ->
KList = riak_kv_wm_utils:any_to_list(K),
case lists:prefix(?HEAD_INDEX_PREFIX, string:to_lower(KList)) of
true ->
IndexField =
list_to_binary(
element(2, lists:split(PrefixSize, KList))),
Values = re:split(V, RE, [{return, binary}]),
[{IndexField, X} || X <- Values] ++ Acc;
false ->
Acc
end
end,
lists:foldl(F, [], mochiweb_headers:to_list(wrq:req_headers(RD))).
-spec content_types_provided(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Producer::atom()}], #wm_reqdata{}, context()}.
was used in the PUT request that stored the document in Riak .
content_types_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'PUT'; Method =:= 'POST' ->
{ContentType, _} = extract_content_type(RD),
{[{ContentType, produce_doc_body}], RD, Ctx};
content_types_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'DELETE' ->
{[{"text/html", to_html}], RD, Ctx};
content_types_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
we can assume DocCtx#ctx.doc is { ok , Doc } because of malformed_request
case select_doc(DocCtx) of
{MD, V} ->
{[{get_ctype(MD,V), produce_doc_body}], RD, DocCtx};
multiple_choices ->
{[{"text/plain", produce_sibling_message_body},
{"multipart/mixed", produce_multipart_body}], RD, DocCtx}
end.
-spec charsets_provided(#wm_reqdata{}, context()) ->
{no_charset|[{Charset::string(), Producer::function()}],
#wm_reqdata{}, context()}.
in the PUT request that stored the document in ( none if
no charset was specified at PUT - time ) .
charsets_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'PUT'; Method =:= 'POST' ->
case extract_content_type(RD) of
{_, undefined} ->
{no_charset, RD, Ctx};
{_, Charset} ->
{[{Charset, fun(X) -> X end}], RD, Ctx}
end;
charsets_provided(RD, Ctx=#ctx{method=Method}=Ctx)
when Method =:= 'DELETE' ->
{no_charset, RD, Ctx};
charsets_provided(RD, Ctx0) ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_CHARSET, MD) of
{ok, CS} ->
{[{CS, fun(X) -> X end}], RD, DocCtx};
error ->
{no_charset, RD, DocCtx}
end;
multiple_choices ->
{no_charset, RD, DocCtx}
end;
{error, _} ->
{no_charset, RD, DocCtx}
end.
-spec encodings_provided(#wm_reqdata{}, context()) ->
{[{Encoding::string(), Producer::function()}], #wm_reqdata{}, context()}.
used in the PUT request that stored the document in Riak , or
" identity " and " gzip " if no encoding was specified at PUT - time .
encodings_provided(RD, Ctx0) ->
DocCtx =
case Ctx0#ctx.method of
UpdM when UpdM =:= 'PUT'; UpdM =:= 'POST'; UpdM =:= 'DELETE' ->
Ctx0;
_ ->
ensure_doc(Ctx0)
end,
case DocCtx#ctx.doc of
{ok, _} ->
case select_doc(DocCtx) of
{MD, _} ->
case dict:find(?MD_ENCODING, MD) of
{ok, Enc} ->
{[{Enc, fun(X) -> X end}], RD, DocCtx};
error ->
{riak_kv_wm_utils:default_encodings(), RD, DocCtx}
end;
multiple_choices ->
{riak_kv_wm_utils:default_encodings(), RD, DocCtx}
end;
_ ->
{riak_kv_wm_utils:default_encodings(), RD, DocCtx}
end.
-spec content_types_accepted(#wm_reqdata{}, context()) ->
{[{ContentType::string(), Acceptor::atom()}],
#wm_reqdata{}, context()}.
of a key - level PUT request will be accepted by this resource .
content_types_accepted(RD, Ctx) ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
{[], RD, Ctx};
CType ->
Media = hd(string:tokens(CType, ";")),
case string:tokens(Media, "/") of
[_Type, _Subtype] ->
{[{Media, accept_doc_body}], RD, Ctx};
_ ->
{[],
wrq:set_resp_header(
?HEAD_CTYPE,
"text/plain",
wrq:set_resp_body(
["\"", Media, "\""
" is not a valid media type"
" for the Content-type header.\n"],
RD)),
Ctx}
end
end.
-spec resource_exists(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
Documents exists if a read request to returns { ok , riak_object ( ) } ,
vtag param matches the vtag of some value of the object .
resource_exists(RD, Ctx0) ->
Method = Ctx0#ctx.method,
ToFetch =
case Method of
UpdM when UpdM =:= 'PUT'; UpdM =:= 'POST'; UpdM =:= 'DELETE' ->
conditional_headers_present(RD) == true;
_ ->
true
end,
case ToFetch of
true ->
DocCtx = ensure_doc(Ctx0),
case DocCtx#ctx.doc of
{ok, Doc} ->
case DocCtx#ctx.vtag of
undefined ->
{true, RD, DocCtx};
Vtag ->
MDs = riak_object:get_metadatas(Doc),
{lists:any(
fun(M) ->
dict:fetch(?MD_VTAG, M) =:= Vtag
end,
MDs),
RD,
DocCtx#ctx{vtag=Vtag}}
end;
{error, _} ->
error conditions from ensure_doc are handled up in
{false, RD, DocCtx}
end;
false ->
it does exist , and if PUT / POST , assume it does n't
case Method of
'DELETE' ->
{true, RD, Ctx0};
_ ->
{false, RD, Ctx0}
end
end.
-spec is_conflict(request_data(), context()) ->
{boolean(), request_data(), context()}.
is_conflict(RD, Ctx) ->
case {Ctx#ctx.method, wrq:get_req_header(?HEAD_IF_NOT_MODIFIED, RD)} of
{_ , undefined} ->
{false, RD, Ctx};
{UpdM, NotModifiedClock} when UpdM =:= 'PUT'; UpdM =:= 'POST' ->
case Ctx#ctx.doc of
{ok, Obj} ->
InClock =
riak_object:decode_vclock(
base64:decode(NotModifiedClock)),
CurrentClock =
riak_object:vclock(Obj),
{not vclock:equal(InClock, CurrentClock), RD, Ctx};
_ ->
{true, RD, Ctx}
end;
_ ->
{false, RD, Ctx}
end.
-spec conditional_headers_present(request_data()) -> boolean().
conditional_headers_present(RD) ->
NoneMatch =
(wrq:get_req_header("If-None-Match", RD) =/= undefined),
Match =
(wrq:get_req_header("If-Match", RD) =/= undefined),
UnModifiedSince =
(wrq:get_req_header("If-Unmodified-Since", RD) =/= undefined),
NotModified =
(wrq:get_req_header(?HEAD_IF_NOT_MODIFIED, RD) =/= undefined),
(NoneMatch or Match or UnModifiedSince or NotModified).
-spec post_is_create(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
requests ( this makes webmachine call create_path/2 , where the key
post_is_create(RD, Ctx=#ctx{key=undefined}) ->
{true, RD, Ctx};
post_is_create(RD, Ctx) ->
{false, RD, Ctx}.
-spec create_path(#wm_reqdata{}, context()) ->
{string(), #wm_reqdata{}, context()}.
201 Created response .
create_path(RD, Ctx=#ctx{prefix=P, bucket_type=T, bucket=B, api_version=V}) ->
K = riak_core_util:unique_id_62(),
{K,
wrq:set_resp_header("Location",
riak_kv_wm_utils:format_uri(T, B, K, P, V),
RD),
Ctx#ctx{key=list_to_binary(K)}}.
-spec process_post(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
as PUT for clients that do not support PUT .
process_post(RD, Ctx) -> accept_doc_body(RD, Ctx).
-spec accept_doc_body(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
@doc Store the data the client is PUTing in the document .
into their final riak_object ( ) form , and executes the put .
accept_doc_body(
RD,
Ctx=#ctx{
bucket_type=T, bucket=B, key=K, client=C,
links=L,
index_fields=IF}) ->
Doc0 = riak_object:new(riak_kv_wm_utils:maybe_bucket_type(T,B), K, <<>>),
VclockDoc = riak_object:set_vclock(Doc0, decode_vclock_header(RD)),
{CType, Charset} = extract_content_type(RD),
UserMeta = extract_user_meta(RD),
CTypeMD = dict:store(?MD_CTYPE, CType, dict:new()),
CharsetMD =
if Charset /= undefined ->
dict:store(?MD_CHARSET, Charset, CTypeMD);
true ->
CTypeMD
end,
EncMD =
case wrq:get_req_header(?HEAD_ENCODING, RD) of
undefined -> CharsetMD;
E -> dict:store(?MD_ENCODING, E, CharsetMD)
end,
LinkMD = dict:store(?MD_LINKS, L, EncMD),
UserMetaMD = dict:store(?MD_USERMETA, UserMeta, LinkMD),
IndexMD = dict:store(?MD_INDEX, IF, UserMetaMD),
MDDoc = riak_object:update_metadata(VclockDoc, IndexMD),
Doc =
riak_object:update_value(
MDDoc, riak_kv_wm_utils:accept_value(CType, wrq:req_body(RD))),
Options0 =
case wrq:get_qs_value(?Q_RETURNBODY, RD) of
?Q_TRUE -> [returnbody];
_ -> []
end,
Options = make_options(Options0, Ctx),
NoneMatch = (wrq:get_req_header("If-None-Match", RD) =/= undefined),
Options2 = case riak_kv_util:consistent_object(B) and NoneMatch of
true ->
[{if_none_match, true}|Options];
false ->
Options
end,
case riak_client:put(Doc, Options2, C) of
{error, Reason} ->
handle_common_error(Reason, RD, Ctx);
ok ->
{true, RD, Ctx#ctx{doc={ok, Doc}}};
{ok, RObj} ->
DocCtx = Ctx#ctx{doc={ok, RObj}},
HasSiblings = (select_doc(DocCtx) == multiple_choices),
send_returnbody(RD, DocCtx, HasSiblings)
end.
send_returnbody(RD, DocCtx, _HasSiblings = false) ->
{Body, DocRD, DocCtx2} = produce_doc_body(RD, DocCtx),
{DocRD2, DocCtx3} = add_conditional_headers(DocRD, DocCtx2),
{true, wrq:append_to_response_body(Body, DocRD2), DocCtx3};
send_returnbody(RD, DocCtx, _HasSiblings = true) ->
AcceptHdr = wrq:get_req_header("Accept", RD),
PossibleTypes = ["multipart/mixed", "text/plain"],
case webmachine_util:choose_media_type(PossibleTypes, AcceptHdr) of
"multipart/mixed" ->
{Body, DocRD, DocCtx2} = produce_multipart_body(RD, DocCtx),
{DocRD2, DocCtx3} = add_conditional_headers(DocRD, DocCtx2),
{true, wrq:append_to_response_body(Body, DocRD2), DocCtx3};
_ ->
{Body, DocRD, DocCtx2} = produce_sibling_message_body(RD, DocCtx),
{DocRD2, DocCtx3} = add_conditional_headers(DocRD, DocCtx2),
{true, wrq:append_to_response_body(Body, DocRD2), DocCtx3}
end.
returnbody on a PUT or POST .
add_conditional_headers(RD, Ctx) ->
{ETag, RD2, Ctx2} = generate_etag(RD, Ctx),
{LM, RD3, Ctx3} = last_modified(RD2, Ctx2),
RD4 =
wrq:set_resp_header(
"ETag", webmachine_util:quoted_string(ETag), RD3),
RD5 =
wrq:set_resp_header(
"Last-Modified",
httpd_util:rfc1123_date(
calendar:universal_time_to_local_time(LM)), RD4),
{RD5,Ctx3}.
-spec extract_content_type(#wm_reqdata{}) ->
{ContentType::string(), Charset::string()|undefined}.
@doc Interpret the Content - Type header in the client 's PUT request .
extract_content_type(RD) ->
case wrq:get_req_header(?HEAD_CTYPE, RD) of
undefined ->
undefined;
RawCType ->
[CType|RawParams] = string:tokens(RawCType, "; "),
Params = [ list_to_tuple(string:tokens(P, "=")) || P <- RawParams],
{CType, proplists:get_value("charset", Params)}
end.
-spec extract_user_meta(#wm_reqdata{}) -> proplists:proplist().
@doc Extract headers prefixed by X - Riak - Meta- in the client 's PUT request
extract_user_meta(RD) ->
lists:filter(fun({K,_V}) ->
lists:prefix(
?HEAD_USERMETA_PREFIX,
string:to_lower(riak_kv_wm_utils:any_to_list(K)))
end,
mochiweb_headers:to_list(wrq:req_headers(RD))).
-spec multiple_choices(#wm_reqdata{}, context()) ->
{boolean(), #wm_reqdata{}, context()}.
vtags that are invalid for this version of the document .
multiple_choices(RD, Ctx=#ctx{vtag=undefined, doc={ok, Doc}}) ->
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:value_count(Doc) of
1 -> {false, RD, Ctx};
_ -> {true, RD, Ctx}
end;
_ ->
{false, RD, Ctx}
end;
multiple_choices(RD, Ctx) ->
specific vtag was specified
if it 's a tombstone add the X - Riak - Deleted header
case select_doc(Ctx) of
{M, _} ->
case dict:find(?MD_DELETED, M) of
{ok, "true"} ->
{false,
wrq:set_resp_header(?HEAD_DELETED, "true", RD),
Ctx};
error ->
{false, RD, Ctx}
end;
multiple_choices ->
throw(
{unexpected_code_path,
?MODULE,
multiple_choices,
multiple_choices})
end.
-spec produce_doc_body(#wm_reqdata{}, context()) ->
{binary(), #wm_reqdata{}, context()}.
Link , X - Riak - Meta- headers , and X - Riak - Index- headers to the
response . One link will point to the bucket , with the
produce_doc_body(RD, Ctx) ->
Prefix = Ctx#ctx.prefix,
Bucket = Ctx#ctx.bucket,
APIVersion = Ctx#ctx.api_version,
case select_doc(Ctx) of
{MD, Doc} ->
Links1 = case dict:find(?MD_LINKS, MD) of
{ok, L} -> L;
error -> []
end,
Links2 =
riak_kv_wm_utils:format_links(
[{Bucket, "up"}|Links1], Prefix, APIVersion),
LinkRD = wrq:merge_resp_headers(Links2, RD),
UserMetaRD = case dict:find(?MD_USERMETA, MD) of
{ok, UserMeta} ->
lists:foldl(
fun({K,V},Acc) ->
wrq:merge_resp_headers([{K,V}],Acc)
end,
LinkRD, UserMeta);
error -> LinkRD
end,
IndexRD =
case dict:find(?MD_INDEX, MD) of
{ok, IndexMeta} ->
lists:foldl(
fun({K,V}, Acc) ->
K1 = riak_kv_wm_utils:any_to_list(K),
V1 = riak_kv_wm_utils:any_to_list(V),
wrq:merge_resp_headers(
[{?HEAD_INDEX_PREFIX ++ K1, V1}], Acc)
end,
UserMetaRD, IndexMeta);
error ->
UserMetaRD
end,
{riak_kv_wm_utils:encode_value(Doc),
encode_vclock_header(IndexRD, Ctx), Ctx};
multiple_choices ->
throw(
{unexpected_code_path,
?MODULE,
produce_doc_body,
multiple_choices})
end.
-spec produce_sibling_message_body(#wm_reqdata{}, context()) ->
{iolist(), #wm_reqdata{}, context()}.
values so they can get to them with the vtag query param .
produce_sibling_message_body(RD, Ctx=#ctx{doc={ok, Doc}}) ->
Vtags = [ dict:fetch(?MD_VTAG, M)
|| M <- riak_object:get_metadatas(Doc) ],
{[<<"Siblings:\n">>, [ [V,<<"\n">>] || V <- Vtags]],
wrq:set_resp_header(?HEAD_CTYPE, "text/plain",
encode_vclock_header(RD, Ctx)),
Ctx}.
-spec produce_multipart_body(#wm_reqdata{}, context()) ->
{iolist(), #wm_reqdata{}, context()}.
values ( siblings ) , each sibling being one part of the larger
produce_multipart_body(RD, Ctx=#ctx{doc={ok, Doc}, bucket=B, prefix=P}) ->
APIVersion = Ctx#ctx.api_version,
Boundary = riak_core_util:unique_id_62(),
{[[["\r\n--",Boundary,"\r\n",
riak_kv_wm_utils:multipart_encode_body(P, B, Content, APIVersion)]
|| Content <- riak_object:get_contents(Doc)],
"\r\n--",Boundary,"--\r\n"],
wrq:set_resp_header(?HEAD_CTYPE,
"multipart/mixed; boundary="++Boundary,
encode_vclock_header(RD, Ctx)),
Ctx}.
-spec select_doc(context()) ->
{Metadata :: term(), Value :: term()}|multiple_choices.
- chooses only / if only one exists
- chooses val / given Vtag if multiple contents exist
select_doc(#ctx{doc={ok, Doc}, vtag=Vtag}) ->
case riak_object:get_update_value(Doc) of
undefined ->
case riak_object:get_contents(Doc) of
[Single] -> Single;
Mult ->
case lists:dropwhile(
fun({M,_}) ->
dict:fetch(?MD_VTAG, M) /= Vtag
end,
Mult) of
[Match|_] -> Match;
[] -> multiple_choices
end
end;
UpdateValue ->
{riak_object:get_update_metadata(Doc), UpdateValue}
end.
-spec encode_vclock_header(#wm_reqdata{}, context()) -> #wm_reqdata{}.
@doc Add the X - Riak - Vclock header to the response .
encode_vclock_header(RD, #ctx{doc={ok, Doc}}) ->
{Head, Val} = riak_object:vclock_header(Doc),
wrq:set_resp_header(Head, Val, RD);
encode_vclock_header(RD, #ctx{doc={error, {deleted, VClock}}}) ->
BinVClock = riak_object:encode_vclock(VClock),
wrq:set_resp_header(
?HEAD_VCLOCK, binary_to_list(base64:encode(BinVClock)), RD).
-spec decode_vclock_header(#wm_reqdata{}) -> vclock:vclock().
@doc Translate the X - Riak - Vclock header value from the request into
its Erlang representation . If no vclock header exists , a fresh
decode_vclock_header(RD) ->
case wrq:get_req_header(?HEAD_VCLOCK, RD) of
undefined -> vclock:fresh();
Head -> riak_object:decode_vclock(base64:decode(Head))
end.
-spec ensure_doc(context()) -> context().
ensure_doc(Ctx=#ctx{doc=undefined, key=undefined}) ->
Ctx#ctx{doc={error, notfound}};
ensure_doc(Ctx=#ctx{doc=undefined, bucket_type=T, bucket=B, key=K, client=C,
basic_quorum=Quorum, notfound_ok=NotFoundOK}) ->
case riak_kv_wm_utils:bucket_type_exists(T) of
true ->
Options0 =
[deletedvclock,
{basic_quorum, Quorum},
{notfound_ok, NotFoundOK}],
Options = make_options(Options0, Ctx),
BT = riak_kv_wm_utils:maybe_bucket_type(T,B),
Ctx#ctx{doc=riak_client:get(BT, K, Options, C)};
false ->
Ctx#ctx{doc={error, bucket_type_unknown}}
end;
ensure_doc(Ctx) -> Ctx.
-spec delete_resource(#wm_reqdata{}, context()) ->
{true, #wm_reqdata{}, context()}.
delete_resource(RD, Ctx=#ctx{bucket_type=T, bucket=B, key=K, client=C}) ->
Options = make_options([], Ctx),
BT = riak_kv_wm_utils:maybe_bucket_type(T,B),
Result =
case wrq:get_req_header(?HEAD_VCLOCK, RD) of
undefined ->
riak_client:delete(BT, K, Options, C);
_ ->
VC = decode_vclock_header(RD),
riak_client:delete_vclock(BT, K, VC, Options, C)
end,
case Result of
ok ->
{true, RD, Ctx};
{error, Reason} ->
handle_common_error(Reason, RD, Ctx)
end.
-ifndef(old_hash).
md5(Bin) ->
crypto:hash(md5, Bin).
-else.
md5(Bin) ->
crypto:md5(Bin).
-endif.
-spec generate_etag(#wm_reqdata{}, context()) ->
{undefined|string(), #wm_reqdata{}, context()}.
generate_etag(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{dict:fetch(?MD_VTAG, MD), RD, Ctx};
multiple_choices ->
{ok, Doc} = Ctx#ctx.doc,
<<ETag:128/integer>> =
md5(term_to_binary(riak_object:vclock(Doc))),
{riak_core_util:integer_to_list(ETag, 62), RD, Ctx}
end.
-spec last_modified(#wm_reqdata{}, context()) ->
{undefined|calendar:datetime(), #wm_reqdata{}, context()}.
last_modified(RD, Ctx) ->
case select_doc(Ctx) of
{MD, _} ->
{normalize_last_modified(MD),RD, Ctx};
multiple_choices ->
{ok, Doc} = Ctx#ctx.doc,
LMDates = [ normalize_last_modified(MD) ||
MD <- riak_object:get_metadatas(Doc) ],
{lists:max(LMDates), RD, Ctx}
end.
-spec normalize_last_modified(riak_kv_wm_object_dict()) -> calendar:datetime().
for use in the last_modified/2 callback .
normalize_last_modified(MD) ->
case dict:fetch(?MD_LASTMOD, MD) of
Now={_,_,_} ->
calendar:now_to_universal_time(Now);
Rfc1123 when is_list(Rfc1123) ->
httpd_util:convert_request_date(Rfc1123)
end.
-spec get_link_heads(#wm_reqdata{}, context()) -> [link()].
get_link_heads(RD, Ctx) ->
APIVersion = Ctx#ctx.api_version,
Prefix = Ctx#ctx.prefix,
Bucket = Ctx#ctx.bucket,
LinkHeaders1 =
case wrq:get_req_header(?HEAD_LINK, RD) of
undefined -> [];
Heads -> string:tokens(Heads, ",")
end,
{BucketLinks, KeyLinks} =
case APIVersion of
1 ->
{ok, BucketRegex} =
re:compile("</" ++ Prefix ++ ?V1_BUCKET_REGEX),
{ok, KeyRegex} =
re:compile("</" ++ Prefix ++ ?V1_KEY_REGEX),
extract_links(LinkHeaders1, BucketRegex, KeyRegex);
@todo Handle links in API Version 3 ?
Two when Two >= 2 ->
{ok, BucketRegex} =
re:compile(?V2_BUCKET_REGEX),
{ok, KeyRegex} =
re:compile(?V2_KEY_REGEX),
extract_links(LinkHeaders1, BucketRegex, KeyRegex)
end,
Validate that the only bucket header is pointing to the parent
IsValid = (BucketLinks == []) orelse (BucketLinks == [{Bucket, <<"up">>}]),
case IsValid of
true ->
KeyLinks;
false ->
throw({invalid_link_headers, LinkHeaders1})
end.
Run each LinkHeader string ( ) through the BucketRegex and
KeyRegex . Return { BucketLinks , KeyLinks } .
extract_links(LinkHeaders, BucketRegex, KeyRegex) ->
extract_links_1(LinkHeaders, BucketRegex, KeyRegex, [], []).
extract_links_1([LinkHeader|Rest], BucketRegex, KeyRegex, BucketAcc, KeyAcc) ->
case re:run(LinkHeader, BucketRegex, [{capture, all_but_first, list}]) of
{match, [Bucket, Tag]} ->
Bucket1 = list_to_binary(mochiweb_util:unquote(Bucket)),
Tag1 = list_to_binary(mochiweb_util:unquote(Tag)),
NewBucketAcc = [{Bucket1, Tag1}|BucketAcc],
extract_links_1(Rest, BucketRegex, KeyRegex, NewBucketAcc, KeyAcc);
nomatch ->
case re:run(LinkHeader, KeyRegex, [{capture, all_but_first, list}]) of
{match, [Bucket, Key, Tag]} ->
Bucket1 = list_to_binary(mochiweb_util:unquote(Bucket)),
Key1 = list_to_binary(mochiweb_util:unquote(Key)),
Tag1 = list_to_binary(mochiweb_util:unquote(Tag)),
NewKeyAcc = [{{Bucket1, Key1}, Tag1}|KeyAcc],
extract_links_1(Rest, BucketRegex, KeyRegex, BucketAcc, NewKeyAcc);
nomatch ->
throw({invalid_link_header, LinkHeader})
end
end;
extract_links_1([], _BucketRegex, _KeyRegex, BucketAcc, KeyAcc) ->
{BucketAcc, KeyAcc}.
-spec get_ctype(riak_kv_wm_object_dict(), term()) -> string().
get_ctype(MD,V) ->
case dict:find(?MD_CTYPE, MD) of
{ok, Ctype} ->
Ctype;
error when is_binary(V) ->
"application/octet-stream";
error ->
"application/x-erlang-binary"
end.
missing_content_type(RD) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
wrq:append_to_response_body(<<"Missing Content-Type request header">>, RD1).
send_precommit_error(RD, Reason) ->
RD1 = wrq:set_resp_header("Content-Type", "text/plain", RD),
Error = if
Reason =:= undefined ->
list_to_binary([atom_to_binary(wrq:method(RD1), utf8),
<<" aborted by pre-commit hook.">>]);
true ->
Reason
end,
wrq:append_to_response_body(Error, RD1).
handle_common_error(Reason, RD, Ctx) ->
case {error, Reason} of
{error, precommit_fail} ->
{{halt, 403}, send_precommit_error(RD, undefined), Ctx};
{error, {precommit_fail, Message}} ->
{{halt, 403}, send_precommit_error(RD, Message), Ctx};
{error, too_many_fails} ->
{{halt, 503}, wrq:append_to_response_body("Too Many write failures"
" to satisfy W/DW\n", RD), Ctx};
{error, timeout} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("request timed out~n",[]),
RD)),
Ctx};
{error, notfound} ->
{{halt, 404},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("not found~n",[]),
RD)),
Ctx};
{error, bucket_type_unknown} ->
{{halt, 404},
wrq:set_resp_body(
io_lib:format("Unknown bucket type: ~s", [Ctx#ctx.bucket_type]),
wrq:set_resp_header(?HEAD_CTYPE, "text/plain", RD)),
Ctx};
{error, {deleted, _VClock}} ->
{{halt, 404},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:set_resp_header(?HEAD_DELETED, "true",
wrq:append_to_response_body(
io_lib:format("not found~n",[]),
encode_vclock_header(RD, Ctx)))),
Ctx};
{error, {n_val_violation, N}} ->
Msg = io_lib:format("Specified w/dw/pw/node_confirms values invalid for bucket"
" n value of ~p~n", [N]),
{{halt, 400}, wrq:append_to_response_body(Msg, RD), Ctx};
{error, {r_val_unsatisfied, Requested, Returned}} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("R-value unsatisfied: ~p/~p~n",
[Returned, Requested]),
RD)),
Ctx};
{error, {dw_val_unsatisfied, DW, NumDW}} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("DW-value unsatisfied: ~p/~p~n",
[NumDW, DW]),
RD)),
Ctx};
{error, {pr_val_unsatisfied, Requested, Returned}} ->
{{halt, 503},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("PR-value unsatisfied: ~p/~p~n",
[Returned, Requested]),
RD)),
Ctx};
{error, {pw_val_unsatisfied, Requested, Returned}} ->
Msg = io_lib:format("PW-value unsatisfied: ~p/~p~n", [Returned,
Requested]),
{{halt, 503}, wrq:append_to_response_body(Msg, RD), Ctx};
{error, {node_confirms_val_unsatisfied, Requested, Returned}} ->
Msg = io_lib:format("node_confirms-value unsatisfied: ~p/~p~n", [Returned,
Requested]),
{{halt, 503}, wrq:append_to_response_body(Msg, RD), Ctx};
{error, failed} ->
{{halt, 412}, RD, Ctx};
{error, Err} ->
{{halt, 500},
wrq:set_resp_header("Content-Type", "text/plain",
wrq:append_to_response_body(
io_lib:format("Error:~n~p~n",[Err]),
RD)),
Ctx}
end.
make_options(Prev, Ctx) ->
NewOpts0 = [{rw, Ctx#ctx.rw}, {r, Ctx#ctx.r}, {w, Ctx#ctx.w},
{pr, Ctx#ctx.pr}, {pw, Ctx#ctx.pw}, {dw, Ctx#ctx.dw},
{node_confirms, Ctx#ctx.node_confirms},
{sync_on_write, Ctx#ctx.sync_on_write},
{timeout, Ctx#ctx.timeout},
{asis, Ctx#ctx.asis}],
NewOpts = [ {Opt, Val} || {Opt, Val} <- NewOpts0,
Val /= undefined, Val /= default ],
Prev ++ NewOpts.
|
3d882aa1d734db496111ab9da60c344101a5e5dfe7f425d9f741f074ad556a9d
|
nklein/userial
|
package.lisp
|
Copyright ( c ) 2011 nklein software
MIT License . See included LICENSE.txt file for licensing details .
(defpackage :userial-tests
(:use :cl :userial)
(:export :run-tests))
| null |
https://raw.githubusercontent.com/nklein/userial/dc34fc73385678a61c39e98f77a4443433eedb1d/userial/tests/package.lisp
|
lisp
|
Copyright ( c ) 2011 nklein software
MIT License . See included LICENSE.txt file for licensing details .
(defpackage :userial-tests
(:use :cl :userial)
(:export :run-tests))
|
|
605914bd5aca5e762be795de398285eb5c9e1173139d0c1dd44e4674d5039394
|
jabber-at/ejabberd-contrib
|
fusco_cp_tests.erl
|
%%% ----------------------------------------------------------------------------
( C ) 2013 , Erlang Solutions Ltd
@author Corbacho < >
@doc Client Pool tests
%%% @end
%%%-----------------------------------------------------------------------------
-module(fusco_cp_tests).
-include_lib("eunit/include/eunit.hrl").
-define(POOL, fusco_pool).
client_pool_test_() ->
{foreach,
fun() ->
{ok, Pid} = fusco_cp:start({"127.0.0.1", 5050, false}, [], 3),
erlang:register(?POOL, Pid),
Pid
end,
fun(Pid) ->
fusco_cp:stop(Pid)
end,
[
{timeout, 60000, {"Get client", fun get_client/0}},
{"Free client", fun free_client/0},
{"Unblock client", fun unblock_client/0}
]
}.
get_client() ->
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual({error, timeout}, fusco_cp:get_client(?POOL)).
free_client() ->
Pid = fusco_cp:get_client(?POOL),
?assertEqual(true, is_pid(Pid)),
?assertEqual(ok, fusco_cp:free_client(?POOL, Pid)),
?assertEqual(Pid, fusco_cp:get_client(?POOL)).
unblock_client() ->
Client = fusco_cp:get_client(?POOL),
?assertEqual(true, is_pid(Client)),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
To = self(),
spawn(fun() ->
Pid = fusco_cp:get_client(?POOL),
To ! {client, Pid}
end),
?assertEqual(ok, fusco_cp:free_client(?POOL, Client)),
?assertEqual({client, Client}, receive
{client, _} = R ->
R
end).
| null |
https://raw.githubusercontent.com/jabber-at/ejabberd-contrib/d5eb036b786c822d9fd56f881d27e31688ec6e91/ejabberd_auth_http/deps/fusco/test/fusco_cp_tests.erl
|
erlang
|
----------------------------------------------------------------------------
@end
-----------------------------------------------------------------------------
|
( C ) 2013 , Erlang Solutions Ltd
@author Corbacho < >
@doc Client Pool tests
-module(fusco_cp_tests).
-include_lib("eunit/include/eunit.hrl").
-define(POOL, fusco_pool).
client_pool_test_() ->
{foreach,
fun() ->
{ok, Pid} = fusco_cp:start({"127.0.0.1", 5050, false}, [], 3),
erlang:register(?POOL, Pid),
Pid
end,
fun(Pid) ->
fusco_cp:stop(Pid)
end,
[
{timeout, 60000, {"Get client", fun get_client/0}},
{"Free client", fun free_client/0},
{"Unblock client", fun unblock_client/0}
]
}.
get_client() ->
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual({error, timeout}, fusco_cp:get_client(?POOL)).
free_client() ->
Pid = fusco_cp:get_client(?POOL),
?assertEqual(true, is_pid(Pid)),
?assertEqual(ok, fusco_cp:free_client(?POOL, Pid)),
?assertEqual(Pid, fusco_cp:get_client(?POOL)).
unblock_client() ->
Client = fusco_cp:get_client(?POOL),
?assertEqual(true, is_pid(Client)),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
?assertEqual(true, is_pid(fusco_cp:get_client(?POOL))),
To = self(),
spawn(fun() ->
Pid = fusco_cp:get_client(?POOL),
To ! {client, Pid}
end),
?assertEqual(ok, fusco_cp:free_client(?POOL, Client)),
?assertEqual({client, Client}, receive
{client, _} = R ->
R
end).
|
dee918581be68463b2dde658301c008f798e23f448499b392a90fc49260f7534
|
aryx/syncweb
|
code.ml
|
Copyright 2009 - 2017 , see copyright.txt
open Common
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
(*****************************************************************************)
(* Types *)
(*****************************************************************************)
(* a view is a codetree list because a orig can contain multiple occurences
* of the view name, that then must be appended to each other in the view
*)
type t = codetree list
and codetree =
| RegularCode of string
| ChunkCode of
chunk_info *
codetree list (* have adjusted indentation *) *
int (* indentation, local *)
and chunk_info = {
chunk_key: string;
(* advanced: md5sum corresponding code_or_chunk list in orig *)
chunk_md5sum: Signature.t option;
mutable pretty_print: position option;
}
(* work with the -less_marks flag *)
and position = First (* s: *) | Middle (* x: *) | Last (* e: *)
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let generate_n_spaces i =
Common2.repeat " " i |> Common.join ""
(*****************************************************************************)
(* Helpers parser *)
(*****************************************************************************)
First version , again we assume line - oriented and special cases .
* Do special case for first chunk , generate chunk corresponding
* to filename with fake prelude and postlude ?
*
* Do multi files ? well no need I think , just call sync multiple
* times with the different view files .
* Do special case for first chunk, generate chunk corresponding
* to filename with fake prelude and postlude ?
*
* Do multi files? well no need I think, just call sync multiple
* times with the different view files.
*)
(* for better error reporting *)
type pinfo = {
file: filename;
line: int;
}
let s_of_pinfo pinfo =
spf "%s:%d" pinfo.file pinfo.line
let mkp file line =
{ file = file; line = line}
type mark2 =
| Regular2 of string * pinfo
| Start2 of string * int * Signature.t option * pinfo
| End2 of string option * int * pinfo
let readjust_mark2_remove_indent i body =
body |> List.map (function
| Start2 (s, j, md5sum, pinfo) ->
if j < i
then failwith (s_of_pinfo pinfo ^
" nested chunk with smaller indentation at ");
Start2 (s, j - i, md5sum, pinfo)
| Regular2 (s, pinfo) ->
if Common2.is_blank_string s
then Regular2 (s, pinfo)
else
if s=~ "\\([ \t]*\\)\\(.*\\)"
then
let spaces, rest = matched2 s in
let j = String.length spaces in
if j < i
then
failwith (s_of_pinfo pinfo ^
" nested chunk with smaller indentation at ");
let spaces' = generate_n_spaces (j - i) in
Regular2 (spaces' ^ rest, pinfo)
else raise Impossible
| End2 (x,i, pinfo) ->
do nt care about End2 indent info
End2 (x, i, pinfo)
)
patch the Start2 with the signature information in the md5sum_aux file
let readjust_start2_with_signatures file xs =
let sigfile = Signature.signaturefile_of_file file in
if Sys.file_exists sigfile
then
let md5s = Signature.parse_signaturefile sigfile in
let rec aux mark2s md5sums =
match mark2s, md5sums with
| [], [] -> []
| (Start2(s, j, md5sum, pinfo) as x)::xs, (s2, md5sum2)::ys ->
if s <> s2
then begin
pr2 (spf "not same key in view and md5sum_auxfile: %s VS %s" s s2);
if (Common2.y_or_no
"This may be because you moved entities. Continue?")
then x::xs
else failwith "Stop here"
end
else
if md5sum =*= None
then
(Start2(s, j, Some md5sum2, pinfo))::aux xs ys
else
failwith "md5sums present in view file"
| ((End2 _|Regular2 _) as x)::xs, ys ->
x::aux xs ys
| (Start2(_, _j, _md5sum, _pinfo) as x)::xs, [] ->
pr2 "more marks in view file than md5sums in md5sum_auxfile";
if (Common2.y_or_no
"This may be because you moved entities. Continue?")
then x::xs
else failwith "Stop here"
| [], _y::_ys ->
pr2 "more md5sums in md5sum_auxfile than start marks in view file";
if (Common2.y_or_no
"This may be because you moved entities. Continue?")
then []
else failwith "Stop here"
in
aux xs md5s
else xs
(*****************************************************************************)
Parser
(*****************************************************************************)
old : was computing a first " implicit " chunk corresponding to the name if
* the file , but not worth the extra complexity .
* the file, but not worth the extra complexity.
*)
let parse2 ~lang file =
let xs = Common.cat file in
let xs' = xs |> Common.index_list_1 |> List.map (fun (s, line) ->
match lang.Lang.parse_mark_startend s with
| Some (tabs, key, md5) ->
[End2 (Some key, String.length tabs, mkp file line);
Start2 (key, String.length tabs, md5, mkp file line);
]
| None ->
(match lang.Lang.parse_mark_start s with
| Some (tabs, key, md5) ->
[Start2 (key, String.length tabs, md5, mkp file line)]
| None ->
(match lang.Lang.parse_mark_end s with
| Some (tabs, key) ->
[End2 (key, String.length tabs, mkp file line)]
| None ->
[Regular2 (s, mkp file line)]
)
)
) |> List.flatten |> readjust_start2_with_signatures file
in
the view does not need to contain the key at the end mark ; it 's
* redundant . But it is used for now to easily find the matching End2
* of a Start2 . If the key is not there , then have to find the
* corresponding End2 by not stopping at the first one and by
* counting .
* redundant. But it is used for now to easily find the matching End2
* of a Start2. If the key is not there, then have to find the
* corresponding End2 by not stopping at the first one and by
* counting.
*)
let rec aux xs =
match xs with
| [] -> []
| x::xs ->
(match x with
| Start2 (s, i, md5sum, pinfo) ->
let (body, _endmark, rest) =
try
Common2.split_when (fun x -> match x with
| End2 (s2,_, _pinfo2) ->
(match s2 with
| None -> raise Todo
| Some s2 -> s = s2
)
| _ -> false
) xs
with Not_found ->
failwith (s_of_pinfo pinfo ^ " could not find end mark")
in
let body' = aux (readjust_mark2_remove_indent i body) in
ChunkCode ({
chunk_key = s;
chunk_md5sum = md5sum;
pretty_print = None;
}, body', i)::aux rest
| End2 (_s, _i, pinfo) ->
failwith (s_of_pinfo pinfo ^ " a end mark without a start at")
| Regular2 (s, _pinfo) ->
RegularCode s::aux xs
)
in
let codetrees = aux xs' in
codetrees
let parse ~lang a =
(* Common.profile_code "Code.parse" (fun () -> *)
parse2 ~lang a
(* ) *)
(*****************************************************************************)
(*****************************************************************************)
let rec adjust_pretty_print_field view =
match view with
| [] -> ()
| x::xs ->
(match x with
| RegularCode _ ->
adjust_pretty_print_field xs
| ChunkCode (info, _, indent) ->
let same_key, rest =
Common.span (fun y ->
match y with
| ChunkCode (info2, _, indent2) ->
info.chunk_key = info2.chunk_key &&
indent =|= indent2 (* always the same ? *)
| _ -> false
) (x::xs)
in
(* recurse *)
adjust_pretty_print_field rest;
same_key |> List.iter (function
| ChunkCode (_info, xs, _i) ->
adjust_pretty_print_field xs
| _ -> raise Impossible
);
let same_key' = same_key |> List.map (function
| ChunkCode(info, _, _) -> info
| _ -> raise Impossible
)
in
if List.length same_key' >= 2 then begin
let (hd, middle, tl) = Common2.head_middle_tail same_key' in
hd.pretty_print <- Some First;
tl.pretty_print <- Some Last;
middle |> List.iter (fun x -> x.pretty_print <- Some Middle);
end
)
assume first chunkcode corresponds to the filename ?
let unparse
?(md5sum_in_auxfile=false)
?(less_marks=false)
~lang views filename
=
let md5sums = ref [] in
if less_marks
then adjust_pretty_print_field views;
Common.with_open_outfile filename (fun (pr_no_nl, _chan) ->
let pr s = pr_no_nl (s ^ "\n") in
let pr_indent indent = Common2.do_n indent (fun () -> pr_no_nl " ") in
let rec aux (x, body, i) =
let key = x.chunk_key in
let md5sum =
if md5sum_in_auxfile
then begin
Common.push (spf "%s |%s" key
(Signature.to_hex (Common2.some x.chunk_md5sum)))
md5sums;
None
end
else x.chunk_md5sum
in
pr_indent (i);
(match x.pretty_print with
| None | Some First ->
pr (lang.Lang.unparse_mark_start key md5sum);
| (Some (Middle|Last)) ->
pr (lang.Lang.unparse_mark_startend key md5sum);
);
body |> List.iter (function
| RegularCode s ->
(* bugfix: otherwise make sync will not fixpoint *)
if Common2.is_blank_string s
then pr s
else begin
pr_indent i;
pr s;
end
| ChunkCode (x, body, j) ->
aux (x, body, i+j);
if decide to not show toplevel chunk
let key = x.chunk_key in
pr_indent ( i+j ) ;
pr ( spf " ( * nw_s : % s |%s
let key = x.chunk_key in
pr_indent (i+j);
pr (spf "(* nw_s: %s |%s*)" key x.chunk_md5sum);
aux (x, i+j);
pr_indent (i+j);
pr (spf "(* nw_e: %s *)" key);
*)
);
(match x.pretty_print with
| None | Some Last ->
(* bugfix: the pr_indent call must be here, not outside *)
pr_indent (i);
pr (lang.Lang.unparse_mark_end key);
| Some (First | Middle) ->
()
)
in
views |> List.iter (function
| ChunkCode (chunkcode, body, i) ->
aux (chunkcode, body, i)
| RegularCode _s ->
failwith "no chunk at toplevel"
);
()
);
if md5sum_in_auxfile then begin
Common.write_file ~file:(Signature.signaturefile_of_file filename)
(!md5sums |> List.rev |> Common.join "\n");
end;
()
| null |
https://raw.githubusercontent.com/aryx/syncweb/8cc3f10599bf65ab57947950f30cb6b18d83db14/frontend/code.ml
|
ocaml
|
***************************************************************************
Prelude
***************************************************************************
***************************************************************************
Types
***************************************************************************
a view is a codetree list because a orig can contain multiple occurences
* of the view name, that then must be appended to each other in the view
have adjusted indentation
indentation, local
advanced: md5sum corresponding code_or_chunk list in orig
work with the -less_marks flag
s:
x:
e:
***************************************************************************
Helpers
***************************************************************************
***************************************************************************
Helpers parser
***************************************************************************
for better error reporting
***************************************************************************
***************************************************************************
Common.profile_code "Code.parse" (fun () ->
)
***************************************************************************
***************************************************************************
always the same ?
recurse
bugfix: otherwise make sync will not fixpoint
bugfix: the pr_indent call must be here, not outside
|
Copyright 2009 - 2017 , see copyright.txt
open Common
type t = codetree list
and codetree =
| RegularCode of string
| ChunkCode of
chunk_info *
and chunk_info = {
chunk_key: string;
chunk_md5sum: Signature.t option;
mutable pretty_print: position option;
}
let generate_n_spaces i =
Common2.repeat " " i |> Common.join ""
First version , again we assume line - oriented and special cases .
* Do special case for first chunk , generate chunk corresponding
* to filename with fake prelude and postlude ?
*
* Do multi files ? well no need I think , just call sync multiple
* times with the different view files .
* Do special case for first chunk, generate chunk corresponding
* to filename with fake prelude and postlude ?
*
* Do multi files? well no need I think, just call sync multiple
* times with the different view files.
*)
type pinfo = {
file: filename;
line: int;
}
let s_of_pinfo pinfo =
spf "%s:%d" pinfo.file pinfo.line
let mkp file line =
{ file = file; line = line}
type mark2 =
| Regular2 of string * pinfo
| Start2 of string * int * Signature.t option * pinfo
| End2 of string option * int * pinfo
let readjust_mark2_remove_indent i body =
body |> List.map (function
| Start2 (s, j, md5sum, pinfo) ->
if j < i
then failwith (s_of_pinfo pinfo ^
" nested chunk with smaller indentation at ");
Start2 (s, j - i, md5sum, pinfo)
| Regular2 (s, pinfo) ->
if Common2.is_blank_string s
then Regular2 (s, pinfo)
else
if s=~ "\\([ \t]*\\)\\(.*\\)"
then
let spaces, rest = matched2 s in
let j = String.length spaces in
if j < i
then
failwith (s_of_pinfo pinfo ^
" nested chunk with smaller indentation at ");
let spaces' = generate_n_spaces (j - i) in
Regular2 (spaces' ^ rest, pinfo)
else raise Impossible
| End2 (x,i, pinfo) ->
do nt care about End2 indent info
End2 (x, i, pinfo)
)
patch the Start2 with the signature information in the md5sum_aux file
let readjust_start2_with_signatures file xs =
let sigfile = Signature.signaturefile_of_file file in
if Sys.file_exists sigfile
then
let md5s = Signature.parse_signaturefile sigfile in
let rec aux mark2s md5sums =
match mark2s, md5sums with
| [], [] -> []
| (Start2(s, j, md5sum, pinfo) as x)::xs, (s2, md5sum2)::ys ->
if s <> s2
then begin
pr2 (spf "not same key in view and md5sum_auxfile: %s VS %s" s s2);
if (Common2.y_or_no
"This may be because you moved entities. Continue?")
then x::xs
else failwith "Stop here"
end
else
if md5sum =*= None
then
(Start2(s, j, Some md5sum2, pinfo))::aux xs ys
else
failwith "md5sums present in view file"
| ((End2 _|Regular2 _) as x)::xs, ys ->
x::aux xs ys
| (Start2(_, _j, _md5sum, _pinfo) as x)::xs, [] ->
pr2 "more marks in view file than md5sums in md5sum_auxfile";
if (Common2.y_or_no
"This may be because you moved entities. Continue?")
then x::xs
else failwith "Stop here"
| [], _y::_ys ->
pr2 "more md5sums in md5sum_auxfile than start marks in view file";
if (Common2.y_or_no
"This may be because you moved entities. Continue?")
then []
else failwith "Stop here"
in
aux xs md5s
else xs
Parser
old : was computing a first " implicit " chunk corresponding to the name if
* the file , but not worth the extra complexity .
* the file, but not worth the extra complexity.
*)
let parse2 ~lang file =
let xs = Common.cat file in
let xs' = xs |> Common.index_list_1 |> List.map (fun (s, line) ->
match lang.Lang.parse_mark_startend s with
| Some (tabs, key, md5) ->
[End2 (Some key, String.length tabs, mkp file line);
Start2 (key, String.length tabs, md5, mkp file line);
]
| None ->
(match lang.Lang.parse_mark_start s with
| Some (tabs, key, md5) ->
[Start2 (key, String.length tabs, md5, mkp file line)]
| None ->
(match lang.Lang.parse_mark_end s with
| Some (tabs, key) ->
[End2 (key, String.length tabs, mkp file line)]
| None ->
[Regular2 (s, mkp file line)]
)
)
) |> List.flatten |> readjust_start2_with_signatures file
in
the view does not need to contain the key at the end mark ; it 's
* redundant . But it is used for now to easily find the matching End2
* of a Start2 . If the key is not there , then have to find the
* corresponding End2 by not stopping at the first one and by
* counting .
* redundant. But it is used for now to easily find the matching End2
* of a Start2. If the key is not there, then have to find the
* corresponding End2 by not stopping at the first one and by
* counting.
*)
let rec aux xs =
match xs with
| [] -> []
| x::xs ->
(match x with
| Start2 (s, i, md5sum, pinfo) ->
let (body, _endmark, rest) =
try
Common2.split_when (fun x -> match x with
| End2 (s2,_, _pinfo2) ->
(match s2 with
| None -> raise Todo
| Some s2 -> s = s2
)
| _ -> false
) xs
with Not_found ->
failwith (s_of_pinfo pinfo ^ " could not find end mark")
in
let body' = aux (readjust_mark2_remove_indent i body) in
ChunkCode ({
chunk_key = s;
chunk_md5sum = md5sum;
pretty_print = None;
}, body', i)::aux rest
| End2 (_s, _i, pinfo) ->
failwith (s_of_pinfo pinfo ^ " a end mark without a start at")
| Regular2 (s, _pinfo) ->
RegularCode s::aux xs
)
in
let codetrees = aux xs' in
codetrees
let parse ~lang a =
parse2 ~lang a
let rec adjust_pretty_print_field view =
match view with
| [] -> ()
| x::xs ->
(match x with
| RegularCode _ ->
adjust_pretty_print_field xs
| ChunkCode (info, _, indent) ->
let same_key, rest =
Common.span (fun y ->
match y with
| ChunkCode (info2, _, indent2) ->
info.chunk_key = info2.chunk_key &&
| _ -> false
) (x::xs)
in
adjust_pretty_print_field rest;
same_key |> List.iter (function
| ChunkCode (_info, xs, _i) ->
adjust_pretty_print_field xs
| _ -> raise Impossible
);
let same_key' = same_key |> List.map (function
| ChunkCode(info, _, _) -> info
| _ -> raise Impossible
)
in
if List.length same_key' >= 2 then begin
let (hd, middle, tl) = Common2.head_middle_tail same_key' in
hd.pretty_print <- Some First;
tl.pretty_print <- Some Last;
middle |> List.iter (fun x -> x.pretty_print <- Some Middle);
end
)
assume first chunkcode corresponds to the filename ?
let unparse
?(md5sum_in_auxfile=false)
?(less_marks=false)
~lang views filename
=
let md5sums = ref [] in
if less_marks
then adjust_pretty_print_field views;
Common.with_open_outfile filename (fun (pr_no_nl, _chan) ->
let pr s = pr_no_nl (s ^ "\n") in
let pr_indent indent = Common2.do_n indent (fun () -> pr_no_nl " ") in
let rec aux (x, body, i) =
let key = x.chunk_key in
let md5sum =
if md5sum_in_auxfile
then begin
Common.push (spf "%s |%s" key
(Signature.to_hex (Common2.some x.chunk_md5sum)))
md5sums;
None
end
else x.chunk_md5sum
in
pr_indent (i);
(match x.pretty_print with
| None | Some First ->
pr (lang.Lang.unparse_mark_start key md5sum);
| (Some (Middle|Last)) ->
pr (lang.Lang.unparse_mark_startend key md5sum);
);
body |> List.iter (function
| RegularCode s ->
if Common2.is_blank_string s
then pr s
else begin
pr_indent i;
pr s;
end
| ChunkCode (x, body, j) ->
aux (x, body, i+j);
if decide to not show toplevel chunk
let key = x.chunk_key in
pr_indent ( i+j ) ;
pr ( spf " ( * nw_s : % s |%s
let key = x.chunk_key in
pr_indent (i+j);
pr (spf "(* nw_s: %s |%s*)" key x.chunk_md5sum);
aux (x, i+j);
pr_indent (i+j);
pr (spf "(* nw_e: %s *)" key);
*)
);
(match x.pretty_print with
| None | Some Last ->
pr_indent (i);
pr (lang.Lang.unparse_mark_end key);
| Some (First | Middle) ->
()
)
in
views |> List.iter (function
| ChunkCode (chunkcode, body, i) ->
aux (chunkcode, body, i)
| RegularCode _s ->
failwith "no chunk at toplevel"
);
()
);
if md5sum_in_auxfile then begin
Common.write_file ~file:(Signature.signaturefile_of_file filename)
(!md5sums |> List.rev |> Common.join "\n");
end;
()
|
1f2bf85956f789b547f28b098d49c881fa33506f1f671fe24aec7ed45d616d1c
|
hyperledger-labs/fabric-chaincode-ocaml
|
FabricChaincodeShim.ml
|
include Shim
module Protobuf = Protobuf
| null |
https://raw.githubusercontent.com/hyperledger-labs/fabric-chaincode-ocaml/bef9008ce8a20fb5155a855dc860f9062340b829/fabric-chaincode-shim/src/FabricChaincodeShim.ml
|
ocaml
|
include Shim
module Protobuf = Protobuf
|
|
87fd79fa8fd73e2e3aadb27e3ee25001e1356054ee9c968dfff9128aef41da30
|
rescript-lang/rescript-compiler
|
bsb_file_groups.mli
|
Copyright ( C ) 2018 - Hongbo Zhang , Authors of ReScript
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
type public = Export_none | Export_all | Export_set of Set_string.t
type build_generator = {
input : string list;
output : string list;
command : string;
}
type file_group = {
dir : string;
sources : Bsb_db.map;
resources : string list;
public : public;
is_dev : bool;
(* false means not in dev mode *)
generators : build_generator list;
(* output of [generators] should be added to [sources],
if it is [.ml,.mli,.res,.resi]
*)
}
type file_groups = file_group list
type t = private { files : file_groups; globbed_dirs : string list }
val empty : t
val merge : t -> t -> t
val cons : file_group:file_group -> ?globbed_dir:string -> t -> t
val is_empty : file_group -> bool
| null |
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/3aedb24ebbc3583adb04f65812fbfc49fb24cb5e/jscomp/bsb/bsb_file_groups.mli
|
ocaml
|
false means not in dev mode
output of [generators] should be added to [sources],
if it is [.ml,.mli,.res,.resi]
|
Copyright ( C ) 2018 - Hongbo Zhang , Authors of ReScript
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
type public = Export_none | Export_all | Export_set of Set_string.t
type build_generator = {
input : string list;
output : string list;
command : string;
}
type file_group = {
dir : string;
sources : Bsb_db.map;
resources : string list;
public : public;
is_dev : bool;
generators : build_generator list;
}
type file_groups = file_group list
type t = private { files : file_groups; globbed_dirs : string list }
val empty : t
val merge : t -> t -> t
val cons : file_group:file_group -> ?globbed_dir:string -> t -> t
val is_empty : file_group -> bool
|
665e31a6f201cc10100766da850691f009a028cc1ef7b6951b5f71314be6751f
|
astrada/ocaml-extjs
|
ext_Date.mli
|
* A set of useful static methods to deal with dateNo ...
{ % < p > A set of useful static methods to deal with date
Note that if < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > is required and loaded , it will copy all methods / properties to
this object for convenience</p >
< p > The date parsing and formatting syntax contains a subset of
< a href=" / date">PHP 's < code > date()</code > function</a > , and the formats that are
supported will provide results equivalent to their PHP versions.</p >
< p > The following is a list of all currently supported formats:</p >
< pre class= " " >
Format Description Example returned values
------ ----------------------------------------------------------------------- -----------------------
d Day of the month , 2 digits with leading zeros 01 to 31
D A short textual representation of the day of the week Mon to Sun
j Day of the month without leading zeros 1 to 31
l A full textual representation of the day of the week Sunday to Saturday
N ISO-8601 numeric representation of the day of the week 1 ( for Monday ) through 7 ( for Sunday )
S English ordinal suffix for the day of the month , 2 characters st , nd , rd or th . Works well with j
w Numeric representation of the day of the week 0 ( for Sunday ) to 6 ( for Saturday )
z The day of the year ( starting from 0 ) 0 to 364 ( 365 in leap years )
W ISO-8601 week number of year , weeks starting on Monday 01 to 53
F A full textual representation of a month , such as January or March January to December
m Numeric representation of a month , with leading zeros 01 to 12
M A short textual representation of a month Jan to Dec
n Numeric representation of a month , without leading zeros 1 to 12
t Number of days in the given month 28 to 31
L Whether it's a leap year 1 if it is a leap year , 0 otherwise .
o ISO-8601 year number ( identical to ( Y ) , but if the ISO week number ( W ) Examples : 1998 or 2004
belongs to the previous or next year , that year is used instead )
Y A full numeric representation of a year , 4 digits Examples : 1999 or 2003
y A two digit representation of a year Examples : 99 or 03
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
g 12 - hour format of an hour without leading zeros 1 to 12
G 24 - hour format of an hour without leading zeros 0 to 23
h 12 - hour format of an hour with leading zeros 01 to 12
H 24 - hour format of an hour with leading zeros 00 to 23
i Minutes , with leading zeros 00 to 59
s Seconds , with leading zeros 00 to 59
u Decimal fraction of a second Examples :
( minimum 1 digit , arbitrary number of digits allowed ) 001 ( i.e. ) or
100 ( i.e. 0.100s ) or
999 ( i.e. 0.999s ) or
999876543210 ( i.e. )
O Difference to Greenwich time ( GMT ) in hours and minutes Example : +1030
P Difference to Greenwich time ( GMT ) with colon between hours and minutes Example : -08:00
T Timezone abbreviation of the machine running the code Examples : EST , MDT , PDT ...
Z Timezone offset in seconds ( negative if west of UTC , positive if east ) -43200 to 50400
c ISO 8601 date
Notes : Examples :
1 ) If unspecified , the month / day defaults to the current month / day , 1991 or
the time defaults to midnight , while the timezone defaults to the 1992 - 10 or
browser 's timezone . If a time is specified , it must include both hours 1993 - 09 - 20 or
and minutes . The " T " delimiter , seconds , milliseconds and timezone 1994 - 08 - 19T16:20 + 01:00 or
are optional . 1995 - 07 - 18T17:21:28 - 02:00 or
2 ) The decimal fraction of a second , if specified , must contain at 1996 - 06 - 17T18:22:29.98765 + 03:00 or
least 1 digit ( there is no limit to the maximum number 1997 - 05 - 16T19:23:30,12345 - 0400 or
of digits allowed ) , and may be delimited by either a ' . ' or a ' , ' 1998 - 04 - 15T20:24:31.2468Z or
Refer to the examples on the right for the various levels of 1999 - 03 - 14T20:24:32Z or
date - time granularity which are supported , or see 2000 - 02 - 13T21:25:33
-datetime for more info . 2001 - 01 - 12 22:26:34
U Seconds since the Unix Epoch ( January 1 1970 00:00:00 GMT ) 1193432466 or -2138434463
MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ ( i.e. UTC milliseconds since epoch ) or
\/Date(1238606590509 + 0800)\/
time A javascript millisecond timestamp 1350024476440
timestamp A UNIX timestamp ( same as U ) 1350024866
< /pre >
< p > Example usage ( note that you must escape format specifiers with ' \ ' to render them as character literals):</p >
< pre><code>// Sample date :
// ' We d Jan 10 2007 15:05:01 GMT-0600 ( Central Standard Time ) '
var dt = new Date('1/10/2007 PM GMT-0600 ' ) ;
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , ' Y - m - d ' ) ) ; // 2007 - 01 - 10
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , ' F j , Y , : i a ' ) ) ; // January 10 , 2007 , 3:05 pm
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , ' l , \\t\\he jS \\of F Y h : i : s A ' ) ) ; // Wednesday , the 10th of January 2007 03:05:01 PM
< /code></pre >
< p > Here are some standard date / time patterns that you might find helpful . They
are not part of the source of < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > , but to use them you can simply copy this
block of code into any script that is included after < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > and they will also become
globally available on the Date object . Feel free to add or remove patterns as needed in your code.</p >
< pre><code > Ext . = \ {
ISO8601Long:"Y - m - d H : i : s " ,
ISO8601Short:"Y - m - d " ,
ShortDate : " n / j / Y " ,
LongDate : " l , F d , Y " ,
FullDateTime : " l , F d , Y g : i : s A " ,
MonthDay : " F d " ,
ShortTime : " g : i A " ,
LongTime : " g : i : s A " ,
SortableDateTime : " Y - m - d\\TH : i : s " ,
UniversalSortableDateTime : " Y - m - d H : i : sO " ,
YearMonth : " F , Y "
\ } ;
< /code></pre >
< p > Example usage:</p >
< pre><code > var dt = new Date ( ) ;
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , Ext . . ) ) ;
< /code></pre >
< p > Developer - written , custom formats may be used by supplying both a formatting and a parsing function
which perform to specialized requirements . The functions are stored in < a href="#!/api / Ext . Date - property - parseFunctions " rel="Ext . Date - property - parseFunctions " class="docClass">parseFunctions</a > and < a href="#!/api / Ext . Date - property - formatFunctions " rel="Ext . Date - property - formatFunctions " class="docClass">formatFunctions</a>.</p > % }
{% <p>A set of useful static methods to deal with date
Note that if <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a> is required and loaded, it will copy all methods / properties to
this object for convenience</p>
<p>The date parsing and formatting syntax contains a subset of
<a href="">PHP's <code>date()</code> function</a>, and the formats that are
supported will provide results equivalent to their PHP versions.</p>
<p>The following is a list of all currently supported formats:</p>
<pre class="">
Format Description Example returned values
------ ----------------------------------------------------------------------- -----------------------
d Day of the month, 2 digits with leading zeros 01 to 31
D A short textual representation of the day of the week Mon to Sun
j Day of the month without leading zeros 1 to 31
l A full textual representation of the day of the week Sunday to Saturday
N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
z The day of the year (starting from 0) 0 to 364 (365 in leap years)
W ISO-8601 week number of year, weeks starting on Monday 01 to 53
F A full textual representation of a month, such as January or March January to December
m Numeric representation of a month, with leading zeros 01 to 12
M A short textual representation of a month Jan to Dec
n Numeric representation of a month, without leading zeros 1 to 12
t Number of days in the given month 28 to 31
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
belongs to the previous or next year, that year is used instead)
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
g 12-hour format of an hour without leading zeros 1 to 12
G 24-hour format of an hour without leading zeros 0 to 23
h 12-hour format of an hour with leading zeros 01 to 12
H 24-hour format of an hour with leading zeros 00 to 23
i Minutes, with leading zeros 00 to 59
s Seconds, with leading zeros 00 to 59
u Decimal fraction of a second Examples:
(minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
100 (i.e. 0.100s) or
999 (i.e. 0.999s) or
999876543210 (i.e. 0.999876543210s)
O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
c ISO 8601 date
Notes: Examples:
1) If unspecified, the month / day defaults to the current month / day, 1991 or
the time defaults to midnight, while the timezone defaults to the 1992-10 or
browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
are optional. 1995-07-18T17:21:28-02:00 or
2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
date-time granularity which are supported, or see 2000-02-13T21:25:33
-datetime for more info. 2001-01-12 22:26:34
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
\/Date(1238606590509+0800)\/
time A javascript millisecond timestamp 1350024476440
timestamp A UNIX timestamp (same as U) 1350024866
</pre>
<p>Example usage (note that you must escape format specifiers with '\' to render them as character literals):</p>
<pre><code>// Sample date:
// 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, 'Y-m-d')); // 2007-01-10
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
</code></pre>
<p>Here are some standard date/time patterns that you might find helpful. They
are not part of the source of <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a>, but to use them you can simply copy this
block of code into any script that is included after <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a> and they will also become
globally available on the Date object. Feel free to add or remove patterns as needed in your code.</p>
<pre><code>Ext.Date.patterns = \{
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
\};
</code></pre>
<p>Example usage:</p>
<pre><code>var dt = new Date();
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, Ext.Date.patterns.ShortDate));
</code></pre>
<p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
which perform to specialized requirements. The functions are stored in <a href="#!/api/Ext.Date-property-parseFunctions" rel="Ext.Date-property-parseFunctions" class="docClass">parseFunctions</a> and <a href="#!/api/Ext.Date-property-formatFunctions" rel="Ext.Date-property-formatFunctions" class="docClass">formatFunctions</a>.</p> %}
*)
class type t =
object('self)
method _DAY : Js.js_string Js.t Js.prop
(** {% <p>Date interval constant</p> %}
Defaults to: ["d"]
*)
method _HOUR : Js.js_string Js.t Js.prop
(** {% <p>Date interval constant</p> %}
Defaults to: ["h"]
*)
method _MILLI : Js.js_string Js.t Js.prop
(** {% <p>Date interval constant</p> %}
Defaults to: ["ms"]
*)
method _MINUTE : Js.js_string Js.t Js.prop
(** {% <p>Date interval constant</p> %}
Defaults to: ["mi"]
*)
method _MONTH : Js.js_string Js.t Js.prop
(** {% <p>Date interval constant</p> %}
Defaults to: ["mo"]
*)
method _SECOND : Js.js_string Js.t Js.prop
(** {% <p>Date interval constant</p> %}
Defaults to: ["s"]
*)
method _YEAR : Js.js_string Js.t Js.prop
(** {% <p>Date interval constant</p> %}
Defaults to: ["y"]
*)
method dayNames : Js.js_string Js.t Js.js_array Js.t Js.prop
* { % < p > An array of textual day names .
Override these values for international dates.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - dayNames " rel="Ext . Date - property - dayNames " class="docClass">Ext . Date.dayNames</a > = [
' SundayInYourLang ' ,
' MondayInYourLang '
// ...
] ;
< /code></pre > % }
Defaults to : [ '' Sunday '' , '' Monday '' , '' Tuesday '' , '' Wednesday '' , '' Thursday '' , '' Friday '' , '' Saturday '' ]
Override these values for international dates.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-dayNames" rel="Ext.Date-property-dayNames" class="docClass">Ext.Date.dayNames</a> = [
'SundayInYourLang',
'MondayInYourLang'
// ...
];
</code></pre> %}
Defaults to: [''Sunday'', ''Monday'', ''Tuesday'', ''Wednesday'', ''Thursday'', ''Friday'', ''Saturday'']
*)
method defaultFormat : Js.js_string Js.t Js.prop
* { % < p > The date format string that the < a href="#!/api / Ext.util . Format - method - dateRenderer " rel="Ext.util . Format - method - dateRenderer " class="docClass">Ext.util . Format.dateRenderer</a >
and < a href="#!/api / Ext.util . Format - method - date " rel="Ext.util . Format - method - date " class="docClass">Ext.util . Format.date</a > functions use . See < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > for details.</p >
< p > This may be overridden in a locale file.</p > % }
Defaults to : [ " m / d / Y " ]
and <a href="#!/api/Ext.util.Format-method-date" rel="Ext.util.Format-method-date" class="docClass">Ext.util.Format.date</a> functions use. See <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a> for details.</p>
<p>This may be overridden in a locale file.</p> %}
Defaults to: ["m/d/Y"]
*)
method defaults : _ Js.t Js.prop
* { % < p > An object hash containing default date values used during date parsing.</p >
< p > The following properties are available:<div class="mdetail - params"><ul >
< li><code > y</code > : Number < div class="sub - desc">The default year value . ( defaults to undefined)</div></li >
< li><code > m</code > : Number < div class="sub - desc">The default 1 - based month value . ( defaults to undefined)</div></li >
< li><code > d</code > : Number < div class="sub - desc">The default day value . ( defaults to undefined)</div></li >
< li><code > h</code > : Number < div class="sub - desc">The default hour value . ( defaults to undefined)</div></li >
< li><code > i</code > : Number < div class="sub - desc">The default minute value . ( defaults to undefined)</div></li >
< li><code > s</code > : Number < div class="sub - desc">The default second value . ( defaults to undefined)</div></li >
< li><code > ms</code > : Number < div class="sub - desc">The default millisecond value . ( defaults to undefined)</div></li >
< /ul></div></p >
< p > Override these properties to customize the default date values used by the < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">parse</a > method.</p >
< p><strong > Note:</strong > In countries which experience Daylight Saving Time ( i.e. DST ) , the < code > h</code > , < code > i</code > , < code > s</code >
and < code > ms</code > properties may coincide with the exact time in which DST takes effect .
It is the responsibility of the developer to account for this.</p >
< p > Example Usage:</p >
< pre><code>// set default day value to the first day of the month
Ext . Date.defaults.d = 1 ;
// parse a February date string containing only year and month values .
// setting the default day value to 1 prevents weird date rollover issues
// when attempting to parse the following date string on , for example , March 31st 2009 .
< a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . , ' Y - m ' ) ; // returns a Date object representing February 1st 2009
< /code></pre > % }
Defaults to : [ \{\ } ]
<p>The following properties are available:<div class="mdetail-params"><ul>
<li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
<li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
<li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
<li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
<li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
<li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
<li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
</ul></div></p>
<p>Override these properties to customize the default date values used by the <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">parse</a> method.</p>
<p><strong>Note:</strong> In countries which experience Daylight Saving Time (i.e. DST), the <code>h</code>, <code>i</code>, <code>s</code>
and <code>ms</code> properties may coincide with the exact time in which DST takes effect.
It is the responsibility of the developer to account for this.</p>
<p>Example Usage:</p>
<pre><code>// set default day value to the first day of the month
Ext.Date.defaults.d = 1;
// parse a February date string containing only year and month values.
// setting the default day value to 1 prevents weird date rollover issues
// when attempting to parse the following date string on, for example, March 31st 2009.
<a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
</code></pre> %}
Defaults to: [\{\}]
*)
method formatCodes : _ Js.t Js.prop
* { % < p > The base format - code to formatting - function hashmap used by the < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">format</a > method .
Formatting functions are strings ( or functions which return strings ) which
will return the appropriate value when evaluated in the context of the Date object
from which the < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">format</a > method is called .
Add to / override these mappings for custom date formatting.</p >
< p><strong > Note:</strong > < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . Date.format</a > ( ) treats characters as literals if an appropriate mapping can not be found.</p >
< p > Example:</p >
< pre><code > Ext . Date.formatCodes.x = " < a href="#!/api / Ext.util . Format - method - leftPad " rel="Ext.util . Format - method - leftPad " class="docClass">Ext.util . Format.leftPad</a>(this.getDate ( ) , 2 , ' 0 ' ) " ;
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . Date ( ) , ' X ' ) ; // returns the current day of the month
< /code></pre > % }
Formatting functions are strings (or functions which return strings) which
will return the appropriate value when evaluated in the context of the Date object
from which the <a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">format</a> method is called.
Add to / override these mappings for custom date formatting.</p>
<p><strong>Note:</strong> <a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>() treats characters as literals if an appropriate mapping cannot be found.</p>
<p>Example:</p>
<pre><code>Ext.Date.formatCodes.x = "<a href="#!/api/Ext.util.Format-method-leftPad" rel="Ext.util.Format-method-leftPad" class="docClass">Ext.util.Format.leftPad</a>(this.getDate(), 2, '0')";
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(new Date(), 'X'); // returns the current day of the month
</code></pre> %}
*)
method formatFunctions : _ Js.t Js.prop
* { % < p > An object hash in which each property is a date formatting function . The property name is the
format string which corresponds to the produced formatted date string.</p >
< p > This object is automatically populated with date formatting functions as
date formats are requested for Ext standard formatting strings.</p >
< p > Custom formatting functions may be inserted into this object , keyed by a name which from then on
may be used as a format string to < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">format</a>.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - formatFunctions " rel="Ext . Date - property - formatFunctions " class="docClass">Ext . Date.formatFunctions</a>['x - date - format ' ] = myDateFormatter ;
< /code></pre >
< p > A formatting function should return a string representation of the passed Date object , and is passed the following parameters:<div class="mdetail - params"><ul >
< li><code > date</code > : Date < div class="sub - desc">The Date to format.</div></li >
< /ul></div></p >
< p > To enable date strings to also be < em > parsed</em > according to that format , a corresponding
parsing function must be placed into the < a href="#!/api / Ext . Date - property - parseFunctions " rel="Ext . Date - property - parseFunctions " class="docClass">parseFunctions</a > property.</p > % }
format string which corresponds to the produced formatted date string.</p>
<p>This object is automatically populated with date formatting functions as
date formats are requested for Ext standard formatting strings.</p>
<p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
may be used as a format string to <a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">format</a>.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-formatFunctions" rel="Ext.Date-property-formatFunctions" class="docClass">Ext.Date.formatFunctions</a>['x-date-format'] = myDateFormatter;
</code></pre>
<p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
<li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
</ul></div></p>
<p>To enable date strings to also be <em>parsed</em> according to that format, a corresponding
parsing function must be placed into the <a href="#!/api/Ext.Date-property-parseFunctions" rel="Ext.Date-property-parseFunctions" class="docClass">parseFunctions</a> property.</p> %}
*)
method monthNames : Js.js_string Js.t Js.js_array Js.t Js.prop
* { % < p > An array of textual month names .
Override these values for international dates.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - monthNames " rel="Ext . Date - property - monthNames " class="docClass">Ext . > = [
' JanInYourLang ' ,
' FebInYourLang '
// ...
] ;
< /code></pre > % }
Defaults to : [ '' January '' , '' February '' , '' March '' , '' April '' , '' May '' , '' June '' , '' July '' , '' August '' , '' September '' , '' October '' , '' November '' , '' December '' ]
Override these values for international dates.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-monthNames" rel="Ext.Date-property-monthNames" class="docClass">Ext.Date.monthNames</a> = [
'JanInYourLang',
'FebInYourLang'
// ...
];
</code></pre> %}
Defaults to: [''January'', ''February'', ''March'', ''April'', ''May'', ''June'', ''July'', ''August'', ''September'', ''October'', ''November'', ''December'']
*)
method monthNumbers : _ Js.t Js.prop
* { % < p > An object hash of zero - based JavaScript month numbers ( with short month names as keys . < strong > Note:</strong > keys are case - sensitive ) .
Override these values for international dates.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - monthNumbers " rel="Ext . Date - property - monthNumbers " class="docClass">Ext . Date.monthNumbers</a > = \ {
' LongJanNameInYourLang ' : 0 ,
' ShortJanNameInYourLang':0 ,
' LongFebNameInYourLang':1 ,
' ShortFebNameInYourLang':1
// ...
\ } ;
< /code></pre > % }
Defaults to : [ \{January : 0 , Jan : 0 , February : 1 , Feb : 1 , March : 2 , Mar : 2 , April : 3 , Apr : 3 , May : 4 , June : 5 , : 5 , July : 6 , Jul : 6 , August : 7 , Aug : 7 , September : 8 , Sep : 8 , October : 9 , Oct : 9 , November : 10 , Nov : 10 , December : 11 , Dec : 11\ } ]
Override these values for international dates.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-monthNumbers" rel="Ext.Date-property-monthNumbers" class="docClass">Ext.Date.monthNumbers</a> = \{
'LongJanNameInYourLang': 0,
'ShortJanNameInYourLang':0,
'LongFebNameInYourLang':1,
'ShortFebNameInYourLang':1
// ...
\};
</code></pre> %}
Defaults to: [\{January: 0, Jan: 0, February: 1, Feb: 1, March: 2, Mar: 2, April: 3, Apr: 3, May: 4, June: 5, Jun: 5, July: 6, Jul: 6, August: 7, Aug: 7, September: 8, Sep: 8, October: 9, Oct: 9, November: 10, Nov: 10, December: 11, Dec: 11\}]
*)
method parseFunctions : _ Js.t Js.prop
* { % < p > An object hash in which each property is a date parsing function . The property name is the
format string which that function parses.</p >
< p > This object is automatically populated with date parsing functions as
date formats are requested for Ext standard formatting strings.</p >
< p > Custom parsing functions may be inserted into this object , keyed by a name which from then on
may be used as a format string to < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - parseFunctions " rel="Ext . Date - property - parseFunctions " class="docClass">Ext . Date.parseFunctions</a>['x - date - format ' ] = myDateParser ;
< /code></pre >
< p > A parsing function should return a Date object , and is passed the following parameters:<div class="mdetail - params"><ul >
< li><code > date</code > : String < div class="sub - desc">The date string to parse.</div></li >
< li><code > > : Boolean < div class="sub - desc">True to validate date strings while parsing
( i.e. prevent JavaScript Date " rollover " ) ( The default must be < code > false</code > ) .
Invalid date strings should return < code > when parsed.</div></li >
< /ul></div></p >
< p > To enable Dates to also be < em > formatted</em > according to that format , a corresponding
formatting function must be placed into the < a href="#!/api / Ext . Date - property - formatFunctions " rel="Ext . Date - property - formatFunctions " class="docClass">formatFunctions</a > property.</p > % }
format string which that function parses.</p>
<p>This object is automatically populated with date parsing functions as
date formats are requested for Ext standard formatting strings.</p>
<p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
may be used as a format string to <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">parse</a>.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-parseFunctions" rel="Ext.Date-property-parseFunctions" class="docClass">Ext.Date.parseFunctions</a>['x-date-format'] = myDateParser;
</code></pre>
<p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
<li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
<li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
(i.e. prevent JavaScript Date "rollover") (The default must be <code>false</code>).
Invalid date strings should return <code>null</code> when parsed.</div></li>
</ul></div></p>
<p>To enable Dates to also be <em>formatted</em> according to that format, a corresponding
formatting function must be placed into the <a href="#!/api/Ext.Date-property-formatFunctions" rel="Ext.Date-property-formatFunctions" class="docClass">formatFunctions</a> property.</p> %}
*)
method useStrict : bool Js.t Js.prop
* { % < p > Global flag which determines if strict date parsing should be used .
Strict date parsing will not roll - over invalid dates , which is the
default behavior of JavaScript Date objects .
( see < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">parse</a > for more information)</p > % }
Defaults to : [ false ]
Strict date parsing will not roll-over invalid dates, which is the
default behavior of JavaScript Date objects.
(see <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">parse</a> for more information)</p> %}
Defaults to: [false]
*)
method add : Js.date Js.t -> Js.js_string Js.t -> Js.number Js.t ->
Js.date Js.t Js.meth
* { % < p > Provides a convenient method for performing basic date arithmetic . This method
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p >
< p > Examples:</p >
< pre><code>// Basic usage :
var dt = < a href="#!/api / Ext . Date - method - add " rel="Ext . Date - method - add " class="docClass">Ext . Date.add</a>(new Date('10/29/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 5 ) ;
console.log(dt ) ; // returns ' Fri Nov 03 2006 00:00:00 '
// Negative values will be subtracted :
var dt2 = < a href="#!/api / Ext . Date - method - add " rel="Ext . Date - method - add " class="docClass">Ext . Date.add</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , -5 ) ;
console.log(dt2 ) ; // returns ' Tue Sep 26 2006 00:00:00 '
// Decimal values can be used :
var dt3 = < a href="#!/api / Ext . Date - method - add " rel="Ext . Date - method - add " class="docClass">Ext . Date.add</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 1.25 ) ;
console.log(dt3 ) ; // returns ' Mon Oct 02 2006 06:00:00 '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to modify</p > % }
}
{ - interval : [ Js.js_string Js.t ]
{ % < p > A valid date interval enum value.</p > % }
}
{ - value : [ Js.number Js.t ]
{ % < p > The amount to add to the current date.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The new Date instance.</p > % }
}
}
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p>
<p>Examples:</p>
<pre><code>// Basic usage:
var dt = <a href="#!/api/Ext.Date-method-add" rel="Ext.Date-method-add" class="docClass">Ext.Date.add</a>(new Date('10/29/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 5);
console.log(dt); // returns 'Fri Nov 03 2006 00:00:00'
// Negative values will be subtracted:
var dt2 = <a href="#!/api/Ext.Date-method-add" rel="Ext.Date-method-add" class="docClass">Ext.Date.add</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, -5);
console.log(dt2); // returns 'Tue Sep 26 2006 00:00:00'
// Decimal values can be used:
var dt3 = <a href="#!/api/Ext.Date-method-add" rel="Ext.Date-method-add" class="docClass">Ext.Date.add</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 1.25);
console.log(dt3); // returns 'Mon Oct 02 2006 06:00:00'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to modify</p> %}
}
{- interval: [Js.js_string Js.t]
{% <p>A valid date interval enum value.</p> %}
}
{- value: [Js.number Js.t]
{% <p>The amount to add to the current date.</p> %}
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The new Date instance.</p> %}
}
}
*)
method between : Js.date Js.t -> Js.date Js.t -> Js.date Js.t -> bool Js.t
Js.meth
* { % < p > Checks if a date falls on or between the given start and end dates.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to check</p > % }
}
{ - start : [ Js.date Js.t ] { % < p > Start date</p > % }
}
{ - _ end : [ Js.date Js.t ]
{ % < p > End date</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if this date falls on or between the given start and end dates.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to check</p> %}
}
{- start: [Js.date Js.t] {% <p>Start date</p> %}
}
{- _end: [Js.date Js.t]
{% <p>End date</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if this date falls on or between the given start and end dates.</p> %}
}
}
*)
method clearTime : Js.date Js.t -> bool Js.t Js.optdef -> Js.date Js.t
Js.meth
* { % < p > Attempts to clear all time information from this Date by setting the time to midnight of the same day ,
automatically adjusting for Daylight Saving Time ( DST ) where applicable.</p >
< p><strong > Note:</strong > DST timezone information for the browser 's host operating system is assumed to be up - to - date.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
{ - clone : [ bool Js.t ] ( optional )
{ % < p><code > true</code > to create a clone of this date , clear the time and return it.</p > % }
Defaults to : false
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > this or the clone.</p > % }
}
}
automatically adjusting for Daylight Saving Time (DST) where applicable.</p>
<p><strong>Note:</strong> DST timezone information for the browser's host operating system is assumed to be up-to-date.</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
{- clone: [bool Js.t] (optional)
{% <p><code>true</code> to create a clone of this date, clear the time and return it.</p> %}
Defaults to: false
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>this or the clone.</p> %}
}
}
*)
method clone : Js.date Js.t -> Js.date Js.t Js.meth
* { % < p > Creates and returns a new Date instance with the exact same date value as the called instance .
Dates are copied and passed by reference , so if a copied date variable is modified later , the original
variable will also be changed . When the intention is to create a new variable that will not
modify the original instance , you should create a clone.</p >
< p > Example of correctly cloning a date:</p >
< pre><code>//wrong way :
var orig = new Date('10/1/2006 ' ) ;
var copy = orig ;
) ;
console.log(orig ) ; // returns ' Thu Oct 05 2006 ' !
//correct way :
var orig = new Date('10/1/2006 ' ) ,
copy = < a href="#!/api / Ext . Date - method - clone " rel="Ext . Date - method - clone " class="docClass">Ext . Date.clone</a>(orig ) ;
) ;
console.log(orig ) ; // returns ' Thu Oct 01 2006 '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The new Date instance.</p > % }
}
}
Dates are copied and passed by reference, so if a copied date variable is modified later, the original
variable will also be changed. When the intention is to create a new variable that will not
modify the original instance, you should create a clone.</p>
<p>Example of correctly cloning a date:</p>
<pre><code>//wrong way:
var orig = new Date('10/1/2006');
var copy = orig;
copy.setDate(5);
console.log(orig); // returns 'Thu Oct 05 2006'!
//correct way:
var orig = new Date('10/1/2006'),
copy = <a href="#!/api/Ext.Date-method-clone" rel="Ext.Date-method-clone" class="docClass">Ext.Date.clone</a>(orig);
copy.setDate(5);
console.log(orig); // returns 'Thu Oct 01 2006'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date.</p> %}
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The new Date instance.</p> %}
}
}
*)
method format : Js.date Js.t -> Js.js_string Js.t -> Js.js_string Js.t
Js.meth
* { % < p > Formats a date given the supplied format string.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to > % }
}
{ - format : [ Js.js_string Js.t ]
{ % < p > The format string</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ]
{ % < p > The formatted date or an empty string if date parameter is not a JavaScript Date object</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to format</p> %}
}
{- format: [Js.js_string Js.t]
{% <p>The format string</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t]
{% <p>The formatted date or an empty string if date parameter is not a JavaScript Date object</p> %}
}
}
*)
method formatContainsDateInfo : Js.js_string Js.t -> bool Js.t Js.meth
* { % < p > Checks if the specified format contains information about
anything other than the time.</p > % }
{ b Parameters } :
{ ul { - format : [ Js.js_string Js.t ]
{ % < p > The format to check</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p > True if the format contains information about
date / day information.</p > % }
}
}
anything other than the time.</p> %}
{b Parameters}:
{ul {- format: [Js.js_string Js.t]
{% <p>The format to check</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p>True if the format contains information about
date/day information.</p> %}
}
}
*)
method formatContainsHourInfo : Js.js_string Js.t -> bool Js.t Js.meth
(** {% <p>Checks if the specified format contains hour information</p> %}
{b Parameters}:
{ul {- format: [Js.js_string Js.t]
{% <p>The format to check</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p>True if the format contains hour information</p> %}
}
}
*)
method getDayOfYear : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the numeric day number of the year , adjusted for leap year.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p>0 to 364 ( 365 in leap years).</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>0 to 364 (365 in leap years).</p> %}
}
}
*)
method getDaysInMonth : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the number of days in the current month , adjusted for leap year.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The number of days in the month.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The number of days in the month.</p> %}
}
}
*)
method getElapsed : Js.date Js.t -> Js.date Js.t Js.optdef ->
Js.number Js.t Js.meth
* { % < p > Returns the number of milliseconds between two dates.</p > % }
{ b Parameters } :
{ ul { - dateA : [ Js.date Js.t ]
{ % < p > The first date.</p > % }
}
{ - dateB : [ Js.date Js.t ] ( optional ) { % < p > The second date.</p > % }
Defaults to : new Date ( )
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The difference in milliseconds</p > % }
}
}
{b Parameters}:
{ul {- dateA: [Js.date Js.t]
{% <p>The first date.</p> %}
}
{- dateB: [Js.date Js.t] (optional) {% <p>The second date.</p> %}
Defaults to: new Date()
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The difference in milliseconds</p> %}
}
}
*)
method getFirstDateOfMonth : Js.date Js.t -> Js.date Js.t Js.meth
* { % < p > Get the date of the first day of the month in which this date resides.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ] { % < p > The date</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t] {% <p>The date</p> %}
}
}
*)
method getFirstDayOfMonth : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the first day of the current month , adjusted for leap year . The returned value
is the numeric day index within the week ( 0 - 6 ) which can be used in conjunction with
the < a href="#!/api / Ext . Date - property - monthNames " rel="Ext . Date - property - monthNames " class="docClass">monthNames</a > array to retrieve the textual day >
< p > Example:</p >
< pre><code > var dt = new Date('1/10/2007 ' ) ,
firstDay = < a href="#!/api / Ext . Date - method - getFirstDayOfMonth " rel="Ext . Date - method - getFirstDayOfMonth " class="docClass">Ext . ) ;
console.log(<a href="#!/api / Ext . Date - property - dayNames " rel="Ext . Date - property - dayNames " class="docClass">Ext . Date.dayNames</a>[firstDay ] ) ; // output : ' Monday '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The day number ( 0 - 6).</p > % }
}
}
is the numeric day index within the week (0-6) which can be used in conjunction with
the <a href="#!/api/Ext.Date-property-monthNames" rel="Ext.Date-property-monthNames" class="docClass">monthNames</a> array to retrieve the textual day name.</p>
<p>Example:</p>
<pre><code>var dt = new Date('1/10/2007'),
firstDay = <a href="#!/api/Ext.Date-method-getFirstDayOfMonth" rel="Ext.Date-method-getFirstDayOfMonth" class="docClass">Ext.Date.getFirstDayOfMonth</a>(dt);
console.log(<a href="#!/api/Ext.Date-property-dayNames" rel="Ext.Date-property-dayNames" class="docClass">Ext.Date.dayNames</a>[firstDay]); // output: 'Monday'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The day number (0-6).</p> %}
}
}
*)
method getGMTOffset : Js.date Js.t -> bool Js.t Js.optdef ->
Js.js_string Js.t Js.meth
* { % < p > Get the offset from GMT of the current date ( equivalent to the format specifier ' O').</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
{ - colon : [ bool Js.t ] ( optional )
{ % < p > true to separate the hours and minutes with a colon.</p > % }
Defaults to : false
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ]
{ % < p > The 4 - character offset string prefixed with + or - ( e.g. ' -0600').</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
{- colon: [bool Js.t] (optional)
{% <p>true to separate the hours and minutes with a colon.</p> %}
Defaults to: false
}
}
{b Returns}:
{ul {- [Js.js_string Js.t]
{% <p>The 4-character offset string prefixed with + or - (e.g. '-0600').</p> %}
}
}
*)
method getLastDateOfMonth : Js.date Js.t -> Js.date Js.t Js.meth
(** {% <p>Get the date of the last day of the month in which this date resides.</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t] {% <p>The date</p> %}
}
}
*)
method getLastDayOfMonth : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the last day of the current month , adjusted for leap year . The returned value
is the numeric day index within the week ( 0 - 6 ) which can be used in conjunction with
the < a href="#!/api / Ext . Date - property - monthNames " rel="Ext . Date - property - monthNames " class="docClass">monthNames</a > array to retrieve the textual day >
< p > Example:</p >
< pre><code > var dt = new Date('1/10/2007 ' ) ,
lastDay = < a href="#!/api / Ext . Date - method - getLastDayOfMonth " rel="Ext . Date - method - getLastDayOfMonth " class="docClass">Ext . ) ;
console.log(<a href="#!/api / Ext . Date - property - dayNames " rel="Ext . Date - property - dayNames " class="docClass">Ext . Date.dayNames</a>[lastDay ] ) ; // output : ' Wednesday '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The day number ( 0 - 6).</p > % }
}
}
is the numeric day index within the week (0-6) which can be used in conjunction with
the <a href="#!/api/Ext.Date-property-monthNames" rel="Ext.Date-property-monthNames" class="docClass">monthNames</a> array to retrieve the textual day name.</p>
<p>Example:</p>
<pre><code>var dt = new Date('1/10/2007'),
lastDay = <a href="#!/api/Ext.Date-method-getLastDayOfMonth" rel="Ext.Date-method-getLastDayOfMonth" class="docClass">Ext.Date.getLastDayOfMonth</a>(dt);
console.log(<a href="#!/api/Ext.Date-property-dayNames" rel="Ext.Date-property-dayNames" class="docClass">Ext.Date.dayNames</a>[lastDay]); // output: 'Wednesday'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The day number (0-6).</p> %}
}
}
*)
method getMonthNumber : Js.js_string Js.t -> Js.number Js.t Js.meth
* { % < p > Get the zero - based JavaScript month number for the given short / full month name .
Override this function for international dates.</p > % }
{ b Parameters } :
{ ul { - name : [ Js.js_string Js.t ]
{ % < p > The short / full month name.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ]
{ % < p > The zero - based JavaScript month number.</p > % }
}
}
Override this function for international dates.</p> %}
{b Parameters}:
{ul {- name: [Js.js_string Js.t]
{% <p>The short/full month name.</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t]
{% <p>The zero-based JavaScript month number.</p> %}
}
}
*)
method getShortDayName : Js.number Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the short day name for the given day number .
Override this function for international dates.</p > % }
{ b Parameters } :
{ ul { - day : [ Js.number Js.t ]
{ % < p > A zero - based JavaScript day number.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p > The short day > % }
}
}
Override this function for international dates.</p> %}
{b Parameters}:
{ul {- day: [Js.number Js.t]
{% <p>A zero-based JavaScript day number.</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>The short day name.</p> %}
}
}
*)
method getShortMonthName : Js.number Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the short month name for the given month number .
Override this function for international dates.</p > % }
{ b Parameters } :
{ ul { - month : [ Js.number Js.t ]
{ % < p > A zero - based JavaScript month number.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p > The short month > % }
}
}
Override this function for international dates.</p> %}
{b Parameters}:
{ul {- month: [Js.number Js.t]
{% <p>A zero-based JavaScript month number.</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>The short month name.</p> %}
}
}
*)
method getSuffix : Js.date Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the English ordinal suffix of the current day ( equivalent to the format specifier ' S').</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p>'st , ' nd ' , ' rd ' or ' th'.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>'st, 'nd', 'rd' or 'th'.</p> %}
}
}
*)
method getTimezone : Js.date Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the timezone abbreviation of the current date ( equivalent to the format specifier ' >
< p><strong > Note:</strong > The date string returned by the JavaScript Date object 's < code > toString()</code > method varies
between browsers ( e.g. FF vs IE ) and system region settings ( e.g. IE in Asia vs IE in America ) .
For a given date string e.g. " Thu Oct 25 2007 22:55:35 GMT+0800 ( Malay Peninsula Standard Time ) " ,
getTimezone ( ) first tries to get the timezone abbreviation from between a pair of parentheses
( which may or may not be present ) , failing which it proceeds to get the timezone abbreviation
from the GMT offset portion of the date string.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ]
{ % < p > The abbreviated timezone name ( e.g. ' CST ' , ' PDT ' , ' EDT ' , ' MPST ' ... ) .</p > % }
}
}
<p><strong>Note:</strong> The date string returned by the JavaScript Date object's <code>toString()</code> method varies
between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
(which may or may not be present), failing which it proceeds to get the timezone abbreviation
from the GMT offset portion of the date string.</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t]
{% <p>The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).</p> %}
}
}
*)
method getWeekOfYear : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the numeric ISO-8601 week number of the year .
( equivalent to the format specifier ' W ' , but without a leading > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p>1 to 53</p > % }
}
}
(equivalent to the format specifier 'W', but without a leading zero).</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>1 to 53</p> %}
}
}
*)
method isDST : Js.date Js.t -> bool Js.t Js.meth
* { % < p > Checks if the current date is affected by Daylight Saving Time ( DST).</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if the current date is affected by DST.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if the current date is affected by DST.</p> %}
}
}
*)
method isEqual : Js.date Js.t -> Js.date Js.t -> bool Js.t Js.meth
* { % < p > Compares if two dates are equal by comparing their values.</p > % }
{ b Parameters } :
{ ul { - date1 : [ Js.date Js.t ]
}
{ - date2 : [ Js.date Js.t ]
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if the date values are equal</p > % }
}
}
{b Parameters}:
{ul {- date1: [Js.date Js.t]
}
{- date2: [Js.date Js.t]
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if the date values are equal</p> %}
}
}
*)
method isLeapYear : Js.date Js.t -> bool Js.t Js.meth
* { % < p > Checks if the current date falls within a leap year.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p > True if the current date falls within a leap year , false otherwise.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p>True if the current date falls within a leap year, false otherwise.</p> %}
}
}
*)
method isValid : Js.number Js.t -> Js.number Js.t -> Js.number Js.t ->
Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef ->
Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> bool Js.t Js.meth
* { % < p > Checks if the passed Date parameters will cause a JavaScript Date " rollover".</p > % }
{ b Parameters } :
{ ul { - year : [ Js.number Js.t ]
{ % < p>4 - digit year</p > % }
}
{ - month : [ Js.number Js.t ]
{ % < p>1 - based month - of - year</p > % }
}
{ - day : [ Js.number Js.t ]
{ % < p > Day of month</p > % }
}
{ - hour : [ Js.number Js.t ] ( optional )
{ % < p > Hour</p > % }
}
{ - minute : [ Js.number Js.t ] ( optional )
{ % < p > Minute</p > % }
}
{ - second : [ Js.number Js.t ] ( optional )
{ % < p > Second</p > % }
}
{ - millisecond : [ Js.number Js.t ] ( optional )
{ % < p > Millisecond</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if the passed parameters do not cause a Date " rollover " , < code > false</code > otherwise.</p > % }
}
}
{b Parameters}:
{ul {- year: [Js.number Js.t]
{% <p>4-digit year</p> %}
}
{- month: [Js.number Js.t]
{% <p>1-based month-of-year</p> %}
}
{- day: [Js.number Js.t]
{% <p>Day of month</p> %}
}
{- hour: [Js.number Js.t] (optional)
{% <p>Hour</p> %}
}
{- minute: [Js.number Js.t] (optional)
{% <p>Minute</p> %}
}
{- second: [Js.number Js.t] (optional)
{% <p>Second</p> %}
}
{- millisecond: [Js.number Js.t] (optional)
{% <p>Millisecond</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if the passed parameters do not cause a Date "rollover", <code>false</code> otherwise.</p> %}
}
}
*)
method now : Js.number Js.t Js.meth
* { % < p > Returns the current timestamp.</p > % }
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > Milliseconds since UNIX epoch.</p > % }
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>Milliseconds since UNIX epoch.</p> %}
}
}
*)
method parse : Js.js_string Js.t -> Js.js_string Js.t ->
bool Js.t Js.optdef -> Js.date Js.t Js.meth
* { % < p > Parses the passed string using the specified date format .
Note that this function expects normal calendar dates , meaning that months are 1 - based ( i.e. 1 = January ) .
The < a href="#!/api / Ext . Date - property - defaults " rel="Ext . Date - property - defaults " > hash will be used for any date value ( i.e. year , month , day , hour , minute , second or millisecond )
which can not be found in the passed string . If a corresponding default date value has not been specified in the < a href="#!/api / Ext . Date - property - defaults " rel="Ext . Date - property - defaults " > hash ,
the current date 's year , month , day or DST - adjusted zero - hour time value will be used instead .
Keep in mind that the input date string must precisely match the specified format string
in order for the parse operation to be successful ( failed parse operations return a null value).</p >
< p > Example:</p >
< pre><code>//dt = Fri May 25 2007 ( current date )
var dt = new Date ( ) ;
//dt = Thu May 25 2006 ( today&#39;s month / day in 2006 )
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 " , " Y " ) ;
//dt = Sun Jan 15 2006 ( all date parts specified )
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 - 01 - 15 " , " Y - m - d " ) ;
//dt = Sun Jan 15 2006 15:20:01
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 - 01 - 15 3:20:01 PM " , " Y - m - d g : i : s A " ) ;
// attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 - 02 - 29 03:20:01 " , " Y - m - d H : i : s " , true ) ; // returns null
< /code></pre > % }
{ b Parameters } :
{ ul { - input : [ Js.js_string Js.t ]
{ % < p > The raw date string.</p > % }
}
{ - format : [ Js.js_string Js.t ]
{ % < p > The expected date string > % }
}
{ - strict : [ bool Js.t ] ( optional )
{ % < p><code > true</code > to validate date strings while parsing ( i.e. prevents JavaScript Date " rollover " ) .
Invalid date strings will return < code > when parsed.</p > % }
Defaults to : false
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The parsed Date.</p > % }
}
}
Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
The <a href="#!/api/Ext.Date-property-defaults" rel="Ext.Date-property-defaults" class="docClass">defaults</a> hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
which cannot be found in the passed string. If a corresponding default date value has not been specified in the <a href="#!/api/Ext.Date-property-defaults" rel="Ext.Date-property-defaults" class="docClass">defaults</a> hash,
the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
Keep in mind that the input date string must precisely match the specified format string
in order for the parse operation to be successful (failed parse operations return a null value).</p>
<p>Example:</p>
<pre><code>//dt = Fri May 25 2007 (current date)
var dt = new Date();
//dt = Thu May 25 2006 (today&#39;s month/day in 2006)
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006", "Y");
//dt = Sun Jan 15 2006 (all date parts specified)
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006-01-15", "Y-m-d");
//dt = Sun Jan 15 2006 15:20:01
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
// attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
</code></pre> %}
{b Parameters}:
{ul {- input: [Js.js_string Js.t]
{% <p>The raw date string.</p> %}
}
{- format: [Js.js_string Js.t]
{% <p>The expected date string format.</p> %}
}
{- strict: [bool Js.t] (optional)
{% <p><code>true</code> to validate date strings while parsing (i.e. prevents JavaScript Date "rollover").
Invalid date strings will return <code>null</code> when parsed.</p> %}
Defaults to: false
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The parsed Date.</p> %}
}
}
*)
method subtract : Js.date Js.t -> Js.js_string Js.t -> Js.number Js.t ->
Js.date Js.t Js.meth
* { % < p > Provides a convenient method for performing basic date arithmetic . This method
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p >
< p > Examples:</p >
< pre><code>// Basic usage :
var dt = < a href="#!/api / Ext . Date - method - subtract " rel="Ext . Date - method - subtract " class="docClass">Ext . Date.subtract</a>(new Date('10/29/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 5 ) ;
console.log(dt ) ; // returns ' Tue Oct 24 2006 00:00:00 '
// Negative values will be added :
var dt2 = < a href="#!/api / Ext . Date - method - subtract " rel="Ext . Date - method - subtract " class="docClass">Ext . Date.subtract</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , -5 ) ;
console.log(dt2 ) ; // returns ' Fri Oct 6 2006 00:00:00 '
// Decimal values can be used :
var dt3 = < a href="#!/api / Ext . Date - method - subtract " rel="Ext . Date - method - subtract " class="docClass">Ext . Date.subtract</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 1.25 ) ;
console.log(dt3 ) ; // returns ' Fri Sep 29 2006 06:00:00 '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to modify</p > % }
}
{ - interval : [ Js.js_string Js.t ]
{ % < p > A valid date interval enum value.</p > % }
}
{ - value : [ Js.number Js.t ]
{ % < p > The amount to subtract from the current date.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The new Date instance.</p > % }
}
}
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p>
<p>Examples:</p>
<pre><code>// Basic usage:
var dt = <a href="#!/api/Ext.Date-method-subtract" rel="Ext.Date-method-subtract" class="docClass">Ext.Date.subtract</a>(new Date('10/29/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 5);
console.log(dt); // returns 'Tue Oct 24 2006 00:00:00'
// Negative values will be added:
var dt2 = <a href="#!/api/Ext.Date-method-subtract" rel="Ext.Date-method-subtract" class="docClass">Ext.Date.subtract</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, -5);
console.log(dt2); // returns 'Fri Oct 6 2006 00:00:00'
// Decimal values can be used:
var dt3 = <a href="#!/api/Ext.Date-method-subtract" rel="Ext.Date-method-subtract" class="docClass">Ext.Date.subtract</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 1.25);
console.log(dt3); // returns 'Fri Sep 29 2006 06:00:00'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to modify</p> %}
}
{- interval: [Js.js_string Js.t]
{% <p>A valid date interval enum value.</p> %}
}
{- value: [Js.number Js.t]
{% <p>The amount to subtract from the current date.</p> %}
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The new Date instance.</p> %}
}
}
*)
method unescapeFormat : Js.js_string Js.t -> Js.js_string Js.t Js.meth
* { % < p > Removes all escaping for a date format string . In date formats ,
using a ' \ ' can be used to escape special characters.</p > % }
{ b Parameters } :
{ ul { - format : [ Js.js_string Js.t ]
{ % < p > The format to unescape</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p > The unescaped > % }
}
}
using a '\' can be used to escape special characters.</p> %}
{b Parameters}:
{ul {- format: [Js.js_string Js.t]
{% <p>The format to unescape</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>The unescaped format</p> %}
}
}
*)
end
class type configs =
object('self)
end
class type events =
object
end
class type statics =
object
end
val get_instance : unit -> t Js.t
(** Singleton instance for lazy-loaded modules. *)
val instance : t Js.t
* instance .
val of_configs : configs Js.t -> t Js.t
(** [of_configs c] casts a config object [c] to an instance of class [t] *)
val to_configs : t Js.t -> configs Js.t
(** [to_configs o] casts instance [o] of class [t] to a config object *)
| null |
https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_Date.mli
|
ocaml
|
* {% <p>Date interval constant</p> %}
Defaults to: ["d"]
* {% <p>Date interval constant</p> %}
Defaults to: ["h"]
* {% <p>Date interval constant</p> %}
Defaults to: ["ms"]
* {% <p>Date interval constant</p> %}
Defaults to: ["mi"]
* {% <p>Date interval constant</p> %}
Defaults to: ["mo"]
* {% <p>Date interval constant</p> %}
Defaults to: ["s"]
* {% <p>Date interval constant</p> %}
Defaults to: ["y"]
* {% <p>Checks if the specified format contains hour information</p> %}
{b Parameters}:
{ul {- format: [Js.js_string Js.t]
{% <p>The format to check</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p>True if the format contains hour information</p> %}
}
}
* {% <p>Get the date of the last day of the month in which this date resides.</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t] {% <p>The date</p> %}
}
}
* Singleton instance for lazy-loaded modules.
* [of_configs c] casts a config object [c] to an instance of class [t]
* [to_configs o] casts instance [o] of class [t] to a config object
|
* A set of useful static methods to deal with dateNo ...
{ % < p > A set of useful static methods to deal with date
Note that if < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > is required and loaded , it will copy all methods / properties to
this object for convenience</p >
< p > The date parsing and formatting syntax contains a subset of
< a href=" / date">PHP 's < code > date()</code > function</a > , and the formats that are
supported will provide results equivalent to their PHP versions.</p >
< p > The following is a list of all currently supported formats:</p >
< pre class= " " >
Format Description Example returned values
------ ----------------------------------------------------------------------- -----------------------
d Day of the month , 2 digits with leading zeros 01 to 31
D A short textual representation of the day of the week Mon to Sun
j Day of the month without leading zeros 1 to 31
l A full textual representation of the day of the week Sunday to Saturday
N ISO-8601 numeric representation of the day of the week 1 ( for Monday ) through 7 ( for Sunday )
S English ordinal suffix for the day of the month , 2 characters st , nd , rd or th . Works well with j
w Numeric representation of the day of the week 0 ( for Sunday ) to 6 ( for Saturday )
z The day of the year ( starting from 0 ) 0 to 364 ( 365 in leap years )
W ISO-8601 week number of year , weeks starting on Monday 01 to 53
F A full textual representation of a month , such as January or March January to December
m Numeric representation of a month , with leading zeros 01 to 12
M A short textual representation of a month Jan to Dec
n Numeric representation of a month , without leading zeros 1 to 12
t Number of days in the given month 28 to 31
L Whether it's a leap year 1 if it is a leap year , 0 otherwise .
o ISO-8601 year number ( identical to ( Y ) , but if the ISO week number ( W ) Examples : 1998 or 2004
belongs to the previous or next year , that year is used instead )
Y A full numeric representation of a year , 4 digits Examples : 1999 or 2003
y A two digit representation of a year Examples : 99 or 03
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
g 12 - hour format of an hour without leading zeros 1 to 12
G 24 - hour format of an hour without leading zeros 0 to 23
h 12 - hour format of an hour with leading zeros 01 to 12
H 24 - hour format of an hour with leading zeros 00 to 23
i Minutes , with leading zeros 00 to 59
s Seconds , with leading zeros 00 to 59
u Decimal fraction of a second Examples :
( minimum 1 digit , arbitrary number of digits allowed ) 001 ( i.e. ) or
100 ( i.e. 0.100s ) or
999 ( i.e. 0.999s ) or
999876543210 ( i.e. )
O Difference to Greenwich time ( GMT ) in hours and minutes Example : +1030
P Difference to Greenwich time ( GMT ) with colon between hours and minutes Example : -08:00
T Timezone abbreviation of the machine running the code Examples : EST , MDT , PDT ...
Z Timezone offset in seconds ( negative if west of UTC , positive if east ) -43200 to 50400
c ISO 8601 date
Notes : Examples :
1 ) If unspecified , the month / day defaults to the current month / day , 1991 or
the time defaults to midnight , while the timezone defaults to the 1992 - 10 or
browser 's timezone . If a time is specified , it must include both hours 1993 - 09 - 20 or
and minutes . The " T " delimiter , seconds , milliseconds and timezone 1994 - 08 - 19T16:20 + 01:00 or
are optional . 1995 - 07 - 18T17:21:28 - 02:00 or
2 ) The decimal fraction of a second , if specified , must contain at 1996 - 06 - 17T18:22:29.98765 + 03:00 or
least 1 digit ( there is no limit to the maximum number 1997 - 05 - 16T19:23:30,12345 - 0400 or
of digits allowed ) , and may be delimited by either a ' . ' or a ' , ' 1998 - 04 - 15T20:24:31.2468Z or
Refer to the examples on the right for the various levels of 1999 - 03 - 14T20:24:32Z or
date - time granularity which are supported , or see 2000 - 02 - 13T21:25:33
-datetime for more info . 2001 - 01 - 12 22:26:34
U Seconds since the Unix Epoch ( January 1 1970 00:00:00 GMT ) 1193432466 or -2138434463
MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ ( i.e. UTC milliseconds since epoch ) or
\/Date(1238606590509 + 0800)\/
time A javascript millisecond timestamp 1350024476440
timestamp A UNIX timestamp ( same as U ) 1350024866
< /pre >
< p > Example usage ( note that you must escape format specifiers with ' \ ' to render them as character literals):</p >
< pre><code>// Sample date :
// ' We d Jan 10 2007 15:05:01 GMT-0600 ( Central Standard Time ) '
var dt = new Date('1/10/2007 PM GMT-0600 ' ) ;
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , ' Y - m - d ' ) ) ; // 2007 - 01 - 10
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , ' F j , Y , : i a ' ) ) ; // January 10 , 2007 , 3:05 pm
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , ' l , \\t\\he jS \\of F Y h : i : s A ' ) ) ; // Wednesday , the 10th of January 2007 03:05:01 PM
< /code></pre >
< p > Here are some standard date / time patterns that you might find helpful . They
are not part of the source of < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > , but to use them you can simply copy this
block of code into any script that is included after < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > and they will also become
globally available on the Date object . Feel free to add or remove patterns as needed in your code.</p >
< pre><code > Ext . = \ {
ISO8601Long:"Y - m - d H : i : s " ,
ISO8601Short:"Y - m - d " ,
ShortDate : " n / j / Y " ,
LongDate : " l , F d , Y " ,
FullDateTime : " l , F d , Y g : i : s A " ,
MonthDay : " F d " ,
ShortTime : " g : i A " ,
LongTime : " g : i : s A " ,
SortableDateTime : " Y - m - d\\TH : i : s " ,
UniversalSortableDateTime : " Y - m - d H : i : sO " ,
YearMonth : " F , Y "
\ } ;
< /code></pre >
< p > Example usage:</p >
< pre><code > var dt = new Date ( ) ;
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . , Ext . . ) ) ;
< /code></pre >
< p > Developer - written , custom formats may be used by supplying both a formatting and a parsing function
which perform to specialized requirements . The functions are stored in < a href="#!/api / Ext . Date - property - parseFunctions " rel="Ext . Date - property - parseFunctions " class="docClass">parseFunctions</a > and < a href="#!/api / Ext . Date - property - formatFunctions " rel="Ext . Date - property - formatFunctions " class="docClass">formatFunctions</a>.</p > % }
{% <p>A set of useful static methods to deal with date
Note that if <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a> is required and loaded, it will copy all methods / properties to
this object for convenience</p>
<p>The date parsing and formatting syntax contains a subset of
<a href="">PHP's <code>date()</code> function</a>, and the formats that are
supported will provide results equivalent to their PHP versions.</p>
<p>The following is a list of all currently supported formats:</p>
<pre class="">
Format Description Example returned values
------ ----------------------------------------------------------------------- -----------------------
d Day of the month, 2 digits with leading zeros 01 to 31
D A short textual representation of the day of the week Mon to Sun
j Day of the month without leading zeros 1 to 31
l A full textual representation of the day of the week Sunday to Saturday
N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
z The day of the year (starting from 0) 0 to 364 (365 in leap years)
W ISO-8601 week number of year, weeks starting on Monday 01 to 53
F A full textual representation of a month, such as January or March January to December
m Numeric representation of a month, with leading zeros 01 to 12
M A short textual representation of a month Jan to Dec
n Numeric representation of a month, without leading zeros 1 to 12
t Number of days in the given month 28 to 31
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
belongs to the previous or next year, that year is used instead)
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
g 12-hour format of an hour without leading zeros 1 to 12
G 24-hour format of an hour without leading zeros 0 to 23
h 12-hour format of an hour with leading zeros 01 to 12
H 24-hour format of an hour with leading zeros 00 to 23
i Minutes, with leading zeros 00 to 59
s Seconds, with leading zeros 00 to 59
u Decimal fraction of a second Examples:
(minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
100 (i.e. 0.100s) or
999 (i.e. 0.999s) or
999876543210 (i.e. 0.999876543210s)
O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
c ISO 8601 date
Notes: Examples:
1) If unspecified, the month / day defaults to the current month / day, 1991 or
the time defaults to midnight, while the timezone defaults to the 1992-10 or
browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
are optional. 1995-07-18T17:21:28-02:00 or
2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
date-time granularity which are supported, or see 2000-02-13T21:25:33
-datetime for more info. 2001-01-12 22:26:34
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
\/Date(1238606590509+0800)\/
time A javascript millisecond timestamp 1350024476440
timestamp A UNIX timestamp (same as U) 1350024866
</pre>
<p>Example usage (note that you must escape format specifiers with '\' to render them as character literals):</p>
<pre><code>// Sample date:
// 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, 'Y-m-d')); // 2007-01-10
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
</code></pre>
<p>Here are some standard date/time patterns that you might find helpful. They
are not part of the source of <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a>, but to use them you can simply copy this
block of code into any script that is included after <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a> and they will also become
globally available on the Date object. Feel free to add or remove patterns as needed in your code.</p>
<pre><code>Ext.Date.patterns = \{
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
\};
</code></pre>
<p>Example usage:</p>
<pre><code>var dt = new Date();
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(dt, Ext.Date.patterns.ShortDate));
</code></pre>
<p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
which perform to specialized requirements. The functions are stored in <a href="#!/api/Ext.Date-property-parseFunctions" rel="Ext.Date-property-parseFunctions" class="docClass">parseFunctions</a> and <a href="#!/api/Ext.Date-property-formatFunctions" rel="Ext.Date-property-formatFunctions" class="docClass">formatFunctions</a>.</p> %}
*)
class type t =
object('self)
method _DAY : Js.js_string Js.t Js.prop
method _HOUR : Js.js_string Js.t Js.prop
method _MILLI : Js.js_string Js.t Js.prop
method _MINUTE : Js.js_string Js.t Js.prop
method _MONTH : Js.js_string Js.t Js.prop
method _SECOND : Js.js_string Js.t Js.prop
method _YEAR : Js.js_string Js.t Js.prop
method dayNames : Js.js_string Js.t Js.js_array Js.t Js.prop
* { % < p > An array of textual day names .
Override these values for international dates.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - dayNames " rel="Ext . Date - property - dayNames " class="docClass">Ext . Date.dayNames</a > = [
' SundayInYourLang ' ,
' MondayInYourLang '
// ...
] ;
< /code></pre > % }
Defaults to : [ '' Sunday '' , '' Monday '' , '' Tuesday '' , '' Wednesday '' , '' Thursday '' , '' Friday '' , '' Saturday '' ]
Override these values for international dates.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-dayNames" rel="Ext.Date-property-dayNames" class="docClass">Ext.Date.dayNames</a> = [
'SundayInYourLang',
'MondayInYourLang'
// ...
];
</code></pre> %}
Defaults to: [''Sunday'', ''Monday'', ''Tuesday'', ''Wednesday'', ''Thursday'', ''Friday'', ''Saturday'']
*)
method defaultFormat : Js.js_string Js.t Js.prop
* { % < p > The date format string that the < a href="#!/api / Ext.util . Format - method - dateRenderer " rel="Ext.util . Format - method - dateRenderer " class="docClass">Ext.util . Format.dateRenderer</a >
and < a href="#!/api / Ext.util . Format - method - date " rel="Ext.util . Format - method - date " class="docClass">Ext.util . Format.date</a > functions use . See < a href="#!/api / Ext . Date " rel="Ext . Date " class="docClass">Ext . Date</a > for details.</p >
< p > This may be overridden in a locale file.</p > % }
Defaults to : [ " m / d / Y " ]
and <a href="#!/api/Ext.util.Format-method-date" rel="Ext.util.Format-method-date" class="docClass">Ext.util.Format.date</a> functions use. See <a href="#!/api/Ext.Date" rel="Ext.Date" class="docClass">Ext.Date</a> for details.</p>
<p>This may be overridden in a locale file.</p> %}
Defaults to: ["m/d/Y"]
*)
method defaults : _ Js.t Js.prop
* { % < p > An object hash containing default date values used during date parsing.</p >
< p > The following properties are available:<div class="mdetail - params"><ul >
< li><code > y</code > : Number < div class="sub - desc">The default year value . ( defaults to undefined)</div></li >
< li><code > m</code > : Number < div class="sub - desc">The default 1 - based month value . ( defaults to undefined)</div></li >
< li><code > d</code > : Number < div class="sub - desc">The default day value . ( defaults to undefined)</div></li >
< li><code > h</code > : Number < div class="sub - desc">The default hour value . ( defaults to undefined)</div></li >
< li><code > i</code > : Number < div class="sub - desc">The default minute value . ( defaults to undefined)</div></li >
< li><code > s</code > : Number < div class="sub - desc">The default second value . ( defaults to undefined)</div></li >
< li><code > ms</code > : Number < div class="sub - desc">The default millisecond value . ( defaults to undefined)</div></li >
< /ul></div></p >
< p > Override these properties to customize the default date values used by the < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">parse</a > method.</p >
< p><strong > Note:</strong > In countries which experience Daylight Saving Time ( i.e. DST ) , the < code > h</code > , < code > i</code > , < code > s</code >
and < code > ms</code > properties may coincide with the exact time in which DST takes effect .
It is the responsibility of the developer to account for this.</p >
< p > Example Usage:</p >
< pre><code>// set default day value to the first day of the month
Ext . Date.defaults.d = 1 ;
// parse a February date string containing only year and month values .
// setting the default day value to 1 prevents weird date rollover issues
// when attempting to parse the following date string on , for example , March 31st 2009 .
< a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . , ' Y - m ' ) ; // returns a Date object representing February 1st 2009
< /code></pre > % }
Defaults to : [ \{\ } ]
<p>The following properties are available:<div class="mdetail-params"><ul>
<li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
<li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
<li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
<li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
<li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
<li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
<li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
</ul></div></p>
<p>Override these properties to customize the default date values used by the <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">parse</a> method.</p>
<p><strong>Note:</strong> In countries which experience Daylight Saving Time (i.e. DST), the <code>h</code>, <code>i</code>, <code>s</code>
and <code>ms</code> properties may coincide with the exact time in which DST takes effect.
It is the responsibility of the developer to account for this.</p>
<p>Example Usage:</p>
<pre><code>// set default day value to the first day of the month
Ext.Date.defaults.d = 1;
// parse a February date string containing only year and month values.
// setting the default day value to 1 prevents weird date rollover issues
// when attempting to parse the following date string on, for example, March 31st 2009.
<a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
</code></pre> %}
Defaults to: [\{\}]
*)
method formatCodes : _ Js.t Js.prop
* { % < p > The base format - code to formatting - function hashmap used by the < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">format</a > method .
Formatting functions are strings ( or functions which return strings ) which
will return the appropriate value when evaluated in the context of the Date object
from which the < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">format</a > method is called .
Add to / override these mappings for custom date formatting.</p >
< p><strong > Note:</strong > < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . Date.format</a > ( ) treats characters as literals if an appropriate mapping can not be found.</p >
< p > Example:</p >
< pre><code > Ext . Date.formatCodes.x = " < a href="#!/api / Ext.util . Format - method - leftPad " rel="Ext.util . Format - method - leftPad " class="docClass">Ext.util . Format.leftPad</a>(this.getDate ( ) , 2 , ' 0 ' ) " ;
console.log(<a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">Ext . Date ( ) , ' X ' ) ; // returns the current day of the month
< /code></pre > % }
Formatting functions are strings (or functions which return strings) which
will return the appropriate value when evaluated in the context of the Date object
from which the <a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">format</a> method is called.
Add to / override these mappings for custom date formatting.</p>
<p><strong>Note:</strong> <a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>() treats characters as literals if an appropriate mapping cannot be found.</p>
<p>Example:</p>
<pre><code>Ext.Date.formatCodes.x = "<a href="#!/api/Ext.util.Format-method-leftPad" rel="Ext.util.Format-method-leftPad" class="docClass">Ext.util.Format.leftPad</a>(this.getDate(), 2, '0')";
console.log(<a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">Ext.Date.format</a>(new Date(), 'X'); // returns the current day of the month
</code></pre> %}
*)
method formatFunctions : _ Js.t Js.prop
* { % < p > An object hash in which each property is a date formatting function . The property name is the
format string which corresponds to the produced formatted date string.</p >
< p > This object is automatically populated with date formatting functions as
date formats are requested for Ext standard formatting strings.</p >
< p > Custom formatting functions may be inserted into this object , keyed by a name which from then on
may be used as a format string to < a href="#!/api / Ext . Date - method - format " rel="Ext . Date - method - format " class="docClass">format</a>.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - formatFunctions " rel="Ext . Date - property - formatFunctions " class="docClass">Ext . Date.formatFunctions</a>['x - date - format ' ] = myDateFormatter ;
< /code></pre >
< p > A formatting function should return a string representation of the passed Date object , and is passed the following parameters:<div class="mdetail - params"><ul >
< li><code > date</code > : Date < div class="sub - desc">The Date to format.</div></li >
< /ul></div></p >
< p > To enable date strings to also be < em > parsed</em > according to that format , a corresponding
parsing function must be placed into the < a href="#!/api / Ext . Date - property - parseFunctions " rel="Ext . Date - property - parseFunctions " class="docClass">parseFunctions</a > property.</p > % }
format string which corresponds to the produced formatted date string.</p>
<p>This object is automatically populated with date formatting functions as
date formats are requested for Ext standard formatting strings.</p>
<p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
may be used as a format string to <a href="#!/api/Ext.Date-method-format" rel="Ext.Date-method-format" class="docClass">format</a>.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-formatFunctions" rel="Ext.Date-property-formatFunctions" class="docClass">Ext.Date.formatFunctions</a>['x-date-format'] = myDateFormatter;
</code></pre>
<p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
<li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
</ul></div></p>
<p>To enable date strings to also be <em>parsed</em> according to that format, a corresponding
parsing function must be placed into the <a href="#!/api/Ext.Date-property-parseFunctions" rel="Ext.Date-property-parseFunctions" class="docClass">parseFunctions</a> property.</p> %}
*)
method monthNames : Js.js_string Js.t Js.js_array Js.t Js.prop
* { % < p > An array of textual month names .
Override these values for international dates.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - monthNames " rel="Ext . Date - property - monthNames " class="docClass">Ext . > = [
' JanInYourLang ' ,
' FebInYourLang '
// ...
] ;
< /code></pre > % }
Defaults to : [ '' January '' , '' February '' , '' March '' , '' April '' , '' May '' , '' June '' , '' July '' , '' August '' , '' September '' , '' October '' , '' November '' , '' December '' ]
Override these values for international dates.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-monthNames" rel="Ext.Date-property-monthNames" class="docClass">Ext.Date.monthNames</a> = [
'JanInYourLang',
'FebInYourLang'
// ...
];
</code></pre> %}
Defaults to: [''January'', ''February'', ''March'', ''April'', ''May'', ''June'', ''July'', ''August'', ''September'', ''October'', ''November'', ''December'']
*)
method monthNumbers : _ Js.t Js.prop
* { % < p > An object hash of zero - based JavaScript month numbers ( with short month names as keys . < strong > Note:</strong > keys are case - sensitive ) .
Override these values for international dates.</p >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - monthNumbers " rel="Ext . Date - property - monthNumbers " class="docClass">Ext . Date.monthNumbers</a > = \ {
' LongJanNameInYourLang ' : 0 ,
' ShortJanNameInYourLang':0 ,
' LongFebNameInYourLang':1 ,
' ShortFebNameInYourLang':1
// ...
\ } ;
< /code></pre > % }
Defaults to : [ \{January : 0 , Jan : 0 , February : 1 , Feb : 1 , March : 2 , Mar : 2 , April : 3 , Apr : 3 , May : 4 , June : 5 , : 5 , July : 6 , Jul : 6 , August : 7 , Aug : 7 , September : 8 , Sep : 8 , October : 9 , Oct : 9 , November : 10 , Nov : 10 , December : 11 , Dec : 11\ } ]
Override these values for international dates.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-monthNumbers" rel="Ext.Date-property-monthNumbers" class="docClass">Ext.Date.monthNumbers</a> = \{
'LongJanNameInYourLang': 0,
'ShortJanNameInYourLang':0,
'LongFebNameInYourLang':1,
'ShortFebNameInYourLang':1
// ...
\};
</code></pre> %}
Defaults to: [\{January: 0, Jan: 0, February: 1, Feb: 1, March: 2, Mar: 2, April: 3, Apr: 3, May: 4, June: 5, Jun: 5, July: 6, Jul: 6, August: 7, Aug: 7, September: 8, Sep: 8, October: 9, Oct: 9, November: 10, Nov: 10, December: 11, Dec: 11\}]
*)
method parseFunctions : _ Js.t Js.prop
* { % < p > An object hash in which each property is a date parsing function . The property name is the
format string which that function parses.</p >
< p > This object is automatically populated with date parsing functions as
date formats are requested for Ext standard formatting strings.</p >
< p > Custom parsing functions may be inserted into this object , keyed by a name which from then on
may be used as a format string to < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " >
< p > Example:</p >
< pre><code><a href="#!/api / Ext . Date - property - parseFunctions " rel="Ext . Date - property - parseFunctions " class="docClass">Ext . Date.parseFunctions</a>['x - date - format ' ] = myDateParser ;
< /code></pre >
< p > A parsing function should return a Date object , and is passed the following parameters:<div class="mdetail - params"><ul >
< li><code > date</code > : String < div class="sub - desc">The date string to parse.</div></li >
< li><code > > : Boolean < div class="sub - desc">True to validate date strings while parsing
( i.e. prevent JavaScript Date " rollover " ) ( The default must be < code > false</code > ) .
Invalid date strings should return < code > when parsed.</div></li >
< /ul></div></p >
< p > To enable Dates to also be < em > formatted</em > according to that format , a corresponding
formatting function must be placed into the < a href="#!/api / Ext . Date - property - formatFunctions " rel="Ext . Date - property - formatFunctions " class="docClass">formatFunctions</a > property.</p > % }
format string which that function parses.</p>
<p>This object is automatically populated with date parsing functions as
date formats are requested for Ext standard formatting strings.</p>
<p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
may be used as a format string to <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">parse</a>.</p>
<p>Example:</p>
<pre><code><a href="#!/api/Ext.Date-property-parseFunctions" rel="Ext.Date-property-parseFunctions" class="docClass">Ext.Date.parseFunctions</a>['x-date-format'] = myDateParser;
</code></pre>
<p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
<li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
<li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
(i.e. prevent JavaScript Date "rollover") (The default must be <code>false</code>).
Invalid date strings should return <code>null</code> when parsed.</div></li>
</ul></div></p>
<p>To enable Dates to also be <em>formatted</em> according to that format, a corresponding
formatting function must be placed into the <a href="#!/api/Ext.Date-property-formatFunctions" rel="Ext.Date-property-formatFunctions" class="docClass">formatFunctions</a> property.</p> %}
*)
method useStrict : bool Js.t Js.prop
* { % < p > Global flag which determines if strict date parsing should be used .
Strict date parsing will not roll - over invalid dates , which is the
default behavior of JavaScript Date objects .
( see < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">parse</a > for more information)</p > % }
Defaults to : [ false ]
Strict date parsing will not roll-over invalid dates, which is the
default behavior of JavaScript Date objects.
(see <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">parse</a> for more information)</p> %}
Defaults to: [false]
*)
method add : Js.date Js.t -> Js.js_string Js.t -> Js.number Js.t ->
Js.date Js.t Js.meth
* { % < p > Provides a convenient method for performing basic date arithmetic . This method
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p >
< p > Examples:</p >
< pre><code>// Basic usage :
var dt = < a href="#!/api / Ext . Date - method - add " rel="Ext . Date - method - add " class="docClass">Ext . Date.add</a>(new Date('10/29/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 5 ) ;
console.log(dt ) ; // returns ' Fri Nov 03 2006 00:00:00 '
// Negative values will be subtracted :
var dt2 = < a href="#!/api / Ext . Date - method - add " rel="Ext . Date - method - add " class="docClass">Ext . Date.add</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , -5 ) ;
console.log(dt2 ) ; // returns ' Tue Sep 26 2006 00:00:00 '
// Decimal values can be used :
var dt3 = < a href="#!/api / Ext . Date - method - add " rel="Ext . Date - method - add " class="docClass">Ext . Date.add</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 1.25 ) ;
console.log(dt3 ) ; // returns ' Mon Oct 02 2006 06:00:00 '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to modify</p > % }
}
{ - interval : [ Js.js_string Js.t ]
{ % < p > A valid date interval enum value.</p > % }
}
{ - value : [ Js.number Js.t ]
{ % < p > The amount to add to the current date.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The new Date instance.</p > % }
}
}
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p>
<p>Examples:</p>
<pre><code>// Basic usage:
var dt = <a href="#!/api/Ext.Date-method-add" rel="Ext.Date-method-add" class="docClass">Ext.Date.add</a>(new Date('10/29/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 5);
console.log(dt); // returns 'Fri Nov 03 2006 00:00:00'
// Negative values will be subtracted:
var dt2 = <a href="#!/api/Ext.Date-method-add" rel="Ext.Date-method-add" class="docClass">Ext.Date.add</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, -5);
console.log(dt2); // returns 'Tue Sep 26 2006 00:00:00'
// Decimal values can be used:
var dt3 = <a href="#!/api/Ext.Date-method-add" rel="Ext.Date-method-add" class="docClass">Ext.Date.add</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 1.25);
console.log(dt3); // returns 'Mon Oct 02 2006 06:00:00'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to modify</p> %}
}
{- interval: [Js.js_string Js.t]
{% <p>A valid date interval enum value.</p> %}
}
{- value: [Js.number Js.t]
{% <p>The amount to add to the current date.</p> %}
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The new Date instance.</p> %}
}
}
*)
method between : Js.date Js.t -> Js.date Js.t -> Js.date Js.t -> bool Js.t
Js.meth
* { % < p > Checks if a date falls on or between the given start and end dates.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to check</p > % }
}
{ - start : [ Js.date Js.t ] { % < p > Start date</p > % }
}
{ - _ end : [ Js.date Js.t ]
{ % < p > End date</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if this date falls on or between the given start and end dates.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to check</p> %}
}
{- start: [Js.date Js.t] {% <p>Start date</p> %}
}
{- _end: [Js.date Js.t]
{% <p>End date</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if this date falls on or between the given start and end dates.</p> %}
}
}
*)
method clearTime : Js.date Js.t -> bool Js.t Js.optdef -> Js.date Js.t
Js.meth
* { % < p > Attempts to clear all time information from this Date by setting the time to midnight of the same day ,
automatically adjusting for Daylight Saving Time ( DST ) where applicable.</p >
< p><strong > Note:</strong > DST timezone information for the browser 's host operating system is assumed to be up - to - date.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
{ - clone : [ bool Js.t ] ( optional )
{ % < p><code > true</code > to create a clone of this date , clear the time and return it.</p > % }
Defaults to : false
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > this or the clone.</p > % }
}
}
automatically adjusting for Daylight Saving Time (DST) where applicable.</p>
<p><strong>Note:</strong> DST timezone information for the browser's host operating system is assumed to be up-to-date.</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
{- clone: [bool Js.t] (optional)
{% <p><code>true</code> to create a clone of this date, clear the time and return it.</p> %}
Defaults to: false
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>this or the clone.</p> %}
}
}
*)
method clone : Js.date Js.t -> Js.date Js.t Js.meth
* { % < p > Creates and returns a new Date instance with the exact same date value as the called instance .
Dates are copied and passed by reference , so if a copied date variable is modified later , the original
variable will also be changed . When the intention is to create a new variable that will not
modify the original instance , you should create a clone.</p >
< p > Example of correctly cloning a date:</p >
< pre><code>//wrong way :
var orig = new Date('10/1/2006 ' ) ;
var copy = orig ;
) ;
console.log(orig ) ; // returns ' Thu Oct 05 2006 ' !
//correct way :
var orig = new Date('10/1/2006 ' ) ,
copy = < a href="#!/api / Ext . Date - method - clone " rel="Ext . Date - method - clone " class="docClass">Ext . Date.clone</a>(orig ) ;
) ;
console.log(orig ) ; // returns ' Thu Oct 01 2006 '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The new Date instance.</p > % }
}
}
Dates are copied and passed by reference, so if a copied date variable is modified later, the original
variable will also be changed. When the intention is to create a new variable that will not
modify the original instance, you should create a clone.</p>
<p>Example of correctly cloning a date:</p>
<pre><code>//wrong way:
var orig = new Date('10/1/2006');
var copy = orig;
copy.setDate(5);
console.log(orig); // returns 'Thu Oct 05 2006'!
//correct way:
var orig = new Date('10/1/2006'),
copy = <a href="#!/api/Ext.Date-method-clone" rel="Ext.Date-method-clone" class="docClass">Ext.Date.clone</a>(orig);
copy.setDate(5);
console.log(orig); // returns 'Thu Oct 01 2006'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date.</p> %}
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The new Date instance.</p> %}
}
}
*)
method format : Js.date Js.t -> Js.js_string Js.t -> Js.js_string Js.t
Js.meth
* { % < p > Formats a date given the supplied format string.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to > % }
}
{ - format : [ Js.js_string Js.t ]
{ % < p > The format string</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ]
{ % < p > The formatted date or an empty string if date parameter is not a JavaScript Date object</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to format</p> %}
}
{- format: [Js.js_string Js.t]
{% <p>The format string</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t]
{% <p>The formatted date or an empty string if date parameter is not a JavaScript Date object</p> %}
}
}
*)
method formatContainsDateInfo : Js.js_string Js.t -> bool Js.t Js.meth
* { % < p > Checks if the specified format contains information about
anything other than the time.</p > % }
{ b Parameters } :
{ ul { - format : [ Js.js_string Js.t ]
{ % < p > The format to check</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p > True if the format contains information about
date / day information.</p > % }
}
}
anything other than the time.</p> %}
{b Parameters}:
{ul {- format: [Js.js_string Js.t]
{% <p>The format to check</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p>True if the format contains information about
date/day information.</p> %}
}
}
*)
method formatContainsHourInfo : Js.js_string Js.t -> bool Js.t Js.meth
method getDayOfYear : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the numeric day number of the year , adjusted for leap year.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p>0 to 364 ( 365 in leap years).</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>0 to 364 (365 in leap years).</p> %}
}
}
*)
method getDaysInMonth : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the number of days in the current month , adjusted for leap year.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The number of days in the month.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The number of days in the month.</p> %}
}
}
*)
method getElapsed : Js.date Js.t -> Js.date Js.t Js.optdef ->
Js.number Js.t Js.meth
* { % < p > Returns the number of milliseconds between two dates.</p > % }
{ b Parameters } :
{ ul { - dateA : [ Js.date Js.t ]
{ % < p > The first date.</p > % }
}
{ - dateB : [ Js.date Js.t ] ( optional ) { % < p > The second date.</p > % }
Defaults to : new Date ( )
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The difference in milliseconds</p > % }
}
}
{b Parameters}:
{ul {- dateA: [Js.date Js.t]
{% <p>The first date.</p> %}
}
{- dateB: [Js.date Js.t] (optional) {% <p>The second date.</p> %}
Defaults to: new Date()
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The difference in milliseconds</p> %}
}
}
*)
method getFirstDateOfMonth : Js.date Js.t -> Js.date Js.t Js.meth
* { % < p > Get the date of the first day of the month in which this date resides.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ] { % < p > The date</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t] {% <p>The date</p> %}
}
}
*)
method getFirstDayOfMonth : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the first day of the current month , adjusted for leap year . The returned value
is the numeric day index within the week ( 0 - 6 ) which can be used in conjunction with
the < a href="#!/api / Ext . Date - property - monthNames " rel="Ext . Date - property - monthNames " class="docClass">monthNames</a > array to retrieve the textual day >
< p > Example:</p >
< pre><code > var dt = new Date('1/10/2007 ' ) ,
firstDay = < a href="#!/api / Ext . Date - method - getFirstDayOfMonth " rel="Ext . Date - method - getFirstDayOfMonth " class="docClass">Ext . ) ;
console.log(<a href="#!/api / Ext . Date - property - dayNames " rel="Ext . Date - property - dayNames " class="docClass">Ext . Date.dayNames</a>[firstDay ] ) ; // output : ' Monday '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The day number ( 0 - 6).</p > % }
}
}
is the numeric day index within the week (0-6) which can be used in conjunction with
the <a href="#!/api/Ext.Date-property-monthNames" rel="Ext.Date-property-monthNames" class="docClass">monthNames</a> array to retrieve the textual day name.</p>
<p>Example:</p>
<pre><code>var dt = new Date('1/10/2007'),
firstDay = <a href="#!/api/Ext.Date-method-getFirstDayOfMonth" rel="Ext.Date-method-getFirstDayOfMonth" class="docClass">Ext.Date.getFirstDayOfMonth</a>(dt);
console.log(<a href="#!/api/Ext.Date-property-dayNames" rel="Ext.Date-property-dayNames" class="docClass">Ext.Date.dayNames</a>[firstDay]); // output: 'Monday'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The day number (0-6).</p> %}
}
}
*)
method getGMTOffset : Js.date Js.t -> bool Js.t Js.optdef ->
Js.js_string Js.t Js.meth
* { % < p > Get the offset from GMT of the current date ( equivalent to the format specifier ' O').</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
{ - colon : [ bool Js.t ] ( optional )
{ % < p > true to separate the hours and minutes with a colon.</p > % }
Defaults to : false
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ]
{ % < p > The 4 - character offset string prefixed with + or - ( e.g. ' -0600').</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
{- colon: [bool Js.t] (optional)
{% <p>true to separate the hours and minutes with a colon.</p> %}
Defaults to: false
}
}
{b Returns}:
{ul {- [Js.js_string Js.t]
{% <p>The 4-character offset string prefixed with + or - (e.g. '-0600').</p> %}
}
}
*)
method getLastDateOfMonth : Js.date Js.t -> Js.date Js.t Js.meth
method getLastDayOfMonth : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the last day of the current month , adjusted for leap year . The returned value
is the numeric day index within the week ( 0 - 6 ) which can be used in conjunction with
the < a href="#!/api / Ext . Date - property - monthNames " rel="Ext . Date - property - monthNames " class="docClass">monthNames</a > array to retrieve the textual day >
< p > Example:</p >
< pre><code > var dt = new Date('1/10/2007 ' ) ,
lastDay = < a href="#!/api / Ext . Date - method - getLastDayOfMonth " rel="Ext . Date - method - getLastDayOfMonth " class="docClass">Ext . ) ;
console.log(<a href="#!/api / Ext . Date - property - dayNames " rel="Ext . Date - property - dayNames " class="docClass">Ext . Date.dayNames</a>[lastDay ] ) ; // output : ' Wednesday '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > The day number ( 0 - 6).</p > % }
}
}
is the numeric day index within the week (0-6) which can be used in conjunction with
the <a href="#!/api/Ext.Date-property-monthNames" rel="Ext.Date-property-monthNames" class="docClass">monthNames</a> array to retrieve the textual day name.</p>
<p>Example:</p>
<pre><code>var dt = new Date('1/10/2007'),
lastDay = <a href="#!/api/Ext.Date-method-getLastDayOfMonth" rel="Ext.Date-method-getLastDayOfMonth" class="docClass">Ext.Date.getLastDayOfMonth</a>(dt);
console.log(<a href="#!/api/Ext.Date-property-dayNames" rel="Ext.Date-property-dayNames" class="docClass">Ext.Date.dayNames</a>[lastDay]); // output: 'Wednesday'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>The day number (0-6).</p> %}
}
}
*)
method getMonthNumber : Js.js_string Js.t -> Js.number Js.t Js.meth
* { % < p > Get the zero - based JavaScript month number for the given short / full month name .
Override this function for international dates.</p > % }
{ b Parameters } :
{ ul { - name : [ Js.js_string Js.t ]
{ % < p > The short / full month name.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ]
{ % < p > The zero - based JavaScript month number.</p > % }
}
}
Override this function for international dates.</p> %}
{b Parameters}:
{ul {- name: [Js.js_string Js.t]
{% <p>The short/full month name.</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t]
{% <p>The zero-based JavaScript month number.</p> %}
}
}
*)
method getShortDayName : Js.number Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the short day name for the given day number .
Override this function for international dates.</p > % }
{ b Parameters } :
{ ul { - day : [ Js.number Js.t ]
{ % < p > A zero - based JavaScript day number.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p > The short day > % }
}
}
Override this function for international dates.</p> %}
{b Parameters}:
{ul {- day: [Js.number Js.t]
{% <p>A zero-based JavaScript day number.</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>The short day name.</p> %}
}
}
*)
method getShortMonthName : Js.number Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the short month name for the given month number .
Override this function for international dates.</p > % }
{ b Parameters } :
{ ul { - month : [ Js.number Js.t ]
{ % < p > A zero - based JavaScript month number.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p > The short month > % }
}
}
Override this function for international dates.</p> %}
{b Parameters}:
{ul {- month: [Js.number Js.t]
{% <p>A zero-based JavaScript month number.</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>The short month name.</p> %}
}
}
*)
method getSuffix : Js.date Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the English ordinal suffix of the current day ( equivalent to the format specifier ' S').</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p>'st , ' nd ' , ' rd ' or ' th'.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>'st, 'nd', 'rd' or 'th'.</p> %}
}
}
*)
method getTimezone : Js.date Js.t -> Js.js_string Js.t Js.meth
* { % < p > Get the timezone abbreviation of the current date ( equivalent to the format specifier ' >
< p><strong > Note:</strong > The date string returned by the JavaScript Date object 's < code > toString()</code > method varies
between browsers ( e.g. FF vs IE ) and system region settings ( e.g. IE in Asia vs IE in America ) .
For a given date string e.g. " Thu Oct 25 2007 22:55:35 GMT+0800 ( Malay Peninsula Standard Time ) " ,
getTimezone ( ) first tries to get the timezone abbreviation from between a pair of parentheses
( which may or may not be present ) , failing which it proceeds to get the timezone abbreviation
from the GMT offset portion of the date string.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ]
{ % < p > The abbreviated timezone name ( e.g. ' CST ' , ' PDT ' , ' EDT ' , ' MPST ' ... ) .</p > % }
}
}
<p><strong>Note:</strong> The date string returned by the JavaScript Date object's <code>toString()</code> method varies
between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
(which may or may not be present), failing which it proceeds to get the timezone abbreviation
from the GMT offset portion of the date string.</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t]
{% <p>The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).</p> %}
}
}
*)
method getWeekOfYear : Js.date Js.t -> Js.number Js.t Js.meth
* { % < p > Get the numeric ISO-8601 week number of the year .
( equivalent to the format specifier ' W ' , but without a leading > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p>1 to 53</p > % }
}
}
(equivalent to the format specifier 'W', but without a leading zero).</p> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>1 to 53</p> %}
}
}
*)
method isDST : Js.date Js.t -> bool Js.t Js.meth
* { % < p > Checks if the current date is affected by Daylight Saving Time ( DST).</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if the current date is affected by DST.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if the current date is affected by DST.</p> %}
}
}
*)
method isEqual : Js.date Js.t -> Js.date Js.t -> bool Js.t Js.meth
* { % < p > Compares if two dates are equal by comparing their values.</p > % }
{ b Parameters } :
{ ul { - date1 : [ Js.date Js.t ]
}
{ - date2 : [ Js.date Js.t ]
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if the date values are equal</p > % }
}
}
{b Parameters}:
{ul {- date1: [Js.date Js.t]
}
{- date2: [Js.date Js.t]
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if the date values are equal</p> %}
}
}
*)
method isLeapYear : Js.date Js.t -> bool Js.t Js.meth
* { % < p > Checks if the current date falls within a leap year.</p > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p > True if the current date falls within a leap year , false otherwise.</p > % }
}
}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p>True if the current date falls within a leap year, false otherwise.</p> %}
}
}
*)
method isValid : Js.number Js.t -> Js.number Js.t -> Js.number Js.t ->
Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef ->
Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef -> bool Js.t Js.meth
* { % < p > Checks if the passed Date parameters will cause a JavaScript Date " rollover".</p > % }
{ b Parameters } :
{ ul { - year : [ Js.number Js.t ]
{ % < p>4 - digit year</p > % }
}
{ - month : [ Js.number Js.t ]
{ % < p>1 - based month - of - year</p > % }
}
{ - day : [ Js.number Js.t ]
{ % < p > Day of month</p > % }
}
{ - hour : [ Js.number Js.t ] ( optional )
{ % < p > Hour</p > % }
}
{ - minute : [ Js.number Js.t ] ( optional )
{ % < p > Minute</p > % }
}
{ - second : [ Js.number Js.t ] ( optional )
{ % < p > Second</p > % }
}
{ - millisecond : [ Js.number Js.t ] ( optional )
{ % < p > Millisecond</p > % }
}
}
{ b Returns } :
{ ul { - [ bool Js.t ]
{ % < p><code > true</code > if the passed parameters do not cause a Date " rollover " , < code > false</code > otherwise.</p > % }
}
}
{b Parameters}:
{ul {- year: [Js.number Js.t]
{% <p>4-digit year</p> %}
}
{- month: [Js.number Js.t]
{% <p>1-based month-of-year</p> %}
}
{- day: [Js.number Js.t]
{% <p>Day of month</p> %}
}
{- hour: [Js.number Js.t] (optional)
{% <p>Hour</p> %}
}
{- minute: [Js.number Js.t] (optional)
{% <p>Minute</p> %}
}
{- second: [Js.number Js.t] (optional)
{% <p>Second</p> %}
}
{- millisecond: [Js.number Js.t] (optional)
{% <p>Millisecond</p> %}
}
}
{b Returns}:
{ul {- [bool Js.t]
{% <p><code>true</code> if the passed parameters do not cause a Date "rollover", <code>false</code> otherwise.</p> %}
}
}
*)
method now : Js.number Js.t Js.meth
* { % < p > Returns the current timestamp.</p > % }
{ b Returns } :
{ ul { - [ Js.number Js.t ] { % < p > Milliseconds since UNIX epoch.</p > % }
}
}
{b Returns}:
{ul {- [Js.number Js.t] {% <p>Milliseconds since UNIX epoch.</p> %}
}
}
*)
method parse : Js.js_string Js.t -> Js.js_string Js.t ->
bool Js.t Js.optdef -> Js.date Js.t Js.meth
* { % < p > Parses the passed string using the specified date format .
Note that this function expects normal calendar dates , meaning that months are 1 - based ( i.e. 1 = January ) .
The < a href="#!/api / Ext . Date - property - defaults " rel="Ext . Date - property - defaults " > hash will be used for any date value ( i.e. year , month , day , hour , minute , second or millisecond )
which can not be found in the passed string . If a corresponding default date value has not been specified in the < a href="#!/api / Ext . Date - property - defaults " rel="Ext . Date - property - defaults " > hash ,
the current date 's year , month , day or DST - adjusted zero - hour time value will be used instead .
Keep in mind that the input date string must precisely match the specified format string
in order for the parse operation to be successful ( failed parse operations return a null value).</p >
< p > Example:</p >
< pre><code>//dt = Fri May 25 2007 ( current date )
var dt = new Date ( ) ;
//dt = Thu May 25 2006 ( today&#39;s month / day in 2006 )
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 " , " Y " ) ;
//dt = Sun Jan 15 2006 ( all date parts specified )
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 - 01 - 15 " , " Y - m - d " ) ;
//dt = Sun Jan 15 2006 15:20:01
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 - 01 - 15 3:20:01 PM " , " Y - m - d g : i : s A " ) ;
// attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
dt = < a href="#!/api / Ext . Date - method - parse " rel="Ext . Date - method - parse " class="docClass">Ext . Date.parse</a>("2006 - 02 - 29 03:20:01 " , " Y - m - d H : i : s " , true ) ; // returns null
< /code></pre > % }
{ b Parameters } :
{ ul { - input : [ Js.js_string Js.t ]
{ % < p > The raw date string.</p > % }
}
{ - format : [ Js.js_string Js.t ]
{ % < p > The expected date string > % }
}
{ - strict : [ bool Js.t ] ( optional )
{ % < p><code > true</code > to validate date strings while parsing ( i.e. prevents JavaScript Date " rollover " ) .
Invalid date strings will return < code > when parsed.</p > % }
Defaults to : false
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The parsed Date.</p > % }
}
}
Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
The <a href="#!/api/Ext.Date-property-defaults" rel="Ext.Date-property-defaults" class="docClass">defaults</a> hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
which cannot be found in the passed string. If a corresponding default date value has not been specified in the <a href="#!/api/Ext.Date-property-defaults" rel="Ext.Date-property-defaults" class="docClass">defaults</a> hash,
the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
Keep in mind that the input date string must precisely match the specified format string
in order for the parse operation to be successful (failed parse operations return a null value).</p>
<p>Example:</p>
<pre><code>//dt = Fri May 25 2007 (current date)
var dt = new Date();
//dt = Thu May 25 2006 (today&#39;s month/day in 2006)
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006", "Y");
//dt = Sun Jan 15 2006 (all date parts specified)
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006-01-15", "Y-m-d");
//dt = Sun Jan 15 2006 15:20:01
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
// attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
dt = <a href="#!/api/Ext.Date-method-parse" rel="Ext.Date-method-parse" class="docClass">Ext.Date.parse</a>("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
</code></pre> %}
{b Parameters}:
{ul {- input: [Js.js_string Js.t]
{% <p>The raw date string.</p> %}
}
{- format: [Js.js_string Js.t]
{% <p>The expected date string format.</p> %}
}
{- strict: [bool Js.t] (optional)
{% <p><code>true</code> to validate date strings while parsing (i.e. prevents JavaScript Date "rollover").
Invalid date strings will return <code>null</code> when parsed.</p> %}
Defaults to: false
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The parsed Date.</p> %}
}
}
*)
method subtract : Js.date Js.t -> Js.js_string Js.t -> Js.number Js.t ->
Js.date Js.t Js.meth
* { % < p > Provides a convenient method for performing basic date arithmetic . This method
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p >
< p > Examples:</p >
< pre><code>// Basic usage :
var dt = < a href="#!/api / Ext . Date - method - subtract " rel="Ext . Date - method - subtract " class="docClass">Ext . Date.subtract</a>(new Date('10/29/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 5 ) ;
console.log(dt ) ; // returns ' Tue Oct 24 2006 00:00:00 '
// Negative values will be added :
var dt2 = < a href="#!/api / Ext . Date - method - subtract " rel="Ext . Date - method - subtract " class="docClass">Ext . Date.subtract</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , -5 ) ;
console.log(dt2 ) ; // returns ' Fri Oct 6 2006 00:00:00 '
// Decimal values can be used :
var dt3 = < a href="#!/api / Ext . Date - method - subtract " rel="Ext . Date - method - subtract " class="docClass">Ext . Date.subtract</a>(new Date('10/1/2006 ' ) , < a href="#!/api / Ext . Date - property - DAY " rel="Ext . Date - property - DAY " class="docClass">Ext . Date . DAY</a > , 1.25 ) ;
console.log(dt3 ) ; // returns ' Fri Sep 29 2006 06:00:00 '
< /code></pre > % }
{ b Parameters } :
{ ul { - date : [ Js.date Js.t ]
{ % < p > The date to modify</p > % }
}
{ - interval : [ Js.js_string Js.t ]
{ % < p > A valid date interval enum value.</p > % }
}
{ - value : [ Js.number Js.t ]
{ % < p > The amount to subtract from the current date.</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.date Js.t ] { % < p > The new Date instance.</p > % }
}
}
does not modify the Date instance being called - it creates and returns
a new Date instance containing the resulting date value.</p>
<p>Examples:</p>
<pre><code>// Basic usage:
var dt = <a href="#!/api/Ext.Date-method-subtract" rel="Ext.Date-method-subtract" class="docClass">Ext.Date.subtract</a>(new Date('10/29/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 5);
console.log(dt); // returns 'Tue Oct 24 2006 00:00:00'
// Negative values will be added:
var dt2 = <a href="#!/api/Ext.Date-method-subtract" rel="Ext.Date-method-subtract" class="docClass">Ext.Date.subtract</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, -5);
console.log(dt2); // returns 'Fri Oct 6 2006 00:00:00'
// Decimal values can be used:
var dt3 = <a href="#!/api/Ext.Date-method-subtract" rel="Ext.Date-method-subtract" class="docClass">Ext.Date.subtract</a>(new Date('10/1/2006'), <a href="#!/api/Ext.Date-property-DAY" rel="Ext.Date-property-DAY" class="docClass">Ext.Date.DAY</a>, 1.25);
console.log(dt3); // returns 'Fri Sep 29 2006 06:00:00'
</code></pre> %}
{b Parameters}:
{ul {- date: [Js.date Js.t]
{% <p>The date to modify</p> %}
}
{- interval: [Js.js_string Js.t]
{% <p>A valid date interval enum value.</p> %}
}
{- value: [Js.number Js.t]
{% <p>The amount to subtract from the current date.</p> %}
}
}
{b Returns}:
{ul {- [Js.date Js.t] {% <p>The new Date instance.</p> %}
}
}
*)
method unescapeFormat : Js.js_string Js.t -> Js.js_string Js.t Js.meth
* { % < p > Removes all escaping for a date format string . In date formats ,
using a ' \ ' can be used to escape special characters.</p > % }
{ b Parameters } :
{ ul { - format : [ Js.js_string Js.t ]
{ % < p > The format to unescape</p > % }
}
}
{ b Returns } :
{ ul { - [ Js.js_string Js.t ] { % < p > The unescaped > % }
}
}
using a '\' can be used to escape special characters.</p> %}
{b Parameters}:
{ul {- format: [Js.js_string Js.t]
{% <p>The format to unescape</p> %}
}
}
{b Returns}:
{ul {- [Js.js_string Js.t] {% <p>The unescaped format</p> %}
}
}
*)
end
class type configs =
object('self)
end
class type events =
object
end
class type statics =
object
end
val get_instance : unit -> t Js.t
val instance : t Js.t
* instance .
val of_configs : configs Js.t -> t Js.t
val to_configs : t Js.t -> configs Js.t
|
269c851aff30c702e44a0073898bb8eeffb71f15f9e7ca1f0737dc714832ad9b
|
LeapYear/aeson-schemas
|
UnwrapQQ.hs
|
# LANGUAGE DataKinds #
# LANGUAGE QuasiQuotes #
# LANGUAGE TypeApplications #
module Tests.UnwrapQQ where
import qualified Data.Text as Text
import Test.Tasty
import Test.Tasty.HUnit
import Text.RawString.QQ (r)
import Data.Aeson.Schema (Object, get)
import TestUtils (json, testParseError)
import Tests.UnwrapQQ.TH
test :: TestTree
test =
testGroup
"`unwrap` quasiquoter"
[ testValidUnwrapDefs
, testInvalidUnwrapDefs
]
testValidUnwrapDefs :: TestTree
testValidUnwrapDefs =
testGroup
"Valid unwrap definitions"
[ testCase "Can unwrap a list" $ do
[unwrapRep| ListSchema.ids |] @?= "[Int]"
[unwrapRep| ListSchema.ids[] |] @?= "Int"
, testCase "Can unwrap a list of keys" $
[unwrapRep| ABCSchema.[a, b] |] @?= "[Bool]"
, testCase "Can unwrap a tuple of keys" $
[unwrapRep| ABCSchema.(a, b, c) |] @?= "(Bool,Bool,Double)"
, testCase "Can unwrap a maybe" $ do
[unwrapRep| MaybeSchema.class |] @?= "Maybe Text"
[unwrapRep| MaybeSchema.class! |] @?= "Text"
[unwrapRep| MaybeSchema.class? |] @?= "Text"
, testCase "Can unwrap a sum type" $ do
[unwrapRep| SumSchema.verbosity@0 |] @?= "Int"
[unwrapRep| SumSchema.verbosity@1 |] @?= "Bool"
, testCase "Can unwrap an included schema" $
[unwrapRep| ListSchema2.list.ids |] @?= "[Int]"
, testCase "Can unwrap an Object twice" $
[unwrapRep| UnwrappedNestedSchema.b |] @?= "Object (SchemaObject { \"c\": Bool })"
, testCase "Can use unwrapped type" $ do
let result :: Object MySchema
result =
[json|
{
"users": [
{ "name": "Alice" },
{ "name": "Bob" },
{ "name": "Claire" }
]
}
|]
users :: [User]
users = [get| result.users |]
getName :: User -> String
getName = Text.unpack . [get| .name |]
map getName users @?= ["Alice", "Bob", "Claire"]
]
testInvalidUnwrapDefs :: TestTree
testInvalidUnwrapDefs =
testGroup
"Invalid unwrap definitions"
[ testCase "Unwrap unknown schema" $
[unwrapErr| FooSchema.asdf |] @?= "Unknown schema: FooSchema"
, testCase "Unwrap non-schema" $
[unwrapErr| NotASchema.foo |] @?= "'Tests.UnwrapQQ.TH.NotASchema' is not a Schema"
, testCase "Unwrap key on non-object" $
[unwrapErr| ListSchema.ids.foo |] @?= "Cannot get key 'foo' in schema: SchemaList Int"
, testCase "Unwrap maybe on non-maybe" $ do
[unwrapErr| ListSchema.ids! |] @?= "Cannot use `!` operator on schema: SchemaList Int"
[unwrapErr| ListSchema.ids? |] @?= "Cannot use `?` operator on schema: SchemaList Int"
, testCase "Unwrap list on non-list" $
[unwrapErr| MaybeSchema.class[] |] @?= "Cannot use `[]` operator on schema: SchemaMaybe Text"
, testCase "Unwrap nonexistent key" $
[unwrapErr| ListSchema.foo |] @?= [r|Key 'foo' does not exist in schema: SchemaObject { "ids": List Int }|]
, testCase "Unwrap list of keys with different types" $
[unwrapErr| ABCSchema.[a,b,c] |] @?= [r|List contains different types in schema: SchemaObject { "a": Bool, "b": Bool, "c": Double }|]
, testCase "Unwrap list of keys on non-object schema" $
[unwrapErr| ListSchema.ids.[a,b] |] @?= "Cannot get keys in schema: SchemaList Int"
, testParseError
"Unwrap beyond list of keys"
"unwrapqq_unwrap_past_list.golden"
[unwrapErr| ABCSchema.[a,b].foo |]
, testCase "Unwrap tuple of keys on non-object schema" $
[unwrapErr| ListSchema.ids.(a,b) |] @?= "Cannot get keys in schema: SchemaList Int"
, testParseError
"Unwrap beyond tuple of keys"
"unwrapqq_unwrap_past_tuple.golden"
[unwrapErr| ABCSchema.(a,b).foo |]
, testCase "Unwrap branch on non-branch" $
[unwrapErr| MaybeSchema.class@0 |] @?= "Cannot use `@` operator on schema: SchemaMaybe Text"
, testCase "Unwrap out of bounds branch" $
[unwrapErr| SumSchema.verbosity@10 |] @?= "Branch out of bounds for schema: SchemaUnion ( Int | Bool )"
]
| null |
https://raw.githubusercontent.com/LeapYear/aeson-schemas/7693390d8f84da6498470ec0a61768a871967abc/test/Tests/UnwrapQQ.hs
|
haskell
|
# LANGUAGE DataKinds #
# LANGUAGE QuasiQuotes #
# LANGUAGE TypeApplications #
module Tests.UnwrapQQ where
import qualified Data.Text as Text
import Test.Tasty
import Test.Tasty.HUnit
import Text.RawString.QQ (r)
import Data.Aeson.Schema (Object, get)
import TestUtils (json, testParseError)
import Tests.UnwrapQQ.TH
test :: TestTree
test =
testGroup
"`unwrap` quasiquoter"
[ testValidUnwrapDefs
, testInvalidUnwrapDefs
]
testValidUnwrapDefs :: TestTree
testValidUnwrapDefs =
testGroup
"Valid unwrap definitions"
[ testCase "Can unwrap a list" $ do
[unwrapRep| ListSchema.ids |] @?= "[Int]"
[unwrapRep| ListSchema.ids[] |] @?= "Int"
, testCase "Can unwrap a list of keys" $
[unwrapRep| ABCSchema.[a, b] |] @?= "[Bool]"
, testCase "Can unwrap a tuple of keys" $
[unwrapRep| ABCSchema.(a, b, c) |] @?= "(Bool,Bool,Double)"
, testCase "Can unwrap a maybe" $ do
[unwrapRep| MaybeSchema.class |] @?= "Maybe Text"
[unwrapRep| MaybeSchema.class! |] @?= "Text"
[unwrapRep| MaybeSchema.class? |] @?= "Text"
, testCase "Can unwrap a sum type" $ do
[unwrapRep| SumSchema.verbosity@0 |] @?= "Int"
[unwrapRep| SumSchema.verbosity@1 |] @?= "Bool"
, testCase "Can unwrap an included schema" $
[unwrapRep| ListSchema2.list.ids |] @?= "[Int]"
, testCase "Can unwrap an Object twice" $
[unwrapRep| UnwrappedNestedSchema.b |] @?= "Object (SchemaObject { \"c\": Bool })"
, testCase "Can use unwrapped type" $ do
let result :: Object MySchema
result =
[json|
{
"users": [
{ "name": "Alice" },
{ "name": "Bob" },
{ "name": "Claire" }
]
}
|]
users :: [User]
users = [get| result.users |]
getName :: User -> String
getName = Text.unpack . [get| .name |]
map getName users @?= ["Alice", "Bob", "Claire"]
]
testInvalidUnwrapDefs :: TestTree
testInvalidUnwrapDefs =
testGroup
"Invalid unwrap definitions"
[ testCase "Unwrap unknown schema" $
[unwrapErr| FooSchema.asdf |] @?= "Unknown schema: FooSchema"
, testCase "Unwrap non-schema" $
[unwrapErr| NotASchema.foo |] @?= "'Tests.UnwrapQQ.TH.NotASchema' is not a Schema"
, testCase "Unwrap key on non-object" $
[unwrapErr| ListSchema.ids.foo |] @?= "Cannot get key 'foo' in schema: SchemaList Int"
, testCase "Unwrap maybe on non-maybe" $ do
[unwrapErr| ListSchema.ids! |] @?= "Cannot use `!` operator on schema: SchemaList Int"
[unwrapErr| ListSchema.ids? |] @?= "Cannot use `?` operator on schema: SchemaList Int"
, testCase "Unwrap list on non-list" $
[unwrapErr| MaybeSchema.class[] |] @?= "Cannot use `[]` operator on schema: SchemaMaybe Text"
, testCase "Unwrap nonexistent key" $
[unwrapErr| ListSchema.foo |] @?= [r|Key 'foo' does not exist in schema: SchemaObject { "ids": List Int }|]
, testCase "Unwrap list of keys with different types" $
[unwrapErr| ABCSchema.[a,b,c] |] @?= [r|List contains different types in schema: SchemaObject { "a": Bool, "b": Bool, "c": Double }|]
, testCase "Unwrap list of keys on non-object schema" $
[unwrapErr| ListSchema.ids.[a,b] |] @?= "Cannot get keys in schema: SchemaList Int"
, testParseError
"Unwrap beyond list of keys"
"unwrapqq_unwrap_past_list.golden"
[unwrapErr| ABCSchema.[a,b].foo |]
, testCase "Unwrap tuple of keys on non-object schema" $
[unwrapErr| ListSchema.ids.(a,b) |] @?= "Cannot get keys in schema: SchemaList Int"
, testParseError
"Unwrap beyond tuple of keys"
"unwrapqq_unwrap_past_tuple.golden"
[unwrapErr| ABCSchema.(a,b).foo |]
, testCase "Unwrap branch on non-branch" $
[unwrapErr| MaybeSchema.class@0 |] @?= "Cannot use `@` operator on schema: SchemaMaybe Text"
, testCase "Unwrap out of bounds branch" $
[unwrapErr| SumSchema.verbosity@10 |] @?= "Branch out of bounds for schema: SchemaUnion ( Int | Bool )"
]
|
|
f45d9fed33357d66f4181b51111388f745b80ad919d1a504d5328cd495c4a54e
|
JustusAdam/language-haskell
|
T0131.hs
|
SYNTAX TEST " source.haskell " " LiquidHaskell annotations "
@ incr : : x : { v : v > x } @
< --------------------------------------- block.liquidhaskell.haskell
^^ keyword.operator.double-colon.haskell
-- ^^ keyword.operator.arrow.haskell
-- -------------------------------- - comment.block.haskell
-- ^^^ - keyword.type.operator.haskell
incr :: Int -> Int
incr x = x + 1
| null |
https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tickets/T0131.hs
|
haskell
|
------------------------------------- block.liquidhaskell.haskell
^^ keyword.operator.arrow.haskell
-------------------------------- - comment.block.haskell
^^^ - keyword.type.operator.haskell
|
SYNTAX TEST " source.haskell " " LiquidHaskell annotations "
@ incr : : x : { v : v > x } @
^^ keyword.operator.double-colon.haskell
incr :: Int -> Int
incr x = x + 1
|
15c10902030259602dcf2b1d5e639a7dcec356593df03dca6ccab071f1457993
|
scslab/gitstar
|
Config.hs
|
# LANGUAGE CPP #
#if PRODUCTION
{-# LANGUAGE Safe #-}
#endif
| This module exports the gitstar ssh server API location and
-- authorization. It is important that the real file not be added
-- to the git repo
module Config ( gitstar_ssh_web_url
, gitstar_ssh_web_authorization ) where
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Base64 as B64
| Url to the gitstar ssh API server
gitstar_ssh_web_url :: String
gitstar_ssh_web_url = ":9292/"
-- | Authorization for accessing server
gitstar_ssh_web_authorization :: S8.ByteString
gitstar_ssh_web_authorization = S8.pack "Basic " `S8.append`
B64.encode (S8.pack "gitstar:w00t")
| null |
https://raw.githubusercontent.com/scslab/gitstar/589663b54d26468a9407be3d9d5ffa4dfa4962a8/Config.hs
|
haskell
|
# LANGUAGE Safe #
authorization. It is important that the real file not be added
to the git repo
| Authorization for accessing server
|
# LANGUAGE CPP #
#if PRODUCTION
#endif
| This module exports the gitstar ssh server API location and
module Config ( gitstar_ssh_web_url
, gitstar_ssh_web_authorization ) where
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Base64 as B64
| Url to the gitstar ssh API server
gitstar_ssh_web_url :: String
gitstar_ssh_web_url = ":9292/"
gitstar_ssh_web_authorization :: S8.ByteString
gitstar_ssh_web_authorization = S8.pack "Basic " `S8.append`
B64.encode (S8.pack "gitstar:w00t")
|
83c7f2ad8881eb19406ada3c1c2956f4a429328e346f4160f71668e9992b1ec2
|
mzp/coq-for-ipad
|
printtyp.ml
|
(***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
and , projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : printtyp.ml 10333 2010 - 04 - 30 07:11:27Z garrigue $
(* Printing functions *)
open Misc
open Ctype
open Format
open Longident
open Path
open Asttypes
open Types
open Btype
open Outcometree
(* Print a long identifier *)
let rec longident ppf = function
| Lident s -> fprintf ppf "%s" s
| Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
| Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
(* Print an identifier *)
let unique_names = ref Ident.empty
let ident_name id =
try Ident.find_same id !unique_names with Not_found -> Ident.name id
let add_unique id =
try ignore (Ident.find_same id !unique_names)
with Not_found ->
unique_names := Ident.add id (Ident.unique_toplevel_name id) !unique_names
let ident ppf id = fprintf ppf "%s" (ident_name id)
(* Print a path *)
let ident_pervasive = Ident.create_persistent "Pervasives"
let rec tree_of_path = function
| Pident id ->
Oide_ident (ident_name id)
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
Oide_ident s
| Pdot(p, s, pos) ->
Oide_dot (tree_of_path p, s)
| Papply(p1, p2) ->
Oide_apply (tree_of_path p1, tree_of_path p2)
let rec path ppf = function
| Pident id ->
ident ppf id
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
fprintf ppf "%s" s
| Pdot(p, s, pos) ->
fprintf ppf "%a.%s" path p s
| Papply(p1, p2) ->
fprintf ppf "%a(%a)" path p1 path p2
(* Print a recursive annotation *)
let tree_of_rec = function
| Trec_not -> Orec_not
| Trec_first -> Orec_first
| Trec_next -> Orec_next
(* Print a raw type expression, with sharing *)
let raw_list pr ppf = function
[] -> fprintf ppf "[]"
| a :: l ->
fprintf ppf "@[<1>[%a%t]@]" pr a
(fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
let rec safe_kind_repr v = function
Fvar {contents=Some k} ->
if List.memq k v then "Fvar loop" else
safe_kind_repr (k::v) k
| Fvar _ -> "Fvar None"
| Fpresent -> "Fpresent"
| Fabsent -> "Fabsent"
let rec safe_commu_repr v = function
Cok -> "Cok"
| Cunknown -> "Cunknown"
| Clink r ->
if List.memq r v then "Clink loop" else
safe_commu_repr (r::v) !r
let rec safe_repr v = function
{desc = Tlink t} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
let rec list_of_memo = function
Mnil -> []
| Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
| Mlink rem -> list_of_memo !rem
let visited = ref []
let rec raw_type ppf ty =
let ty = safe_repr [] ty in
if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
visited := ty :: !visited;
fprintf ppf "@[<1>{id=%d;level=%d;desc=@,%a}@]" ty.id ty.level
raw_type_desc ty.desc
end
and raw_type_list tl = raw_list raw_type tl
and raw_type_desc ppf = function
Tvar -> fprintf ppf "Tvar"
| Tarrow(l,t1,t2,c) ->
fprintf ppf "@[<hov1>Tarrow(%s,@,%a,@,%a,@,%s)@]"
l raw_type t1 raw_type t2
(safe_commu_repr [] c)
| Ttuple tl ->
fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
| Tconstr (p, tl, abbrev) ->
fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
raw_type_list tl
(raw_list path) (list_of_memo !abbrev)
| Tobject (t, nm) ->
fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
(fun ppf ->
match !nm with None -> fprintf ppf " None"
| Some(p,tl) ->
fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
| Tfield (f, k, t1, t2) ->
fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
(safe_kind_repr [] k)
raw_type t1 raw_type t2
| Tnil -> fprintf ppf "Tnil"
| Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
| Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
| Tunivar -> fprintf ppf "Tunivar"
| Tpoly (t, tl) ->
fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
raw_type t
raw_type_list tl
| Tvariant row ->
fprintf ppf
"@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%b;@ %s%b;@ @[<1>%s%t@]}@]"
"row_fields="
(raw_list (fun ppf (l, f) ->
fprintf ppf "@[%s,@ %a@]" l raw_field f))
row.row_fields
"row_more=" raw_type row.row_more
"row_closed=" row.row_closed
"row_fixed=" row.row_fixed
"row_name="
(fun ppf ->
match row.row_name with None -> fprintf ppf "None"
| Some(p,tl) ->
fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
| Tpackage (p, _, tl) ->
fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
raw_type_list tl
and raw_field ppf = function
Rpresent None -> fprintf ppf "Rpresent None"
| Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
| Reither (c,tl,m,e) ->
fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
raw_type_list tl m
(fun ppf ->
match !e with None -> fprintf ppf " None"
| Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
| Rabsent -> fprintf ppf "Rabsent"
let raw_type_expr ppf t =
visited := [];
raw_type ppf t;
visited := []
(* Print a type expression *)
let names = ref ([] : (type_expr * string) list)
let name_counter = ref 0
let reset_names () = names := []; name_counter := 0
let new_name () =
let name =
if !name_counter < 26
then String.make 1 (Char.chr(97 + !name_counter))
else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
string_of_int(!name_counter / 26) in
incr name_counter;
name
let name_of_type t =
try List.assq t !names with Not_found ->
let name = new_name () in
names := (t, name) :: !names;
name
let check_name_of_type t = ignore(name_of_type t)
let non_gen_mark sch ty =
if sch && ty.desc = Tvar && ty.level <> generic_level then "_" else ""
let print_name_of_type sch ppf t =
fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
let visited_objects = ref ([] : type_expr list)
let aliased = ref ([] : type_expr list)
let delayed = ref ([] : type_expr list)
let add_delayed t =
if not (List.memq t !delayed) then delayed := t :: !delayed
let is_aliased ty = List.memq (proxy ty) !aliased
let add_alias ty =
let px = proxy ty in
if not (is_aliased px) then aliased := px :: !aliased
let aliasable ty =
match ty.desc with Tvar | Tunivar | Tpoly _ -> false | _ -> true
let namable_row row =
row.row_name <> None &&
List.for_all
(fun (_, f) ->
match row_field_repr f with
| Reither(c, l, _, _) ->
row.row_closed && if c then l = [] else List.length l = 1
| _ -> true)
row.row_fields
let rec mark_loops_rec visited ty =
let ty = repr ty in
let px = proxy ty in
if List.memq px visited && aliasable ty then add_alias px else
let visited = px :: visited in
match ty.desc with
| Tvar -> ()
| Tarrow(_, ty1, ty2, _) ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
| Tconstr(_, tyl, _) | Tpackage (_, _, tyl) ->
List.iter (mark_loops_rec visited) tyl
| Tvariant row ->
if List.memq px !visited_objects then add_alias px else
begin
let row = row_repr row in
if not (static_row row) then
visited_objects := px :: !visited_objects;
match row.row_name with
| Some(p, tyl) when namable_row row ->
List.iter (mark_loops_rec visited) tyl
| _ ->
iter_row (mark_loops_rec visited) row
end
| Tobject (fi, nm) ->
if List.memq px !visited_objects then add_alias px else
begin
if opened_object ty then
visited_objects := px :: !visited_objects;
begin match !nm with
| None ->
let fields, _ = flatten_fields fi in
List.iter
(fun (_, kind, ty) ->
if field_kind_repr kind = Fpresent then
mark_loops_rec visited ty)
fields
| Some (_, l) ->
List.iter (mark_loops_rec visited) (List.tl l)
end
end
| Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Tfield(_, _, _, ty2) ->
mark_loops_rec visited ty2
| Tnil -> ()
| Tsubst ty -> mark_loops_rec visited ty
| Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
| Tpoly (ty, tyl) ->
List.iter (fun t -> add_alias t) tyl;
mark_loops_rec visited ty
| Tunivar -> ()
let mark_loops ty =
normalize_type Env.empty ty;
mark_loops_rec [] ty;;
let reset_loop_marks () =
visited_objects := []; aliased := []; delayed := []
let reset () =
unique_names := Ident.empty; reset_names (); reset_loop_marks ()
let reset_and_mark_loops ty =
reset (); mark_loops ty
let reset_and_mark_loops_list tyl =
reset (); List.iter mark_loops tyl
(* Disabled in classic mode when printing an unification error *)
let print_labels = ref true
let print_label ppf l =
if !print_labels && l <> "" || is_optional l then fprintf ppf "%s:" l
let rec tree_of_typexp sch ty =
let ty = repr ty in
let px = proxy ty in
if List.mem_assq px !names && not (List.memq px !delayed) then
let mark = is_non_gen sch ty in
Otyp_var (mark, name_of_type px) else
let pr_typ () =
match ty.desc with
| Tvar ->
Otyp_var (is_non_gen sch ty, name_of_type ty)
| Tarrow(l, ty1, ty2, _) ->
let pr_arrow l ty1 ty2 =
let lab =
if !print_labels && l <> "" || is_optional l then l else ""
in
let t1 =
if is_optional l then
match (repr ty1).desc with
| Tconstr(path, [ty], _)
when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty1 in
Otyp_arrow (lab, t1, tree_of_typexp sch ty2) in
pr_arrow l ty1 ty2
| Ttuple tyl ->
Otyp_tuple (tree_of_typlist sch tyl)
| Tconstr(p, tyl, abbrev) ->
Otyp_constr (tree_of_path p, tree_of_typlist sch tyl)
| Tvariant row ->
let row = row_repr row in
let fields =
if row.row_closed then
List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
row.row_fields
else row.row_fields in
let present =
List.filter
(fun (_, f) ->
match row_field_repr f with
| Rpresent _ -> true
| _ -> false)
fields in
let all_present = List.length present = List.length fields in
begin match row.row_name with
| Some(p, tyl) when namable_row row ->
let id = tree_of_path p in
let args = tree_of_typlist sch tyl in
if row.row_closed && all_present then
Otyp_constr (id, args)
else
let non_gen = is_non_gen sch px in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_name(tree_of_path p, args),
row.row_closed, tags)
| _ ->
let non_gen =
not (row.row_closed && all_present) && is_non_gen sch px in
let fields = List.map (tree_of_row_field sch) fields in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
end
| Tobject (fi, nm) ->
tree_of_typobject sch fi nm
| Tsubst ty ->
tree_of_typexp sch ty
| Tlink _ | Tnil | Tfield _ ->
fatal_error "Printtyp.tree_of_typexp"
| Tpoly (ty, []) ->
tree_of_typexp sch ty
| Tpoly (ty, tyl) ->
let tyl = List.map repr tyl in
let tyl = List.filter is_aliased tyl in
if tyl = [] then tree_of_typexp sch ty else begin
let old_delayed = !delayed in
List.iter add_delayed tyl;
let tl = List.map name_of_type tyl in
let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
delayed := old_delayed; tr
end
| Tunivar ->
Otyp_var (false, name_of_type ty)
| Tpackage (p, n, tyl) ->
Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
in
if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
if is_aliased px && aliasable ty then begin
check_name_of_type px;
Otyp_alias (pr_typ (), name_of_type px) end
else pr_typ ()
and tree_of_row_field sch (l, f) =
match row_field_repr f with
| Rpresent None | Reither(true, [], _, _) -> (l, false, [])
| Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
| Reither(c, tyl, _, _) ->
contradiction : un constructeur constant qui a un argument
then (l, true, tree_of_typlist sch tyl)
else (l, false, tree_of_typlist sch tyl)
| Rabsent -> (l, false, [] (* une erreur, en fait *))
and tree_of_typlist sch tyl =
List.map (tree_of_typexp sch) tyl
and tree_of_typobject sch fi nm =
begin match !nm with
| None ->
let pr_fields fi =
let (fields, rest) = flatten_fields fi in
let present_fields =
List.fold_right
(fun (n, k, t) l ->
match field_kind_repr k with
| Fpresent -> (n, t) :: l
| _ -> l)
fields [] in
let sorted_fields =
Sort.list (fun (n, _) (n', _) -> n <= n') present_fields in
tree_of_typfields sch rest sorted_fields in
let (fields, rest) = pr_fields fi in
Otyp_object (fields, rest)
| Some (p, ty :: tyl) ->
let non_gen = is_non_gen sch (repr ty) in
let args = tree_of_typlist sch tyl in
Otyp_class (non_gen, tree_of_path p, args)
| _ ->
fatal_error "Printtyp.tree_of_typobject"
end
and is_non_gen sch ty =
sch && ty.desc = Tvar && ty.level <> generic_level
and tree_of_typfields sch rest = function
| [] ->
let rest =
match rest.desc with
| Tvar | Tunivar -> Some (is_non_gen sch rest)
| Tconstr _ -> Some false
| Tnil -> None
| _ -> fatal_error "typfields (1)"
in
([], rest)
| (s, t) :: l ->
let field = (s, tree_of_typexp sch t) in
let (fields, rest) = tree_of_typfields sch rest l in
(field :: fields, rest)
let typexp sch prio ppf ty =
!Oprint.out_type ppf (tree_of_typexp sch ty)
let type_expr ppf ty = typexp false 0 ppf ty
and type_sch ppf ty = typexp true 0 ppf ty
and type_scheme ppf ty = reset_and_mark_loops ty; typexp true 0 ppf ty
(* Maxence *)
let type_scheme_max ?(b_reset_names=true) ppf ty =
if b_reset_names then reset_names () ;
typexp true 0 ppf ty
let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
Print one type declaration
let tree_of_constraints params =
List.fold_right
(fun ty list ->
let ty' = unalias ty in
if proxy ty != proxy ty' then
let tr = tree_of_typexp true ty in
(tr, tree_of_typexp true ty') :: list
else list)
params []
let filter_params tyl =
let params =
List.fold_left
(fun tyl ty ->
let ty = repr ty in
if List.memq ty tyl then Btype.newgenty (Tsubst ty) :: tyl
else ty :: tyl)
[] tyl
in List.rev params
let string_of_mutable = function
| Immutable -> ""
| Mutable -> "mutable "
let rec tree_of_type_decl id decl =
reset();
let params = filter_params decl.type_params in
List.iter add_alias params;
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
let ty_manifest =
match decl.type_manifest with
| None -> None
| Some ty ->
let ty =
(* Special hack to hide variant name *)
match repr ty with {desc=Tvariant row} ->
let row = row_repr row in
begin match row.row_name with
Some (Pident id', _) when Ident.same id id' ->
newgenty (Tvariant {row with row_name = None})
| _ -> ty
end
| _ -> ty
in
mark_loops ty;
Some ty
in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant [] -> ()
| Type_variant cstrs ->
List.iter (fun (_, args) -> List.iter mark_loops args) cstrs
| Type_record(l, rep) ->
List.iter (fun (_, _, ty) -> mark_loops ty) l
end;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let type_defined decl =
let abstr =
match decl.type_kind with
Type_abstract ->
decl.type_manifest = None || decl.type_private = Private
| Type_variant _ | Type_record _ ->
decl.type_private = Private
in
let vari =
List.map2
(fun ty (co,cn,ct) ->
if abstr || (repr ty).desc <> Tvar then (co,cn) else (true,true))
decl.type_params decl.type_variance
in
(Ident.name id,
List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
params vari)
in
let tree_of_manifest ty1 =
match ty_manifest with
| None -> ty1
| Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
in
let (name, args) = type_defined decl in
let constraints = tree_of_constraints params in
let ty, priv =
match decl.type_kind with
| Type_abstract ->
begin match ty_manifest with
| None -> (Otyp_abstract, Public)
| Some ty ->
tree_of_typexp false ty, decl.type_private
end
| Type_variant cstrs ->
tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
decl.type_private
| Type_record(lbls, rep) ->
tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
decl.type_private
in
(name, args, ty, priv, constraints)
and tree_of_constructor (name, args) =
(name, tree_of_typlist false args)
and tree_of_label (name, mut, arg) =
(name, mut = Mutable, tree_of_typexp false arg)
let tree_of_type_declaration id decl rs =
Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
let type_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
(* Print an exception declaration *)
let tree_of_exception_declaration id decl =
reset_and_mark_loops_list decl;
let tyl = tree_of_typlist false decl in
Osig_exception (Ident.name id, tyl)
let exception_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_exception_declaration id decl)
(* Print a value declaration *)
let tree_of_value_description id decl =
let id = Ident.name id in
let ty = tree_of_type_scheme decl.val_type in
let prims =
match decl.val_kind with
| Val_prim p -> Primitive.description_list p
| _ -> []
in
Osig_value (id, ty, prims)
let value_description id ppf decl =
!Oprint.out_sig_item ppf (tree_of_value_description id decl)
(* Print a class type *)
let class_var sch ppf l (m, t) =
fprintf ppf
"@ @[<2>val %s%s :@ %a@]" (string_of_mutable m) l (typexp sch 0) t
let method_type (_, kind, ty) =
match field_kind_repr kind, repr ty with
Fpresent, {desc=Tpoly(ty, _)} -> ty
| _ , ty -> ty
let tree_of_metho sch concrete csil (lab, kind, ty) =
if lab <> dummy_method then begin
let kind = field_kind_repr kind in
let priv = kind <> Fpresent in
let virt = not (Concr.mem lab concrete) in
let ty = method_type (lab, kind, ty) in
Ocsg_method (lab, priv, virt, tree_of_typexp sch ty) :: csil
end
else csil
let rec prepare_class_type params = function
| Tcty_constr (p, tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
|| List.exists (deep_occur sty) tyl
then prepare_class_type params cty
else List.iter mark_loops tyl
| Tcty_signature sign ->
let sty = repr sign.cty_self in
(* Self may have a name *)
let px = proxy sty in
if List.memq px !visited_objects then add_alias sty
else visited_objects := px :: !visited_objects;
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
List.iter (fun met -> mark_loops (method_type met)) fields;
Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
| Tcty_fun (_, ty, cty) ->
mark_loops ty;
prepare_class_type params cty
let rec tree_of_class_type sch params =
function
| Tcty_constr (p', tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
then
tree_of_class_type sch params cty
else
Octy_constr (tree_of_path p', tree_of_typlist true tyl)
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let self_ty =
if is_aliased sty then
Some (Otyp_var (false, name_of_type (proxy sty)))
else None
in
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
let csil = [] in
let csil =
List.fold_left
(fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
csil (tree_of_constraints params)
in
let all_vars =
Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.cty_vars []
in
Consequence of PR#3607 : order of Map.fold has changed !
let all_vars = List.rev all_vars in
let csil =
List.fold_left
(fun csil (l, m, v, t) ->
Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
:: csil)
csil all_vars
in
let csil =
List.fold_left (tree_of_metho sch sign.cty_concr) csil fields
in
Octy_signature (self_ty, List.rev csil)
| Tcty_fun (l, ty, cty) ->
let lab = if !print_labels && l <> "" || is_optional l then l else "" in
let ty =
if is_optional l then
match (repr ty).desc with
| Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
| _ -> newconstr (Path.Pident(Ident.create "<hidden>")) []
else ty in
let tr = tree_of_typexp sch ty in
Octy_fun (lab, tr, tree_of_class_type sch params cty)
let class_type ppf cty =
reset ();
prepare_class_type [] cty;
!Oprint.out_class_type ppf (tree_of_class_type false [] cty)
let tree_of_class_param param variance =
(match tree_of_typexp true param with
Otyp_var (_, s) -> s
| _ -> "?"),
if (repr param).desc = Tvar then (true, true) else variance
let tree_of_class_params params =
let tyl = tree_of_typlist true params in
List.map (function Otyp_var (_, s) -> s | _ -> "?") tyl
let tree_of_class_declaration id cl rs =
let params = filter_params cl.cty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.cty_type;
let sty = self_type cl.cty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let vir_flag = cl.cty_new = None in
Osig_class
(vir_flag, Ident.name id,
List.map2 tree_of_class_param params cl.cty_variance,
tree_of_class_type true params cl.cty_type,
tree_of_rec rs)
let class_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
let tree_of_cltype_declaration id cl rs =
let params = List.map repr cl.clty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.clty_type;
let sty = self_type cl.clty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let sign = Ctype.signature_of_class_type cl.clty_type in
let virt =
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in
List.exists
(fun (lab, _, ty) ->
not (lab = dummy_method || Concr.mem lab sign.cty_concr))
fields
|| Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.cty_vars false
in
Osig_class_type
(virt, Ident.name id,
List.map2 tree_of_class_param params cl.clty_variance,
tree_of_class_type true params cl.clty_type,
tree_of_rec rs)
let cltype_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
(* Print a module type *)
let rec tree_of_modtype = function
| Tmty_ident p ->
Omty_ident (tree_of_path p)
| Tmty_signature sg ->
Omty_signature (tree_of_signature sg)
| Tmty_functor(param, ty_arg, ty_res) ->
Omty_functor
(Ident.name param, tree_of_modtype ty_arg, tree_of_modtype ty_res)
and tree_of_signature = function
| [] -> []
| Tsig_value(id, decl) :: rem ->
tree_of_value_description id decl :: tree_of_signature rem
| Tsig_type(id, _, _) :: rem when is_row_name (Ident.name id) ->
tree_of_signature rem
| Tsig_type(id, decl, rs) :: rem ->
Osig_type(tree_of_type_decl id decl, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_exception(id, decl) :: rem ->
tree_of_exception_declaration id decl :: tree_of_signature rem
| Tsig_module(id, mty, rs) :: rem ->
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_modtype(id, decl) :: rem ->
tree_of_modtype_declaration id decl :: tree_of_signature rem
| Tsig_class(id, decl, rs) :: ctydecl :: tydecl1 :: tydecl2 :: rem ->
tree_of_class_declaration id decl rs :: tree_of_signature rem
| Tsig_cltype(id, decl, rs) :: tydecl1 :: tydecl2 :: rem ->
tree_of_cltype_declaration id decl rs :: tree_of_signature rem
| _ ->
assert false
and tree_of_modtype_declaration id decl =
let mty =
match decl with
| Tmodtype_abstract -> Omty_abstract
| Tmodtype_manifest mty -> tree_of_modtype mty
in
Osig_modtype (Ident.name id, mty)
let tree_of_module id mty rs =
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs)
let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
let modtype_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
Print a signature body ( used by -i when compiling a .ml )
let print_signature ppf tree =
fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
let signature ppf sg =
fprintf ppf "%a" print_signature (tree_of_signature sg)
(* Print an unification error *)
let type_expansion t ppf t' =
if t == t' then type_expr ppf t else
let t' = if proxy t == proxy t' then unalias t' else t' in
fprintf ppf "@[<2>%a@ =@ %a@]" type_expr t type_expr t'
let rec trace fst txt ppf = function
| (t1, t1') :: (t2, t2') :: rem ->
if not fst then fprintf ppf "@,";
fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
(type_expansion t1) t1' txt (type_expansion t2) t2'
(trace false txt) rem
| _ -> ()
let rec filter_trace = function
| (t1, t1') :: (t2, t2') :: rem ->
let rem' = filter_trace rem in
if t1 == t1' && t2 == t2'
then rem'
else (t1, t1') :: (t2, t2') :: rem'
| _ -> []
(* Hide variant name and var, to force printing the expanded type *)
let hide_variant_name t =
match repr t with
| {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
newty2 t.level
(Tvariant {(row_repr row) with row_name = None;
row_more = newty2 (row_more row).level Tvar})
| _ -> t
let prepare_expansion (t, t') =
let t' = hide_variant_name t' in
mark_loops t; if t != t' then mark_loops t';
(t, t')
let may_prepare_expansion compact (t, t') =
match (repr t').desc with
Tvariant _ | Tobject _ when compact ->
mark_loops t; (t, t)
| _ -> prepare_expansion (t, t')
let print_tags ppf fields =
match fields with [] -> ()
| (t, _) :: fields ->
fprintf ppf "`%s" t;
List.iter (fun (t, _) -> fprintf ppf ",@ `%s" t) fields
let has_explanation unif t3 t4 =
match t3.desc, t4.desc with
Tfield _, _ | _, Tfield _
| Tunivar, Tvar | Tvar, Tunivar
| Tvariant _, Tvariant _ -> true
| Tconstr (p, _, _), Tvar | Tvar, Tconstr (p, _, _) ->
unif && min t3.level t4.level < Path.binding_time p
| _ -> false
let rec mismatch unif = function
(_, t) :: (_, t') :: rem ->
begin match mismatch unif rem with
Some _ as m -> m
| None ->
if has_explanation unif t t' then Some(t,t') else None
end
| [] -> None
| _ -> assert false
let explanation unif t3 t4 ppf =
match t3.desc, t4.desc with
| Tfield _, Tvar | Tvar, Tfield _ ->
fprintf ppf "@,Self type cannot escape its class"
| Tconstr (p, _, _), Tvar
when unif && t4.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tconstr (p, _, _)
when unif && t3.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tunivar | Tunivar, Tvar ->
fprintf ppf "@,The universal variable %a would escape its scope"
type_expr (if t3.desc = Tunivar then t3 else t4)
| Tfield (lab, _, _, _), _
| _, Tfield (lab, _, _, _) when lab = dummy_method ->
fprintf ppf
"@,Self type cannot be unified with a closed object type"
| Tfield (l, _, _, _), Tfield (l', _, _, _) when l = l' ->
fprintf ppf "@,Types for method %s are incompatible" l
| _, Tfield (l, _, _, _) ->
fprintf ppf
"@,@[The first object type has no method %s@]" l
| Tfield (l, _, _, _), _ ->
fprintf ppf
"@,@[The second object type has no method %s@]" l
| Tvariant row1, Tvariant row2 ->
let row1 = row_repr row1 and row2 = row_repr row2 in
begin match
row1.row_fields, row1.row_closed, row2.row_fields, row2.row_closed with
| [], true, [], true ->
fprintf ppf "@,These two variant types have no intersection"
| [], true, fields, _ ->
fprintf ppf
"@,@[The first variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| fields, _, [], true ->
fprintf ppf
"@,@[The second variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| [l1,_], true, [l2,_], true when l1 = l2 ->
fprintf ppf "@,Types for tag `%s are incompatible" l1
| _ -> ()
end
| _ -> ()
let explanation unif mis ppf =
match mis with
None -> ()
| Some (t3, t4) -> explanation unif t3 t4 ppf
let ident_same_name id1 id2 =
if Ident.equal id1 id2 && not (Ident.same id1 id2) then begin
add_unique id1; add_unique id2
end
let rec path_same_name p1 p2 =
match p1, p2 with
Pident id1, Pident id2 -> ident_same_name id1 id2
| Pdot (p1, s1, _), Pdot (p2, s2, _) when s1 = s2 -> path_same_name p1 p2
| Papply (p1, p1'), Papply (p2, p2') ->
path_same_name p1 p2; path_same_name p1' p2'
| _ -> ()
let type_same_name t1 t2 =
match (repr t1).desc, (repr t2).desc with
Tconstr (p1, _, _), Tconstr (p2, _, _) -> path_same_name p1 p2
| _ -> ()
let rec trace_same_names = function
(t1, t1') :: (t2, t2') :: rem ->
type_same_name t1 t2; type_same_name t1' t2'; trace_same_names rem
| _ -> ()
let unification_error unif tr txt1 ppf txt2 =
reset ();
trace_same_names tr;
let tr = List.map (fun (t, t') -> (t, hide_variant_name t')) tr in
let mis = mismatch unif tr in
match tr with
| [] | _ :: [] -> assert false
| t1 :: t2 :: tr ->
try
let tr = filter_trace tr in
let t1, t1' = may_prepare_expansion (tr = []) t1
and t2, t2' = may_prepare_expansion (tr = []) t2 in
print_labels := not !Clflags.classic;
let tr = List.map prepare_expansion tr in
fprintf ppf
"@[<v>\
@[%t@;<1 2>%a@ \
%t@;<1 2>%a\
@]%a%t\
@]"
txt1 (type_expansion t1) t1'
txt2 (type_expansion t2) t2'
(trace false "is not compatible with type") tr
(explanation unif mis);
print_labels := true
with exn ->
print_labels := true;
raise exn
let report_unification_error ppf tr txt1 txt2 =
unification_error true tr txt1 ppf txt2;;
let trace fst txt ppf tr =
print_labels := not !Clflags.classic;
trace_same_names tr;
try match tr with
t1 :: t2 :: tr' ->
if fst then trace fst txt ppf (t1 :: t2 :: filter_trace tr')
else trace fst txt ppf (filter_trace tr);
print_labels := true
| _ -> ()
with exn ->
print_labels := true;
raise exn
let report_subtyping_error ppf tr1 txt1 tr2 =
reset ();
let tr1 = List.map prepare_expansion tr1
and tr2 = List.map prepare_expansion tr2 in
trace true txt1 ppf tr1;
if tr2 = [] then () else
let mis = mismatch true tr2 in
trace false "is not compatible with type" ppf tr2;
explanation true mis ppf
| null |
https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/typing/printtyp.ml
|
ocaml
|
*********************************************************************
Objective Caml
*********************************************************************
Printing functions
Print a long identifier
Print an identifier
Print a path
Print a recursive annotation
Print a raw type expression, with sharing
Print a type expression
Disabled in classic mode when printing an unification error
une erreur, en fait
Maxence
Special hack to hide variant name
Print an exception declaration
Print a value declaration
Print a class type
Self may have a name
Print a module type
Print an unification error
Hide variant name and var, to force printing the expanded type
|
and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : printtyp.ml 10333 2010 - 04 - 30 07:11:27Z garrigue $
open Misc
open Ctype
open Format
open Longident
open Path
open Asttypes
open Types
open Btype
open Outcometree
let rec longident ppf = function
| Lident s -> fprintf ppf "%s" s
| Ldot(p, s) -> fprintf ppf "%a.%s" longident p s
| Lapply(p1, p2) -> fprintf ppf "%a(%a)" longident p1 longident p2
let unique_names = ref Ident.empty
let ident_name id =
try Ident.find_same id !unique_names with Not_found -> Ident.name id
let add_unique id =
try ignore (Ident.find_same id !unique_names)
with Not_found ->
unique_names := Ident.add id (Ident.unique_toplevel_name id) !unique_names
let ident ppf id = fprintf ppf "%s" (ident_name id)
let ident_pervasive = Ident.create_persistent "Pervasives"
let rec tree_of_path = function
| Pident id ->
Oide_ident (ident_name id)
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
Oide_ident s
| Pdot(p, s, pos) ->
Oide_dot (tree_of_path p, s)
| Papply(p1, p2) ->
Oide_apply (tree_of_path p1, tree_of_path p2)
let rec path ppf = function
| Pident id ->
ident ppf id
| Pdot(Pident id, s, pos) when Ident.same id ident_pervasive ->
fprintf ppf "%s" s
| Pdot(p, s, pos) ->
fprintf ppf "%a.%s" path p s
| Papply(p1, p2) ->
fprintf ppf "%a(%a)" path p1 path p2
let tree_of_rec = function
| Trec_not -> Orec_not
| Trec_first -> Orec_first
| Trec_next -> Orec_next
let raw_list pr ppf = function
[] -> fprintf ppf "[]"
| a :: l ->
fprintf ppf "@[<1>[%a%t]@]" pr a
(fun ppf -> List.iter (fun x -> fprintf ppf ";@,%a" pr x) l)
let rec safe_kind_repr v = function
Fvar {contents=Some k} ->
if List.memq k v then "Fvar loop" else
safe_kind_repr (k::v) k
| Fvar _ -> "Fvar None"
| Fpresent -> "Fpresent"
| Fabsent -> "Fabsent"
let rec safe_commu_repr v = function
Cok -> "Cok"
| Cunknown -> "Cunknown"
| Clink r ->
if List.memq r v then "Clink loop" else
safe_commu_repr (r::v) !r
let rec safe_repr v = function
{desc = Tlink t} when not (List.memq t v) ->
safe_repr (t::v) t
| t -> t
let rec list_of_memo = function
Mnil -> []
| Mcons (priv, p, t1, t2, rem) -> p :: list_of_memo rem
| Mlink rem -> list_of_memo !rem
let visited = ref []
let rec raw_type ppf ty =
let ty = safe_repr [] ty in
if List.memq ty !visited then fprintf ppf "{id=%d}" ty.id else begin
visited := ty :: !visited;
fprintf ppf "@[<1>{id=%d;level=%d;desc=@,%a}@]" ty.id ty.level
raw_type_desc ty.desc
end
and raw_type_list tl = raw_list raw_type tl
and raw_type_desc ppf = function
Tvar -> fprintf ppf "Tvar"
| Tarrow(l,t1,t2,c) ->
fprintf ppf "@[<hov1>Tarrow(%s,@,%a,@,%a,@,%s)@]"
l raw_type t1 raw_type t2
(safe_commu_repr [] c)
| Ttuple tl ->
fprintf ppf "@[<1>Ttuple@,%a@]" raw_type_list tl
| Tconstr (p, tl, abbrev) ->
fprintf ppf "@[<hov1>Tconstr(@,%a,@,%a,@,%a)@]" path p
raw_type_list tl
(raw_list path) (list_of_memo !abbrev)
| Tobject (t, nm) ->
fprintf ppf "@[<hov1>Tobject(@,%a,@,@[<1>ref%t@])@]" raw_type t
(fun ppf ->
match !nm with None -> fprintf ppf " None"
| Some(p,tl) ->
fprintf ppf "(Some(@,%a,@,%a))" path p raw_type_list tl)
| Tfield (f, k, t1, t2) ->
fprintf ppf "@[<hov1>Tfield(@,%s,@,%s,@,%a,@;<0 -1>%a)@]" f
(safe_kind_repr [] k)
raw_type t1 raw_type t2
| Tnil -> fprintf ppf "Tnil"
| Tlink t -> fprintf ppf "@[<1>Tlink@,%a@]" raw_type t
| Tsubst t -> fprintf ppf "@[<1>Tsubst@,%a@]" raw_type t
| Tunivar -> fprintf ppf "Tunivar"
| Tpoly (t, tl) ->
fprintf ppf "@[<hov1>Tpoly(@,%a,@,%a)@]"
raw_type t
raw_type_list tl
| Tvariant row ->
fprintf ppf
"@[<hov1>{@[%s@,%a;@]@ @[%s@,%a;@]@ %s%b;@ %s%b;@ @[<1>%s%t@]}@]"
"row_fields="
(raw_list (fun ppf (l, f) ->
fprintf ppf "@[%s,@ %a@]" l raw_field f))
row.row_fields
"row_more=" raw_type row.row_more
"row_closed=" row.row_closed
"row_fixed=" row.row_fixed
"row_name="
(fun ppf ->
match row.row_name with None -> fprintf ppf "None"
| Some(p,tl) ->
fprintf ppf "Some(@,%a,@,%a)" path p raw_type_list tl)
| Tpackage (p, _, tl) ->
fprintf ppf "@[<hov1>Tpackage(@,%a@,%a)@]" path p
raw_type_list tl
and raw_field ppf = function
Rpresent None -> fprintf ppf "Rpresent None"
| Rpresent (Some t) -> fprintf ppf "@[<1>Rpresent(Some@,%a)@]" raw_type t
| Reither (c,tl,m,e) ->
fprintf ppf "@[<hov1>Reither(%b,@,%a,@,%b,@,@[<1>ref%t@])@]" c
raw_type_list tl m
(fun ppf ->
match !e with None -> fprintf ppf " None"
| Some f -> fprintf ppf "@,@[<1>(%a)@]" raw_field f)
| Rabsent -> fprintf ppf "Rabsent"
let raw_type_expr ppf t =
visited := [];
raw_type ppf t;
visited := []
let names = ref ([] : (type_expr * string) list)
let name_counter = ref 0
let reset_names () = names := []; name_counter := 0
let new_name () =
let name =
if !name_counter < 26
then String.make 1 (Char.chr(97 + !name_counter))
else String.make 1 (Char.chr(97 + !name_counter mod 26)) ^
string_of_int(!name_counter / 26) in
incr name_counter;
name
let name_of_type t =
try List.assq t !names with Not_found ->
let name = new_name () in
names := (t, name) :: !names;
name
let check_name_of_type t = ignore(name_of_type t)
let non_gen_mark sch ty =
if sch && ty.desc = Tvar && ty.level <> generic_level then "_" else ""
let print_name_of_type sch ppf t =
fprintf ppf "'%s%s" (non_gen_mark sch t) (name_of_type t)
let visited_objects = ref ([] : type_expr list)
let aliased = ref ([] : type_expr list)
let delayed = ref ([] : type_expr list)
let add_delayed t =
if not (List.memq t !delayed) then delayed := t :: !delayed
let is_aliased ty = List.memq (proxy ty) !aliased
let add_alias ty =
let px = proxy ty in
if not (is_aliased px) then aliased := px :: !aliased
let aliasable ty =
match ty.desc with Tvar | Tunivar | Tpoly _ -> false | _ -> true
let namable_row row =
row.row_name <> None &&
List.for_all
(fun (_, f) ->
match row_field_repr f with
| Reither(c, l, _, _) ->
row.row_closed && if c then l = [] else List.length l = 1
| _ -> true)
row.row_fields
let rec mark_loops_rec visited ty =
let ty = repr ty in
let px = proxy ty in
if List.memq px visited && aliasable ty then add_alias px else
let visited = px :: visited in
match ty.desc with
| Tvar -> ()
| Tarrow(_, ty1, ty2, _) ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Ttuple tyl -> List.iter (mark_loops_rec visited) tyl
| Tconstr(_, tyl, _) | Tpackage (_, _, tyl) ->
List.iter (mark_loops_rec visited) tyl
| Tvariant row ->
if List.memq px !visited_objects then add_alias px else
begin
let row = row_repr row in
if not (static_row row) then
visited_objects := px :: !visited_objects;
match row.row_name with
| Some(p, tyl) when namable_row row ->
List.iter (mark_loops_rec visited) tyl
| _ ->
iter_row (mark_loops_rec visited) row
end
| Tobject (fi, nm) ->
if List.memq px !visited_objects then add_alias px else
begin
if opened_object ty then
visited_objects := px :: !visited_objects;
begin match !nm with
| None ->
let fields, _ = flatten_fields fi in
List.iter
(fun (_, kind, ty) ->
if field_kind_repr kind = Fpresent then
mark_loops_rec visited ty)
fields
| Some (_, l) ->
List.iter (mark_loops_rec visited) (List.tl l)
end
end
| Tfield(_, kind, ty1, ty2) when field_kind_repr kind = Fpresent ->
mark_loops_rec visited ty1; mark_loops_rec visited ty2
| Tfield(_, _, _, ty2) ->
mark_loops_rec visited ty2
| Tnil -> ()
| Tsubst ty -> mark_loops_rec visited ty
| Tlink _ -> fatal_error "Printtyp.mark_loops_rec (2)"
| Tpoly (ty, tyl) ->
List.iter (fun t -> add_alias t) tyl;
mark_loops_rec visited ty
| Tunivar -> ()
let mark_loops ty =
normalize_type Env.empty ty;
mark_loops_rec [] ty;;
let reset_loop_marks () =
visited_objects := []; aliased := []; delayed := []
let reset () =
unique_names := Ident.empty; reset_names (); reset_loop_marks ()
let reset_and_mark_loops ty =
reset (); mark_loops ty
let reset_and_mark_loops_list tyl =
reset (); List.iter mark_loops tyl
let print_labels = ref true
let print_label ppf l =
if !print_labels && l <> "" || is_optional l then fprintf ppf "%s:" l
let rec tree_of_typexp sch ty =
let ty = repr ty in
let px = proxy ty in
if List.mem_assq px !names && not (List.memq px !delayed) then
let mark = is_non_gen sch ty in
Otyp_var (mark, name_of_type px) else
let pr_typ () =
match ty.desc with
| Tvar ->
Otyp_var (is_non_gen sch ty, name_of_type ty)
| Tarrow(l, ty1, ty2, _) ->
let pr_arrow l ty1 ty2 =
let lab =
if !print_labels && l <> "" || is_optional l then l else ""
in
let t1 =
if is_optional l then
match (repr ty1).desc with
| Tconstr(path, [ty], _)
when Path.same path Predef.path_option ->
tree_of_typexp sch ty
| _ -> Otyp_stuff "<hidden>"
else tree_of_typexp sch ty1 in
Otyp_arrow (lab, t1, tree_of_typexp sch ty2) in
pr_arrow l ty1 ty2
| Ttuple tyl ->
Otyp_tuple (tree_of_typlist sch tyl)
| Tconstr(p, tyl, abbrev) ->
Otyp_constr (tree_of_path p, tree_of_typlist sch tyl)
| Tvariant row ->
let row = row_repr row in
let fields =
if row.row_closed then
List.filter (fun (_, f) -> row_field_repr f <> Rabsent)
row.row_fields
else row.row_fields in
let present =
List.filter
(fun (_, f) ->
match row_field_repr f with
| Rpresent _ -> true
| _ -> false)
fields in
let all_present = List.length present = List.length fields in
begin match row.row_name with
| Some(p, tyl) when namable_row row ->
let id = tree_of_path p in
let args = tree_of_typlist sch tyl in
if row.row_closed && all_present then
Otyp_constr (id, args)
else
let non_gen = is_non_gen sch px in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_name(tree_of_path p, args),
row.row_closed, tags)
| _ ->
let non_gen =
not (row.row_closed && all_present) && is_non_gen sch px in
let fields = List.map (tree_of_row_field sch) fields in
let tags =
if all_present then None else Some (List.map fst present) in
Otyp_variant (non_gen, Ovar_fields fields, row.row_closed, tags)
end
| Tobject (fi, nm) ->
tree_of_typobject sch fi nm
| Tsubst ty ->
tree_of_typexp sch ty
| Tlink _ | Tnil | Tfield _ ->
fatal_error "Printtyp.tree_of_typexp"
| Tpoly (ty, []) ->
tree_of_typexp sch ty
| Tpoly (ty, tyl) ->
let tyl = List.map repr tyl in
let tyl = List.filter is_aliased tyl in
if tyl = [] then tree_of_typexp sch ty else begin
let old_delayed = !delayed in
List.iter add_delayed tyl;
let tl = List.map name_of_type tyl in
let tr = Otyp_poly (tl, tree_of_typexp sch ty) in
delayed := old_delayed; tr
end
| Tunivar ->
Otyp_var (false, name_of_type ty)
| Tpackage (p, n, tyl) ->
Otyp_module (Path.name p, n, tree_of_typlist sch tyl)
in
if List.memq px !delayed then delayed := List.filter ((!=) px) !delayed;
if is_aliased px && aliasable ty then begin
check_name_of_type px;
Otyp_alias (pr_typ (), name_of_type px) end
else pr_typ ()
and tree_of_row_field sch (l, f) =
match row_field_repr f with
| Rpresent None | Reither(true, [], _, _) -> (l, false, [])
| Rpresent(Some ty) -> (l, false, [tree_of_typexp sch ty])
| Reither(c, tyl, _, _) ->
contradiction : un constructeur constant qui a un argument
then (l, true, tree_of_typlist sch tyl)
else (l, false, tree_of_typlist sch tyl)
and tree_of_typlist sch tyl =
List.map (tree_of_typexp sch) tyl
and tree_of_typobject sch fi nm =
begin match !nm with
| None ->
let pr_fields fi =
let (fields, rest) = flatten_fields fi in
let present_fields =
List.fold_right
(fun (n, k, t) l ->
match field_kind_repr k with
| Fpresent -> (n, t) :: l
| _ -> l)
fields [] in
let sorted_fields =
Sort.list (fun (n, _) (n', _) -> n <= n') present_fields in
tree_of_typfields sch rest sorted_fields in
let (fields, rest) = pr_fields fi in
Otyp_object (fields, rest)
| Some (p, ty :: tyl) ->
let non_gen = is_non_gen sch (repr ty) in
let args = tree_of_typlist sch tyl in
Otyp_class (non_gen, tree_of_path p, args)
| _ ->
fatal_error "Printtyp.tree_of_typobject"
end
and is_non_gen sch ty =
sch && ty.desc = Tvar && ty.level <> generic_level
and tree_of_typfields sch rest = function
| [] ->
let rest =
match rest.desc with
| Tvar | Tunivar -> Some (is_non_gen sch rest)
| Tconstr _ -> Some false
| Tnil -> None
| _ -> fatal_error "typfields (1)"
in
([], rest)
| (s, t) :: l ->
let field = (s, tree_of_typexp sch t) in
let (fields, rest) = tree_of_typfields sch rest l in
(field :: fields, rest)
let typexp sch prio ppf ty =
!Oprint.out_type ppf (tree_of_typexp sch ty)
let type_expr ppf ty = typexp false 0 ppf ty
and type_sch ppf ty = typexp true 0 ppf ty
and type_scheme ppf ty = reset_and_mark_loops ty; typexp true 0 ppf ty
let type_scheme_max ?(b_reset_names=true) ppf ty =
if b_reset_names then reset_names () ;
typexp true 0 ppf ty
let tree_of_type_scheme ty = reset_and_mark_loops ty; tree_of_typexp true ty
Print one type declaration
let tree_of_constraints params =
List.fold_right
(fun ty list ->
let ty' = unalias ty in
if proxy ty != proxy ty' then
let tr = tree_of_typexp true ty in
(tr, tree_of_typexp true ty') :: list
else list)
params []
let filter_params tyl =
let params =
List.fold_left
(fun tyl ty ->
let ty = repr ty in
if List.memq ty tyl then Btype.newgenty (Tsubst ty) :: tyl
else ty :: tyl)
[] tyl
in List.rev params
let string_of_mutable = function
| Immutable -> ""
| Mutable -> "mutable "
let rec tree_of_type_decl id decl =
reset();
let params = filter_params decl.type_params in
List.iter add_alias params;
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
let ty_manifest =
match decl.type_manifest with
| None -> None
| Some ty ->
let ty =
match repr ty with {desc=Tvariant row} ->
let row = row_repr row in
begin match row.row_name with
Some (Pident id', _) when Ident.same id id' ->
newgenty (Tvariant {row with row_name = None})
| _ -> ty
end
| _ -> ty
in
mark_loops ty;
Some ty
in
begin match decl.type_kind with
| Type_abstract -> ()
| Type_variant [] -> ()
| Type_variant cstrs ->
List.iter (fun (_, args) -> List.iter mark_loops args) cstrs
| Type_record(l, rep) ->
List.iter (fun (_, _, ty) -> mark_loops ty) l
end;
let type_param =
function
| Otyp_var (_, id) -> id
| _ -> "?"
in
let type_defined decl =
let abstr =
match decl.type_kind with
Type_abstract ->
decl.type_manifest = None || decl.type_private = Private
| Type_variant _ | Type_record _ ->
decl.type_private = Private
in
let vari =
List.map2
(fun ty (co,cn,ct) ->
if abstr || (repr ty).desc <> Tvar then (co,cn) else (true,true))
decl.type_params decl.type_variance
in
(Ident.name id,
List.map2 (fun ty cocn -> type_param (tree_of_typexp false ty), cocn)
params vari)
in
let tree_of_manifest ty1 =
match ty_manifest with
| None -> ty1
| Some ty -> Otyp_manifest (tree_of_typexp false ty, ty1)
in
let (name, args) = type_defined decl in
let constraints = tree_of_constraints params in
let ty, priv =
match decl.type_kind with
| Type_abstract ->
begin match ty_manifest with
| None -> (Otyp_abstract, Public)
| Some ty ->
tree_of_typexp false ty, decl.type_private
end
| Type_variant cstrs ->
tree_of_manifest (Otyp_sum (List.map tree_of_constructor cstrs)),
decl.type_private
| Type_record(lbls, rep) ->
tree_of_manifest (Otyp_record (List.map tree_of_label lbls)),
decl.type_private
in
(name, args, ty, priv, constraints)
and tree_of_constructor (name, args) =
(name, tree_of_typlist false args)
and tree_of_label (name, mut, arg) =
(name, mut = Mutable, tree_of_typexp false arg)
let tree_of_type_declaration id decl rs =
Osig_type (tree_of_type_decl id decl, tree_of_rec rs)
let type_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_type_declaration id decl Trec_first)
let tree_of_exception_declaration id decl =
reset_and_mark_loops_list decl;
let tyl = tree_of_typlist false decl in
Osig_exception (Ident.name id, tyl)
let exception_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_exception_declaration id decl)
let tree_of_value_description id decl =
let id = Ident.name id in
let ty = tree_of_type_scheme decl.val_type in
let prims =
match decl.val_kind with
| Val_prim p -> Primitive.description_list p
| _ -> []
in
Osig_value (id, ty, prims)
let value_description id ppf decl =
!Oprint.out_sig_item ppf (tree_of_value_description id decl)
let class_var sch ppf l (m, t) =
fprintf ppf
"@ @[<2>val %s%s :@ %a@]" (string_of_mutable m) l (typexp sch 0) t
let method_type (_, kind, ty) =
match field_kind_repr kind, repr ty with
Fpresent, {desc=Tpoly(ty, _)} -> ty
| _ , ty -> ty
let tree_of_metho sch concrete csil (lab, kind, ty) =
if lab <> dummy_method then begin
let kind = field_kind_repr kind in
let priv = kind <> Fpresent in
let virt = not (Concr.mem lab concrete) in
let ty = method_type (lab, kind, ty) in
Ocsg_method (lab, priv, virt, tree_of_typexp sch ty) :: csil
end
else csil
let rec prepare_class_type params = function
| Tcty_constr (p, tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
|| List.exists (deep_occur sty) tyl
then prepare_class_type params cty
else List.iter mark_loops tyl
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let px = proxy sty in
if List.memq px !visited_objects then add_alias sty
else visited_objects := px :: !visited_objects;
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
List.iter (fun met -> mark_loops (method_type met)) fields;
Vars.iter (fun _ (_, _, ty) -> mark_loops ty) sign.cty_vars
| Tcty_fun (_, ty, cty) ->
mark_loops ty;
prepare_class_type params cty
let rec tree_of_class_type sch params =
function
| Tcty_constr (p', tyl, cty) ->
let sty = Ctype.self_type cty in
if List.memq (proxy sty) !visited_objects
|| List.exists (fun ty -> (repr ty).desc <> Tvar) params
then
tree_of_class_type sch params cty
else
Octy_constr (tree_of_path p', tree_of_typlist true tyl)
| Tcty_signature sign ->
let sty = repr sign.cty_self in
let self_ty =
if is_aliased sty then
Some (Otyp_var (false, name_of_type (proxy sty)))
else None
in
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self)
in
let csil = [] in
let csil =
List.fold_left
(fun csil (ty1, ty2) -> Ocsg_constraint (ty1, ty2) :: csil)
csil (tree_of_constraints params)
in
let all_vars =
Vars.fold (fun l (m, v, t) all -> (l, m, v, t) :: all) sign.cty_vars []
in
Consequence of PR#3607 : order of Map.fold has changed !
let all_vars = List.rev all_vars in
let csil =
List.fold_left
(fun csil (l, m, v, t) ->
Ocsg_value (l, m = Mutable, v = Virtual, tree_of_typexp sch t)
:: csil)
csil all_vars
in
let csil =
List.fold_left (tree_of_metho sch sign.cty_concr) csil fields
in
Octy_signature (self_ty, List.rev csil)
| Tcty_fun (l, ty, cty) ->
let lab = if !print_labels && l <> "" || is_optional l then l else "" in
let ty =
if is_optional l then
match (repr ty).desc with
| Tconstr(path, [ty], _) when Path.same path Predef.path_option -> ty
| _ -> newconstr (Path.Pident(Ident.create "<hidden>")) []
else ty in
let tr = tree_of_typexp sch ty in
Octy_fun (lab, tr, tree_of_class_type sch params cty)
let class_type ppf cty =
reset ();
prepare_class_type [] cty;
!Oprint.out_class_type ppf (tree_of_class_type false [] cty)
let tree_of_class_param param variance =
(match tree_of_typexp true param with
Otyp_var (_, s) -> s
| _ -> "?"),
if (repr param).desc = Tvar then (true, true) else variance
let tree_of_class_params params =
let tyl = tree_of_typlist true params in
List.map (function Otyp_var (_, s) -> s | _ -> "?") tyl
let tree_of_class_declaration id cl rs =
let params = filter_params cl.cty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.cty_type;
let sty = self_type cl.cty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let vir_flag = cl.cty_new = None in
Osig_class
(vir_flag, Ident.name id,
List.map2 tree_of_class_param params cl.cty_variance,
tree_of_class_type true params cl.cty_type,
tree_of_rec rs)
let class_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_class_declaration id cl Trec_first)
let tree_of_cltype_declaration id cl rs =
let params = List.map repr cl.clty_params in
reset ();
List.iter add_alias params;
prepare_class_type params cl.clty_type;
let sty = self_type cl.clty_type in
List.iter mark_loops params;
List.iter check_name_of_type (List.map proxy params);
if is_aliased sty then check_name_of_type (proxy sty);
let sign = Ctype.signature_of_class_type cl.clty_type in
let virt =
let (fields, _) =
Ctype.flatten_fields (Ctype.object_fields sign.cty_self) in
List.exists
(fun (lab, _, ty) ->
not (lab = dummy_method || Concr.mem lab sign.cty_concr))
fields
|| Vars.fold (fun _ (_,vr,_) b -> vr = Virtual || b) sign.cty_vars false
in
Osig_class_type
(virt, Ident.name id,
List.map2 tree_of_class_param params cl.clty_variance,
tree_of_class_type true params cl.clty_type,
tree_of_rec rs)
let cltype_declaration id ppf cl =
!Oprint.out_sig_item ppf (tree_of_cltype_declaration id cl Trec_first)
let rec tree_of_modtype = function
| Tmty_ident p ->
Omty_ident (tree_of_path p)
| Tmty_signature sg ->
Omty_signature (tree_of_signature sg)
| Tmty_functor(param, ty_arg, ty_res) ->
Omty_functor
(Ident.name param, tree_of_modtype ty_arg, tree_of_modtype ty_res)
and tree_of_signature = function
| [] -> []
| Tsig_value(id, decl) :: rem ->
tree_of_value_description id decl :: tree_of_signature rem
| Tsig_type(id, _, _) :: rem when is_row_name (Ident.name id) ->
tree_of_signature rem
| Tsig_type(id, decl, rs) :: rem ->
Osig_type(tree_of_type_decl id decl, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_exception(id, decl) :: rem ->
tree_of_exception_declaration id decl :: tree_of_signature rem
| Tsig_module(id, mty, rs) :: rem ->
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs) ::
tree_of_signature rem
| Tsig_modtype(id, decl) :: rem ->
tree_of_modtype_declaration id decl :: tree_of_signature rem
| Tsig_class(id, decl, rs) :: ctydecl :: tydecl1 :: tydecl2 :: rem ->
tree_of_class_declaration id decl rs :: tree_of_signature rem
| Tsig_cltype(id, decl, rs) :: tydecl1 :: tydecl2 :: rem ->
tree_of_cltype_declaration id decl rs :: tree_of_signature rem
| _ ->
assert false
and tree_of_modtype_declaration id decl =
let mty =
match decl with
| Tmodtype_abstract -> Omty_abstract
| Tmodtype_manifest mty -> tree_of_modtype mty
in
Osig_modtype (Ident.name id, mty)
let tree_of_module id mty rs =
Osig_module (Ident.name id, tree_of_modtype mty, tree_of_rec rs)
let modtype ppf mty = !Oprint.out_module_type ppf (tree_of_modtype mty)
let modtype_declaration id ppf decl =
!Oprint.out_sig_item ppf (tree_of_modtype_declaration id decl)
Print a signature body ( used by -i when compiling a .ml )
let print_signature ppf tree =
fprintf ppf "@[<v>%a@]" !Oprint.out_signature tree
let signature ppf sg =
fprintf ppf "%a" print_signature (tree_of_signature sg)
let type_expansion t ppf t' =
if t == t' then type_expr ppf t else
let t' = if proxy t == proxy t' then unalias t' else t' in
fprintf ppf "@[<2>%a@ =@ %a@]" type_expr t type_expr t'
let rec trace fst txt ppf = function
| (t1, t1') :: (t2, t2') :: rem ->
if not fst then fprintf ppf "@,";
fprintf ppf "@[Type@;<1 2>%a@ %s@;<1 2>%a@] %a"
(type_expansion t1) t1' txt (type_expansion t2) t2'
(trace false txt) rem
| _ -> ()
let rec filter_trace = function
| (t1, t1') :: (t2, t2') :: rem ->
let rem' = filter_trace rem in
if t1 == t1' && t2 == t2'
then rem'
else (t1, t1') :: (t2, t2') :: rem'
| _ -> []
let hide_variant_name t =
match repr t with
| {desc = Tvariant row} as t when (row_repr row).row_name <> None ->
newty2 t.level
(Tvariant {(row_repr row) with row_name = None;
row_more = newty2 (row_more row).level Tvar})
| _ -> t
let prepare_expansion (t, t') =
let t' = hide_variant_name t' in
mark_loops t; if t != t' then mark_loops t';
(t, t')
let may_prepare_expansion compact (t, t') =
match (repr t').desc with
Tvariant _ | Tobject _ when compact ->
mark_loops t; (t, t)
| _ -> prepare_expansion (t, t')
let print_tags ppf fields =
match fields with [] -> ()
| (t, _) :: fields ->
fprintf ppf "`%s" t;
List.iter (fun (t, _) -> fprintf ppf ",@ `%s" t) fields
let has_explanation unif t3 t4 =
match t3.desc, t4.desc with
Tfield _, _ | _, Tfield _
| Tunivar, Tvar | Tvar, Tunivar
| Tvariant _, Tvariant _ -> true
| Tconstr (p, _, _), Tvar | Tvar, Tconstr (p, _, _) ->
unif && min t3.level t4.level < Path.binding_time p
| _ -> false
let rec mismatch unif = function
(_, t) :: (_, t') :: rem ->
begin match mismatch unif rem with
Some _ as m -> m
| None ->
if has_explanation unif t t' then Some(t,t') else None
end
| [] -> None
| _ -> assert false
let explanation unif t3 t4 ppf =
match t3.desc, t4.desc with
| Tfield _, Tvar | Tvar, Tfield _ ->
fprintf ppf "@,Self type cannot escape its class"
| Tconstr (p, _, _), Tvar
when unif && t4.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tconstr (p, _, _)
when unif && t3.level < Path.binding_time p ->
fprintf ppf
"@,@[The type constructor@;<1 2>%a@ would escape its scope@]"
path p
| Tvar, Tunivar | Tunivar, Tvar ->
fprintf ppf "@,The universal variable %a would escape its scope"
type_expr (if t3.desc = Tunivar then t3 else t4)
| Tfield (lab, _, _, _), _
| _, Tfield (lab, _, _, _) when lab = dummy_method ->
fprintf ppf
"@,Self type cannot be unified with a closed object type"
| Tfield (l, _, _, _), Tfield (l', _, _, _) when l = l' ->
fprintf ppf "@,Types for method %s are incompatible" l
| _, Tfield (l, _, _, _) ->
fprintf ppf
"@,@[The first object type has no method %s@]" l
| Tfield (l, _, _, _), _ ->
fprintf ppf
"@,@[The second object type has no method %s@]" l
| Tvariant row1, Tvariant row2 ->
let row1 = row_repr row1 and row2 = row_repr row2 in
begin match
row1.row_fields, row1.row_closed, row2.row_fields, row2.row_closed with
| [], true, [], true ->
fprintf ppf "@,These two variant types have no intersection"
| [], true, fields, _ ->
fprintf ppf
"@,@[The first variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| fields, _, [], true ->
fprintf ppf
"@,@[The second variant type does not allow tag(s)@ @[<hov>%a@]@]"
print_tags fields
| [l1,_], true, [l2,_], true when l1 = l2 ->
fprintf ppf "@,Types for tag `%s are incompatible" l1
| _ -> ()
end
| _ -> ()
let explanation unif mis ppf =
match mis with
None -> ()
| Some (t3, t4) -> explanation unif t3 t4 ppf
let ident_same_name id1 id2 =
if Ident.equal id1 id2 && not (Ident.same id1 id2) then begin
add_unique id1; add_unique id2
end
let rec path_same_name p1 p2 =
match p1, p2 with
Pident id1, Pident id2 -> ident_same_name id1 id2
| Pdot (p1, s1, _), Pdot (p2, s2, _) when s1 = s2 -> path_same_name p1 p2
| Papply (p1, p1'), Papply (p2, p2') ->
path_same_name p1 p2; path_same_name p1' p2'
| _ -> ()
let type_same_name t1 t2 =
match (repr t1).desc, (repr t2).desc with
Tconstr (p1, _, _), Tconstr (p2, _, _) -> path_same_name p1 p2
| _ -> ()
let rec trace_same_names = function
(t1, t1') :: (t2, t2') :: rem ->
type_same_name t1 t2; type_same_name t1' t2'; trace_same_names rem
| _ -> ()
let unification_error unif tr txt1 ppf txt2 =
reset ();
trace_same_names tr;
let tr = List.map (fun (t, t') -> (t, hide_variant_name t')) tr in
let mis = mismatch unif tr in
match tr with
| [] | _ :: [] -> assert false
| t1 :: t2 :: tr ->
try
let tr = filter_trace tr in
let t1, t1' = may_prepare_expansion (tr = []) t1
and t2, t2' = may_prepare_expansion (tr = []) t2 in
print_labels := not !Clflags.classic;
let tr = List.map prepare_expansion tr in
fprintf ppf
"@[<v>\
@[%t@;<1 2>%a@ \
%t@;<1 2>%a\
@]%a%t\
@]"
txt1 (type_expansion t1) t1'
txt2 (type_expansion t2) t2'
(trace false "is not compatible with type") tr
(explanation unif mis);
print_labels := true
with exn ->
print_labels := true;
raise exn
let report_unification_error ppf tr txt1 txt2 =
unification_error true tr txt1 ppf txt2;;
let trace fst txt ppf tr =
print_labels := not !Clflags.classic;
trace_same_names tr;
try match tr with
t1 :: t2 :: tr' ->
if fst then trace fst txt ppf (t1 :: t2 :: filter_trace tr')
else trace fst txt ppf (filter_trace tr);
print_labels := true
| _ -> ()
with exn ->
print_labels := true;
raise exn
let report_subtyping_error ppf tr1 txt1 tr2 =
reset ();
let tr1 = List.map prepare_expansion tr1
and tr2 = List.map prepare_expansion tr2 in
trace true txt1 ppf tr1;
if tr2 = [] then () else
let mis = mismatch true tr2 in
trace false "is not compatible with type" ppf tr2;
explanation true mis ppf
|
a2d245824198744ab4dc6125ebc1a1efeeb147b83c88720bfffdd2e55bf5e7bc
|
AllAlgorithms/racket
|
array-median.rkt
|
#lang racket
(provide list-median
vector-median)
(define (list-median ls)
(let ([ls (sort ls <)]
[len (length ls)]
[avg (lambda (a b) (exact->inexact (/ (+ a b) 2)))])
(if (odd? len)
(list-ref ls (/ (sub1 len) 2))
(avg (list-ref ls (sub1 (/ len 2)))
(list-ref ls (/ len 2))))))
(define (vector-median vec)
(let ([vec (vector-sort vec <)]
[len (vector-length vec)]
[avg (lambda (a b) (exact->inexact (/ (+ a b) 2)))])
(if (odd? len)
(vector-ref vec (/ (sub1 len) 2))
(avg (vector-ref vec (sub1 (/ len 2)))
(vector-ref vec (/ len 2))))))
| null |
https://raw.githubusercontent.com/AllAlgorithms/racket/46b2a4b963b0536351273ee8068f58fed4884dde/algorithms/dynamic-programming/array-median.rkt
|
racket
|
#lang racket
(provide list-median
vector-median)
(define (list-median ls)
(let ([ls (sort ls <)]
[len (length ls)]
[avg (lambda (a b) (exact->inexact (/ (+ a b) 2)))])
(if (odd? len)
(list-ref ls (/ (sub1 len) 2))
(avg (list-ref ls (sub1 (/ len 2)))
(list-ref ls (/ len 2))))))
(define (vector-median vec)
(let ([vec (vector-sort vec <)]
[len (vector-length vec)]
[avg (lambda (a b) (exact->inexact (/ (+ a b) 2)))])
(if (odd? len)
(vector-ref vec (/ (sub1 len) 2))
(avg (vector-ref vec (sub1 (/ len 2)))
(vector-ref vec (/ len 2))))))
|
|
fcfeccf8f22c1ccd7cee8f8af4ed223db590044f0df5c8ad0aa4b793492ff851
|
uim/uim
|
test-intl.scm
|
Copyright ( c ) 2003 - 2013 uim Project
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
;;; SUCH DAMAGE.
;;;;
These tests are passed at revision 6605 ( new repository )
(define-module test.test-intl
(use test.unit.test-case)
(use test.uim-test)
(use file.util)
(use gauche.process))
(select-module test.test-intl)
(define (guess-current-locale)
(let ((locale-process (run-process '("locale" "-a")
:output :pipe
:error :pipe
:wait #t)))
(or ;(and (= 0 (process-exit-status locale-process))
; (find #/\./ (port->string-list (process-output locale-process))))
(sys-getenv "LANG")
(sys-getenv "LC_ALL"))))
(define locale-dir (uim-test-build-path "test" "locale"))
(define domain "uim")
(define msgid "hello")
(define msgstr "Hello")
(define (setup)
(let* ((current-LANG (sys-getenv "LANG"))
(current-LC_ALL (sys-getenv "LC_ALL"))
At least on glibc 2.6.1 - 1ubuntu9 on Ubuntu 7.10 , gettext(3 )
;; does not read the translation for "en_US" and "C". So I
;; specify "ja_JP" as an arbitrary locale for these tests.
-- YamaKen 2008 - 03 - 23
;;(define lang "en_US") ;; doesn't work
;;(define lang "C") ;; doesn't work
;;(define lang "ja_JP")
;;
;; "ja_JP" doesn't work on "ja_JP" isn't generated environment.
;; For example, "ja_JP" isn't generated but "ja_JP.UTF-8" is
;; generated on my environment. So, I guess available locales
;; from "locale -a" and use the current locale as fallback locale.
-- kou 2009 - 03 - 22 -- Wow ! just ( - a - year 1 ) ago !
;;
at last , just use LANG -- ek 2011 - 05 - 11
(lang (guess-current-locale))
(LC_MESSAGES-dir (build-path locale-dir lang "LC_MESSAGES")))
(make-directory* LC_MESSAGES-dir)
(with-output-to-file (build-path LC_MESSAGES-dir #`",|domain|.po")
(lambda ()
(display
(string-join
`("msgid \"\""
"msgstr \"\""
"\"MIME-Version: 1.0\\n\""
"\"Content-Type: text/plain; charset=UTF-8\\n\""
"\"Content-Transfer-Encoding: 8bit\\n\""
""
,#`"msgid \",|msgid|\""
,#`"msgstr \",|msgstr|\"")
"\n"))))
(run-process "msgfmt" "-o"
(build-path LC_MESSAGES-dir #`",|domain|.mo")
(build-path LC_MESSAGES-dir #`",|domain|.po")
:wait #t)
(uim-test-with-environment-variables
`(("LANG" . ,lang)
("LC_ALL" . ,lang))
uim-test-setup)))
(define (teardown)
(uim-test-teardown)
(remove-directory* locale-dir))
(define (test-gettext)
(assert-uim-equal msgid `(gettext ,msgid))
(assert-uim-equal locale-dir `(bindtextdomain ,domain ,locale-dir))
(assert-uim-equal locale-dir `(bindtextdomain ,domain #f))
(assert-uim-equal msgstr `(dgettext ,domain ,msgid))
(assert-uim-equal domain `(textdomain ,domain))
(assert-uim-equal domain `(textdomain #f))
(assert-uim-equal msgstr `(gettext ,msgid))
#f)
(provide "test/test-intl")
| null |
https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/test/test-intl.scm
|
scheme
|
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
(and (= 0 (process-exit-status locale-process))
(find #/\./ (port->string-list (process-output locale-process))))
does not read the translation for "en_US" and "C". So I
specify "ja_JP" as an arbitrary locale for these tests.
(define lang "en_US") ;; doesn't work
(define lang "C") ;; doesn't work
(define lang "ja_JP")
"ja_JP" doesn't work on "ja_JP" isn't generated environment.
For example, "ja_JP" isn't generated but "ja_JP.UTF-8" is
generated on my environment. So, I guess available locales
from "locale -a" and use the current locale as fallback locale.
charset=UTF-8\\n\""
|
Copyright ( c ) 2003 - 2013 uim Project
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
These tests are passed at revision 6605 ( new repository )
(define-module test.test-intl
(use test.unit.test-case)
(use test.uim-test)
(use file.util)
(use gauche.process))
(select-module test.test-intl)
(define (guess-current-locale)
(let ((locale-process (run-process '("locale" "-a")
:output :pipe
:error :pipe
:wait #t)))
(sys-getenv "LANG")
(sys-getenv "LC_ALL"))))
(define locale-dir (uim-test-build-path "test" "locale"))
(define domain "uim")
(define msgid "hello")
(define msgstr "Hello")
(define (setup)
(let* ((current-LANG (sys-getenv "LANG"))
(current-LC_ALL (sys-getenv "LC_ALL"))
At least on glibc 2.6.1 - 1ubuntu9 on Ubuntu 7.10 , gettext(3 )
-- YamaKen 2008 - 03 - 23
-- kou 2009 - 03 - 22 -- Wow ! just ( - a - year 1 ) ago !
at last , just use LANG -- ek 2011 - 05 - 11
(lang (guess-current-locale))
(LC_MESSAGES-dir (build-path locale-dir lang "LC_MESSAGES")))
(make-directory* LC_MESSAGES-dir)
(with-output-to-file (build-path LC_MESSAGES-dir #`",|domain|.po")
(lambda ()
(display
(string-join
`("msgid \"\""
"msgstr \"\""
"\"MIME-Version: 1.0\\n\""
"\"Content-Transfer-Encoding: 8bit\\n\""
""
,#`"msgid \",|msgid|\""
,#`"msgstr \",|msgstr|\"")
"\n"))))
(run-process "msgfmt" "-o"
(build-path LC_MESSAGES-dir #`",|domain|.mo")
(build-path LC_MESSAGES-dir #`",|domain|.po")
:wait #t)
(uim-test-with-environment-variables
`(("LANG" . ,lang)
("LC_ALL" . ,lang))
uim-test-setup)))
(define (teardown)
(uim-test-teardown)
(remove-directory* locale-dir))
(define (test-gettext)
(assert-uim-equal msgid `(gettext ,msgid))
(assert-uim-equal locale-dir `(bindtextdomain ,domain ,locale-dir))
(assert-uim-equal locale-dir `(bindtextdomain ,domain #f))
(assert-uim-equal msgstr `(dgettext ,domain ,msgid))
(assert-uim-equal domain `(textdomain ,domain))
(assert-uim-equal domain `(textdomain #f))
(assert-uim-equal msgstr `(gettext ,msgid))
#f)
(provide "test/test-intl")
|
7af6516ace7a2b1fe81a77cb26b2b1303a0d0644d52e410fd13a1fea23115452
|
racket/typed-racket
|
new-metrics.rkt
|
#lang typed/racket/shallow
(provide results run-all-tests)
(require (except-in scheme/list count) scheme/math scheme/path mzlib/match
(prefix-in srfi13: srfi/13) scheme/file
(for-syntax scheme/base))
(require/typed (prefix-in srfi48: srfi/48)
[srfi48:format ( Port String String Any * -> Any)] )
(define-type-alias NumF (U Number #f))
(define-type-alias (Unit C) ((C -> (Listof NumF)) -> (Path -> (Listof (U #f (Listof NumF))))))
;; ============================================================
CONFIG
(define COLLECTS-PATH (make-parameter (build-path "/home/samth/Desktop/collects-tmp/")))
(define PLANET-CODE-PATH (make-parameter (build-path "/home/samth/Desktop/most-recent-archives/")))
; collects-path : a path to the collects directory to compare
; planet-code-path : a path to the "other" code to compare (i.e. unpacked, most recent versions
; of all planet packages)
;; ============================================================
;; STATS
(: t-test ((Listof Number) (Listof Number) -> Number))
;; computes t value for the given sequences. t-tests measure
the extent to which difference in mean between two sets of
;; _interval-valued_ samples (e.g. distances, times, weights, counts ...)
;; can be explained by chance. Generally speaking, higher absolute
;; values of t correspond to higher confidence that an observed difference
;; in mean cannot be explained by chance.
(define (t-test seqA seqB)
(manual-t-test
(avg seqA) (avg seqB)
(variance seqA) (variance seqB)
(length seqA) (length seqB)))
(: manual-t-test (Number Number Number Number Number Number -> Number))
(define (manual-t-test avga avgb vara varb cta ctb)
(/ (- avga avgb)
(assert (sqrt (+ (/ vara cta) (/ varb ctb))) number?)))
(: chi-square ((Listof Number) (Listof Number) -> Number))
;; chi-square is a simple measure of the extent to which the
difference in the frequency of 0 's and 1 's in the first
sequence and their frequency in the second sequence can
;; be explained by chance. higher numbers means higher confidence
;; that they cannot.
(define (chi-square seqA seqB)
(with-handlers ([exn:fail? (λ (e) +nan.0)])
(let* ([ct-a (length seqA)]
[ct-b (length seqB)]
[total-subjects (+ ct-a ct-b)]
[a-hits (apply + seqA)]
[b-hits (apply + seqB)] ;; these assume that the data is coded as 1 = present, 0 = not present
[a-misses (- ct-a a-hits)]
[b-misses (- ct-b b-hits)]
[table
`((,a-hits ,b-hits)
(,a-misses ,b-misses))]
[expected (λ: ([i : Integer] [j : Integer])
(/ (* (row-total i table) (col-total j table)) total-subjects))])
(exact->inexact
(table-sum
(λ (i j) (/ (sqr (- (expected i j) (table-ref i j table))) (expected i j)))
table)))))
;; ============================================================
;; UNITS OF MEASUREMENT IMPLEMENTATIONS
(: per-module (All (X) (((Listof Any) -> X) -> (Path -> (List (U #f X))))))
(define (per-module f)
(λ (path)
(with-handlers ([exn:fail:read? (λ (e) (list #f))])
(let ([initial-sexp (with-input-from-file path read)])
(match initial-sexp
[`(module ,_ ,_ ,bodies ...)
(list (f bodies))]
[_ (list #f)])))))
(: per-module-top-level-expression ((Any -> (Listof NumF)) -> MetricFn))
(define (per-module-top-level-expression f)
(let ([calc (per-module (λ: ([exprs : (Listof Any)]) (map f exprs)))])
(λ (p) (let ([r (calc p)]) (if (car r) (car r) r)))))
;; ============================================================
;; BASIC CALCULATIONS
;; (for use with metric definitions below)
;; ----------------------------------------
;; depth
(: sexp-depth (Any -> Integer))
(define (sexp-depth sexp)
(cond
[(pair? sexp)
(+ (max-sexp-depth sexp) 1)]
[else 0]))
(: max-sexp-depth (Any -> Integer))
(define (max-sexp-depth losx)
(improper-foldr (λ: ([t : Any] [r : Integer]) (max (sexp-depth t) r)) 0 losx))
(: avg-sexp-depth ((Listof Any) -> Number))
(define (avg-sexp-depth sexps)
(cond
[(null? sexps) 0]
[else (avg (map sexp-depth sexps))]))
;; ----------------------------------------
;; setbang counts
(: count-setbangs/ilist (Any -> Number))
(define (count-setbangs/ilist exprs)
(apply + (imap count-setbangs/expr exprs)))
(: count-setbangs/expr (Any -> Number))
(define (count-setbangs/expr expr)
(match expr
[`(,(? setbang?) ,rest ...) (+ 1 (count-setbangs/ilist rest))]
[('quote _) 0]
[('quasiquote _) 0] ; undercount potentially, but how many `,(set! ...)'s can there be?
[`(,e1 . ,e2) (count-setbangs/ilist expr)]
[_ 0]))
(: setbang? (Any -> Any))
(define (setbang? v)
(and (symbol? v)
(regexp-match #rx"^set(-.*)?!" (symbol->string v))))
count - fns
(: count-fns-with-setbangs ((Listof Any) -> Number))
(define (count-fns-with-setbangs exprs)
(apply + (map (λ (e) (if (= (count-setbangs/expr e) 0) 0 1)) exprs)))
(: module-has-setbangs? ((Listof Any) -> Boolean))
(define (module-has-setbangs? exprs) (ormap expr-uses-setbangs? exprs))
(: expr-uses-setbangs? (Any -> Boolean))
(define (expr-uses-setbangs? expr)
(not (= (count-setbangs/expr expr) 0)))
(: setbangs-per-1000-atoms ((Listof Any) -> NumF))
(define (setbangs-per-1000-atoms exprs)
(if (null? exprs)
#f
(let ([set!s (count-setbangs/ilist exprs)]
[atoms (atoms exprs)])
(* (/ set!s atoms) 1000.0))))
;; ----------------------------------------
;; contracts
(: uses-contracts ((Listof Any) -> Boolean))
(define (uses-contracts exprs)
(ormap (λ (e)
(ann
(match e
[`(provide/contract ,_ ...) #t]
[_ #f])
: Boolean))
exprs))
(: contracted-provides ((Listof Any) -> Number))
(define (contracted-provides exprs)
(foldl
(λ: ([t : Any] [r : Number])
(ann
(match t
[(provide/contract ,p ...) (+ (length p) r)]
[_ r]) : Number))
0
exprs))
(: uncontracted-provides ((Listof Any) -> Number))
(define (uncontracted-provides exprs)
(foldl
(λ: ([t : Any] [r : Number])
(ann
(match t
[`(provide ,p ...) (+ (length p) r)]
[_ r]) : Number))
0
exprs))
;; ----------------------------------------
;; macros
(: number-of-macro-definitions (Any -> Number))
(define (number-of-macro-definitions expr)
(match expr
[`(define-syntax ,_ ...) 1]
[`(define-syntaxes (,s ...) ,_ ...) (length s)]
[`(define-syntax-set (,s ...) ,_ ...) (length s)]
[_ 0]))
(: num-of-define-syntax ((Listof Any) -> Number))
(define (num-of-define-syntax exprs)
(foldl (λ: ([t : Any] [r : Number]) (+ (number-of-macro-definitions t) r)) 0 exprs))
;; ----------------------------------------
;; expression size
(: atoms (Any -> Integer))
(define (atoms sexp)
(cond
[(null? sexp) 0]
[(not (pair? sexp)) 1]
[else (+ (atoms (car sexp)) (atoms (cdr sexp)))]))
(: max-atoms ((Listof Any) -> NumF))
(define (max-atoms exprs)
(let ([atom-counts (map atoms exprs)])
(if (null? atom-counts)
#f
(apply max atom-counts))))
(: avg-atoms ((Listof Any) -> NumF))
(define (avg-atoms exprs)
(let ([atom-counts (map atoms exprs)])
(if (null? atom-counts)
#f
(avg (map atoms exprs)))))
(: total-atoms ((Listof Any) -> Number))
(define (total-atoms exprs)
(apply + (map atoms exprs)))
;; ============================================================
;; METRIC DEFINITIONS
' a ' b metric : ( string * ( listof sexp - > ' a option ) * ( ( listof ' a ) ( listof ' a ) - > ' b )
(define-typed-struct (b c d) metric ([analysis-unit : (Unit c)]
[computation : (c -> d)]
[>display : ((Listof d) (Listof d) -> b)]))
(define-type-alias Table (Listof (Listof Number)))
(define-type-alias Atom-display (cons Symbol (Listof Number)))
(: standard-display (Symbol ((Listof Number) -> Number) ((Listof Number) (Listof Number) -> Number)
-> ((Listof NumF) (Listof NumF) -> Atom-display)))
(define ((standard-display name summarize significance-test) seqA seqB)
(let ([clean-seqA (nonfalses seqA)]
[clean-seqB (nonfalses seqB)])
(list name (summarize clean-seqA) (summarize clean-seqB) (significance-test clean-seqA clean-seqB))))
(: interval (All (c) ((Unit c) Symbol (c -> NumF) -> (metric Atom-display c NumF))))
(define (interval u name compute) (make-metric u compute (standard-display name avg t-test)))
(: count (All (c) ((Unit c) Symbol (c -> Boolean) -> (metric Atom-display c NumF))))
(define (count u name compute) (make-metric u (λ: ([es : c]) (if (compute es) 1 0)) (standard-display name avg chi-square)))
(: combine-metrics (All (c) ((Listof (metric Atom-display c NumF)) -> (metric (Listof Atom-display) c (Listof NumF)))))
(define (combine-metrics ms)
(let ([u (metric-analysis-unit (car ms))])
;; This test now redundant b/c of typechecking
(unless (andmap (λ: ([m : (metric Atom-display c NumF) ]) (eq? u (metric-analysis-unit m))) ms)
(error 'combine-metrics "all combined metrics must operate on the same unit of analysis"))
(make-metric
u
(λ: ([exprs : c]) (map (λ: ([m : (metric Atom-display c NumF)]) ((metric-computation m) exprs)) ms))
(λ: ([seqA : (Listof (Listof NumF))] [seqB : (Listof (Listof NumF))])
(map (λ: ([m : (metric Atom-display c NumF)]
[sA : (Listof NumF)]
[sB : (Listof NumF)])
((metric->display m) sA sB)) ms (pivot seqA) (pivot seqB))))))
FIXME - ( filter ( lambda ( x ) x ) l )
(: nonfalses (All (X) ((Listof (U #f X)) -> (Listof X))))
(define (nonfalses l)
(let loop ([lst l])
(if (null? lst)
'()
(let ([x (car lst)])
(if x
(cons x (loop (cdr lst)))
(loop (cdr lst)))))))
(: avg ((Listof Number) -> Number))
(define (avg l) (/ (exact->inexact (apply + l)) (length l)))
(: avg* ((Listof Number) -> Number))
(define (avg* l) (avg (nonfalses l)))
(define-syntax define-metrics
(syntax-rules ()
[(define-metrics all-metrics-id unit-of-analysis (name kind fn) ...)
(begin
(define u unit-of-analysis)
(define name (kind u 'name fn )) ...
(define all-metrics-id (combine-metrics (list name ...))))]))
(define-metrics module-metrics #{per-module @ (Listof NumF)}
(maximum-sexp-depth interval max-sexp-depth)
(average-sexp-depth interval avg-sexp-depth)
(number-of-setbangs/mod interval count-setbangs/ilist)
(number-of-exprs interval #{length @ Any})
(uses-setbang?/mod count module-has-setbangs?)
(uses-contracts? count uses-contracts)
(number-of-contracts interval contracted-provides)
(num-uncontracted-provides interval uncontracted-provides)
(number-of-macro-defs interval num-of-define-syntax)
(maximum-num-atoms interval max-atoms)
(average-num-atoms interval avg-atoms)
(total-num-atoms/mod interval total-atoms)
(set!s-per-1000-atoms interval setbangs-per-1000-atoms))
(define-metrics tl-expr-metrics per-module-top-level-expression
(uses-setbang?/fn count expr-uses-setbangs?)
(number-of-setbangs/fn interval count-setbangs/expr)
(total-num-atoms/fn interval atoms))
(: all-metrics (List (metric (Listof Atom-display) (Listof Any) (Listof NumF))
(metric (Listof Atom-display) Any (Listof NumF)) ))
(define all-metrics (list module-metrics tl-expr-metrics))
;; ============================================================
;; EXPERIMENT RUNNING
(define-syntax (define-excluder stx)
(define (path->clause c)
(syntax-case c ()
[(item ...)
#`[`(#,@(reverse (syntax-e #'(item ...))) ,_ (... ...)) #t]]
[item
#`[`(item) #t]]))
(syntax-case stx ()
[(_ name path ...)
(with-syntax ([(match-clause ...) (map path->clause (syntax-e #'(path ...)))])
#`(define (name p )
(let* ([dirnames (map path->string (filter path? (explode-path p)))])
(match (reverse dirnames) ; goofy backwards matching because ... matches greedily
match-clause ...
[_ #f]))))]))
(: default-excluder (Path -> Boolean))
(define-excluder default-excluder
"compiled" ".svn" #;("collects" "drscheme") #;("collects" "framework"))
(define exclude-directory? (make-parameter default-excluder))
;; ----------------------------------------
apply - to - scheme - files : ( path[file ] - > X ) path[directory ] - > ( listof X )
;; applies the given function to each .rkt or .ss or .scm file in the given
;; directory hierarchy; returns all results in a list
(: apply-to-scheme-files (All (X) ((Path -> X) Path -> (Listof X))))
(define (apply-to-scheme-files f root)
(fold-files
(λ: ([path : Path] [kind : (U 'file 'dir 'link)] [acc : (Listof X)])
(case kind
[(file)
(let ([extension (filename-extension path)])
(cond
[(not extension) (values acc #t)]
[(regexp-match #rx"(ss|scm)$" extension)
(let ([resl (f path)])
(if resl
(values (cons resl acc) #t)
(values acc #t)))]
[else (values acc #t)]))]
[(dir)
(let* ([p (normalize-path path root)])
(if ((exclude-directory?) p)
(values acc #f)
(values acc #t)))]
[(link) (values acc #t)]))
'()
root))
(define-typed-struct (a b c) result ([metric : (metric b c a)] [seqA : (Listof a)] [seqB : (Listof a)]))
(define-type-alias MetricFn (Path -> (Listof (U #f (Listof NumF)))))
(define-type-alias (M b c) (metric b c (Listof NumF)))
(define-type-alias (M2 b c c*) (U (M b c) (M b c*)))
get - sequences : ( listof ' a metric ) path - > ( listof ( listof ' a ) )
(: get-sequences (All (b c C) ((List (M b c) (M b C)) Path -> (Listof (Listof (Listof NumF))))))
(define (get-sequences metrics path)
(: selector (case-lambda [(M b c) -> MetricFn] [(M b C) -> MetricFn]))
(define (selector m) ((metric-analysis-unit m) (metric-computation m)))
(let* ([metric-fns (map #{selector :: ((M2 b c C) -> MetricFn)} metrics)]
[result-seqs (apply-to-scheme-files
(λ: ([file : Path])
(map (λ: ([fn : MetricFn]) (fn file)) metric-fns)) path)])
(map
(λ: ([l : (Listof (Listof (U #f (Listof NumF))))])
(nonfalses (apply append l)))
(pivot (nonfalses result-seqs)))))
(: compare*
(All (b c c*)
((List (M b c) (M b c*))
->
(List (result (Listof NumF) b c)
(result (Listof NumF) b c*)))))
(define (compare* metrics)
(let* ([seqAs (get-sequences metrics (COLLECTS-PATH))]
[seqBs (get-sequences metrics (PLANET-CODE-PATH))])
(list
(make-result (car metrics) (car seqAs) (car seqBs))
(make-result (cadr metrics) (cadr seqAs) (cadr seqBs)))))
(: show (All (a b c) ((result a b c) -> b)))
(define (show result)
((metric->display (result-metric result))
(result-seqA result)
(result-seqB result)))
(: pretty-print-result
(case-lambda
((result (Listof NumF) (Listof Atom-display) (Listof Any)) -> Void)
((result (Listof NumF) (Listof Atom-display) Any) -> Void)))
(define (pretty-print-result result)
(for-each
(λ: ([l : (Listof Any)])
(apply srfi48:format
(current-output-port)
"~26F | ~8,2F | ~6,2F | ~12,2F\n"
(format "~a" (car l))
(cdr l)))
(list* '("test name" "collects" "planet" "significance")
'("---------" "--------" "------" "------------")
(show result))))
;; applies only to the combined metric [or more generally to listof-answer results]
(: total (All (b c) (Integer (result (Listof Number) b c) -> (Listof Number))))
(define (total experiment-number result)
(: total/s (Table -> Number))
(define (total/s s) (apply + (list-ref (pivot s) experiment-number)))
(list (total/s (result-seqA result)) (total/s (result-seqB result))))
;; ============================================================
;; UTILITY
(: imap (All (Y) ((Any -> Y) Any -> (Listof Y))))
(define (imap f il)
(cond
[(null? il) '()]
[(not (pair? il)) (list (f il))]
[else (cons (f (car il)) (imap f (cdr il)))]))
(: pivot (All (X) ((Listof (Listof X)) -> (Listof (Listof X)))))
(define (pivot l)
(cond
[(null? l) '()]
[else
(let ([n (length (car l))])
(build-list n (λ: ([i : Integer]) (map (λ: ([j : (Listof X)]) (list-ref j i)) l))))]))
(: variance ((Listof Number) -> Number))
(define (variance xs)
(let ([avg (/ (apply + xs) (length xs))])
(/ (apply + (map (λ: ([x : Number]) (sqr (- x avg))) xs))
(sub1 (length xs)))))
(: table-ref (Integer Integer Table -> Number))
(define (table-ref i j table)
(list-ref (list-ref table i) j))
(: row-total (Integer Table -> Number))
(define (row-total i table)
(apply + (list-ref table i)))
(: col-total (Integer Table -> Number))
(define (col-total j table)
(apply + (map (λ: ([x : (Listof Number)]) (list-ref x j)) table)))
(: table-sum ((Integer Integer -> Number) Table -> Number))
(define (table-sum f table)
(let ([rows (length table)]
[cols (length (car table))])
(let loop ([i 0] [j 0] [#{sum : Number} 0])
(cond
[(>= j cols) sum]
[(>= i rows) (loop 0 (add1 j) sum)]
[else (loop (add1 i) j (+ sum (f i j)))]))))
(: improper-foldr (All (Y) ((Any Y -> Y) Y Any -> Y)))
(define (improper-foldr f b l)
(cond
[(null? l) b]
[(not (pair? l))
(f l b)]
[else
(f (car l) (improper-foldr f b (cdr l)))]))
(: /* (All (a ...) ((Listof Number) (Listof Number) ... a -> (Listof Number))))
(define (/* arg . args)
(apply map (λ: ([n : Number] . [ns : Number ... a]) (apply / n ns)) arg args))
;; ============================================================
;; MAIN ENTRY POINT
(: results (U #f (Listof (U (result (Listof NumF) (Listof Atom-display) (Listof Any))
(result (Listof NumF) (Listof Atom-display) Any)))))
(define results #f) ; just in case i want to do some more analysis on the results afterwards,
so i do n't have to waste a minute if i forget to bind the return value to something
(define (run-all-tests)
(let ([rs (compare* all-metrics)])
(set! results rs)
(for-each
(ann pretty-print-result ((U (result (Listof NumF) (Listof Atom-display) (Listof Any))
(result (Listof NumF) (Listof Atom-display) Any))
-> Any))
rs)
rs))
| null |
https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/new-metrics.rkt
|
racket
|
============================================================
collects-path : a path to the collects directory to compare
planet-code-path : a path to the "other" code to compare (i.e. unpacked, most recent versions
of all planet packages)
============================================================
STATS
computes t value for the given sequences. t-tests measure
_interval-valued_ samples (e.g. distances, times, weights, counts ...)
can be explained by chance. Generally speaking, higher absolute
values of t correspond to higher confidence that an observed difference
in mean cannot be explained by chance.
chi-square is a simple measure of the extent to which the
be explained by chance. higher numbers means higher confidence
that they cannot.
these assume that the data is coded as 1 = present, 0 = not present
============================================================
UNITS OF MEASUREMENT IMPLEMENTATIONS
============================================================
BASIC CALCULATIONS
(for use with metric definitions below)
----------------------------------------
depth
----------------------------------------
setbang counts
undercount potentially, but how many `,(set! ...)'s can there be?
----------------------------------------
contracts
----------------------------------------
macros
----------------------------------------
expression size
============================================================
METRIC DEFINITIONS
This test now redundant b/c of typechecking
============================================================
EXPERIMENT RUNNING
goofy backwards matching because ... matches greedily
("collects" "drscheme") #;("collects" "framework"))
----------------------------------------
applies the given function to each .rkt or .ss or .scm file in the given
directory hierarchy; returns all results in a list
applies only to the combined metric [or more generally to listof-answer results]
============================================================
UTILITY
============================================================
MAIN ENTRY POINT
just in case i want to do some more analysis on the results afterwards,
|
#lang typed/racket/shallow
(provide results run-all-tests)
(require (except-in scheme/list count) scheme/math scheme/path mzlib/match
(prefix-in srfi13: srfi/13) scheme/file
(for-syntax scheme/base))
(require/typed (prefix-in srfi48: srfi/48)
[srfi48:format ( Port String String Any * -> Any)] )
(define-type-alias NumF (U Number #f))
(define-type-alias (Unit C) ((C -> (Listof NumF)) -> (Path -> (Listof (U #f (Listof NumF))))))
CONFIG
(define COLLECTS-PATH (make-parameter (build-path "/home/samth/Desktop/collects-tmp/")))
(define PLANET-CODE-PATH (make-parameter (build-path "/home/samth/Desktop/most-recent-archives/")))
(: t-test ((Listof Number) (Listof Number) -> Number))
the extent to which difference in mean between two sets of
(define (t-test seqA seqB)
(manual-t-test
(avg seqA) (avg seqB)
(variance seqA) (variance seqB)
(length seqA) (length seqB)))
(: manual-t-test (Number Number Number Number Number Number -> Number))
(define (manual-t-test avga avgb vara varb cta ctb)
(/ (- avga avgb)
(assert (sqrt (+ (/ vara cta) (/ varb ctb))) number?)))
(: chi-square ((Listof Number) (Listof Number) -> Number))
difference in the frequency of 0 's and 1 's in the first
sequence and their frequency in the second sequence can
(define (chi-square seqA seqB)
(with-handlers ([exn:fail? (λ (e) +nan.0)])
(let* ([ct-a (length seqA)]
[ct-b (length seqB)]
[total-subjects (+ ct-a ct-b)]
[a-hits (apply + seqA)]
[a-misses (- ct-a a-hits)]
[b-misses (- ct-b b-hits)]
[table
`((,a-hits ,b-hits)
(,a-misses ,b-misses))]
[expected (λ: ([i : Integer] [j : Integer])
(/ (* (row-total i table) (col-total j table)) total-subjects))])
(exact->inexact
(table-sum
(λ (i j) (/ (sqr (- (expected i j) (table-ref i j table))) (expected i j)))
table)))))
(: per-module (All (X) (((Listof Any) -> X) -> (Path -> (List (U #f X))))))
(define (per-module f)
(λ (path)
(with-handlers ([exn:fail:read? (λ (e) (list #f))])
(let ([initial-sexp (with-input-from-file path read)])
(match initial-sexp
[`(module ,_ ,_ ,bodies ...)
(list (f bodies))]
[_ (list #f)])))))
(: per-module-top-level-expression ((Any -> (Listof NumF)) -> MetricFn))
(define (per-module-top-level-expression f)
(let ([calc (per-module (λ: ([exprs : (Listof Any)]) (map f exprs)))])
(λ (p) (let ([r (calc p)]) (if (car r) (car r) r)))))
(: sexp-depth (Any -> Integer))
(define (sexp-depth sexp)
(cond
[(pair? sexp)
(+ (max-sexp-depth sexp) 1)]
[else 0]))
(: max-sexp-depth (Any -> Integer))
(define (max-sexp-depth losx)
(improper-foldr (λ: ([t : Any] [r : Integer]) (max (sexp-depth t) r)) 0 losx))
(: avg-sexp-depth ((Listof Any) -> Number))
(define (avg-sexp-depth sexps)
(cond
[(null? sexps) 0]
[else (avg (map sexp-depth sexps))]))
(: count-setbangs/ilist (Any -> Number))
(define (count-setbangs/ilist exprs)
(apply + (imap count-setbangs/expr exprs)))
(: count-setbangs/expr (Any -> Number))
(define (count-setbangs/expr expr)
(match expr
[`(,(? setbang?) ,rest ...) (+ 1 (count-setbangs/ilist rest))]
[('quote _) 0]
[`(,e1 . ,e2) (count-setbangs/ilist expr)]
[_ 0]))
(: setbang? (Any -> Any))
(define (setbang? v)
(and (symbol? v)
(regexp-match #rx"^set(-.*)?!" (symbol->string v))))
count - fns
(: count-fns-with-setbangs ((Listof Any) -> Number))
(define (count-fns-with-setbangs exprs)
(apply + (map (λ (e) (if (= (count-setbangs/expr e) 0) 0 1)) exprs)))
(: module-has-setbangs? ((Listof Any) -> Boolean))
(define (module-has-setbangs? exprs) (ormap expr-uses-setbangs? exprs))
(: expr-uses-setbangs? (Any -> Boolean))
(define (expr-uses-setbangs? expr)
(not (= (count-setbangs/expr expr) 0)))
(: setbangs-per-1000-atoms ((Listof Any) -> NumF))
(define (setbangs-per-1000-atoms exprs)
(if (null? exprs)
#f
(let ([set!s (count-setbangs/ilist exprs)]
[atoms (atoms exprs)])
(* (/ set!s atoms) 1000.0))))
(: uses-contracts ((Listof Any) -> Boolean))
(define (uses-contracts exprs)
(ormap (λ (e)
(ann
(match e
[`(provide/contract ,_ ...) #t]
[_ #f])
: Boolean))
exprs))
(: contracted-provides ((Listof Any) -> Number))
(define (contracted-provides exprs)
(foldl
(λ: ([t : Any] [r : Number])
(ann
(match t
[(provide/contract ,p ...) (+ (length p) r)]
[_ r]) : Number))
0
exprs))
(: uncontracted-provides ((Listof Any) -> Number))
(define (uncontracted-provides exprs)
(foldl
(λ: ([t : Any] [r : Number])
(ann
(match t
[`(provide ,p ...) (+ (length p) r)]
[_ r]) : Number))
0
exprs))
(: number-of-macro-definitions (Any -> Number))
(define (number-of-macro-definitions expr)
(match expr
[`(define-syntax ,_ ...) 1]
[`(define-syntaxes (,s ...) ,_ ...) (length s)]
[`(define-syntax-set (,s ...) ,_ ...) (length s)]
[_ 0]))
(: num-of-define-syntax ((Listof Any) -> Number))
(define (num-of-define-syntax exprs)
(foldl (λ: ([t : Any] [r : Number]) (+ (number-of-macro-definitions t) r)) 0 exprs))
(: atoms (Any -> Integer))
(define (atoms sexp)
(cond
[(null? sexp) 0]
[(not (pair? sexp)) 1]
[else (+ (atoms (car sexp)) (atoms (cdr sexp)))]))
(: max-atoms ((Listof Any) -> NumF))
(define (max-atoms exprs)
(let ([atom-counts (map atoms exprs)])
(if (null? atom-counts)
#f
(apply max atom-counts))))
(: avg-atoms ((Listof Any) -> NumF))
(define (avg-atoms exprs)
(let ([atom-counts (map atoms exprs)])
(if (null? atom-counts)
#f
(avg (map atoms exprs)))))
(: total-atoms ((Listof Any) -> Number))
(define (total-atoms exprs)
(apply + (map atoms exprs)))
' a ' b metric : ( string * ( listof sexp - > ' a option ) * ( ( listof ' a ) ( listof ' a ) - > ' b )
(define-typed-struct (b c d) metric ([analysis-unit : (Unit c)]
[computation : (c -> d)]
[>display : ((Listof d) (Listof d) -> b)]))
(define-type-alias Table (Listof (Listof Number)))
(define-type-alias Atom-display (cons Symbol (Listof Number)))
(: standard-display (Symbol ((Listof Number) -> Number) ((Listof Number) (Listof Number) -> Number)
-> ((Listof NumF) (Listof NumF) -> Atom-display)))
(define ((standard-display name summarize significance-test) seqA seqB)
(let ([clean-seqA (nonfalses seqA)]
[clean-seqB (nonfalses seqB)])
(list name (summarize clean-seqA) (summarize clean-seqB) (significance-test clean-seqA clean-seqB))))
(: interval (All (c) ((Unit c) Symbol (c -> NumF) -> (metric Atom-display c NumF))))
(define (interval u name compute) (make-metric u compute (standard-display name avg t-test)))
(: count (All (c) ((Unit c) Symbol (c -> Boolean) -> (metric Atom-display c NumF))))
(define (count u name compute) (make-metric u (λ: ([es : c]) (if (compute es) 1 0)) (standard-display name avg chi-square)))
(: combine-metrics (All (c) ((Listof (metric Atom-display c NumF)) -> (metric (Listof Atom-display) c (Listof NumF)))))
(define (combine-metrics ms)
(let ([u (metric-analysis-unit (car ms))])
(unless (andmap (λ: ([m : (metric Atom-display c NumF) ]) (eq? u (metric-analysis-unit m))) ms)
(error 'combine-metrics "all combined metrics must operate on the same unit of analysis"))
(make-metric
u
(λ: ([exprs : c]) (map (λ: ([m : (metric Atom-display c NumF)]) ((metric-computation m) exprs)) ms))
(λ: ([seqA : (Listof (Listof NumF))] [seqB : (Listof (Listof NumF))])
(map (λ: ([m : (metric Atom-display c NumF)]
[sA : (Listof NumF)]
[sB : (Listof NumF)])
((metric->display m) sA sB)) ms (pivot seqA) (pivot seqB))))))
FIXME - ( filter ( lambda ( x ) x ) l )
(: nonfalses (All (X) ((Listof (U #f X)) -> (Listof X))))
(define (nonfalses l)
(let loop ([lst l])
(if (null? lst)
'()
(let ([x (car lst)])
(if x
(cons x (loop (cdr lst)))
(loop (cdr lst)))))))
(: avg ((Listof Number) -> Number))
(define (avg l) (/ (exact->inexact (apply + l)) (length l)))
(: avg* ((Listof Number) -> Number))
(define (avg* l) (avg (nonfalses l)))
(define-syntax define-metrics
(syntax-rules ()
[(define-metrics all-metrics-id unit-of-analysis (name kind fn) ...)
(begin
(define u unit-of-analysis)
(define name (kind u 'name fn )) ...
(define all-metrics-id (combine-metrics (list name ...))))]))
(define-metrics module-metrics #{per-module @ (Listof NumF)}
(maximum-sexp-depth interval max-sexp-depth)
(average-sexp-depth interval avg-sexp-depth)
(number-of-setbangs/mod interval count-setbangs/ilist)
(number-of-exprs interval #{length @ Any})
(uses-setbang?/mod count module-has-setbangs?)
(uses-contracts? count uses-contracts)
(number-of-contracts interval contracted-provides)
(num-uncontracted-provides interval uncontracted-provides)
(number-of-macro-defs interval num-of-define-syntax)
(maximum-num-atoms interval max-atoms)
(average-num-atoms interval avg-atoms)
(total-num-atoms/mod interval total-atoms)
(set!s-per-1000-atoms interval setbangs-per-1000-atoms))
(define-metrics tl-expr-metrics per-module-top-level-expression
(uses-setbang?/fn count expr-uses-setbangs?)
(number-of-setbangs/fn interval count-setbangs/expr)
(total-num-atoms/fn interval atoms))
(: all-metrics (List (metric (Listof Atom-display) (Listof Any) (Listof NumF))
(metric (Listof Atom-display) Any (Listof NumF)) ))
(define all-metrics (list module-metrics tl-expr-metrics))
(define-syntax (define-excluder stx)
(define (path->clause c)
(syntax-case c ()
[(item ...)
#`[`(#,@(reverse (syntax-e #'(item ...))) ,_ (... ...)) #t]]
[item
#`[`(item) #t]]))
(syntax-case stx ()
[(_ name path ...)
(with-syntax ([(match-clause ...) (map path->clause (syntax-e #'(path ...)))])
#`(define (name p )
(let* ([dirnames (map path->string (filter path? (explode-path p)))])
match-clause ...
[_ #f]))))]))
(: default-excluder (Path -> Boolean))
(define-excluder default-excluder
(define exclude-directory? (make-parameter default-excluder))
apply - to - scheme - files : ( path[file ] - > X ) path[directory ] - > ( listof X )
(: apply-to-scheme-files (All (X) ((Path -> X) Path -> (Listof X))))
(define (apply-to-scheme-files f root)
(fold-files
(λ: ([path : Path] [kind : (U 'file 'dir 'link)] [acc : (Listof X)])
(case kind
[(file)
(let ([extension (filename-extension path)])
(cond
[(not extension) (values acc #t)]
[(regexp-match #rx"(ss|scm)$" extension)
(let ([resl (f path)])
(if resl
(values (cons resl acc) #t)
(values acc #t)))]
[else (values acc #t)]))]
[(dir)
(let* ([p (normalize-path path root)])
(if ((exclude-directory?) p)
(values acc #f)
(values acc #t)))]
[(link) (values acc #t)]))
'()
root))
(define-typed-struct (a b c) result ([metric : (metric b c a)] [seqA : (Listof a)] [seqB : (Listof a)]))
(define-type-alias MetricFn (Path -> (Listof (U #f (Listof NumF)))))
(define-type-alias (M b c) (metric b c (Listof NumF)))
(define-type-alias (M2 b c c*) (U (M b c) (M b c*)))
get - sequences : ( listof ' a metric ) path - > ( listof ( listof ' a ) )
(: get-sequences (All (b c C) ((List (M b c) (M b C)) Path -> (Listof (Listof (Listof NumF))))))
(define (get-sequences metrics path)
(: selector (case-lambda [(M b c) -> MetricFn] [(M b C) -> MetricFn]))
(define (selector m) ((metric-analysis-unit m) (metric-computation m)))
(let* ([metric-fns (map #{selector :: ((M2 b c C) -> MetricFn)} metrics)]
[result-seqs (apply-to-scheme-files
(λ: ([file : Path])
(map (λ: ([fn : MetricFn]) (fn file)) metric-fns)) path)])
(map
(λ: ([l : (Listof (Listof (U #f (Listof NumF))))])
(nonfalses (apply append l)))
(pivot (nonfalses result-seqs)))))
(: compare*
(All (b c c*)
((List (M b c) (M b c*))
->
(List (result (Listof NumF) b c)
(result (Listof NumF) b c*)))))
(define (compare* metrics)
(let* ([seqAs (get-sequences metrics (COLLECTS-PATH))]
[seqBs (get-sequences metrics (PLANET-CODE-PATH))])
(list
(make-result (car metrics) (car seqAs) (car seqBs))
(make-result (cadr metrics) (cadr seqAs) (cadr seqBs)))))
(: show (All (a b c) ((result a b c) -> b)))
(define (show result)
((metric->display (result-metric result))
(result-seqA result)
(result-seqB result)))
(: pretty-print-result
(case-lambda
((result (Listof NumF) (Listof Atom-display) (Listof Any)) -> Void)
((result (Listof NumF) (Listof Atom-display) Any) -> Void)))
(define (pretty-print-result result)
(for-each
(λ: ([l : (Listof Any)])
(apply srfi48:format
(current-output-port)
"~26F | ~8,2F | ~6,2F | ~12,2F\n"
(format "~a" (car l))
(cdr l)))
(list* '("test name" "collects" "planet" "significance")
'("---------" "--------" "------" "------------")
(show result))))
(: total (All (b c) (Integer (result (Listof Number) b c) -> (Listof Number))))
(define (total experiment-number result)
(: total/s (Table -> Number))
(define (total/s s) (apply + (list-ref (pivot s) experiment-number)))
(list (total/s (result-seqA result)) (total/s (result-seqB result))))
(: imap (All (Y) ((Any -> Y) Any -> (Listof Y))))
(define (imap f il)
(cond
[(null? il) '()]
[(not (pair? il)) (list (f il))]
[else (cons (f (car il)) (imap f (cdr il)))]))
(: pivot (All (X) ((Listof (Listof X)) -> (Listof (Listof X)))))
(define (pivot l)
(cond
[(null? l) '()]
[else
(let ([n (length (car l))])
(build-list n (λ: ([i : Integer]) (map (λ: ([j : (Listof X)]) (list-ref j i)) l))))]))
(: variance ((Listof Number) -> Number))
(define (variance xs)
(let ([avg (/ (apply + xs) (length xs))])
(/ (apply + (map (λ: ([x : Number]) (sqr (- x avg))) xs))
(sub1 (length xs)))))
(: table-ref (Integer Integer Table -> Number))
(define (table-ref i j table)
(list-ref (list-ref table i) j))
(: row-total (Integer Table -> Number))
(define (row-total i table)
(apply + (list-ref table i)))
(: col-total (Integer Table -> Number))
(define (col-total j table)
(apply + (map (λ: ([x : (Listof Number)]) (list-ref x j)) table)))
(: table-sum ((Integer Integer -> Number) Table -> Number))
(define (table-sum f table)
(let ([rows (length table)]
[cols (length (car table))])
(let loop ([i 0] [j 0] [#{sum : Number} 0])
(cond
[(>= j cols) sum]
[(>= i rows) (loop 0 (add1 j) sum)]
[else (loop (add1 i) j (+ sum (f i j)))]))))
(: improper-foldr (All (Y) ((Any Y -> Y) Y Any -> Y)))
(define (improper-foldr f b l)
(cond
[(null? l) b]
[(not (pair? l))
(f l b)]
[else
(f (car l) (improper-foldr f b (cdr l)))]))
(: /* (All (a ...) ((Listof Number) (Listof Number) ... a -> (Listof Number))))
(define (/* arg . args)
(apply map (λ: ([n : Number] . [ns : Number ... a]) (apply / n ns)) arg args))
(: results (U #f (Listof (U (result (Listof NumF) (Listof Atom-display) (Listof Any))
(result (Listof NumF) (Listof Atom-display) Any)))))
so i do n't have to waste a minute if i forget to bind the return value to something
(define (run-all-tests)
(let ([rs (compare* all-metrics)])
(set! results rs)
(for-each
(ann pretty-print-result ((U (result (Listof NumF) (Listof Atom-display) (Listof Any))
(result (Listof NumF) (Listof Atom-display) Any))
-> Any))
rs)
rs))
|
a00df78a9ce4ec0b9166a521547018a7a44210e5adca17c5c3445ecd72778004
|
metabase/metabase
|
application.clj
|
(ns metabase-enterprise.advanced-permissions.api.application
"`/advanced-permisisons/application` Routes.
Implements the Permissions routes needed for application permission - a class of permissions that control access to features
like access Setting pages, access monitoring tools ... etc"
(:require
[compojure.core :refer [GET PUT]]
[metabase-enterprise.advanced-permissions.models.permissions.application-permissions :as a-perms]
[metabase.api.common :as api]))
(set! *warn-on-reflection* true)
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/graph"
"Fetch a graph of Application Permissions."
[]
(api/check-superuser)
(a-perms/graph))
(defn- dejsonify-application-permissions
[application-permissions]
(into {} (for [[perm-type perm-value] application-permissions]
[perm-type (keyword perm-value)])))
(defn- dejsonify-groups
[groups]
(into {} (for [[group-id application-permissions] groups]
[(Integer/parseInt (name group-id))
(dejsonify-application-permissions application-permissions)])))
(defn- dejsonify-graph
"Fix the types in the graph when it comes in from the API, e.g. converting things like `\"yes\"` to `:yes` and
parsing object keys keyword."
[graph]
(update graph :groups dejsonify-groups))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema PUT "/graph"
"Do a batch update of Application Permissions by passing a modified graph."
[:as {:keys [body]}]
(api/check-superuser)
(-> body
dejsonify-graph
a-perms/update-graph!)
(a-perms/graph))
(api/define-routes)
| null |
https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/enterprise/backend/src/metabase_enterprise/advanced_permissions/api/application.clj
|
clojure
|
(ns metabase-enterprise.advanced-permissions.api.application
"`/advanced-permisisons/application` Routes.
Implements the Permissions routes needed for application permission - a class of permissions that control access to features
like access Setting pages, access monitoring tools ... etc"
(:require
[compojure.core :refer [GET PUT]]
[metabase-enterprise.advanced-permissions.models.permissions.application-permissions :as a-perms]
[metabase.api.common :as api]))
(set! *warn-on-reflection* true)
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema GET "/graph"
"Fetch a graph of Application Permissions."
[]
(api/check-superuser)
(a-perms/graph))
(defn- dejsonify-application-permissions
[application-permissions]
(into {} (for [[perm-type perm-value] application-permissions]
[perm-type (keyword perm-value)])))
(defn- dejsonify-groups
[groups]
(into {} (for [[group-id application-permissions] groups]
[(Integer/parseInt (name group-id))
(dejsonify-application-permissions application-permissions)])))
(defn- dejsonify-graph
"Fix the types in the graph when it comes in from the API, e.g. converting things like `\"yes\"` to `:yes` and
parsing object keys keyword."
[graph]
(update graph :groups dejsonify-groups))
#_{:clj-kondo/ignore [:deprecated-var]}
(api/defendpoint-schema PUT "/graph"
"Do a batch update of Application Permissions by passing a modified graph."
[:as {:keys [body]}]
(api/check-superuser)
(-> body
dejsonify-graph
a-perms/update-graph!)
(a-perms/graph))
(api/define-routes)
|
|
d56d81633b38f163db201eb1cc0134876a401f42e2e84378cf9c2e17f0308c3b
|
ninenines/gun
|
gun_raw.erl
|
Copyright ( c ) 2019 - 2023 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(gun_raw).
-export([check_options/1]).
-export([name/0]).
-export([opts_name/0]).
-export([has_keepalive/0]).
-export([init/4]).
-export([handle/5]).
-export([update_flow/4]).
-export([closing/4]).
-export([close/4]).
-export([data/7]).
-export([down/1]).
-record(raw_state, {
ref :: undefined | gun:stream_ref(),
reply_to :: pid(),
socket :: inet:socket() | ssl:sslsocket(),
transport :: module(),
flow :: integer() | infinity
}).
check_options(Opts) ->
do_check_options(maps:to_list(Opts)).
do_check_options([]) ->
ok;
do_check_options([{flow, Flow}|Opts]) when is_integer(Flow); Flow == infinity ->
do_check_options(Opts);
do_check_options([Opt|_]) ->
{error, {options, {raw, Opt}}}.
name() -> raw.
opts_name() -> raw_opts.
has_keepalive() -> false.
init(ReplyTo, Socket, Transport, Opts) ->
StreamRef = maps:get(stream_ref, Opts, undefined),
InitialFlow = maps:get(flow, Opts, infinity),
{ok, connected_data_only, #raw_state{ref=StreamRef, reply_to=ReplyTo,
socket=Socket, transport=Transport, flow=InitialFlow}}.
handle(Data, State=#raw_state{ref=StreamRef, reply_to=ReplyTo, flow=Flow0},
CookieStore, _, EvHandlerState) ->
%% When we take over the entire connection there is no stream reference.
ReplyTo ! {gun_data, self(), StreamRef, nofin, Data},
Flow = case Flow0 of
infinity -> infinity;
_ -> Flow0 - 1
end,
{[
{state, State#raw_state{flow=Flow}},
{active, Flow > 0}
], CookieStore, EvHandlerState}.
update_flow(State=#raw_state{flow=Flow0}, _ReplyTo, _StreamRef, Inc) ->
Flow = case Flow0 of
infinity -> infinity;
_ -> Flow0 + Inc
end,
[
{state, State#raw_state{flow=Flow}},
{active, Flow > 0}
].
%% We can always close immediately.
closing(_, _, _, EvHandlerState) ->
{close, EvHandlerState}.
close(_, _, _, EvHandlerState) ->
EvHandlerState.
@todo Initiate closing on IsFin = fin .
data(#raw_state{ref=StreamRef, socket=Socket, transport=Transport}, StreamRef,
_ReplyTo, _IsFin, Data, _EvHandler, EvHandlerState) ->
case Transport:send(Socket, Data) of
ok -> {[], EvHandlerState};
Error={error, _} -> {Error, EvHandlerState}
end.
%% raw has no concept of streams.
down(_) ->
[].
| null |
https://raw.githubusercontent.com/ninenines/gun/33223e751267c5f249f3db1277c13904a1801b92/src/gun_raw.erl
|
erlang
|
Permission to use, copy, modify, and/or 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.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
When we take over the entire connection there is no stream reference.
We can always close immediately.
raw has no concept of streams.
|
Copyright ( c ) 2019 - 2023 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(gun_raw).
-export([check_options/1]).
-export([name/0]).
-export([opts_name/0]).
-export([has_keepalive/0]).
-export([init/4]).
-export([handle/5]).
-export([update_flow/4]).
-export([closing/4]).
-export([close/4]).
-export([data/7]).
-export([down/1]).
-record(raw_state, {
ref :: undefined | gun:stream_ref(),
reply_to :: pid(),
socket :: inet:socket() | ssl:sslsocket(),
transport :: module(),
flow :: integer() | infinity
}).
check_options(Opts) ->
do_check_options(maps:to_list(Opts)).
do_check_options([]) ->
ok;
do_check_options([{flow, Flow}|Opts]) when is_integer(Flow); Flow == infinity ->
do_check_options(Opts);
do_check_options([Opt|_]) ->
{error, {options, {raw, Opt}}}.
name() -> raw.
opts_name() -> raw_opts.
has_keepalive() -> false.
init(ReplyTo, Socket, Transport, Opts) ->
StreamRef = maps:get(stream_ref, Opts, undefined),
InitialFlow = maps:get(flow, Opts, infinity),
{ok, connected_data_only, #raw_state{ref=StreamRef, reply_to=ReplyTo,
socket=Socket, transport=Transport, flow=InitialFlow}}.
handle(Data, State=#raw_state{ref=StreamRef, reply_to=ReplyTo, flow=Flow0},
CookieStore, _, EvHandlerState) ->
ReplyTo ! {gun_data, self(), StreamRef, nofin, Data},
Flow = case Flow0 of
infinity -> infinity;
_ -> Flow0 - 1
end,
{[
{state, State#raw_state{flow=Flow}},
{active, Flow > 0}
], CookieStore, EvHandlerState}.
update_flow(State=#raw_state{flow=Flow0}, _ReplyTo, _StreamRef, Inc) ->
Flow = case Flow0 of
infinity -> infinity;
_ -> Flow0 + Inc
end,
[
{state, State#raw_state{flow=Flow}},
{active, Flow > 0}
].
closing(_, _, _, EvHandlerState) ->
{close, EvHandlerState}.
close(_, _, _, EvHandlerState) ->
EvHandlerState.
@todo Initiate closing on IsFin = fin .
data(#raw_state{ref=StreamRef, socket=Socket, transport=Transport}, StreamRef,
_ReplyTo, _IsFin, Data, _EvHandler, EvHandlerState) ->
case Transport:send(Socket, Data) of
ok -> {[], EvHandlerState};
Error={error, _} -> {Error, EvHandlerState}
end.
down(_) ->
[].
|
92c1045418ce2957b54899b911a73ae1f63bd5ddb23d63d9c5dd92e09bf4f616
|
zk/nsfw
|
devbus.cljs
|
(ns nsfw.devbus
(:require [nsfw.util :as nu]
[taoensso.timbre :as log :include-macros true]
[datascript.transit :as dt]
[cljs.test
:refer-macros [deftest is
testing run-tests
async]]
[cljs.core.async
:refer [<! chan put! timeout close!]
:refer-macros [go go-loop]]))
(def DEFAULT_READ_HANDLERS
(merge
dt/read-handlers))
(def DEFAULT_WRITE_HANDLERS
(merge
dt/write-handlers))
(defn ws [url
{:keys [on-open
on-close
on-message
on-error]}]
(let [s (js/WebSocket. url)]
(set! (.-onopen s) on-open)
(set! (.-onclose s) on-close)
(set! (.-onmessage s) on-message)
(set! (.-onerror s) on-error)
s))
(defn close-ws [s]
(when s
(.close s)))
(defn <ws [url]
(let [ch (chan)
socket (ws
url
{:on-open (fn [o]
(put! ch {:event-type :open
:event o}))
:on-error (fn [o]
(put! ch {:event-type :error
:event o})
(close! ch))
:on-message (fn [o]
(put! ch {:event-type :message
:event o}))
:on-close (fn [o]
(put! ch {:event-type :close
:event o})
(close! ch))})]
{:ch ch
:socket socket}))
(defn pws [url {:keys [on-open
on-message
on-close
on-error]
:or {on-open (fn [_])
on-message (fn [_])
on-close (fn [_])
on-error (fn [_])}}]
(let [!run? (atom true)
!socket (atom nil)
out {:close (fn []
(reset! !run? false)
(when @!socket
(.close @!socket)))
:send (fn [data]
(.send @!socket data))
:!socket !socket}]
(go-loop []
(let [{:keys [ch socket]} (<ws url)]
(reset! !socket socket)
(loop []
(let [{:keys [event-type event] :as message} (<! ch)]
(condp = event-type
:open (on-open event out)
:message (on-message event out)
:close (on-close event out)
:error (on-error event out))
(when (get #{:open :message} event-type)
(recur))))
(when @!socket
(log/debug "Closing socket")
(.close @!socket))
(log/info "Connection lost")
(when @!run?
(<! (timeout 1000))
(log/info "Reconnecting")
(recur))
(log/info "Stopping pws")))
out))
(defn close-pws [{:keys [close] :as pws}]
(when pws
(close)))
(defn pws-open? [{:keys [!socket]}]
(when-let [s @!socket]
(let [state (.-readyState s)]
(= (.-OPEN s) state))))
(deftest test-pws-close
(let [p (pws "ws:44100/devbus"
{:on-close (fn [] (prn "close"))
:on-error (fn [] (prn "error"))})]
(async done
(go
(<! (timeout 500))
(close-pws p)
(is (not (pws-open? p)))
(done)))))
(defn stop-client [conn]
(close-pws conn))
(defn handlers-client [url handlers
& [{:keys [on-open
on-error
on-close
transit-read-handlers]
:or {on-open (fn [_])
on-error (fn [_])
on-close (fn [_])}}]]
(pws
url
{:on-open
(fn [o pws-client]
(on-open (.-target o) pws-client))
:on-error
(fn [o]
(on-error (.-target o)))
:on-message
(fn [o pws-client]
(let [res (try
(nu/from-transit (.-data o)
{:handlers
(merge
DEFAULT_READ_HANDLERS
transit-read-handlers)})
(catch js/Error e
(log/debug "Error decoding message" (.-data o))
nil))]
(when res
(let [[key & args] res
handler (get handlers key)]
(when handler
(handler pws-client args))))))
:on-close
(fn [o]
(prn "oc")
(on-close (.-target o)))}))
(deftype ObjectHandler []
Object
(tag [this v] "jsobj")
(rep [this v] (str v))
(stringRep [this v] (str v)))
(defn send [{sendpws :send :as pws}
data
&
[{:keys [write-handlers]}]]
(when-not sendpws
(nu/throw-str (str "send requires pws object, got " pws)))
(when sendpws
(try
(sendpws (nu/to-transit data
{:handlers (merge
DEFAULT_WRITE_HANDLERS
write-handlers)}))
(catch js/Error e
(log/info "Error encoding" e)
#_(.error js/console (str "Error serializing"
(pr-str data)))
nil))))
(defn send-state [devbus-conn {:keys [ref] :as state-item}]
(send devbus-conn
[(merge
(select-keys
state-item
[:title :section])
(when ref
{:value (deref ref)}))]))
(def !state (atom nil))
(defn realize-state-item
[{:keys [ref] :as si}]
(if ref
(-> si
(dissoc :ref)
(assoc :value (deref ref))
(assoc :updated-at (nu/now)))
si))
(defn realize-state-items [sis]
(->> sis
(map realize-state-item)
vec))
(defn app-client [url & [opts]]
(when (:devbus-conn @!state)
(stop-client (:devbus-conn @!state)))
(let [devbus-conn
(handlers-client
url
{:request-state-items
(fn [devbus-conn]
(send
devbus-conn
[:state-items
(->> @!state
:state-items
realize-state-items)]))
:request-test-states
(fn [devbus-conn]
(send
devbus-conn
[:test-states (-> @!state :test-states)]))
:load-test-state
(fn [_ [test-state]]
(when-let [on-receive (:on-receive @!state)]
(on-receive test-state)))
:heartbeat
(fn [devbus-conn]
(prn "got heartbeat"))}
(merge
{:on-open
(fn [ws devbus-conn]
(log/debug "Startup broadcast for :state-items, :test-states")
(send devbus-conn
[:state-items
(->> @!state
:state-items
realize-state-items)]
opts)
(send devbus-conn
[:test-states
(->> @!state
:test-states)]
opts))}
opts))]
(swap! !state assoc :devbus-conn devbus-conn)))
(defn debug-client [url
{:keys [on-state-items
on-test-states
on-open]
:as opts}]
(handlers-client
url
{:state-items
(fn [_ [state-items]]
(on-state-items state-items))
:test-states
(fn [_ [test-states]]
(on-test-states test-states))
:heartbeat (fn [_]
(prn "heartbeat"))}
(merge
opts
{:on-open (fn [db pws]
(log/debug "Connected, broadcasting"
(->> [:request-state-items
:request-test-states]
(interpose ", ")
(apply str)))
(send pws [:request-state-items])
(send pws [:request-test-states])
(when on-open
(on-open db pws)))})))
(defn shutdown []
(log/info "Devbus shutdown")
(when-let [devbus-conn (:devbus-conn @!state)]
(log/info "Shutting down devbus-conn")
(stop-client devbus-conn))
(doseq [{:keys [ref] :as item} (:state-items @!state)]
(when ref
(remove-watch
ref
:devbus)))
(reset! !state nil))
(defn distinct-by
([f coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[x :as xs] seen]
(when-let [s (seq xs)]
(let [v (f x)]
(if (contains? seen v)
(recur (rest s) seen)
(cons x (step (rest s) (conj seen v)))))))
xs seen)))]
(step coll #{}))))
(defn process-state-items [sis]
(->> sis
(map (fn [{:keys [title section ref value key]}]
(merge
{:key (if key
(str (namespace key) "." (name key))
(str section "." title))}
(when ref
{:ref ref})
(when value
{:value value}))))))
(defn trackmult [state-items]
(let [state-items (process-state-items state-items)
new-state-items (set
(distinct-by
:key
(concat
state-items
(:state-items @!state))))]
(swap! !state assoc :state-items new-state-items)
(when-let [devbus-conn (:devbus-conn @!state)]
(send devbus-conn
[:state-items
(->> state-items
realize-state-items)]))
(doseq [{:keys [ref key] :as item} (->> state-items
(filter :ref))]
(when ref
(add-watch ref :devbus
(fn [_ _ _ state]
(when-let [devbus-conn (:devbus-conn @!state)]
(send devbus-conn
[:state-items
[(realize-state-item item)]]))))))))
(defn track [si]
(trackmult [si]))
(defn atom? [o]
(satisfies? IAtom o))
(defn watch [k v]
(try
(track
(merge
{:key k}
(if (atom? v)
{:ref v}
{:value v})))
(catch js/Error e
(println "Couldn't watch" k "-" e))))
(defn hook-test-states
[test-states
on-receive]
(swap! !state
assoc
:test-states test-states
:on-receive on-receive)
(when-let [conn (:devbus-conn @!state)]
(send conn [:test-states test-states])))
| null |
https://raw.githubusercontent.com/zk/nsfw/ea07ba20cc5453b34a56b34c9d8738bf9bf8e92f/src/cljs/nsfw/devbus.cljs
|
clojure
|
(ns nsfw.devbus
(:require [nsfw.util :as nu]
[taoensso.timbre :as log :include-macros true]
[datascript.transit :as dt]
[cljs.test
:refer-macros [deftest is
testing run-tests
async]]
[cljs.core.async
:refer [<! chan put! timeout close!]
:refer-macros [go go-loop]]))
(def DEFAULT_READ_HANDLERS
(merge
dt/read-handlers))
(def DEFAULT_WRITE_HANDLERS
(merge
dt/write-handlers))
(defn ws [url
{:keys [on-open
on-close
on-message
on-error]}]
(let [s (js/WebSocket. url)]
(set! (.-onopen s) on-open)
(set! (.-onclose s) on-close)
(set! (.-onmessage s) on-message)
(set! (.-onerror s) on-error)
s))
(defn close-ws [s]
(when s
(.close s)))
(defn <ws [url]
(let [ch (chan)
socket (ws
url
{:on-open (fn [o]
(put! ch {:event-type :open
:event o}))
:on-error (fn [o]
(put! ch {:event-type :error
:event o})
(close! ch))
:on-message (fn [o]
(put! ch {:event-type :message
:event o}))
:on-close (fn [o]
(put! ch {:event-type :close
:event o})
(close! ch))})]
{:ch ch
:socket socket}))
(defn pws [url {:keys [on-open
on-message
on-close
on-error]
:or {on-open (fn [_])
on-message (fn [_])
on-close (fn [_])
on-error (fn [_])}}]
(let [!run? (atom true)
!socket (atom nil)
out {:close (fn []
(reset! !run? false)
(when @!socket
(.close @!socket)))
:send (fn [data]
(.send @!socket data))
:!socket !socket}]
(go-loop []
(let [{:keys [ch socket]} (<ws url)]
(reset! !socket socket)
(loop []
(let [{:keys [event-type event] :as message} (<! ch)]
(condp = event-type
:open (on-open event out)
:message (on-message event out)
:close (on-close event out)
:error (on-error event out))
(when (get #{:open :message} event-type)
(recur))))
(when @!socket
(log/debug "Closing socket")
(.close @!socket))
(log/info "Connection lost")
(when @!run?
(<! (timeout 1000))
(log/info "Reconnecting")
(recur))
(log/info "Stopping pws")))
out))
(defn close-pws [{:keys [close] :as pws}]
(when pws
(close)))
(defn pws-open? [{:keys [!socket]}]
(when-let [s @!socket]
(let [state (.-readyState s)]
(= (.-OPEN s) state))))
(deftest test-pws-close
(let [p (pws "ws:44100/devbus"
{:on-close (fn [] (prn "close"))
:on-error (fn [] (prn "error"))})]
(async done
(go
(<! (timeout 500))
(close-pws p)
(is (not (pws-open? p)))
(done)))))
(defn stop-client [conn]
(close-pws conn))
(defn handlers-client [url handlers
& [{:keys [on-open
on-error
on-close
transit-read-handlers]
:or {on-open (fn [_])
on-error (fn [_])
on-close (fn [_])}}]]
(pws
url
{:on-open
(fn [o pws-client]
(on-open (.-target o) pws-client))
:on-error
(fn [o]
(on-error (.-target o)))
:on-message
(fn [o pws-client]
(let [res (try
(nu/from-transit (.-data o)
{:handlers
(merge
DEFAULT_READ_HANDLERS
transit-read-handlers)})
(catch js/Error e
(log/debug "Error decoding message" (.-data o))
nil))]
(when res
(let [[key & args] res
handler (get handlers key)]
(when handler
(handler pws-client args))))))
:on-close
(fn [o]
(prn "oc")
(on-close (.-target o)))}))
(deftype ObjectHandler []
Object
(tag [this v] "jsobj")
(rep [this v] (str v))
(stringRep [this v] (str v)))
(defn send [{sendpws :send :as pws}
data
&
[{:keys [write-handlers]}]]
(when-not sendpws
(nu/throw-str (str "send requires pws object, got " pws)))
(when sendpws
(try
(sendpws (nu/to-transit data
{:handlers (merge
DEFAULT_WRITE_HANDLERS
write-handlers)}))
(catch js/Error e
(log/info "Error encoding" e)
#_(.error js/console (str "Error serializing"
(pr-str data)))
nil))))
(defn send-state [devbus-conn {:keys [ref] :as state-item}]
(send devbus-conn
[(merge
(select-keys
state-item
[:title :section])
(when ref
{:value (deref ref)}))]))
(def !state (atom nil))
(defn realize-state-item
[{:keys [ref] :as si}]
(if ref
(-> si
(dissoc :ref)
(assoc :value (deref ref))
(assoc :updated-at (nu/now)))
si))
(defn realize-state-items [sis]
(->> sis
(map realize-state-item)
vec))
(defn app-client [url & [opts]]
(when (:devbus-conn @!state)
(stop-client (:devbus-conn @!state)))
(let [devbus-conn
(handlers-client
url
{:request-state-items
(fn [devbus-conn]
(send
devbus-conn
[:state-items
(->> @!state
:state-items
realize-state-items)]))
:request-test-states
(fn [devbus-conn]
(send
devbus-conn
[:test-states (-> @!state :test-states)]))
:load-test-state
(fn [_ [test-state]]
(when-let [on-receive (:on-receive @!state)]
(on-receive test-state)))
:heartbeat
(fn [devbus-conn]
(prn "got heartbeat"))}
(merge
{:on-open
(fn [ws devbus-conn]
(log/debug "Startup broadcast for :state-items, :test-states")
(send devbus-conn
[:state-items
(->> @!state
:state-items
realize-state-items)]
opts)
(send devbus-conn
[:test-states
(->> @!state
:test-states)]
opts))}
opts))]
(swap! !state assoc :devbus-conn devbus-conn)))
(defn debug-client [url
{:keys [on-state-items
on-test-states
on-open]
:as opts}]
(handlers-client
url
{:state-items
(fn [_ [state-items]]
(on-state-items state-items))
:test-states
(fn [_ [test-states]]
(on-test-states test-states))
:heartbeat (fn [_]
(prn "heartbeat"))}
(merge
opts
{:on-open (fn [db pws]
(log/debug "Connected, broadcasting"
(->> [:request-state-items
:request-test-states]
(interpose ", ")
(apply str)))
(send pws [:request-state-items])
(send pws [:request-test-states])
(when on-open
(on-open db pws)))})))
(defn shutdown []
(log/info "Devbus shutdown")
(when-let [devbus-conn (:devbus-conn @!state)]
(log/info "Shutting down devbus-conn")
(stop-client devbus-conn))
(doseq [{:keys [ref] :as item} (:state-items @!state)]
(when ref
(remove-watch
ref
:devbus)))
(reset! !state nil))
(defn distinct-by
([f coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[x :as xs] seen]
(when-let [s (seq xs)]
(let [v (f x)]
(if (contains? seen v)
(recur (rest s) seen)
(cons x (step (rest s) (conj seen v)))))))
xs seen)))]
(step coll #{}))))
(defn process-state-items [sis]
(->> sis
(map (fn [{:keys [title section ref value key]}]
(merge
{:key (if key
(str (namespace key) "." (name key))
(str section "." title))}
(when ref
{:ref ref})
(when value
{:value value}))))))
(defn trackmult [state-items]
(let [state-items (process-state-items state-items)
new-state-items (set
(distinct-by
:key
(concat
state-items
(:state-items @!state))))]
(swap! !state assoc :state-items new-state-items)
(when-let [devbus-conn (:devbus-conn @!state)]
(send devbus-conn
[:state-items
(->> state-items
realize-state-items)]))
(doseq [{:keys [ref key] :as item} (->> state-items
(filter :ref))]
(when ref
(add-watch ref :devbus
(fn [_ _ _ state]
(when-let [devbus-conn (:devbus-conn @!state)]
(send devbus-conn
[:state-items
[(realize-state-item item)]]))))))))
(defn track [si]
(trackmult [si]))
(defn atom? [o]
(satisfies? IAtom o))
(defn watch [k v]
(try
(track
(merge
{:key k}
(if (atom? v)
{:ref v}
{:value v})))
(catch js/Error e
(println "Couldn't watch" k "-" e))))
(defn hook-test-states
[test-states
on-receive]
(swap! !state
assoc
:test-states test-states
:on-receive on-receive)
(when-let [conn (:devbus-conn @!state)]
(send conn [:test-states test-states])))
|
|
045340405543b93da9b4f17c4dc5f92a6ccc444d2590079c0fbe14df5258e1f8
|
roelvandijk/numerals
|
TestData.hs
|
|
[ @ISO639 - 1@ ] -
[ @ISO639 - 2@ ] -
[ @ISO639 - 3@ ] caf
[ @Native name@ ] Dakeł ( ᑕᗸᒡ )
[ @English name@ ] Southern Carrier
[@ISO639-1@] -
[@ISO639-2@] -
[@ISO639-3@] caf
[@Native name@] Dakeł (ᑕᗸᒡ)
[@English name@] Southern Carrier
-}
module Text.Numeral.Language.CAF.TestData
( cardinals
, syllabic_cardinals
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "numerals" Text.Numeral.Grammar ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
{-
Sources:
-to-count-in-carrier/en/caf/
-}
cardinals :: (Num i) => TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (1, "lhuk’i")
, (2, "nankoh")
, (3, "tak’ih")
, (4, "dink’ih")
, (5, "skwunlai")
, (6, "lhk’uttak’ih")
, (7, "lhtak’alt’i")
, (8, "lhk’utdink’ih")
, (9, "lhuk’i hooloh")
, (10, "lanezyi")
, (11, "lanezyi ’o’un lhuk’i")
, (12, "lanezyi ’o’un nankoh")
, (13, "lanezyi ’o’un tak’ih")
, (14, "lanezyi ’o’un dink’ih")
, (15, "lanezyi ’o’un skwunlai")
, (16, "lanezyi ’o’un lhk’uttak’ih")
, (17, "lanezyi ’o’un lhtak’alt’i")
, (18, "lanezyi ’o’un lhk’utdink’ih")
, (19, "lanezyi ’o’un lhuk’i hooloh")
, (20, "nat lanezyi")
, (21, "nat lanezyi ’o’un lhuk’i")
, (22, "nat lanezyi ’o’un nankoh")
, (23, "nat lanezyi ’o’un tak’ih")
, (24, "nat lanezyi ’o’un dink’ih")
, (25, "nat lanezyi ’o’un skwunlai")
, (26, "nat lanezyi ’o’un lhk’uttak’ih")
, (27, "nat lanezyi ’o’un lhtak’alt’i")
, (28, "nat lanezyi ’o’un lhk’utdink’ih")
, (29, "nat lanezyi ’o’un lhuk’i hooloh")
, (30, "tat lanezyi")
, (31, "tat lanezyi ’o’un lhuk’i")
, (32, "tat lanezyi ’o’un nankoh")
, (33, "tat lanezyi ’o’un tak’ih")
, (34, "tat lanezyi ’o’un dink’ih")
, (35, "tat lanezyi ’o’un skwunlai")
, (36, "tat lanezyi ’o’un lhk’uttak’ih")
, (37, "tat lanezyi ’o’un lhtak’alt’i")
, (38, "tat lanezyi ’o’un lhk’utdink’ih")
, (39, "tat lanezyi ’o’un lhuk’i hooloh")
, (40, "dit lanezyi")
, (41, "dit lanezyi ’o’un lhuk’i")
, (42, "dit lanezyi ’o’un nankoh")
, (43, "dit lanezyi ’o’un tak’ih")
, (44, "dit lanezyi ’o’un dink’ih")
, (45, "dit lanezyi ’o’un skwunlai")
, (46, "dit lanezyi ’o’un lhk’uttak’ih")
, (47, "dit lanezyi ’o’un lhtak’alt’i")
, (48, "dit lanezyi ’o’un lhk’utdink’ih")
, (49, "dit lanezyi ’o’un lhuk’i hooloh")
, (50, "skwunlat lanezyi")
, (51, "skwunlat lanezyi ’o’un lhuk’i")
, (52, "skwunlat lanezyi ’o’un nankoh")
, (53, "skwunlat lanezyi ’o’un tak’ih")
, (54, "skwunlat lanezyi ’o’un dink’ih")
, (55, "skwunlat lanezyi ’o’un skwunlai")
, (56, "skwunlat lanezyi ’o’un lhk’uttak’ih")
, (57, "skwunlat lanezyi ’o’un lhtak’alt’i")
, (58, "skwunlat lanezyi ’o’un lhk’utdink’ih")
, (59, "skwunlat lanezyi ’o’un lhuk’i hooloh")
, (60, "lhk’utat lanezyi")
, (61, "lhk’utat lanezyi ’o’un lhuk’i")
, (62, "lhk’utat lanezyi ’o’un nankoh")
, (63, "lhk’utat lanezyi ’o’un tak’ih")
, (64, "lhk’utat lanezyi ’o’un dink’ih")
, (65, "lhk’utat lanezyi ’o’un skwunlai")
, (66, "lhk’utat lanezyi ’o’un lhk’uttak’ih")
, (67, "lhk’utat lanezyi ’o’un lhtak’alt’i")
, (68, "lhk’utat lanezyi ’o’un lhk’utdink’ih")
, (69, "lhk’utat lanezyi ’o’un lhuk’i hooloh")
, (70, "lhtak’alt’it lanezyi")
, (71, "lhtak’alt’it lanezyi ’o’un lhuk’i")
, (72, "lhtak’alt’it lanezyi ’o’un nankoh")
, (73, "lhtak’alt’it lanezyi ’o’un tak’ih")
, (74, "lhtak’alt’it lanezyi ’o’un dink’ih")
, (75, "lhtak’alt’it lanezyi ’o’un skwunlai")
, (76, "lhtak’alt’it lanezyi ’o’un lhk’uttak’ih")
, (77, "lhtak’alt’it lanezyi ’o’un lhtak’alt’i")
, (78, "lhtak’alt’it lanezyi ’o’un lhk’utdink’ih")
, (79, "lhtak’alt’it lanezyi ’o’un lhuk’i hooloh")
, (80, "lhk’udit lanezyi")
, (81, "lhk’udit lanezyi ’o’un lhuk’i")
, (82, "lhk’udit lanezyi ’o’un nankoh")
, (83, "lhk’udit lanezyi ’o’un tak’ih")
, (84, "lhk’udit lanezyi ’o’un dink’ih")
, (85, "lhk’udit lanezyi ’o’un skwunlai")
, (86, "lhk’udit lanezyi ’o’un lhk’uttak’ih")
, (87, "lhk’udit lanezyi ’o’un lhtak’alt’i")
, (88, "lhk’udit lanezyi ’o’un lhk’utdink’ih")
, (89, "lhk’udit lanezyi ’o’un lhuk’i hooloh")
, (90, "lhuk’i hooloh lanezyi")
, (91, "lhuk’i hooloh lanezyi ’o’un lhuk’i")
, (92, "lhuk’i hooloh lanezyi ’o’un nankoh")
, (93, "lhuk’i hooloh lanezyi ’o’un tak’ih")
, (94, "lhuk’i hooloh lanezyi ’o’un dink’ih")
, (95, "lhuk’i hooloh lanezyi ’o’un skwunlai")
, (96, "lhuk’i hooloh lanezyi ’o’un lhk’uttak’ih")
, (97, "lhuk’i hooloh lanezyi ’o’un lhtak’alt’i")
, (98, "lhuk’i hooloh lanezyi ’o’un lhk’utdink’ih")
, (99, "lhuk’i hooloh lanezyi ’o’un lhuk’i hooloh")
, (100, "lhk’ut’lanezyi")
]
)
]
Using Carrier sylllabics
syllabic_cardinals :: (Num i) => TestData i
syllabic_cardinals =
[ ( "default"
, defaultInflection
, [ (1, "ᘰᗿ")
, (2, "ᘇᐣᗶᑋ")
, (3, "ᗡᗿᑋ")
, (4, "ᑔᐣᗿᑋ")
, (5, "ᔆᐠᗒᐣᘧᐉ")
, (6, "ᒡᗽᐪᗡᗿᑋ")
, (7, "ᒡᗡᘀᑊᗦ")
, (8, "ᒡᗽᐪᑔᐣᗿᑋ")
, (9, "ᘰᗿ ᐯᘣᑋ")
, (10, "ᘧᘅᙆᘒ")
, (11, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (12, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (13, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (14, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (15, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (16, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (17, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (18, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (19, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (20, "ᘇᐪ ᘧᘅᙆᘒ")
, (21, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (22, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (23, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (24, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (25, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (26, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (27, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (28, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (29, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (30, "ᗡᐪ ᘧᘅᙆᘒ")
, (31, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (32, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (33, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (34, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (35, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (36, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (37, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (38, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (39, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (40, "ᑔᐪ ᘧᘅᙆᘒ")
, (41, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (42, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (43, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (44, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (45, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (46, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (47, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (48, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (49, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (50, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ")
, (51, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (52, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (53, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (54, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (55, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (56, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (57, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (58, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (59, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (60, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ")
, (61, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (62, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (63, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (64, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (65, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (66, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (67, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (68, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (69, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (70, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ")
, (71, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (72, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (73, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (74, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (75, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (76, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (77, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (78, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (79, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (80, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ")
, (81, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (82, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (83, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (84, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (85, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (86, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (87, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (88, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (89, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (90, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ")
, (91, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (92, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (93, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (94, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (95, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (96, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (97, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (98, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (99, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (100, "ᒡᗽᐪᐧᘧᘅᙆᘒ")
]
)
]
| null |
https://raw.githubusercontent.com/roelvandijk/numerals/b1e4121e0824ac0646a3230bd311818e159ec127/src-test/Text/Numeral/Language/CAF/TestData.hs
|
haskell
|
------------------------------------------------------------------------------
Imports
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Test data
------------------------------------------------------------------------------
Sources:
-to-count-in-carrier/en/caf/
|
|
[ @ISO639 - 1@ ] -
[ @ISO639 - 2@ ] -
[ @ISO639 - 3@ ] caf
[ @Native name@ ] Dakeł ( ᑕᗸᒡ )
[ @English name@ ] Southern Carrier
[@ISO639-1@] -
[@ISO639-2@] -
[@ISO639-3@] caf
[@Native name@] Dakeł (ᑕᗸᒡ)
[@English name@] Southern Carrier
-}
module Text.Numeral.Language.CAF.TestData
( cardinals
, syllabic_cardinals
) where
import "numerals" Text.Numeral.Grammar ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
cardinals :: (Num i) => TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (1, "lhuk’i")
, (2, "nankoh")
, (3, "tak’ih")
, (4, "dink’ih")
, (5, "skwunlai")
, (6, "lhk’uttak’ih")
, (7, "lhtak’alt’i")
, (8, "lhk’utdink’ih")
, (9, "lhuk’i hooloh")
, (10, "lanezyi")
, (11, "lanezyi ’o’un lhuk’i")
, (12, "lanezyi ’o’un nankoh")
, (13, "lanezyi ’o’un tak’ih")
, (14, "lanezyi ’o’un dink’ih")
, (15, "lanezyi ’o’un skwunlai")
, (16, "lanezyi ’o’un lhk’uttak’ih")
, (17, "lanezyi ’o’un lhtak’alt’i")
, (18, "lanezyi ’o’un lhk’utdink’ih")
, (19, "lanezyi ’o’un lhuk’i hooloh")
, (20, "nat lanezyi")
, (21, "nat lanezyi ’o’un lhuk’i")
, (22, "nat lanezyi ’o’un nankoh")
, (23, "nat lanezyi ’o’un tak’ih")
, (24, "nat lanezyi ’o’un dink’ih")
, (25, "nat lanezyi ’o’un skwunlai")
, (26, "nat lanezyi ’o’un lhk’uttak’ih")
, (27, "nat lanezyi ’o’un lhtak’alt’i")
, (28, "nat lanezyi ’o’un lhk’utdink’ih")
, (29, "nat lanezyi ’o’un lhuk’i hooloh")
, (30, "tat lanezyi")
, (31, "tat lanezyi ’o’un lhuk’i")
, (32, "tat lanezyi ’o’un nankoh")
, (33, "tat lanezyi ’o’un tak’ih")
, (34, "tat lanezyi ’o’un dink’ih")
, (35, "tat lanezyi ’o’un skwunlai")
, (36, "tat lanezyi ’o’un lhk’uttak’ih")
, (37, "tat lanezyi ’o’un lhtak’alt’i")
, (38, "tat lanezyi ’o’un lhk’utdink’ih")
, (39, "tat lanezyi ’o’un lhuk’i hooloh")
, (40, "dit lanezyi")
, (41, "dit lanezyi ’o’un lhuk’i")
, (42, "dit lanezyi ’o’un nankoh")
, (43, "dit lanezyi ’o’un tak’ih")
, (44, "dit lanezyi ’o’un dink’ih")
, (45, "dit lanezyi ’o’un skwunlai")
, (46, "dit lanezyi ’o’un lhk’uttak’ih")
, (47, "dit lanezyi ’o’un lhtak’alt’i")
, (48, "dit lanezyi ’o’un lhk’utdink’ih")
, (49, "dit lanezyi ’o’un lhuk’i hooloh")
, (50, "skwunlat lanezyi")
, (51, "skwunlat lanezyi ’o’un lhuk’i")
, (52, "skwunlat lanezyi ’o’un nankoh")
, (53, "skwunlat lanezyi ’o’un tak’ih")
, (54, "skwunlat lanezyi ’o’un dink’ih")
, (55, "skwunlat lanezyi ’o’un skwunlai")
, (56, "skwunlat lanezyi ’o’un lhk’uttak’ih")
, (57, "skwunlat lanezyi ’o’un lhtak’alt’i")
, (58, "skwunlat lanezyi ’o’un lhk’utdink’ih")
, (59, "skwunlat lanezyi ’o’un lhuk’i hooloh")
, (60, "lhk’utat lanezyi")
, (61, "lhk’utat lanezyi ’o’un lhuk’i")
, (62, "lhk’utat lanezyi ’o’un nankoh")
, (63, "lhk’utat lanezyi ’o’un tak’ih")
, (64, "lhk’utat lanezyi ’o’un dink’ih")
, (65, "lhk’utat lanezyi ’o’un skwunlai")
, (66, "lhk’utat lanezyi ’o’un lhk’uttak’ih")
, (67, "lhk’utat lanezyi ’o’un lhtak’alt’i")
, (68, "lhk’utat lanezyi ’o’un lhk’utdink’ih")
, (69, "lhk’utat lanezyi ’o’un lhuk’i hooloh")
, (70, "lhtak’alt’it lanezyi")
, (71, "lhtak’alt’it lanezyi ’o’un lhuk’i")
, (72, "lhtak’alt’it lanezyi ’o’un nankoh")
, (73, "lhtak’alt’it lanezyi ’o’un tak’ih")
, (74, "lhtak’alt’it lanezyi ’o’un dink’ih")
, (75, "lhtak’alt’it lanezyi ’o’un skwunlai")
, (76, "lhtak’alt’it lanezyi ’o’un lhk’uttak’ih")
, (77, "lhtak’alt’it lanezyi ’o’un lhtak’alt’i")
, (78, "lhtak’alt’it lanezyi ’o’un lhk’utdink’ih")
, (79, "lhtak’alt’it lanezyi ’o’un lhuk’i hooloh")
, (80, "lhk’udit lanezyi")
, (81, "lhk’udit lanezyi ’o’un lhuk’i")
, (82, "lhk’udit lanezyi ’o’un nankoh")
, (83, "lhk’udit lanezyi ’o’un tak’ih")
, (84, "lhk’udit lanezyi ’o’un dink’ih")
, (85, "lhk’udit lanezyi ’o’un skwunlai")
, (86, "lhk’udit lanezyi ’o’un lhk’uttak’ih")
, (87, "lhk’udit lanezyi ’o’un lhtak’alt’i")
, (88, "lhk’udit lanezyi ’o’un lhk’utdink’ih")
, (89, "lhk’udit lanezyi ’o’un lhuk’i hooloh")
, (90, "lhuk’i hooloh lanezyi")
, (91, "lhuk’i hooloh lanezyi ’o’un lhuk’i")
, (92, "lhuk’i hooloh lanezyi ’o’un nankoh")
, (93, "lhuk’i hooloh lanezyi ’o’un tak’ih")
, (94, "lhuk’i hooloh lanezyi ’o’un dink’ih")
, (95, "lhuk’i hooloh lanezyi ’o’un skwunlai")
, (96, "lhuk’i hooloh lanezyi ’o’un lhk’uttak’ih")
, (97, "lhuk’i hooloh lanezyi ’o’un lhtak’alt’i")
, (98, "lhuk’i hooloh lanezyi ’o’un lhk’utdink’ih")
, (99, "lhuk’i hooloh lanezyi ’o’un lhuk’i hooloh")
, (100, "lhk’ut’lanezyi")
]
)
]
Using Carrier sylllabics
syllabic_cardinals :: (Num i) => TestData i
syllabic_cardinals =
[ ( "default"
, defaultInflection
, [ (1, "ᘰᗿ")
, (2, "ᘇᐣᗶᑋ")
, (3, "ᗡᗿᑋ")
, (4, "ᑔᐣᗿᑋ")
, (5, "ᔆᐠᗒᐣᘧᐉ")
, (6, "ᒡᗽᐪᗡᗿᑋ")
, (7, "ᒡᗡᘀᑊᗦ")
, (8, "ᒡᗽᐪᑔᐣᗿᑋ")
, (9, "ᘰᗿ ᐯᘣᑋ")
, (10, "ᘧᘅᙆᘒ")
, (11, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (12, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (13, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (14, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (15, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (16, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (17, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (18, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (19, "ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (20, "ᘇᐪ ᘧᘅᙆᘒ")
, (21, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (22, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (23, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (24, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (25, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (26, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (27, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (28, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (29, "ᘇᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (30, "ᗡᐪ ᘧᘅᙆᘒ")
, (31, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (32, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (33, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (34, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (35, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (36, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (37, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (38, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (39, "ᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (40, "ᑔᐪ ᘧᘅᙆᘒ")
, (41, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (42, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (43, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (44, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (45, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (46, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (47, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (48, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (49, "ᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (50, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ")
, (51, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (52, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (53, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (54, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (55, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (56, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (57, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (58, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (59, "ᔆᐠᗒᐣᘧᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (60, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ")
, (61, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (62, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (63, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (64, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (65, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (66, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (67, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (68, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (69, "ᒡᗽᗡᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (70, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ")
, (71, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (72, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (73, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (74, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (75, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (76, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (77, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (78, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (79, "ᒡᗡᘀᑊᗦᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (80, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ")
, (81, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (82, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (83, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (84, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (85, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (86, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (87, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (88, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (89, "ᒡᗽᑔᐪ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (90, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ")
, (91, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ")
, (92, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘇᐣᗶᑋ")
, (93, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᗡᗿᑋ")
, (94, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᑔᐣᗿᑋ")
, (95, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᔆᐠᗒᐣᘧᐉ")
, (96, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᗡᗿᑋ")
, (97, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗡᘀᑊᗦ")
, (98, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᒡᗽᐪᑔᐣᗿᑋ")
, (99, "ᘰᗿ ᐯᘣᑋ ᘧᘅᙆᘒ ᐧᐃᐧᐅᐣ ᘰᗿ ᐯᘣᑋ")
, (100, "ᒡᗽᐪᐧᘧᘅᙆᘒ")
]
)
]
|
02fa2dde32572aff58768ec3310590a91389b2e497cced8c1322f86cbb221199
|
cljfx/cljfx
|
tree_table_column.clj
|
(ns cljfx.fx.tree-table-column
"Part of a public API"
(:require [cljfx.composite :as composite]
[cljfx.lifecycle :as lifecycle]
[cljfx.coerce :as coerce]
[cljfx.fx.table-column-base :as fx.table-column-base]
[cljfx.fx.tree-table-cell :as fx.tree-table-cell]
[cljfx.ext.cell-factory :as ext.cell-factory])
(:import [javafx.scene.control TreeTableColumn TreeTableColumn$SortType
TreeTableColumn$CellDataFeatures]
[javafx.util Callback]))
(set! *warn-on-reflection* true)
(defn- tree-table-cell-value-factory [x]
(cond
(instance? Callback x)
x
(ifn? x)
(reify Callback
(call [_ param]
(let [^TreeTableColumn$CellDataFeatures features param]
(coerce/constant-observable-value (x (.getValue (.getValue features)))))))
:else
(coerce/fail Callback x)))
(defn cell-factory [x]
(cond
(instance? Callback x) x
(fn? x) (reify Callback
(call [_ _]
(fx.tree-table-cell/create x)))
:else (coerce/fail Callback x)))
(def props
(merge
fx.table-column-base/props
(composite/props TreeTableColumn
;; overrides
:style-class [:list lifecycle/scalar :coerce coerce/style-class :default "table-column"]
;; definitions
:cell-factory [:setter (lifecycle/if-desc map?
ext.cell-factory/lifecycle
(lifecycle/detached-prop-map fx.tree-table-cell/props))
:coerce cell-factory
:default TreeTableColumn/DEFAULT_CELL_FACTORY]
:cell-value-factory [:setter lifecycle/scalar
:coerce tree-table-cell-value-factory]
:columns [:list lifecycle/dynamics]
:on-edit-cancel [:setter lifecycle/event-handler :coerce coerce/event-handler]
:on-edit-commit [:setter lifecycle/event-handler :coerce coerce/event-handler] ;; has private default
:on-edit-start [:setter lifecycle/event-handler :coerce coerce/event-handler]
:sort-type [:setter lifecycle/scalar
:coerce (coerce/enum TreeTableColumn$SortType)
:default :ascending])))
(def lifecycle
(lifecycle/annotate
(composite/describe TreeTableColumn
:ctor []
:props props)
:tree-table-column))
| null |
https://raw.githubusercontent.com/cljfx/cljfx/543f7409290051e9444771d2cd86dadeb8cdce33/src/cljfx/fx/tree_table_column.clj
|
clojure
|
overrides
definitions
has private default
|
(ns cljfx.fx.tree-table-column
"Part of a public API"
(:require [cljfx.composite :as composite]
[cljfx.lifecycle :as lifecycle]
[cljfx.coerce :as coerce]
[cljfx.fx.table-column-base :as fx.table-column-base]
[cljfx.fx.tree-table-cell :as fx.tree-table-cell]
[cljfx.ext.cell-factory :as ext.cell-factory])
(:import [javafx.scene.control TreeTableColumn TreeTableColumn$SortType
TreeTableColumn$CellDataFeatures]
[javafx.util Callback]))
(set! *warn-on-reflection* true)
(defn- tree-table-cell-value-factory [x]
(cond
(instance? Callback x)
x
(ifn? x)
(reify Callback
(call [_ param]
(let [^TreeTableColumn$CellDataFeatures features param]
(coerce/constant-observable-value (x (.getValue (.getValue features)))))))
:else
(coerce/fail Callback x)))
(defn cell-factory [x]
(cond
(instance? Callback x) x
(fn? x) (reify Callback
(call [_ _]
(fx.tree-table-cell/create x)))
:else (coerce/fail Callback x)))
(def props
(merge
fx.table-column-base/props
(composite/props TreeTableColumn
:style-class [:list lifecycle/scalar :coerce coerce/style-class :default "table-column"]
:cell-factory [:setter (lifecycle/if-desc map?
ext.cell-factory/lifecycle
(lifecycle/detached-prop-map fx.tree-table-cell/props))
:coerce cell-factory
:default TreeTableColumn/DEFAULT_CELL_FACTORY]
:cell-value-factory [:setter lifecycle/scalar
:coerce tree-table-cell-value-factory]
:columns [:list lifecycle/dynamics]
:on-edit-cancel [:setter lifecycle/event-handler :coerce coerce/event-handler]
:on-edit-start [:setter lifecycle/event-handler :coerce coerce/event-handler]
:sort-type [:setter lifecycle/scalar
:coerce (coerce/enum TreeTableColumn$SortType)
:default :ascending])))
(def lifecycle
(lifecycle/annotate
(composite/describe TreeTableColumn
:ctor []
:props props)
:tree-table-column))
|
f36990ce55eb96f18464340fd789a7ca715dc651b8b2c1f92f6a2e9a9eedc506
|
soegaard/web-tutorial
|
server.rkt
|
#lang racket/base
;;;
;;; Server
;;;
; This file configures a web-server.
; Starts the web-server.
Opens the start page in a browser .
(require web-server/dispatch web-server/servlet-env
"control.rkt")
(define-values (listit-dispatch listit-url)
(dispatch-rules
[("") dispatch-on-action]
[else dispatch-on-action]))
(define (start)
(serve/servlet listit-dispatch
#:servlet-regexp #rx""))
(start)
; Note: If you want to use the repl and have the web-server running in the
; background, you can start the server in a new thread:
; (thread (λ () (start)))
| null |
https://raw.githubusercontent.com/soegaard/web-tutorial/511a03410a440ed32475484ae93483f4ddd6656c/listit2/server.rkt
|
racket
|
Server
This file configures a web-server.
Starts the web-server.
Note: If you want to use the repl and have the web-server running in the
background, you can start the server in a new thread:
(thread (λ () (start)))
|
#lang racket/base
Opens the start page in a browser .
(require web-server/dispatch web-server/servlet-env
"control.rkt")
(define-values (listit-dispatch listit-url)
(dispatch-rules
[("") dispatch-on-action]
[else dispatch-on-action]))
(define (start)
(serve/servlet listit-dispatch
#:servlet-regexp #rx""))
(start)
|
334c366f925b8e57312110530873887ba25ba12399a30d7ff52b6df5bd050933
|
soegaard/metapict
|
root-spiral.rkt
|
#lang racket
(require metapict)
;;; EXAMPLE
;;; Inspiration:
;;; -helix/
(def max-r 86)
(def dark-green (make-color* 175 193 36))
(def almost-black (make-color* 50 50 50))
(define (shade r) ; white -> dark-green -> almost-black
(cond
[(<= 0 r 1/2) (color-med (* 2 r) "white" dark-green )]
[(<= r 1) (color-med (* 2 (- r 1/2)) dark-green almost-black )]
[else (error 'shader (~a "got: " r))]))
(define (spiral drawing max-r)
(def (node p r)
(def circ (circle p 1.5))
(def filled (color "white" (fill circ)))
(def label (label-cnt (~a r) p))
(draw filled circ label))
(defv (spiral θ)
(for/fold ([drawing drawing] [θ 0])
([r (in-range 1 max-r)])
(def √r (sqrt r))
(def (rotθ c) (scaled 4 (rotated θ c)))
(defv (A B C) (values (pt 0 0) (rotθ (pt √r 0)) (rotθ (pt √r 1))))
(def triangle (curve A -- B -- C -- cycle))
(def filled (color (shade (/ r 86)) (fill triangle)))
(values (draw drawing filled triangle (node B r))
(+ θ (acos (sqrt (/ r (+ 1 r))))))))
(draw spiral
(node (scaled 4 (pt@ (sqrt max-r) θ)) max-r)))
(set-curve-pict-size 600 600)
(with-window (window -40 40 -40 40)
(penwidth 0
(for/fold ([drawing (draw)]) ([r '(86 38 15)])
(spiral drawing r))))
| null |
https://raw.githubusercontent.com/soegaard/metapict/47ae265f73cbb92ff3e7bdd61e49f4af17597fdf/metapict/examples/root-spiral.rkt
|
racket
|
EXAMPLE
Inspiration:
-helix/
white -> dark-green -> almost-black
|
#lang racket
(require metapict)
(def max-r 86)
(def dark-green (make-color* 175 193 36))
(def almost-black (make-color* 50 50 50))
(cond
[(<= 0 r 1/2) (color-med (* 2 r) "white" dark-green )]
[(<= r 1) (color-med (* 2 (- r 1/2)) dark-green almost-black )]
[else (error 'shader (~a "got: " r))]))
(define (spiral drawing max-r)
(def (node p r)
(def circ (circle p 1.5))
(def filled (color "white" (fill circ)))
(def label (label-cnt (~a r) p))
(draw filled circ label))
(defv (spiral θ)
(for/fold ([drawing drawing] [θ 0])
([r (in-range 1 max-r)])
(def √r (sqrt r))
(def (rotθ c) (scaled 4 (rotated θ c)))
(defv (A B C) (values (pt 0 0) (rotθ (pt √r 0)) (rotθ (pt √r 1))))
(def triangle (curve A -- B -- C -- cycle))
(def filled (color (shade (/ r 86)) (fill triangle)))
(values (draw drawing filled triangle (node B r))
(+ θ (acos (sqrt (/ r (+ 1 r))))))))
(draw spiral
(node (scaled 4 (pt@ (sqrt max-r) θ)) max-r)))
(set-curve-pict-size 600 600)
(with-window (window -40 40 -40 40)
(penwidth 0
(for/fold ([drawing (draw)]) ([r '(86 38 15)])
(spiral drawing r))))
|
ea8e31600d56181da0ee1ccf86f41e37ef49dc19371a8a6985584bb5419fc406
|
dradtke/Lisp-Text-Editor
|
glib.gerror.lisp
|
(in-package :glib)
(defcstruct g-error
(:domain g-quark)
(:code :int)
(:message (:string :free-from-foreign nil)))
(defcfun g-error-new-literal :pointer
(domain g-quark)
(code :int)
(message :string))
(defcfun g-error-free :void
(error :pointer))
(defcfun g-error-copy :pointer
(error :pointer))
(defcfun g-error-matches :boolean
(error :pointer)
(domain g-quark)
(code :int))
(defcfun g-set-error-literal :void
(err-ptr :pointer)
(domain g-quark)
(code :int)
(message :string))
(defcfun g-propagate-error :void
(dest-ptr :pointer)
(src-ptr :pointer))
(defcfun g-clear-error :void
(err-ptr :pointer))
(define-condition g-error-condition (error)
((domain :initarg :domain :initform nil :reader g-error-condition-domain)
(code :initarg :code :initform nil :reader g-error-condition-code)
(message :initarg :message :initform nil :reader g-error-condition-message))
(:report (lambda (e stream)
(format stream "GError was raised. Domain: ~S, code: ~S, message: ~A"
(g-error-condition-domain e)
(g-error-condition-code e)
(g-error-condition-message e)))))
(defun mayber-raise-g-error-condition (err)
(unless (null-pointer-p err)
(error 'g-error-condition
:domain (foreign-slot-value err 'g-error :domain)
:code (foreign-slot-value err 'g-error :code)
:message (foreign-slot-value err 'g-error :message))))
(defmacro with-g-error ((err) &body body)
`(with-foreign-object (,err :pointer)
(setf (mem-ref ,err :pointer) (null-pointer))
(unwind-protect
(progn ,@body)
(mayber-raise-g-error-condition (mem-ref ,err :pointer))
(g-clear-error ,err))))
(defmacro with-catching-to-g-error ((err) &body body)
`(handler-case
(progn ,@body)
(g-error-condition (e)
(g-set-error-literal ,err
(g-error-condition-domain e)
(g-error-condition-code e)
(g-error-condition-message e)))))
void g_prefix_error ( GError * * err ,
;; const gchar *format,
;; ...);
void g_propagate_prefixed_error ( GError * * dest ,
;; GError *src,
;; const gchar *format,
;; ...);
| null |
https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/cl-gtk2/glib/glib.gerror.lisp
|
lisp
|
const gchar *format,
...);
GError *src,
const gchar *format,
...);
|
(in-package :glib)
(defcstruct g-error
(:domain g-quark)
(:code :int)
(:message (:string :free-from-foreign nil)))
(defcfun g-error-new-literal :pointer
(domain g-quark)
(code :int)
(message :string))
(defcfun g-error-free :void
(error :pointer))
(defcfun g-error-copy :pointer
(error :pointer))
(defcfun g-error-matches :boolean
(error :pointer)
(domain g-quark)
(code :int))
(defcfun g-set-error-literal :void
(err-ptr :pointer)
(domain g-quark)
(code :int)
(message :string))
(defcfun g-propagate-error :void
(dest-ptr :pointer)
(src-ptr :pointer))
(defcfun g-clear-error :void
(err-ptr :pointer))
(define-condition g-error-condition (error)
((domain :initarg :domain :initform nil :reader g-error-condition-domain)
(code :initarg :code :initform nil :reader g-error-condition-code)
(message :initarg :message :initform nil :reader g-error-condition-message))
(:report (lambda (e stream)
(format stream "GError was raised. Domain: ~S, code: ~S, message: ~A"
(g-error-condition-domain e)
(g-error-condition-code e)
(g-error-condition-message e)))))
(defun mayber-raise-g-error-condition (err)
(unless (null-pointer-p err)
(error 'g-error-condition
:domain (foreign-slot-value err 'g-error :domain)
:code (foreign-slot-value err 'g-error :code)
:message (foreign-slot-value err 'g-error :message))))
(defmacro with-g-error ((err) &body body)
`(with-foreign-object (,err :pointer)
(setf (mem-ref ,err :pointer) (null-pointer))
(unwind-protect
(progn ,@body)
(mayber-raise-g-error-condition (mem-ref ,err :pointer))
(g-clear-error ,err))))
(defmacro with-catching-to-g-error ((err) &body body)
`(handler-case
(progn ,@body)
(g-error-condition (e)
(g-set-error-literal ,err
(g-error-condition-domain e)
(g-error-condition-code e)
(g-error-condition-message e)))))
void g_prefix_error ( GError * * err ,
void g_propagate_prefixed_error ( GError * * dest ,
|
39fdb42de8570024499e5960f563ae7af1b3836952ca0971d3df88f3e5e47c4b
|
rayiner/amd64-asm
|
mach-o-binaries.lisp
|
macho-binaries.lisp
; Support for generating mach-o object files
(in-package "AMD64-ASM")
(defconstant +mh-magic-64+ #xFEEDFACF)
(defconstant +cpu-type-x86-64+ #x01000007)
(defconstant +cpu-subtype-all+ 3)
(defconstant +mh-object+ 1)
(defconstant +mh-def-flags+ #x0)
(defconstant +lc-segment-64+ #x19)
(defconstant +mh-def-prot+ #x7)
(defconstant +mh-def-text-flags+ #x80000000)
(defconstant +mh-def-data-flags+ #x0)
(defconstant +lc-symtab+ #x2)
(defconstant +n-ext+ #x1)
(defconstant +n-undef+ #x0)
(defconstant +n-abs+ #x2)
(defconstant +n-sect+ #xe)
(defconstant +no-sect+ 0)
(defconstant +cs-num+ 1)
(defconstant +ds-num+ 2)
(defconstant +x86-64-reloc-unsigned+ 0)
(defconstant +x86-64-reloc-signed+ 1)
(defconstant +x86-64-reloc-branch+ 2)
(defconstant +r-pcrel-shift+ 24)
(defconstant +r-length-shift+ 25)
(defconstant +r-extern-shift+ 27)
(defconstant +r-type-shift+ 28)
(define-c-struct mach-header-64
(magic :half)
(cputype :half)
(cpusubtype :half)
(filetype :half)
(ncmds :half)
(sizeofcmds :half)
(flags :half)
(reserved :half))
(define-c-struct segment-command-64
(cmd :half)
(cmdsize :half)
(segname :byte 16)
(vmaddr :word)
(vmsize :word)
(fileoff :word)
(filesize :word)
(maxprot :half)
(initprot :half)
(nsects :half)
(flags :half))
(define-c-struct section-64
(sectname :byte 16)
(segname :byte 16)
(addr :word)
(size :word)
(offset :half)
(align :half)
(reloff :half)
(nreloc :half)
(flags :half)
(reserved1 :half)
(reserved2 :half)
(reserved3 :half))
(define-c-struct symtab-command
(cmd :half)
(cmdsize :half)
(symoff :half)
(nsyms :half)
(stroff :half)
(strsize :half))
(define-c-struct nlist-64
(nstrx :half)
(ntype :byte)
(nsect :byte)
(ndesc :byte 2)
(nvalue :word))
(define-c-struct relocation-info
(r-address :half)
(r-symbolnum-and-flags :half))
(defstruct mach-o-symtab
strtab
ntab
nvec)
(defun new-mach-o-symtab ()
(make-mach-o-symtab :strtab (new-strtab)
:ntab (make-hash-table)
:nvec (make-array 0 :fill-pointer t)))
(defun add-mach-o-sym (st name sc sect addr)
(assert (not (gethash name (mach-o-symtab-ntab st))))
(let* ((nl (make-nlist-64 :nstrx (strtab-intern (mach-o-symtab-strtab st)
name)
:ntype (ecase sc
(:int +n-sect+)
(:ext (+ +n-sect+ +n-ext+))
(:und (+ +n-undef+ +n-ext+)))
:nsect sect
:ndesc #(0 0)
:nvalue addr)))
(setf (gethash name (mach-o-symtab-ntab st))
(length (mach-o-symtab-nvec st)))
(vector-push-extend nl (mach-o-symtab-nvec st))))
(defun mach-o-symtab-member? (st name)
(gethash name (mach-o-symtab-ntab st)))
(defun mach-o-symtab-strsize (st)
(strtab-size (mach-o-symtab-strtab st)))
(defun mach-o-symtab-count (st)
(length (mach-o-symtab-nvec st)))
(defun mach-o-sym-index (st sym)
(gethash sym (mach-o-symtab-ntab st)))
(defun generate-mach-o-symtab (obj)
(let ((tab (new-mach-o-symtab))
(fp 0))
(iter (for def in-vector (asmobj-cdefs obj))
(add-mach-o-sym tab
(asmdef-name def)
(asmdef-scope def)
+cs-num+
fp)
(incf fp (length (asmbin-buffer (asmdef-bin def)))))
(iter (for def in-vector (asmobj-ddefs obj))
(add-mach-o-sym tab
(asmdef-name def)
(asmdef-scope def)
+ds-num+
fp)
(incf fp (length (asmbin-buffer (asmdef-bin def)))))
(iter (for def in-vector (asmobj-cdefs obj))
(iter (for rel in-vector (asmbin-relocs (asmdef-bin def)))
(unless (mach-o-symtab-member? tab (asmrel-symbol rel))
(add-mach-o-sym tab
(asmrel-symbol rel)
:und
+no-sect+
0))))
(iter (for def in-vector (asmobj-ddefs obj))
(iter (for rel in-vector (asmbin-relocs (asmdef-bin def)))
(unless (mach-o-symtab-member? tab (asmrel-symbol rel))
(add-mach-o-sym tab
(asmrel-symbol rel)
:und
+no-sect+
0))))
tab))
(defun compose-mach-o-rel-num-and-flags (snum pcrel length ext type)
(assert (and (<= pcrel 1) (<= length 3) (<= ext 1) (<= type 15)))
(+ snum
(ash pcrel +r-pcrel-shift+)
(ash length +r-length-shift+)
(ash ext +r-extern-shift+)
(ash type +r-type-shift+)))
(defun add-mach-o-rel (rel fp st relvec)
(let* ((addr (+ fp (asmrel-offset rel)))
(sn (mach-o-sym-index st (asmrel-symbol rel)))
(pcrel (ecase (asmrel-type rel)
(:abs 0)
(:rel 1)
(:bra 1)))
(len (floor (log (asmrel-width rel) 2)))
(ext 1)
(type (ecase (asmrel-type rel)
(:abs +x86-64-reloc-unsigned+)
(:rel +x86-64-reloc-signed+)
(:bra +x86-64-reloc-branch+)))
(snf (compose-mach-o-rel-num-and-flags sn pcrel len ext type)))
(vector-push-extend (make-relocation-info :r-address addr
:r-symbolnum-and-flags snf)
relvec)))
(defun add-mach-o-rels-for-defs (defs st relvec)
(let ((fp 0))
(iter (for def in-vector defs)
(iter (for rel in-vector (asmbin-relocs (asmdef-bin def)))
(add-mach-o-rel rel fp st relvec))
(incf fp (length (asmbin-buffer (asmdef-bin def)))))))
(defun generate-mach-o-relvec (obj st)
(let ((relvec (make-array 0 :fill-pointer t)))
(add-mach-o-rels-for-defs (asmobj-cdefs obj) st relvec)
(add-mach-o-rels-for-defs (asmobj-ddefs obj) st relvec)
relvec))
(defstruct mach-o-metrics
header-off
lc-off
cs-off
ds-off
crel-off
drel-off
symtab-off
strtab-off
strtab-sz
crel-count
drel-count
sym-count)
(defun code-section-size (obj)
(iter (for def in-vector (asmobj-cdefs obj))
(sum (length (asmbin-buffer (asmdef-bin def))))))
(defun data-section-size (obj)
(iter (for def in-vector (asmobj-ddefs obj))
(sum (length (asmbin-buffer (asmdef-bin def))))))
(defun count-code-relocations (obj)
(iter (for def in-vector (asmobj-cdefs obj))
(sum (length (asmbin-relocs (asmdef-bin def))))))
(defun count-data-relocations (obj)
(iter (for def in-vector (asmobj-ddefs obj))
(sum (length (asmbin-relocs (asmdef-bin def))))))
; mach-o file map
mach header ( 32 bytes )
segment command ( 72 bytes )
code section descriptor ( 80 bytes )
data section descriptor ( 80 bytes )
symtab command ( 24 bytes )
; code section data
; data section data
; relocation entries
; symbol table entries
; string table
(defun compute-mach-o-metrics (obj st)
(let* ((mh-size (sizeof-c-struct (make-mach-header-64)))
(sc-size (sizeof-c-struct (make-segment-command-64)))
(sectc-size (sizeof-c-struct (make-section-64)))
(symc-size (sizeof-c-struct (make-symtab-command)))
(nlist-size (sizeof-c-struct (make-nlist-64)))
(rel-size (sizeof-c-struct (make-relocation-info)))
(cs-size (code-section-size obj))
(ds-size (data-section-size obj))
(crel-count (count-code-relocations obj))
(drel-count (count-data-relocations obj))
(crel-size (* rel-size crel-count))
(drel-size (* rel-size drel-count))
(sym-count (mach-o-symtab-count st))
(symt-size (* nlist-size sym-count))
(header-off 0)
(lc-off mh-size)
(lc-size (+ sc-size (* 2 sectc-size) symc-size))
(cs-off (+ lc-off lc-size))
(ds-off (+ cs-off cs-size))
(crel-off (+ ds-off ds-size))
(drel-off (+ crel-off crel-size))
(symtab-off (+ drel-off drel-size))
(strtab-off (+ symtab-off symt-size))
(strtab-sz (mach-o-symtab-strsize st)))
(make-mach-o-metrics :header-off header-off
:lc-off lc-off
:cs-off cs-off
:ds-off ds-off
:crel-off crel-off
:drel-off drel-off
:symtab-off symtab-off
:strtab-off strtab-off
:strtab-sz strtab-sz
:crel-count crel-count
:drel-count drel-count
:sym-count sym-count)))
(defun emit-mach-o-header (met frag)
(let* ((cmdsize (- (mach-o-metrics-cs-off met) (mach-o-metrics-lc-off met)))
(mh (make-mach-header-64 :magic +mh-magic-64+
:cputype +cpu-type-x86-64+
:cpusubtype +cpu-subtype-all+
:filetype +mh-object+
:ncmds 2
:sizeofcmds cmdsize
:flags +mh-def-flags+
:reserved 0)))
(emit-c-struct mh frag)))
(defun emit-mach-o-seg-lc (met frag)
(let* ((sc-size (sizeof-c-struct (make-segment-command-64)))
(sct-size (sizeof-c-struct (make-section-64)))
(lc-size (+ sc-size (* 2 sct-size)))
(seg-size (- (mach-o-metrics-crel-off met)
(mach-o-metrics-cs-off met)))
(cs-size (- (mach-o-metrics-ds-off met) (mach-o-metrics-cs-off met)))
(ds-size (- (mach-o-metrics-crel-off met) (mach-o-metrics-ds-off met)))
(cs-addr 0)
(ds-addr cs-size)
(crel-count (mach-o-metrics-crel-count met))
(drel-count (mach-o-metrics-drel-count met))
(crel-off (if (> crel-count 0) (mach-o-metrics-crel-off met) 0))
(drel-off (if (> drel-count 0) (mach-o-metrics-drel-off met) 0))
(seg-lc (make-segment-command-64 :cmd +lc-segment-64+
:cmdsize lc-size
:segname ""
:vmaddr 0
:vmsize seg-size
:fileoff (mach-o-metrics-cs-off met)
:filesize seg-size
:maxprot +mh-def-prot+
:initprot +mh-def-prot+
:nsects 2
:flags 0))
(cs-lc (make-section-64 :sectname (asciify-string "__text")
:segname (asciify-string "__TEXT")
:addr cs-addr
:size cs-size
:offset (mach-o-metrics-cs-off met)
:align 0
:reloff crel-off
:nreloc crel-count
:flags +mh-def-text-flags+
:reserved1 0
:reserved2 0
:reserved3 0))
(ds-lc (make-section-64 :sectname (asciify-string "__data")
:segname (asciify-string "__DATA")
:addr ds-addr
:size ds-size
:offset (mach-o-metrics-ds-off met)
:align 0
:reloff drel-off
:nreloc drel-count
:flags +mh-def-data-flags+
:reserved1 0
:reserved2 0
:reserved3 0)))
(emit-c-struct seg-lc frag)
(emit-c-struct cs-lc frag)
(emit-c-struct ds-lc frag)))
(defun emit-mach-o-symtab-lc (met frag)
(let* ((symc-size (sizeof-c-struct (make-symtab-command)))
(symt-lc
(make-symtab-command :cmd +lc-symtab+
:cmdsize symc-size
:symoff (mach-o-metrics-symtab-off met)
:nsyms (mach-o-metrics-sym-count met)
:stroff (mach-o-metrics-strtab-off met)
:strsize (mach-o-metrics-strtab-sz met))))
(emit-c-struct symt-lc frag)))
(defun emit-mach-o-def-vec (defs frag)
(iter (for def in-vector defs)
(emit-byte-vector frag (asmbin-buffer (asmdef-bin def)))))
(defun emit-mach-o-sects (obj frag)
(emit-mach-o-def-vec (asmobj-cdefs obj) frag)
(emit-mach-o-def-vec (asmobj-ddefs obj) frag))
(defun emit-mach-o-symtab (tab frag)
(iter (for nl in-vector (mach-o-symtab-nvec tab))
(emit-c-struct nl frag))
(emit-byte-vector frag (strtab-vec (mach-o-symtab-strtab tab))))
(defun emit-mach-o-relocs (rv frag)
(iter (for rel in-vector rv)
(emit-c-struct rel frag)))
(defun generate-mach-o-obj (obj)
(let* ((frag (new-asmfrag))
(st (generate-mach-o-symtab obj))
(rv (generate-mach-o-relvec obj st))
(met (compute-mach-o-metrics obj st)))
(emit-mach-o-header met frag)
(emit-mach-o-seg-lc met frag)
(emit-mach-o-symtab-lc met frag)
(emit-mach-o-sects obj frag)
(emit-mach-o-relocs rv frag)
(emit-mach-o-symtab st frag)
(asmfrag-buffer frag)))
| null |
https://raw.githubusercontent.com/rayiner/amd64-asm/27ac3e683557d691cd68472c94d110f32334f61a/mach-o-binaries.lisp
|
lisp
|
Support for generating mach-o object files
mach-o file map
code section data
data section data
relocation entries
symbol table entries
string table
|
macho-binaries.lisp
(in-package "AMD64-ASM")
(defconstant +mh-magic-64+ #xFEEDFACF)
(defconstant +cpu-type-x86-64+ #x01000007)
(defconstant +cpu-subtype-all+ 3)
(defconstant +mh-object+ 1)
(defconstant +mh-def-flags+ #x0)
(defconstant +lc-segment-64+ #x19)
(defconstant +mh-def-prot+ #x7)
(defconstant +mh-def-text-flags+ #x80000000)
(defconstant +mh-def-data-flags+ #x0)
(defconstant +lc-symtab+ #x2)
(defconstant +n-ext+ #x1)
(defconstant +n-undef+ #x0)
(defconstant +n-abs+ #x2)
(defconstant +n-sect+ #xe)
(defconstant +no-sect+ 0)
(defconstant +cs-num+ 1)
(defconstant +ds-num+ 2)
(defconstant +x86-64-reloc-unsigned+ 0)
(defconstant +x86-64-reloc-signed+ 1)
(defconstant +x86-64-reloc-branch+ 2)
(defconstant +r-pcrel-shift+ 24)
(defconstant +r-length-shift+ 25)
(defconstant +r-extern-shift+ 27)
(defconstant +r-type-shift+ 28)
(define-c-struct mach-header-64
(magic :half)
(cputype :half)
(cpusubtype :half)
(filetype :half)
(ncmds :half)
(sizeofcmds :half)
(flags :half)
(reserved :half))
(define-c-struct segment-command-64
(cmd :half)
(cmdsize :half)
(segname :byte 16)
(vmaddr :word)
(vmsize :word)
(fileoff :word)
(filesize :word)
(maxprot :half)
(initprot :half)
(nsects :half)
(flags :half))
(define-c-struct section-64
(sectname :byte 16)
(segname :byte 16)
(addr :word)
(size :word)
(offset :half)
(align :half)
(reloff :half)
(nreloc :half)
(flags :half)
(reserved1 :half)
(reserved2 :half)
(reserved3 :half))
(define-c-struct symtab-command
(cmd :half)
(cmdsize :half)
(symoff :half)
(nsyms :half)
(stroff :half)
(strsize :half))
(define-c-struct nlist-64
(nstrx :half)
(ntype :byte)
(nsect :byte)
(ndesc :byte 2)
(nvalue :word))
(define-c-struct relocation-info
(r-address :half)
(r-symbolnum-and-flags :half))
(defstruct mach-o-symtab
strtab
ntab
nvec)
(defun new-mach-o-symtab ()
(make-mach-o-symtab :strtab (new-strtab)
:ntab (make-hash-table)
:nvec (make-array 0 :fill-pointer t)))
(defun add-mach-o-sym (st name sc sect addr)
(assert (not (gethash name (mach-o-symtab-ntab st))))
(let* ((nl (make-nlist-64 :nstrx (strtab-intern (mach-o-symtab-strtab st)
name)
:ntype (ecase sc
(:int +n-sect+)
(:ext (+ +n-sect+ +n-ext+))
(:und (+ +n-undef+ +n-ext+)))
:nsect sect
:ndesc #(0 0)
:nvalue addr)))
(setf (gethash name (mach-o-symtab-ntab st))
(length (mach-o-symtab-nvec st)))
(vector-push-extend nl (mach-o-symtab-nvec st))))
(defun mach-o-symtab-member? (st name)
(gethash name (mach-o-symtab-ntab st)))
(defun mach-o-symtab-strsize (st)
(strtab-size (mach-o-symtab-strtab st)))
(defun mach-o-symtab-count (st)
(length (mach-o-symtab-nvec st)))
(defun mach-o-sym-index (st sym)
(gethash sym (mach-o-symtab-ntab st)))
(defun generate-mach-o-symtab (obj)
(let ((tab (new-mach-o-symtab))
(fp 0))
(iter (for def in-vector (asmobj-cdefs obj))
(add-mach-o-sym tab
(asmdef-name def)
(asmdef-scope def)
+cs-num+
fp)
(incf fp (length (asmbin-buffer (asmdef-bin def)))))
(iter (for def in-vector (asmobj-ddefs obj))
(add-mach-o-sym tab
(asmdef-name def)
(asmdef-scope def)
+ds-num+
fp)
(incf fp (length (asmbin-buffer (asmdef-bin def)))))
(iter (for def in-vector (asmobj-cdefs obj))
(iter (for rel in-vector (asmbin-relocs (asmdef-bin def)))
(unless (mach-o-symtab-member? tab (asmrel-symbol rel))
(add-mach-o-sym tab
(asmrel-symbol rel)
:und
+no-sect+
0))))
(iter (for def in-vector (asmobj-ddefs obj))
(iter (for rel in-vector (asmbin-relocs (asmdef-bin def)))
(unless (mach-o-symtab-member? tab (asmrel-symbol rel))
(add-mach-o-sym tab
(asmrel-symbol rel)
:und
+no-sect+
0))))
tab))
(defun compose-mach-o-rel-num-and-flags (snum pcrel length ext type)
(assert (and (<= pcrel 1) (<= length 3) (<= ext 1) (<= type 15)))
(+ snum
(ash pcrel +r-pcrel-shift+)
(ash length +r-length-shift+)
(ash ext +r-extern-shift+)
(ash type +r-type-shift+)))
(defun add-mach-o-rel (rel fp st relvec)
(let* ((addr (+ fp (asmrel-offset rel)))
(sn (mach-o-sym-index st (asmrel-symbol rel)))
(pcrel (ecase (asmrel-type rel)
(:abs 0)
(:rel 1)
(:bra 1)))
(len (floor (log (asmrel-width rel) 2)))
(ext 1)
(type (ecase (asmrel-type rel)
(:abs +x86-64-reloc-unsigned+)
(:rel +x86-64-reloc-signed+)
(:bra +x86-64-reloc-branch+)))
(snf (compose-mach-o-rel-num-and-flags sn pcrel len ext type)))
(vector-push-extend (make-relocation-info :r-address addr
:r-symbolnum-and-flags snf)
relvec)))
(defun add-mach-o-rels-for-defs (defs st relvec)
(let ((fp 0))
(iter (for def in-vector defs)
(iter (for rel in-vector (asmbin-relocs (asmdef-bin def)))
(add-mach-o-rel rel fp st relvec))
(incf fp (length (asmbin-buffer (asmdef-bin def)))))))
(defun generate-mach-o-relvec (obj st)
(let ((relvec (make-array 0 :fill-pointer t)))
(add-mach-o-rels-for-defs (asmobj-cdefs obj) st relvec)
(add-mach-o-rels-for-defs (asmobj-ddefs obj) st relvec)
relvec))
(defstruct mach-o-metrics
header-off
lc-off
cs-off
ds-off
crel-off
drel-off
symtab-off
strtab-off
strtab-sz
crel-count
drel-count
sym-count)
(defun code-section-size (obj)
(iter (for def in-vector (asmobj-cdefs obj))
(sum (length (asmbin-buffer (asmdef-bin def))))))
(defun data-section-size (obj)
(iter (for def in-vector (asmobj-ddefs obj))
(sum (length (asmbin-buffer (asmdef-bin def))))))
(defun count-code-relocations (obj)
(iter (for def in-vector (asmobj-cdefs obj))
(sum (length (asmbin-relocs (asmdef-bin def))))))
(defun count-data-relocations (obj)
(iter (for def in-vector (asmobj-ddefs obj))
(sum (length (asmbin-relocs (asmdef-bin def))))))
mach header ( 32 bytes )
segment command ( 72 bytes )
code section descriptor ( 80 bytes )
data section descriptor ( 80 bytes )
symtab command ( 24 bytes )
(defun compute-mach-o-metrics (obj st)
(let* ((mh-size (sizeof-c-struct (make-mach-header-64)))
(sc-size (sizeof-c-struct (make-segment-command-64)))
(sectc-size (sizeof-c-struct (make-section-64)))
(symc-size (sizeof-c-struct (make-symtab-command)))
(nlist-size (sizeof-c-struct (make-nlist-64)))
(rel-size (sizeof-c-struct (make-relocation-info)))
(cs-size (code-section-size obj))
(ds-size (data-section-size obj))
(crel-count (count-code-relocations obj))
(drel-count (count-data-relocations obj))
(crel-size (* rel-size crel-count))
(drel-size (* rel-size drel-count))
(sym-count (mach-o-symtab-count st))
(symt-size (* nlist-size sym-count))
(header-off 0)
(lc-off mh-size)
(lc-size (+ sc-size (* 2 sectc-size) symc-size))
(cs-off (+ lc-off lc-size))
(ds-off (+ cs-off cs-size))
(crel-off (+ ds-off ds-size))
(drel-off (+ crel-off crel-size))
(symtab-off (+ drel-off drel-size))
(strtab-off (+ symtab-off symt-size))
(strtab-sz (mach-o-symtab-strsize st)))
(make-mach-o-metrics :header-off header-off
:lc-off lc-off
:cs-off cs-off
:ds-off ds-off
:crel-off crel-off
:drel-off drel-off
:symtab-off symtab-off
:strtab-off strtab-off
:strtab-sz strtab-sz
:crel-count crel-count
:drel-count drel-count
:sym-count sym-count)))
(defun emit-mach-o-header (met frag)
(let* ((cmdsize (- (mach-o-metrics-cs-off met) (mach-o-metrics-lc-off met)))
(mh (make-mach-header-64 :magic +mh-magic-64+
:cputype +cpu-type-x86-64+
:cpusubtype +cpu-subtype-all+
:filetype +mh-object+
:ncmds 2
:sizeofcmds cmdsize
:flags +mh-def-flags+
:reserved 0)))
(emit-c-struct mh frag)))
(defun emit-mach-o-seg-lc (met frag)
(let* ((sc-size (sizeof-c-struct (make-segment-command-64)))
(sct-size (sizeof-c-struct (make-section-64)))
(lc-size (+ sc-size (* 2 sct-size)))
(seg-size (- (mach-o-metrics-crel-off met)
(mach-o-metrics-cs-off met)))
(cs-size (- (mach-o-metrics-ds-off met) (mach-o-metrics-cs-off met)))
(ds-size (- (mach-o-metrics-crel-off met) (mach-o-metrics-ds-off met)))
(cs-addr 0)
(ds-addr cs-size)
(crel-count (mach-o-metrics-crel-count met))
(drel-count (mach-o-metrics-drel-count met))
(crel-off (if (> crel-count 0) (mach-o-metrics-crel-off met) 0))
(drel-off (if (> drel-count 0) (mach-o-metrics-drel-off met) 0))
(seg-lc (make-segment-command-64 :cmd +lc-segment-64+
:cmdsize lc-size
:segname ""
:vmaddr 0
:vmsize seg-size
:fileoff (mach-o-metrics-cs-off met)
:filesize seg-size
:maxprot +mh-def-prot+
:initprot +mh-def-prot+
:nsects 2
:flags 0))
(cs-lc (make-section-64 :sectname (asciify-string "__text")
:segname (asciify-string "__TEXT")
:addr cs-addr
:size cs-size
:offset (mach-o-metrics-cs-off met)
:align 0
:reloff crel-off
:nreloc crel-count
:flags +mh-def-text-flags+
:reserved1 0
:reserved2 0
:reserved3 0))
(ds-lc (make-section-64 :sectname (asciify-string "__data")
:segname (asciify-string "__DATA")
:addr ds-addr
:size ds-size
:offset (mach-o-metrics-ds-off met)
:align 0
:reloff drel-off
:nreloc drel-count
:flags +mh-def-data-flags+
:reserved1 0
:reserved2 0
:reserved3 0)))
(emit-c-struct seg-lc frag)
(emit-c-struct cs-lc frag)
(emit-c-struct ds-lc frag)))
(defun emit-mach-o-symtab-lc (met frag)
(let* ((symc-size (sizeof-c-struct (make-symtab-command)))
(symt-lc
(make-symtab-command :cmd +lc-symtab+
:cmdsize symc-size
:symoff (mach-o-metrics-symtab-off met)
:nsyms (mach-o-metrics-sym-count met)
:stroff (mach-o-metrics-strtab-off met)
:strsize (mach-o-metrics-strtab-sz met))))
(emit-c-struct symt-lc frag)))
(defun emit-mach-o-def-vec (defs frag)
(iter (for def in-vector defs)
(emit-byte-vector frag (asmbin-buffer (asmdef-bin def)))))
(defun emit-mach-o-sects (obj frag)
(emit-mach-o-def-vec (asmobj-cdefs obj) frag)
(emit-mach-o-def-vec (asmobj-ddefs obj) frag))
(defun emit-mach-o-symtab (tab frag)
(iter (for nl in-vector (mach-o-symtab-nvec tab))
(emit-c-struct nl frag))
(emit-byte-vector frag (strtab-vec (mach-o-symtab-strtab tab))))
(defun emit-mach-o-relocs (rv frag)
(iter (for rel in-vector rv)
(emit-c-struct rel frag)))
(defun generate-mach-o-obj (obj)
(let* ((frag (new-asmfrag))
(st (generate-mach-o-symtab obj))
(rv (generate-mach-o-relvec obj st))
(met (compute-mach-o-metrics obj st)))
(emit-mach-o-header met frag)
(emit-mach-o-seg-lc met frag)
(emit-mach-o-symtab-lc met frag)
(emit-mach-o-sects obj frag)
(emit-mach-o-relocs rv frag)
(emit-mach-o-symtab st frag)
(asmfrag-buffer frag)))
|
e4fbb93489efaa611c183b81ce4f3b6349cef1e07c67fd798dd71b60310632f3
|
Opetushallitus/ataru
|
suoritus_client.clj
|
(ns ataru.suoritus.suoritus-client
(:require [ataru.cas.client :as cas-client]
[ataru.config.url-helper :as url]
[cheshire.core :as json]
[clj-time.format :as format]
[clojure.core.match :refer [match]]
[clojure.string :as string]))
(def yo-komo "1.2.246.562.5.2013061010184237348007")
(def erikoisammattitutkinto-komo "erikoisammattitutkinto komo oid")
(def ammattitutkinto-komo "ammatillinentutkinto komo oid")
(def ammatillinen-perustutkinto-komo "TODO ammatillinen komo oid")
(defn- ->suoritus-tila
[data]
(case (:tila data)
"VALMIS" :valmis
"KESKEN" :kesken
"KESKEYTYNYT" :keskeytynyt
(throw
(new RuntimeException
(str "Unknown suorituksen tila " (:tila data)
" in suoritus " data)))))
(defn- ->suoritus-person-oid
[data]
(when (string/blank? (:henkiloOid data))
(throw (new RuntimeException (str "No henkiloOid in suoritus " data))))
(:henkiloOid data))
(defn- ->suoritus
[data]
{:tila (->suoritus-tila data)
:person-oid (->suoritus-person-oid data)})
(defn- ->student-ja-luokka
[data]
{:person-oid (:henkiloOid data)
:luokka (:luokka data)})
(defn- format-modified-since
[modified-since]
(format/unparse (:date-time format/formatters)
modified-since))
(defn- suoritukset-for-komo
[cas-client person-oid modified-since komo]
(match [(cas-client/cas-authenticated-get
cas-client
(url/resolve-url
"suoritusrekisteri.suoritukset"
(cond-> {"komo" komo}
(some? person-oid)
(assoc "henkilo" person-oid)
(some? modified-since)
(assoc "muokattuJalkeen"
(format-modified-since modified-since)))))]
[{:status 200 :body s}]
(map ->suoritus (json/parse-string s true))
[r]
(throw (new RuntimeException
(str "Fetching ylioppilas suoritukset failed: " r)))))
(defn oppilaitoksen-opiskelijat
[cas-client oppilaitos-oid vuosi luokkatasot]
(let [url (url/resolve-url
"suoritusrekisteri.oppilaitoksenopiskelijat"
oppilaitos-oid
(cond-> {}
(some? vuosi)
(assoc "vuosi" vuosi)
(some? luokkatasot)
(assoc "luokkaTasot" luokkatasot)))]
(match [(cas-client/cas-authenticated-get
cas-client
url)]
[{:status 200 :body body}]
(map ->student-ja-luokka (json/parse-string body true))
[r]
(throw (new RuntimeException
(str "Fetching oppilaitoksen opiskelijat failed: " r))))))
(defn ylioppilas-ja-ammatilliset-suoritukset [cas-client person-oid modified-since]
(mapcat (partial suoritukset-for-komo cas-client person-oid modified-since)
[yo-komo
ammatillinen-perustutkinto-komo
ammattitutkinto-komo
erikoisammattitutkinto-komo]))
(defn oppilaitoksen-luokat
[cas-client oppilaitos-oid vuosi luokkatasot]
(let [url (url/resolve-url
"suoritusrekisteri.oppilaitoksenluokat"
oppilaitos-oid
(cond-> {}
(some? vuosi)
(assoc "vuosi" vuosi)
(some? luokkatasot)
(assoc "luokkaTasot" luokkatasot)))]
(match [(cas-client/cas-authenticated-get
cas-client
url)]
[{:status 200 :body body}]
(json/parse-string body true)
[r]
(throw (new RuntimeException
(str "Fetching oppilaitoksen luokat failed: " r))))))
(defn opiskelijat [cas-client henkilo-oid vuosi]
(let [url (url/resolve-url
"suoritusrekisteri.opiskelijat"
(cond-> {"henkilo" henkilo-oid}
(some? vuosi)
(assoc "vuosi" vuosi)))]
(match [(cas-client/cas-authenticated-get
cas-client
url)]
[{:status 200 :body body}]
(json/parse-string body true)
[r]
(throw (new RuntimeException
(str "Fetching opiskelijat failed: " r))))))
| null |
https://raw.githubusercontent.com/Opetushallitus/ataru/a84743140d2a7c879572583ec412166f829fc030/src/clj/ataru/suoritus/suoritus_client.clj
|
clojure
|
(ns ataru.suoritus.suoritus-client
(:require [ataru.cas.client :as cas-client]
[ataru.config.url-helper :as url]
[cheshire.core :as json]
[clj-time.format :as format]
[clojure.core.match :refer [match]]
[clojure.string :as string]))
(def yo-komo "1.2.246.562.5.2013061010184237348007")
(def erikoisammattitutkinto-komo "erikoisammattitutkinto komo oid")
(def ammattitutkinto-komo "ammatillinentutkinto komo oid")
(def ammatillinen-perustutkinto-komo "TODO ammatillinen komo oid")
(defn- ->suoritus-tila
[data]
(case (:tila data)
"VALMIS" :valmis
"KESKEN" :kesken
"KESKEYTYNYT" :keskeytynyt
(throw
(new RuntimeException
(str "Unknown suorituksen tila " (:tila data)
" in suoritus " data)))))
(defn- ->suoritus-person-oid
[data]
(when (string/blank? (:henkiloOid data))
(throw (new RuntimeException (str "No henkiloOid in suoritus " data))))
(:henkiloOid data))
(defn- ->suoritus
[data]
{:tila (->suoritus-tila data)
:person-oid (->suoritus-person-oid data)})
(defn- ->student-ja-luokka
[data]
{:person-oid (:henkiloOid data)
:luokka (:luokka data)})
(defn- format-modified-since
[modified-since]
(format/unparse (:date-time format/formatters)
modified-since))
(defn- suoritukset-for-komo
[cas-client person-oid modified-since komo]
(match [(cas-client/cas-authenticated-get
cas-client
(url/resolve-url
"suoritusrekisteri.suoritukset"
(cond-> {"komo" komo}
(some? person-oid)
(assoc "henkilo" person-oid)
(some? modified-since)
(assoc "muokattuJalkeen"
(format-modified-since modified-since)))))]
[{:status 200 :body s}]
(map ->suoritus (json/parse-string s true))
[r]
(throw (new RuntimeException
(str "Fetching ylioppilas suoritukset failed: " r)))))
(defn oppilaitoksen-opiskelijat
[cas-client oppilaitos-oid vuosi luokkatasot]
(let [url (url/resolve-url
"suoritusrekisteri.oppilaitoksenopiskelijat"
oppilaitos-oid
(cond-> {}
(some? vuosi)
(assoc "vuosi" vuosi)
(some? luokkatasot)
(assoc "luokkaTasot" luokkatasot)))]
(match [(cas-client/cas-authenticated-get
cas-client
url)]
[{:status 200 :body body}]
(map ->student-ja-luokka (json/parse-string body true))
[r]
(throw (new RuntimeException
(str "Fetching oppilaitoksen opiskelijat failed: " r))))))
(defn ylioppilas-ja-ammatilliset-suoritukset [cas-client person-oid modified-since]
(mapcat (partial suoritukset-for-komo cas-client person-oid modified-since)
[yo-komo
ammatillinen-perustutkinto-komo
ammattitutkinto-komo
erikoisammattitutkinto-komo]))
(defn oppilaitoksen-luokat
[cas-client oppilaitos-oid vuosi luokkatasot]
(let [url (url/resolve-url
"suoritusrekisteri.oppilaitoksenluokat"
oppilaitos-oid
(cond-> {}
(some? vuosi)
(assoc "vuosi" vuosi)
(some? luokkatasot)
(assoc "luokkaTasot" luokkatasot)))]
(match [(cas-client/cas-authenticated-get
cas-client
url)]
[{:status 200 :body body}]
(json/parse-string body true)
[r]
(throw (new RuntimeException
(str "Fetching oppilaitoksen luokat failed: " r))))))
(defn opiskelijat [cas-client henkilo-oid vuosi]
(let [url (url/resolve-url
"suoritusrekisteri.opiskelijat"
(cond-> {"henkilo" henkilo-oid}
(some? vuosi)
(assoc "vuosi" vuosi)))]
(match [(cas-client/cas-authenticated-get
cas-client
url)]
[{:status 200 :body body}]
(json/parse-string body true)
[r]
(throw (new RuntimeException
(str "Fetching opiskelijat failed: " r))))))
|
|
355b54925ccea849c4e010250ca0aa3bbcb4559ee3228d4070ac84fe13205e92
|
xxyzz/SICP
|
Exercise_4_35.rkt
|
#lang sicp
;; -lang.org/sicp-manual/Installation.html
(define (require p) (if (not p) (amb)))
(define (an-integer-between a b)
(require (<= a b))
(amb a (an-integer-between (+ a 1) b)))
(an-integer-between 1 5)
1
| null |
https://raw.githubusercontent.com/xxyzz/SICP/e26aea1c58fd896297dbf5406f7fcd32bb4f8f78/4_Metalinguistic_Abstraction/4.3_Variations_on_a_Scheme_Nondeterministic_Computing/Exercise_4_35.rkt
|
racket
|
-lang.org/sicp-manual/Installation.html
|
#lang sicp
(define (require p) (if (not p) (amb)))
(define (an-integer-between a b)
(require (<= a b))
(amb a (an-integer-between (+ a 1) b)))
(an-integer-between 1 5)
1
|
4134edfb4ef8335cc6eb35a3b9c7d57c6fd797e3dc2dd577060144cdad0df3e1
|
seanhess/robotquest
|
Types.hs
|
# LANGUAGE OverloadedStrings , DeriveGeneric , DeriveDataTypeable #
module Botland.Types where
import qualified Data.Aeson as A
import Data.Aeson (FromJSON(..), ToJSON(..), object, (.=), (.:), Value(..))
import qualified Data.Aeson.Types as AT
import Data.Aeson.Types (Parser)
import Data.Bson (Val(..), Value(..))
import qualified Data.Bson as B
import qualified Data.CompactString.UTF8 as C
import Data.Maybe (fromMaybe, isJust, fromJust)
import qualified Data.Text as T
import Data.DateTime (DateTime, fromSeconds)
import Data.Map (Map)
import Data.Typeable (Typeable)
import Database.MongoDB (val, Document, Field(..), at, lookup)
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero, guard)
import GHC.Generics (Generic)
import Prelude hiding (lookup)
import Safe (readMay)
type Field = Map Point Bot
-- DATA TYPES ---------------------------------------------------------------
-- heartbeat doesn't need to be a part of the client-side logic, just in the db
data Player = Player { playerId :: String, playerName :: String, source :: String } deriving (Show)
-- this is roughly what it looks like in the database
-- {x, y, _id, color, playerId, name, source}
data Bot = Bot { point :: Point
, name :: String
, player :: String
, sprite :: String
, botId :: String
, botPlayerId :: String
, kills :: Int
, created :: DateTime
, botState :: BotState
, command :: Maybe BotCommand
} deriving (Show)
-- sometimes you just need to talk about a point
data Point = Point { x :: Int, y :: Int }
| InvalidPoint
deriving (Show, Ord, Eq)
-- gives the field and interval
data GameInfo = GameInfo { width :: Int
, height :: Int
, tick :: Integer
} deriving (Show, Generic)
-- available actions
data BotCommand = BotCommand { action :: BotAction, direction :: Direction } deriving (Show, Eq, Typeable, Generic)
data Direction = DLeft | DRight | DUp | DDown deriving (Show, Read, Eq, Typeable)
data BotAction = Stop | Move | Attack deriving (Show, Read, Eq, Typeable)
data BotState = Active | Dead deriving (Show, Read, Eq, Typeable)
-- things that can go wrong
data Fault = Fault String
| NotFound
| NotAuthorized
| NotImplemented
| InvalidPosition
deriving (Generic, Show)
-- when I just want to send back an id
data Id = Id { id :: String } deriving (Show, Generic)
-- just means the server was successful
data Ok = Ok deriving (Show)
-- JSON SUPPORT --------------------------------------------------------------
instance ToJSON GameInfo
instance FromJSON GameInfo
instance ToJSON Id where
toJSON (Id id) = A.String $ T.pack id
instance ToJSON Ok where
toJSON _ = object ["ok" .= True]
instance FromJSON BotCommand
-- Actions --
instance ToJSON BotAction where
toJSON = typeToJSON show
instance FromJSON BotAction where
parseJSON = typeParseJSON readMay
-- Direction
removeFirstLetter = tail
addD cs = 'D':cs
instance ToJSON Direction where
toJSON = typeToJSON (removeFirstLetter.show)
instance FromJSON Direction where
parseJSON = typeParseJSON (readMay.addD)
State
instance ToJSON BotState where
toJSON = typeToJSON show
instance FromJSON BotState where
parseJSON = typeParseJSON readMay
-- Bot
-- sometimes kills exists, sometimes it doesn't
-- 0 means it doesn't matter
instance ToJSON Bot where
toJSON b = object fs
where p = point b
id = botId b
fs = [ "id" .= id
, "x" .= x p
, "y" .= y p
, "name" .= name b
, "player" .= player b
, "sprite" .= sprite b
, "state" .= botState b
, "kills" .= kills b
, "created" .= created b
]
-- you don't need the other fields from the client. So just make them up with defaults
instance FromJSON Bot where
parseJSON (Object v) = do
x <- v .: "x"
y <- v .: "y"
name <- v .: "name"
sprite <- v .: "sprite"
return $ Bot (Point x y) name "" sprite "" "" 0 (fromSeconds 0) Active Nothing
parseJSON _ = mzero
-- Player: json only has a name (not the id) --
instance FromJSON Player where
parseJSON (Object v) = do
name <- v .: "name"
source <- v .: "source"
return $ Player "" name source
parseJSON _ = mzero
instance ToJSON Player where
toJSON (Player id name source) = object ["name" .= name, "source" .= source]
-- SERVER MESSAGES ----------------------------------------------------------
instance FromJSON Fault where
parseJSON (Object v) = Fault <$> v .: "message"
instance ToJSON Fault where
toJSON f = object ["message" .= message f]
message :: Fault -> String
message NotFound = "Not Found"
message NotAuthorized = "Not Authorized"
message NotImplemented = "Not Implemented"
message InvalidPosition = "Invalid Position"
message (Fault m) = m
-- MONGODB -----------------------------------------------------------------
class ToDoc a where
toDoc :: a -> Document
class FromDoc a where
fromDoc :: Document -> a
instance ToDoc Bot where
toDoc b =
let p = point b in
[ "x" := val (x p)
, "y" := val (y p)
, "name" := val (name b)
, "player" := val (player b)
, "sprite" := val (sprite b)
, "_id" := val (botId b)
, "playerId" := val (botPlayerId b)
, "created" := val (created b)
, "state" := val (botState b)
, "command" := val (command b)
]
instance FromDoc Bot where
fromDoc d = Bot (Point (at "x" d) (at "y" d))
(at "name" d)
(at "player" d)
(at "sprite" d)
(fromMaybe "" (lookup "_id" d))
(fromMaybe "" (lookup "playerId" d))
(fromMaybe 0 (lookup "kills" d))
(fromMaybe (fromSeconds 0) (lookup "created" d))
(at "state" d)
(lookup "command" d)
instance FromDoc Point where
fromDoc p = Point (at "x" p) (at "y" p)
instance FromDoc Player where
fromDoc p = Player (fromMaybe "" (lookup "_id" p)) (at "name" p) (at "source" p)
instance ToDoc Player where
toDoc p = [ "_id" := val (playerId p)
, "name" := val (playerName p)
, "source" := val (source p)
]
instance Val BotCommand where
val (BotCommand a d) = val ["action" := val a, "direction" := val d]
cast' (Doc d) = Just $ BotCommand (at "action" d) (at "direction" d)
cast' _ = Nothing
instance Val BotAction where
val = typeToBSON show
cast' = typeFromBSON readMay
instance Val Direction where
val = typeToBSON (removeFirstLetter.show)
cast' = typeFromBSON (readMay.addD)
instance Val BotState where
val = typeToBSON show
cast' = typeFromBSON readMay
BSON HELPERS ---------------------------------------------------------------
typeToBSON :: (a -> String) -> a -> B.Value
typeToBSON show = val . show
typeFromBSON :: (String -> Maybe a) -> B.Value -> Maybe a
typeFromBSON read (B.String bs) = do
m <- read $ T.unpack bs
return m
-- JSON HELPERS ---------------------------------------------------------------
typeToJSON :: (a -> String) -> a -> A.Value
typeToJSON show = A.String . T.pack . show
typeParseJSON :: (String -> Maybe a) -> A.Value -> AT.Parser a
typeParseJSON read (A.String t) = do
let ma = read $ T.unpack t
case ma of
Nothing -> mzero
Just a -> return a
typeParseJSON _ _ = mzero
--typeParseJSON (A.String t) = do
let mt = readMay $ T.unpack t
guard ( isJust mt )
-- return $ fromJust mt
--typeParseJSON _ = mzero
| null |
https://raw.githubusercontent.com/seanhess/robotquest/98328579d6bbfad2cd678811a9759c907cf6b268/Botland/Types.hs
|
haskell
|
DATA TYPES ---------------------------------------------------------------
heartbeat doesn't need to be a part of the client-side logic, just in the db
this is roughly what it looks like in the database
{x, y, _id, color, playerId, name, source}
sometimes you just need to talk about a point
gives the field and interval
available actions
things that can go wrong
when I just want to send back an id
just means the server was successful
JSON SUPPORT --------------------------------------------------------------
Actions --
Direction
Bot
sometimes kills exists, sometimes it doesn't
0 means it doesn't matter
you don't need the other fields from the client. So just make them up with defaults
Player: json only has a name (not the id) --
SERVER MESSAGES ----------------------------------------------------------
MONGODB -----------------------------------------------------------------
-------------------------------------------------------------
JSON HELPERS ---------------------------------------------------------------
typeParseJSON (A.String t) = do
return $ fromJust mt
typeParseJSON _ = mzero
|
# LANGUAGE OverloadedStrings , DeriveGeneric , DeriveDataTypeable #
module Botland.Types where
import qualified Data.Aeson as A
import Data.Aeson (FromJSON(..), ToJSON(..), object, (.=), (.:), Value(..))
import qualified Data.Aeson.Types as AT
import Data.Aeson.Types (Parser)
import Data.Bson (Val(..), Value(..))
import qualified Data.Bson as B
import qualified Data.CompactString.UTF8 as C
import Data.Maybe (fromMaybe, isJust, fromJust)
import qualified Data.Text as T
import Data.DateTime (DateTime, fromSeconds)
import Data.Map (Map)
import Data.Typeable (Typeable)
import Database.MongoDB (val, Document, Field(..), at, lookup)
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero, guard)
import GHC.Generics (Generic)
import Prelude hiding (lookup)
import Safe (readMay)
type Field = Map Point Bot
data Player = Player { playerId :: String, playerName :: String, source :: String } deriving (Show)
data Bot = Bot { point :: Point
, name :: String
, player :: String
, sprite :: String
, botId :: String
, botPlayerId :: String
, kills :: Int
, created :: DateTime
, botState :: BotState
, command :: Maybe BotCommand
} deriving (Show)
data Point = Point { x :: Int, y :: Int }
| InvalidPoint
deriving (Show, Ord, Eq)
data GameInfo = GameInfo { width :: Int
, height :: Int
, tick :: Integer
} deriving (Show, Generic)
data BotCommand = BotCommand { action :: BotAction, direction :: Direction } deriving (Show, Eq, Typeable, Generic)
data Direction = DLeft | DRight | DUp | DDown deriving (Show, Read, Eq, Typeable)
data BotAction = Stop | Move | Attack deriving (Show, Read, Eq, Typeable)
data BotState = Active | Dead deriving (Show, Read, Eq, Typeable)
data Fault = Fault String
| NotFound
| NotAuthorized
| NotImplemented
| InvalidPosition
deriving (Generic, Show)
data Id = Id { id :: String } deriving (Show, Generic)
data Ok = Ok deriving (Show)
instance ToJSON GameInfo
instance FromJSON GameInfo
instance ToJSON Id where
toJSON (Id id) = A.String $ T.pack id
instance ToJSON Ok where
toJSON _ = object ["ok" .= True]
instance FromJSON BotCommand
instance ToJSON BotAction where
toJSON = typeToJSON show
instance FromJSON BotAction where
parseJSON = typeParseJSON readMay
removeFirstLetter = tail
addD cs = 'D':cs
instance ToJSON Direction where
toJSON = typeToJSON (removeFirstLetter.show)
instance FromJSON Direction where
parseJSON = typeParseJSON (readMay.addD)
State
instance ToJSON BotState where
toJSON = typeToJSON show
instance FromJSON BotState where
parseJSON = typeParseJSON readMay
instance ToJSON Bot where
toJSON b = object fs
where p = point b
id = botId b
fs = [ "id" .= id
, "x" .= x p
, "y" .= y p
, "name" .= name b
, "player" .= player b
, "sprite" .= sprite b
, "state" .= botState b
, "kills" .= kills b
, "created" .= created b
]
instance FromJSON Bot where
parseJSON (Object v) = do
x <- v .: "x"
y <- v .: "y"
name <- v .: "name"
sprite <- v .: "sprite"
return $ Bot (Point x y) name "" sprite "" "" 0 (fromSeconds 0) Active Nothing
parseJSON _ = mzero
instance FromJSON Player where
parseJSON (Object v) = do
name <- v .: "name"
source <- v .: "source"
return $ Player "" name source
parseJSON _ = mzero
instance ToJSON Player where
toJSON (Player id name source) = object ["name" .= name, "source" .= source]
instance FromJSON Fault where
parseJSON (Object v) = Fault <$> v .: "message"
instance ToJSON Fault where
toJSON f = object ["message" .= message f]
message :: Fault -> String
message NotFound = "Not Found"
message NotAuthorized = "Not Authorized"
message NotImplemented = "Not Implemented"
message InvalidPosition = "Invalid Position"
message (Fault m) = m
class ToDoc a where
toDoc :: a -> Document
class FromDoc a where
fromDoc :: Document -> a
instance ToDoc Bot where
toDoc b =
let p = point b in
[ "x" := val (x p)
, "y" := val (y p)
, "name" := val (name b)
, "player" := val (player b)
, "sprite" := val (sprite b)
, "_id" := val (botId b)
, "playerId" := val (botPlayerId b)
, "created" := val (created b)
, "state" := val (botState b)
, "command" := val (command b)
]
instance FromDoc Bot where
fromDoc d = Bot (Point (at "x" d) (at "y" d))
(at "name" d)
(at "player" d)
(at "sprite" d)
(fromMaybe "" (lookup "_id" d))
(fromMaybe "" (lookup "playerId" d))
(fromMaybe 0 (lookup "kills" d))
(fromMaybe (fromSeconds 0) (lookup "created" d))
(at "state" d)
(lookup "command" d)
instance FromDoc Point where
fromDoc p = Point (at "x" p) (at "y" p)
instance FromDoc Player where
fromDoc p = Player (fromMaybe "" (lookup "_id" p)) (at "name" p) (at "source" p)
instance ToDoc Player where
toDoc p = [ "_id" := val (playerId p)
, "name" := val (playerName p)
, "source" := val (source p)
]
instance Val BotCommand where
val (BotCommand a d) = val ["action" := val a, "direction" := val d]
cast' (Doc d) = Just $ BotCommand (at "action" d) (at "direction" d)
cast' _ = Nothing
instance Val BotAction where
val = typeToBSON show
cast' = typeFromBSON readMay
instance Val Direction where
val = typeToBSON (removeFirstLetter.show)
cast' = typeFromBSON (readMay.addD)
instance Val BotState where
val = typeToBSON show
cast' = typeFromBSON readMay
typeToBSON :: (a -> String) -> a -> B.Value
typeToBSON show = val . show
typeFromBSON :: (String -> Maybe a) -> B.Value -> Maybe a
typeFromBSON read (B.String bs) = do
m <- read $ T.unpack bs
return m
typeToJSON :: (a -> String) -> a -> A.Value
typeToJSON show = A.String . T.pack . show
typeParseJSON :: (String -> Maybe a) -> A.Value -> AT.Parser a
typeParseJSON read (A.String t) = do
let ma = read $ T.unpack t
case ma of
Nothing -> mzero
Just a -> return a
typeParseJSON _ _ = mzero
let mt = readMay $ T.unpack t
guard ( isJust mt )
|
316b4de579ba0d89e49dc0ebd68f59018226feb13aba21fd81eeff17348f404e
|
ulisses/Static-Code-Analyzer
|
StrategyPrelude.hs
|
------------------------------------------------------------------------------
-- |
Maintainer : ,
-- Stability : experimental
-- Portability : portable
--
This module is part of ' StrategyLib ' , a library of functional strategy
-- combinators, including combinators for generic traversal. This module
-- is basically a wrapper for the strategy primitives plus some extra
-- basic strategy combinators that can be defined immediately in terms
-- of the primitive ones.
------------------------------------------------------------------------------
module Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrelude (
module Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrimitives,
module Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrelude
) where
import Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrimitives
import Control.Monad
import Data.Monoid
------------------------------------------------------------------------------
-- * Useful defaults for strategy update (see 'adhocTU' and 'adhocTP').
-- | Type-preserving identity. Returns the incoming term without change.
idTP :: Monad m => TP m
idTP = paraTP return
-- | Type-preserving failure. Always fails, independent of the incoming
term . Uses ' MonadPlus ' to model partiality .
failTP :: MonadPlus m => TP m
failTP = paraTP (const mzero)
-- | Type-unifying failure. Always fails, independent of the incoming
term . Uses ' MonadPlus ' to model partiality .
failTU :: MonadPlus m => TU a m
failTU = paraTU (const mzero)
-- | Type-unifying constant strategy. Always returns the argument value 'a',
-- independent of the incoming term.
constTU :: Monad m => a -> TU a m
constTU a = paraTU (const (return a))
-- | Type-unifying monadic constant strategy. Always performs the argument
-- computation 'a', independent of the incoming term. This is a monadic
-- variation of 'constTU'.
compTU :: Monad m => m a -> TU a m
compTU a = paraTU (const a)
------------------------------------------------------------------------------
-- * Lift a function to a strategy type with failure as default
-- | Apply the monomorphic, type-preserving argument function, if its
-- input type matches the input term's type. Otherwise, fail.
monoTP :: (Term a, MonadPlus m) => (a -> m a) -> TP m
monoTP = adhocTP failTP
-- | Apply the monomorphic, type-unifying argument function, if its
-- input type matches the input term's type. Otherwise, fail.
monoTU :: (Term a, MonadPlus m) => (a -> m b) -> TU b m
monoTU = adhocTU failTU
------------------------------------------------------------------------------
-- * Function composition
-- | Sequential ccomposition of monomorphic function and type-unifying strategy.
-- In other words, after the type-unifying strategy 's' has been applied,
-- the monomorphic function 'f' is applied to the resulting value.
dotTU :: Monad m => (a -> b) -> TU a m -> TU b m
dotTU f s = s `passTU` (constTU . f)
| Parallel combination of two type - unifying strategies with a binary
-- combinator. In other words, the values resulting from applying the
-- type-unifying strategies are combined to a final value by applying
-- the combinator 'o'.
op2TU :: Monad m => (a -> b -> c) -> TU a m -> TU b m -> TU c m
op2TU o s s' = s `passTU` \a ->
s' `passTU` \b ->
constTU (o a b)
------------------------------------------------------------------------------
-- * Reduce a strategy's performance to its effects
-- | Reduce a type-preserving strategy to a type-unifying one that
-- ignores its result term and returns void, but retains its
-- monadic effects.
voidTP :: Monad m => TP m -> TU () m
voidTP s = s `seqTU` constTU ()
-- | Reduce a type-unifying strategy to a type-unifying one that
-- ignores its result value and returns void, but retains its
-- monadic effects.
voidTU :: Monad m => TU u m -> TU () m
voidTU s = s `passTU` \_ -> constTU ()
------------------------------------------------------------------------------
-- * Shape test combinators
-- | Test for constant term, i.e.\ having no subterms.
con :: MonadPlus m => TP m
con = allTP failTP
| Test for compound term , i.e.\ having at least one subterm .
com :: MonadPlus m => TP m
com = oneTP idTP
------------------------------------------------------------------------------
| null |
https://raw.githubusercontent.com/ulisses/Static-Code-Analyzer/4c3f6423d43e1bccb9d1cf04e74ae60d9170186f/Analyzer/Strafunski/Data/Generics/Strafunski/StrategyLib/StrategyPrelude.hs
|
haskell
|
----------------------------------------------------------------------------
|
Stability : experimental
Portability : portable
combinators, including combinators for generic traversal. This module
is basically a wrapper for the strategy primitives plus some extra
basic strategy combinators that can be defined immediately in terms
of the primitive ones.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
* Useful defaults for strategy update (see 'adhocTU' and 'adhocTP').
| Type-preserving identity. Returns the incoming term without change.
| Type-preserving failure. Always fails, independent of the incoming
| Type-unifying failure. Always fails, independent of the incoming
| Type-unifying constant strategy. Always returns the argument value 'a',
independent of the incoming term.
| Type-unifying monadic constant strategy. Always performs the argument
computation 'a', independent of the incoming term. This is a monadic
variation of 'constTU'.
----------------------------------------------------------------------------
* Lift a function to a strategy type with failure as default
| Apply the monomorphic, type-preserving argument function, if its
input type matches the input term's type. Otherwise, fail.
| Apply the monomorphic, type-unifying argument function, if its
input type matches the input term's type. Otherwise, fail.
----------------------------------------------------------------------------
* Function composition
| Sequential ccomposition of monomorphic function and type-unifying strategy.
In other words, after the type-unifying strategy 's' has been applied,
the monomorphic function 'f' is applied to the resulting value.
combinator. In other words, the values resulting from applying the
type-unifying strategies are combined to a final value by applying
the combinator 'o'.
----------------------------------------------------------------------------
* Reduce a strategy's performance to its effects
| Reduce a type-preserving strategy to a type-unifying one that
ignores its result term and returns void, but retains its
monadic effects.
| Reduce a type-unifying strategy to a type-unifying one that
ignores its result value and returns void, but retains its
monadic effects.
----------------------------------------------------------------------------
* Shape test combinators
| Test for constant term, i.e.\ having no subterms.
----------------------------------------------------------------------------
|
Maintainer : ,
This module is part of ' StrategyLib ' , a library of functional strategy
module Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrelude (
module Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrimitives,
module Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrelude
) where
import Strafunski.Data.Generics.Strafunski.StrategyLib.StrategyPrimitives
import Control.Monad
import Data.Monoid
idTP :: Monad m => TP m
idTP = paraTP return
term . Uses ' MonadPlus ' to model partiality .
failTP :: MonadPlus m => TP m
failTP = paraTP (const mzero)
term . Uses ' MonadPlus ' to model partiality .
failTU :: MonadPlus m => TU a m
failTU = paraTU (const mzero)
constTU :: Monad m => a -> TU a m
constTU a = paraTU (const (return a))
compTU :: Monad m => m a -> TU a m
compTU a = paraTU (const a)
monoTP :: (Term a, MonadPlus m) => (a -> m a) -> TP m
monoTP = adhocTP failTP
monoTU :: (Term a, MonadPlus m) => (a -> m b) -> TU b m
monoTU = adhocTU failTU
dotTU :: Monad m => (a -> b) -> TU a m -> TU b m
dotTU f s = s `passTU` (constTU . f)
| Parallel combination of two type - unifying strategies with a binary
op2TU :: Monad m => (a -> b -> c) -> TU a m -> TU b m -> TU c m
op2TU o s s' = s `passTU` \a ->
s' `passTU` \b ->
constTU (o a b)
voidTP :: Monad m => TP m -> TU () m
voidTP s = s `seqTU` constTU ()
voidTU :: Monad m => TU u m -> TU () m
voidTU s = s `passTU` \_ -> constTU ()
con :: MonadPlus m => TP m
con = allTP failTP
| Test for compound term , i.e.\ having at least one subterm .
com :: MonadPlus m => TP m
com = oneTP idTP
|
ffb1da72e87d82454d7faa9d3798a360388811ee3a74dff144c988267fc66dd9
|
JustusAdam/language-haskell
|
T0028b.hs
|
SYNTAX TEST " source.haskell " " Highlighting type signature before do arrow "
someFunc :: IO ()
someFunc = do
result <- ioAction
result :: Int <- ioAction
^^^ storage.type.haskell
-- ^^ keyword.operator.arrow.left.haskell
( result :: Int ) <- ioAction
^^^ storage.type.haskell
-- ^^ keyword.operator.arrow.left.haskell
| null |
https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tickets/T0028b.hs
|
haskell
|
^^ keyword.operator.arrow.left.haskell
^^ keyword.operator.arrow.left.haskell
|
SYNTAX TEST " source.haskell " " Highlighting type signature before do arrow "
someFunc :: IO ()
someFunc = do
result <- ioAction
result :: Int <- ioAction
^^^ storage.type.haskell
( result :: Int ) <- ioAction
^^^ storage.type.haskell
|
8b761c68c5383fb3d5283994f97ba48e6276aafe436e10cfabcaafbb9da0a074
|
mentat-collective/emmy
|
exponent_test.cljc
|
#_"SPDX-License-Identifier: GPL-3.0"
(ns emmy.polynomial.exponent-test
(:require [clojure.test :refer [is deftest testing]]
[clojure.test.check.generators :as gen]
[com.gfredericks.test.chuck.clojure-test :refer [checking]]
[emmy.generators :as sg]
[emmy.polynomial.exponent :as xpt]))
(deftest exponents-tests
(checking "(l*r)/r == l" 100
[l (sg/poly:exponents 10)
r (sg/poly:exponents 10)]
(is (= l (-> (xpt/mul l r)
(xpt/div r)))))
(checking "(l*r)/gcd(l,r) == lcm(l,r)" 100
[l (sg/poly:exponents 10)
r (sg/poly:exponents 10)]
(is (= (xpt/lcm l r)
(-> (xpt/mul l r)
(xpt/div (xpt/gcd l r))))))
(checking "->sort+unsort" 100
[m (sg/poly:exponents 100)]
(let [[sort-m unsort-m] (xpt/->sort+unsort m)]
(and (= (vals (sort-m m))
(sort (vals m)))
(= m (unsort-m (sort-m m))))))
(checking "assoc" 100 [m (sg/poly:exponents 10)
x gen/nat
n gen/nat]
(is (= n (-> (xpt/assoc m x n)
(xpt/monomial-degree x)))))
(checking "raise/lower" 100
[m (sg/poly:exponents 10)
x gen/nat]
(is (= m (xpt/lower
(xpt/raise m)))
"raise, lower with defalt indices")
(is (= m (-> (xpt/raise m x)
(xpt/lower x)))
"raise, lower with explicit index"))
(checking "lowering all the way == empty" 100
[m (sg/poly:exponents 10)]
(is (= xpt/empty
(-> (iterate xpt/lower m)
(nth 10))))))
(deftest monomial-ordering-tests
(testing "monomial orderings"
(let [x3 (xpt/dense->exponents [3 0 0])
x2z2 (xpt/dense->exponents [2 0 2])
xy2z (xpt/dense->exponents [1 2 1])
z2 (xpt/dense->exponents [0 0 2])
monomials [x3 x2z2 xy2z z2]
sort-with #(sort % monomials)]
(is (= [z2 xy2z x2z2 x3]
(sort-with xpt/lex-order)))
(is (= [z2 x3 xy2z x2z2]
(sort-with xpt/graded-lex-order)))
(is (= [z2 x3 x2z2 xy2z]
(sort-with xpt/graded-reverse-lex-order))))
(testing "monomial ordering example from wikipedia"
(let [x2 (xpt/make 0 2)
xy (xpt/make 0 1 1 1)
xz (xpt/make 0 1 2 1)
y2 (xpt/make 1 2)
yz (xpt/make 1 1 2 1)
z2 (xpt/make 2 2)
monomials [x2 xy xz y2 yz z2]
sort-with #(sort % monomials)]
(is (= [z2 yz y2 xz xy x2]
(sort-with xpt/lex-order)
(sort-with xpt/graded-lex-order))
"grlex and lex match when all orders are the same")
(is (= [z2 yz xz y2 xy x2]
(sort-with xpt/graded-reverse-lex-order)))))))
| null |
https://raw.githubusercontent.com/mentat-collective/emmy/535b237a8e3fd7067b9c0ade8b2a4b3419f9f132/test/emmy/polynomial/exponent_test.cljc
|
clojure
|
#_"SPDX-License-Identifier: GPL-3.0"
(ns emmy.polynomial.exponent-test
(:require [clojure.test :refer [is deftest testing]]
[clojure.test.check.generators :as gen]
[com.gfredericks.test.chuck.clojure-test :refer [checking]]
[emmy.generators :as sg]
[emmy.polynomial.exponent :as xpt]))
(deftest exponents-tests
(checking "(l*r)/r == l" 100
[l (sg/poly:exponents 10)
r (sg/poly:exponents 10)]
(is (= l (-> (xpt/mul l r)
(xpt/div r)))))
(checking "(l*r)/gcd(l,r) == lcm(l,r)" 100
[l (sg/poly:exponents 10)
r (sg/poly:exponents 10)]
(is (= (xpt/lcm l r)
(-> (xpt/mul l r)
(xpt/div (xpt/gcd l r))))))
(checking "->sort+unsort" 100
[m (sg/poly:exponents 100)]
(let [[sort-m unsort-m] (xpt/->sort+unsort m)]
(and (= (vals (sort-m m))
(sort (vals m)))
(= m (unsort-m (sort-m m))))))
(checking "assoc" 100 [m (sg/poly:exponents 10)
x gen/nat
n gen/nat]
(is (= n (-> (xpt/assoc m x n)
(xpt/monomial-degree x)))))
(checking "raise/lower" 100
[m (sg/poly:exponents 10)
x gen/nat]
(is (= m (xpt/lower
(xpt/raise m)))
"raise, lower with defalt indices")
(is (= m (-> (xpt/raise m x)
(xpt/lower x)))
"raise, lower with explicit index"))
(checking "lowering all the way == empty" 100
[m (sg/poly:exponents 10)]
(is (= xpt/empty
(-> (iterate xpt/lower m)
(nth 10))))))
(deftest monomial-ordering-tests
(testing "monomial orderings"
(let [x3 (xpt/dense->exponents [3 0 0])
x2z2 (xpt/dense->exponents [2 0 2])
xy2z (xpt/dense->exponents [1 2 1])
z2 (xpt/dense->exponents [0 0 2])
monomials [x3 x2z2 xy2z z2]
sort-with #(sort % monomials)]
(is (= [z2 xy2z x2z2 x3]
(sort-with xpt/lex-order)))
(is (= [z2 x3 xy2z x2z2]
(sort-with xpt/graded-lex-order)))
(is (= [z2 x3 x2z2 xy2z]
(sort-with xpt/graded-reverse-lex-order))))
(testing "monomial ordering example from wikipedia"
(let [x2 (xpt/make 0 2)
xy (xpt/make 0 1 1 1)
xz (xpt/make 0 1 2 1)
y2 (xpt/make 1 2)
yz (xpt/make 1 1 2 1)
z2 (xpt/make 2 2)
monomials [x2 xy xz y2 yz z2]
sort-with #(sort % monomials)]
(is (= [z2 yz y2 xz xy x2]
(sort-with xpt/lex-order)
(sort-with xpt/graded-lex-order))
"grlex and lex match when all orders are the same")
(is (= [z2 yz xz y2 xy x2]
(sort-with xpt/graded-reverse-lex-order)))))))
|
|
924c21f33b8d97e3a329a0bc7bcbb380d8d68616433312d06cce3b8f019bdb09
|
lichtblau/CommonQt
|
marshal.lisp
|
;;; -*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
Copyright ( c ) 2009 . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :qt)
(named-readtables:in-readtable :qt)
(defun resolve-cast (<from> <to>)
(let* ((module (ldb-module <from>))
(compatible-<to>
(if (eql module (ldb-module <to>))
<to>
(find-qclass-in-module module (qclass-name <to>)))))
(values (data-castfn (data-ref module))
compatible-<to>)))
(defun perform-cast (obj castfn <from> <to>)
(cffi:foreign-funcall-pointer
castfn
()
:pointer (qobject-pointer obj)
:short (unbash <from>)
:short (unbash <to>)
:pointer))
(defun %cast (obj <to>)
;;; (let* ((from-class (qobject-class obj))
;;; (module (ldb-module from-class))
;;; (to-class
;;; (if (eql module (ldb-module to-class))
;;; to-class
;;; (find-qclass-in-module module (qclass-name to-class)))))
;;; (cffi:foreign-funcall-pointer
;;; (data-castfn (data-ref module))
;;; ()
: pointer ( qobject - pointer obj )
;;; :short (unbash from-class)
;;; :short (unbash to-class)
;;; :pointer))
(let ((<from> (qobject-class obj)))
(multiple-value-bind (fn <cto>)
(resolve-cast <from> <to>)
(perform-cast obj fn <from> <cto>))))
(defun marshal (value type stack-item cont)
(funcall (marshaller value type) value stack-item cont))
(defun marshaller (obj <type>)
(let* ((set-thunk
(macrolet
((si (slot)
`(cffi:foreign-slot-value si '|union StackItem| ',slot))
(dispatching ((getter slot) &body body)
`(ecase ,slot
,@ (mapcar (lambda (slot)
`((,slot)
(macrolet ((,getter () `(si ,',slot)))
,@body)))
'(ptr bool char uchar short ushort int
uint long ulong float double enum class)))))
(let ((slot (qtype-stack-item-slot <type>)))
(case slot
(bool (lambda (val si) (setf (si bool) (if val 1 0))))
(class (if (typep obj 'qobject)
(let ((<from> (qobject-class obj)))
(multiple-value-bind (castfn <to>)
(resolve-cast <from> (qtype-class <type>))
(lambda (val si)
(setf (si class)
(perform-cast val castfn <from> <to>)))))
(lambda (val si)
(setf (si class)
(if (typep val 'cffi:foreign-pointer)
val
(qobject-pointer val))))))
(enum (etypecase obj
(integer
(lambda (val si) (setf (si enum) val)))
(enum
(lambda (val si) (setf (si enum) (primitive-value val))))))
(int (etypecase obj
(integer
(lambda (val si) (setf (si int) val)))
(enum
(lambda (val si) (setf (si int) (primitive-value val))))))
(uint (etypecase obj
(integer
(lambda (val si) (setf (si uint) val)))
(enum
(lambda (val si) (setf (si uint) (primitive-value val))))))
(float (lambda (val si) (setf (si float) (float val 1.0s0))))
(double (lambda (val si) (setf (si double) (float val 1.0d0))))
;; that leaves:
ptr char uchar short ushort int uint long ulong
(t
(dispatching (%si slot)
(lambda (val si)
(setf (%si) val))))))))
(primary-cons
(get (qtype-interned-name <type>) 'marshaller/primary))
(around-cons
(get (qtype-interned-name <type>) 'marshaller/around))
(primary-type (car primary-cons))
(primary-thunk (cdr primary-cons))
(around-type (car around-cons))
(around-thunk (cdr around-cons)))
(cond
((and primary-thunk (typep obj primary-type))
(assert (null around-thunk))
(named-lambda marshal-primary-outer (value stack-item cont)
(funcall set-thunk
(funcall primary-thunk value)
stack-item)
(funcall cont)))
((and around-thunk (typep obj around-type))
(named-lambda marshal-around-outer (value stack-item cont)
(funcall around-thunk
value
(named-lambda marshal-around-inner (new-value)
(funcall set-thunk new-value stack-item)
(funcall cont)))))
(t
(named-lambda marshal-default (value stack-item cont)
(funcall set-thunk value stack-item)
(funcall cont))))))
(defmacro defmarshal ((var name &key around (type t)) &body body)
(if (consp name)
`(progn
,@(iter (for n1 in name)
(collect `(defmarshal (,var ,n1 :around ,around :type ,type) ,@body))))
(let ((function-name (intern (format nil "~a-~a" name 'marshaller))))
(if around
`(setf (get ',name 'marshaller/primary) nil
(get ',name 'marshaller/around)
(cons ',type (named-lambda ,function-name (,var ,around) ,@body)))
`(setf (get ',name 'marshaller/primary)
(cons ',type (named-lambda ,function-name (,var) ,@body))
(get ',name 'marshaller/around) nil)))))
(defmarshal (value (:|QString| :|const QString&|) :around cont :type string)
(let ((qstring (sw_make_qstring value)))
(unwind-protect
(funcall cont qstring)
(sw_delete_qstring qstring))))
;;; Don't delete the string because it may be used afterwards by Qt
(defmarshal (value :|QString*| :around cont :type string)
(funcall cont (sw_make_qstring value)))
(defmarshal (value :|const char*| :around cont :type string)
(let ((char* (cffi:foreign-string-alloc value)))
(unwind-protect
(funcall cont char*)
(cffi:foreign-free char*))))
(defmarshal (value :|unsigned char*| :around cont :type string)
(let ((char* (cffi:foreign-string-alloc value)))
(unwind-protect
(funcall cont char*)
(cffi:foreign-free char*))))
(defmarshal (value (:|QByteArray| :|const QByteArray&|) :around cont :type string)
(let ((qbytearray (sw_make_qbytearray value)))
(unwind-protect
(funcall cont qbytearray)
(sw_delete_qbytearray qbytearray))))
| null |
https://raw.githubusercontent.com/lichtblau/CommonQt/fa14472594b2b2b34695ec3fff6f858a03ec5813/marshal.lisp
|
lisp
|
-*- show-trailing-whitespace: t; indent-tabs-mode: nil -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(let* ((from-class (qobject-class obj))
(module (ldb-module from-class))
(to-class
(if (eql module (ldb-module to-class))
to-class
(find-qclass-in-module module (qclass-name to-class)))))
(cffi:foreign-funcall-pointer
(data-castfn (data-ref module))
()
:short (unbash from-class)
:short (unbash to-class)
:pointer))
that leaves:
Don't delete the string because it may be used afterwards by Qt
|
Copyright ( c ) 2009 . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :qt)
(named-readtables:in-readtable :qt)
(defun resolve-cast (<from> <to>)
(let* ((module (ldb-module <from>))
(compatible-<to>
(if (eql module (ldb-module <to>))
<to>
(find-qclass-in-module module (qclass-name <to>)))))
(values (data-castfn (data-ref module))
compatible-<to>)))
(defun perform-cast (obj castfn <from> <to>)
(cffi:foreign-funcall-pointer
castfn
()
:pointer (qobject-pointer obj)
:short (unbash <from>)
:short (unbash <to>)
:pointer))
(defun %cast (obj <to>)
: pointer ( qobject - pointer obj )
(let ((<from> (qobject-class obj)))
(multiple-value-bind (fn <cto>)
(resolve-cast <from> <to>)
(perform-cast obj fn <from> <cto>))))
(defun marshal (value type stack-item cont)
(funcall (marshaller value type) value stack-item cont))
(defun marshaller (obj <type>)
(let* ((set-thunk
(macrolet
((si (slot)
`(cffi:foreign-slot-value si '|union StackItem| ',slot))
(dispatching ((getter slot) &body body)
`(ecase ,slot
,@ (mapcar (lambda (slot)
`((,slot)
(macrolet ((,getter () `(si ,',slot)))
,@body)))
'(ptr bool char uchar short ushort int
uint long ulong float double enum class)))))
(let ((slot (qtype-stack-item-slot <type>)))
(case slot
(bool (lambda (val si) (setf (si bool) (if val 1 0))))
(class (if (typep obj 'qobject)
(let ((<from> (qobject-class obj)))
(multiple-value-bind (castfn <to>)
(resolve-cast <from> (qtype-class <type>))
(lambda (val si)
(setf (si class)
(perform-cast val castfn <from> <to>)))))
(lambda (val si)
(setf (si class)
(if (typep val 'cffi:foreign-pointer)
val
(qobject-pointer val))))))
(enum (etypecase obj
(integer
(lambda (val si) (setf (si enum) val)))
(enum
(lambda (val si) (setf (si enum) (primitive-value val))))))
(int (etypecase obj
(integer
(lambda (val si) (setf (si int) val)))
(enum
(lambda (val si) (setf (si int) (primitive-value val))))))
(uint (etypecase obj
(integer
(lambda (val si) (setf (si uint) val)))
(enum
(lambda (val si) (setf (si uint) (primitive-value val))))))
(float (lambda (val si) (setf (si float) (float val 1.0s0))))
(double (lambda (val si) (setf (si double) (float val 1.0d0))))
ptr char uchar short ushort int uint long ulong
(t
(dispatching (%si slot)
(lambda (val si)
(setf (%si) val))))))))
(primary-cons
(get (qtype-interned-name <type>) 'marshaller/primary))
(around-cons
(get (qtype-interned-name <type>) 'marshaller/around))
(primary-type (car primary-cons))
(primary-thunk (cdr primary-cons))
(around-type (car around-cons))
(around-thunk (cdr around-cons)))
(cond
((and primary-thunk (typep obj primary-type))
(assert (null around-thunk))
(named-lambda marshal-primary-outer (value stack-item cont)
(funcall set-thunk
(funcall primary-thunk value)
stack-item)
(funcall cont)))
((and around-thunk (typep obj around-type))
(named-lambda marshal-around-outer (value stack-item cont)
(funcall around-thunk
value
(named-lambda marshal-around-inner (new-value)
(funcall set-thunk new-value stack-item)
(funcall cont)))))
(t
(named-lambda marshal-default (value stack-item cont)
(funcall set-thunk value stack-item)
(funcall cont))))))
(defmacro defmarshal ((var name &key around (type t)) &body body)
(if (consp name)
`(progn
,@(iter (for n1 in name)
(collect `(defmarshal (,var ,n1 :around ,around :type ,type) ,@body))))
(let ((function-name (intern (format nil "~a-~a" name 'marshaller))))
(if around
`(setf (get ',name 'marshaller/primary) nil
(get ',name 'marshaller/around)
(cons ',type (named-lambda ,function-name (,var ,around) ,@body)))
`(setf (get ',name 'marshaller/primary)
(cons ',type (named-lambda ,function-name (,var) ,@body))
(get ',name 'marshaller/around) nil)))))
(defmarshal (value (:|QString| :|const QString&|) :around cont :type string)
(let ((qstring (sw_make_qstring value)))
(unwind-protect
(funcall cont qstring)
(sw_delete_qstring qstring))))
(defmarshal (value :|QString*| :around cont :type string)
(funcall cont (sw_make_qstring value)))
(defmarshal (value :|const char*| :around cont :type string)
(let ((char* (cffi:foreign-string-alloc value)))
(unwind-protect
(funcall cont char*)
(cffi:foreign-free char*))))
(defmarshal (value :|unsigned char*| :around cont :type string)
(let ((char* (cffi:foreign-string-alloc value)))
(unwind-protect
(funcall cont char*)
(cffi:foreign-free char*))))
(defmarshal (value (:|QByteArray| :|const QByteArray&|) :around cont :type string)
(let ((qbytearray (sw_make_qbytearray value)))
(unwind-protect
(funcall cont qbytearray)
(sw_delete_qbytearray qbytearray))))
|
588b49e502277ee62604d656371a77e6df705162e32751adc3ff8620d73c41ec
|
discoproject/disco
|
worker_utils.erl
|
-module(worker_utils).
-include("common_types.hrl").
-include("disco.hrl").
-include("pipeline.hrl").
-export([annotate_input/1]).
-spec annotate_input(data_input()) -> {ok, data_input()} | {error, term()}.
annotate_input({data, _} = I) ->
% Note: we could compute data_size() here if really needed.
{ok, I};
annotate_input({dir, {Host, DirUrl, []}}) ->
Url = disco:dir_to_url(DirUrl),
Fetch = try
{ok, {_S, _H, Content}} = httpc:request(get, {Url, []},
[{version, "HTTP/1.0"}], []),
{ok, Content}
catch K:V ->
lager:error("Error (~p:~p) fetching ~p (~p): ~p",
[K, V, Url, DirUrl, erlang:get_stacktrace()]),
{error, DirUrl}
end,
case Fetch of
{ok, C} ->
{ok, {dir, {Host, DirUrl, labelled_sizes(C)}}};
{error, _} = Err ->
Err
end;
annotate_input({dir, {_H, _U, [_|_]}} = I) ->
{ok, I}.
labelled_sizes(C) when is_list(C) ->
labelled_sizes(list_to_binary(C));
labelled_sizes(C) ->
% TODO: We need to handle dir files with the old format,
% i.e. without sizes.
{match, Lines} = re:run(C, "(.*?) (.*?) (.*?)\n",
[global, {capture, all_but_first, binary}]),
LabelSizes = lists:sort([{list_to_integer(binary_to_list(L)),
list_to_integer(binary_to_list(S))}
|| [L, _, S] <- Lines]),
[labelled_group(Group) || Group <- disco_util:groupby(1, LabelSizes)].
labelled_group(Group) ->
{[L|_], Sizes} = lists:unzip(Group),
{L, lists:sum(Sizes)}.
| null |
https://raw.githubusercontent.com/discoproject/disco/be65272d3eecca184a3c8f2fa911b86ac87a4e8a/master/src/worker_utils.erl
|
erlang
|
Note: we could compute data_size() here if really needed.
TODO: We need to handle dir files with the old format,
i.e. without sizes.
|
-module(worker_utils).
-include("common_types.hrl").
-include("disco.hrl").
-include("pipeline.hrl").
-export([annotate_input/1]).
-spec annotate_input(data_input()) -> {ok, data_input()} | {error, term()}.
annotate_input({data, _} = I) ->
{ok, I};
annotate_input({dir, {Host, DirUrl, []}}) ->
Url = disco:dir_to_url(DirUrl),
Fetch = try
{ok, {_S, _H, Content}} = httpc:request(get, {Url, []},
[{version, "HTTP/1.0"}], []),
{ok, Content}
catch K:V ->
lager:error("Error (~p:~p) fetching ~p (~p): ~p",
[K, V, Url, DirUrl, erlang:get_stacktrace()]),
{error, DirUrl}
end,
case Fetch of
{ok, C} ->
{ok, {dir, {Host, DirUrl, labelled_sizes(C)}}};
{error, _} = Err ->
Err
end;
annotate_input({dir, {_H, _U, [_|_]}} = I) ->
{ok, I}.
labelled_sizes(C) when is_list(C) ->
labelled_sizes(list_to_binary(C));
labelled_sizes(C) ->
{match, Lines} = re:run(C, "(.*?) (.*?) (.*?)\n",
[global, {capture, all_but_first, binary}]),
LabelSizes = lists:sort([{list_to_integer(binary_to_list(L)),
list_to_integer(binary_to_list(S))}
|| [L, _, S] <- Lines]),
[labelled_group(Group) || Group <- disco_util:groupby(1, LabelSizes)].
labelled_group(Group) ->
{[L|_], Sizes} = lists:unzip(Group),
{L, lists:sum(Sizes)}.
|
6af5d7c30e8a27865cfb15a20bcc879bc85ce3501b3c588a61e94e652a804068
|
oakes/Nightweb
|
core.clj
|
(ns nightweb-desktop.core
(:gen-class)
(:require [clojure.java.io :as java.io]
[nightweb.router :as router]
[nightweb-desktop.server :as server]
[nightweb-desktop.utils :as utils]
[nightweb-desktop.window :as window]))
(defn get-data-dir
[]
(let [home-dir (System/getProperty "user.home")
app-name "Nightweb"
app-name-lower (clojure.string/lower-case app-name)
osx-dir (java.io/file home-dir "Library" "Application Support" app-name)
win-dir (java.io/file home-dir "AppData" "Roaming" app-name)
lin-dir (java.io/file home-dir (str "." app-name-lower))]
(.getCanonicalPath
(cond
(.exists (.getParentFile osx-dir)) osx-dir
(.exists (.getParentFile win-dir)) win-dir
(.exists lin-dir) lin-dir
:else (if-let [config-dir (System/getenv "XDG_CONFIG_HOME")]
(java.io/file config-dir app-name-lower)
(java.io/file home-dir ".config" app-name-lower))))))
(defn -main
[& args]
(router/start-router! (if (contains? (set args) "--portable")
"nightweb"
(get-data-dir)))
(server/start-server!)
(when-not (contains? (set args) "-nw")
(window/start-window!)))
| null |
https://raw.githubusercontent.com/oakes/Nightweb/089c7a99a9a875fde33cc29d56e1faf54dc9de84/desktop/src/nightweb_desktop/core.clj
|
clojure
|
(ns nightweb-desktop.core
(:gen-class)
(:require [clojure.java.io :as java.io]
[nightweb.router :as router]
[nightweb-desktop.server :as server]
[nightweb-desktop.utils :as utils]
[nightweb-desktop.window :as window]))
(defn get-data-dir
[]
(let [home-dir (System/getProperty "user.home")
app-name "Nightweb"
app-name-lower (clojure.string/lower-case app-name)
osx-dir (java.io/file home-dir "Library" "Application Support" app-name)
win-dir (java.io/file home-dir "AppData" "Roaming" app-name)
lin-dir (java.io/file home-dir (str "." app-name-lower))]
(.getCanonicalPath
(cond
(.exists (.getParentFile osx-dir)) osx-dir
(.exists (.getParentFile win-dir)) win-dir
(.exists lin-dir) lin-dir
:else (if-let [config-dir (System/getenv "XDG_CONFIG_HOME")]
(java.io/file config-dir app-name-lower)
(java.io/file home-dir ".config" app-name-lower))))))
(defn -main
[& args]
(router/start-router! (if (contains? (set args) "--portable")
"nightweb"
(get-data-dir)))
(server/start-server!)
(when-not (contains? (set args) "-nw")
(window/start-window!)))
|
|
f679aeef3f95586f1bbb1d11bad5e705dbf06221417f6e4a873548b7891a2bfd
|
gonzojive/sbcl
|
macros.lisp
|
;;;; macros, global variable definitions, and other miscellaneous support stuff
used by the rest of the PCL subsystem
This software is part of the SBCL system . See the README file for
;;;; more information.
This software is derived from software originally released by Xerox
;;;; Corporation. Copyright and release statements follow. Later modifications
;;;; to the software are in the public domain and are provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for more
;;;; information.
copyright information from original PCL sources :
;;;;
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
;;;; All rights reserved.
;;;;
;;;; Use and copying of this software and preparation of derivative works based
;;;; upon this software are permitted. Any distribution of this software or
derivative works must comply with all applicable United States export
;;;; control laws.
;;;;
This software is made available AS IS , and Xerox Corporation makes no
;;;; warranty about the software, its performance or its conformity to any
;;;; specification.
(in-package "SB!PCL")
(/show "starting pcl/macros.lisp")
;; FIXME: DECLAIM is not very ANSI of us since it only guarantees
;; declarations for this file
(declaim (declaration
As of sbcl-0.7.0.6 , SBCL actively uses this declaration
;; to propagate information needed to set up nice debug
names ( as seen e.g. in BACKTRACE ) for method functions .
%method-name
;; These nonstandard declarations seem to be used privately
within PCL itself to pass information around , so we ca n't
;; just delete them.
%class
%method-lambda-list
This declaration may also be used within PCL to pass
information around , I 'm not sure . -- WHN 2000 - 12 - 30
%variable-rebinding))
(def!constant n-fixnum-bits (integer-length sb-xc:most-positive-fixnum))
This DEFVAR was originally in defs.lisp , now moved here .
;;;
Possible values are NIL , EARLY , BRAID , or COMPLETE .
(declaim (type (member nil early braid complete) **boot-state**))
(defglobal **boot-state** nil)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *optimize-speed*
'(optimize (speed 3) (safety 0))))
(/show "done with DECLAIM DECLARATION")
(defmacro doplist ((key val) plist &body body)
"Loops over the property list PLIST binding KEY and VAL at each
iteration. In addition, .plist-tail. is bound to the tail of the
plist that has not yet been processed in the loop."
`(let ((.plist-tail. ,plist) ,key ,val)
(loop (when (null .plist-tail.) (return nil))
(setq ,key (pop .plist-tail.))
(when (null .plist-tail.)
(error "malformed plist, odd number of elements"))
(setq ,val (pop .plist-tail.))
(progn ,@body))))
(defmacro dolist-carefully ((var list improper-list-handler) &body body)
"Loops over the LIST as in DOLIST, but if the list turns out to be
improper (current head of list isn't a cons calls the handler named by
IMPROPER-LIST-HANDLER"
`(let ((,var nil)
(.dolist-carefully. ,list))
(loop (when (null .dolist-carefully.) (return nil))
(if (consp .dolist-carefully.)
(progn
(setq ,var (pop .dolist-carefully.))
,@body)
(,improper-list-handler)))))
(defmacro dotimes-fixnum ((var count &optional (result nil)) &body body)
`(dotimes (,var (the fixnum ,count) ,result)
(declare (fixnum ,var))
,@body))
(declaim (inline random-fixnum))
(defun random-fixnum ()
(random (1+ most-positive-fixnum)))
;;; Lambda which executes its body (or not) randomly. Used to drop
;;; random cache entries.
(defmacro randomly-punting-lambda (lambda-list &body body)
(with-unique-names (drops drop-pos)
`(let ((,drops (random-fixnum))
(,drop-pos ,n-fixnum-bits))
(declare (fixnum ,drops)
(type (integer 0 ,n-fixnum-bits) ,drop-pos))
(lambda ,lambda-list
(when (logbitp (the unsigned-byte (decf ,drop-pos)) ,drops)
(locally ,@body))
(when (zerop ,drop-pos)
(setf ,drops (random-fixnum)
,drop-pos ,n-fixnum-bits))))))
(defmacro function-funcall (form &rest args)
`(funcall (the function ,form) ,@args))
(defmacro function-apply (form &rest args)
`(apply (the function ,form) ,@args))
;;;; FIND-CLASS
;;;;
This is documented in the CLOS specification .
FIXME : Only compile CL - conflicting stuff to target for now . We
;;; might want to find a way to shadow find-class on the host so we
;;; can use our versions of find-class etc in code that uses SB!PCL
( SB - PCL would n't shadow CL 's symbols , but define them ) . There 's
;;; probably a way to do this already, but RED doesn't know about it.
(defun sb-xc:find-class (symbol &optional (errorp t) environment)
(declare (ignore environment))
#+sb-xc-host
(error "Unimplemented so far")
#+sb-xc
(find-class-from-cell symbol
(find-classoid-cell symbol)
errorp))
(defun (setf sb-xc:find-class) (new-value name &optional errorp environment)
(declare (ignore errorp environment))
#+sb-xc-host
(error "Unimplemented so far")
#+sb-xc
(cond ((legal-class-name-p name)
(with-single-package-locked-error
(:symbol name "Using ~A as the class-name argument in ~
(SETF FIND-CLASS)"))
(with-world-lock ()
(let ((cell (find-classoid-cell name :create new-value)))
(cond (new-value
(setf (classoid-cell-pcl-class cell) new-value)
(when (eq **boot-state** 'complete)
(let ((classoid (class-classoid new-value)))
(setf (find-classoid name) classoid)
(%set-class-type-translation new-value classoid))))
(cell
(%clear-classoid name cell)))
(when (or (eq **boot-state** 'complete)
(eq **boot-state** 'braid))
(update-ctors 'setf-find-class :class new-value :name name))
new-value)))
(t
(error "~S is not a legal class name." name))))
(/show "pcl/macros.lisp 119")
(declaim (inline legal-class-name-p))
(defun legal-class-name-p (x)
(symbolp x))
(defun get-setf-fun-name (name)
`(setf ,name))
(declaim (inline class-classoid))
(defun class-classoid (class)
(layout-classoid (class-wrapper class)))
(defvar *create-classes-from-internal-structure-definitions-p* t)
(defun find-class-from-cell (symbol cell &optional (errorp t))
(or (when cell
(or (classoid-cell-pcl-class cell)
(when *create-classes-from-internal-structure-definitions-p*
(let ((classoid (classoid-cell-classoid cell)))
(when (and classoid
(or (condition-classoid-p classoid)
(defstruct-classoid-p classoid)))
(ensure-non-standard-class symbol classoid))))))
(cond ((null errorp) nil)
((legal-class-name-p symbol)
(error "There is no class named ~S." symbol))
(t
(error "~S is not a legal class name." symbol)))))
(/show "pcl/macros.lisp 187")
FIXME : defining compiler macros for CL forms has unspecified
;;; behavior (could be an error
#+sb-xc
(define-compiler-macro sb-xc:find-class (&whole form
symbol &optional (errorp t) environment)
(declare (ignore environment))
(if (and (constantp symbol)
(legal-class-name-p (setf symbol (constant-form-value symbol)))
(constantp errorp)
(boundp '**boot-state**)
(member **boot-state** '(braid complete)))
(let ((errorp (not (null (constant-form-value errorp))))
(cell (make-symbol "CLASSOID-CELL")))
`(let ((,cell (load-time-value (find-classoid-cell ',symbol :create t))))
(or (classoid-cell-pcl-class ,cell)
,(if errorp
`(find-class-from-cell ',symbol ,cell t)
`(when (classoid-cell-classoid ,cell)
(find-class-from-cell ',symbol ,cell nil))))))
form))
#+sb-xc
(defsetf slot-value set-slot-value)
#+sb-xc-host
(defsetf slot-value-xs set-slot-value)
(/show "finished with pcl/macros.lisp")
| null |
https://raw.githubusercontent.com/gonzojive/sbcl/3210d8ed721541d5bba85cbf51831238990e33f1/src/pcl/macros.lisp
|
lisp
|
macros, global variable definitions, and other miscellaneous support stuff
more information.
Corporation. Copyright and release statements follow. Later modifications
to the software are in the public domain and are provided with
absolutely no warranty. See the COPYING and CREDITS files for more
information.
All rights reserved.
Use and copying of this software and preparation of derivative works based
upon this software are permitted. Any distribution of this software or
control laws.
warranty about the software, its performance or its conformity to any
specification.
FIXME: DECLAIM is not very ANSI of us since it only guarantees
declarations for this file
to propagate information needed to set up nice debug
These nonstandard declarations seem to be used privately
just delete them.
Lambda which executes its body (or not) randomly. Used to drop
random cache entries.
FIND-CLASS
might want to find a way to shadow find-class on the host so we
can use our versions of find-class etc in code that uses SB!PCL
probably a way to do this already, but RED doesn't know about it.
behavior (could be an error
|
used by the rest of the PCL subsystem
This software is part of the SBCL system . See the README file for
This software is derived from software originally released by Xerox
copyright information from original PCL sources :
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
derivative works must comply with all applicable United States export
This software is made available AS IS , and Xerox Corporation makes no
(in-package "SB!PCL")
(/show "starting pcl/macros.lisp")
(declaim (declaration
As of sbcl-0.7.0.6 , SBCL actively uses this declaration
names ( as seen e.g. in BACKTRACE ) for method functions .
%method-name
within PCL itself to pass information around , so we ca n't
%class
%method-lambda-list
This declaration may also be used within PCL to pass
information around , I 'm not sure . -- WHN 2000 - 12 - 30
%variable-rebinding))
(def!constant n-fixnum-bits (integer-length sb-xc:most-positive-fixnum))
This DEFVAR was originally in defs.lisp , now moved here .
Possible values are NIL , EARLY , BRAID , or COMPLETE .
(declaim (type (member nil early braid complete) **boot-state**))
(defglobal **boot-state** nil)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *optimize-speed*
'(optimize (speed 3) (safety 0))))
(/show "done with DECLAIM DECLARATION")
(defmacro doplist ((key val) plist &body body)
"Loops over the property list PLIST binding KEY and VAL at each
iteration. In addition, .plist-tail. is bound to the tail of the
plist that has not yet been processed in the loop."
`(let ((.plist-tail. ,plist) ,key ,val)
(loop (when (null .plist-tail.) (return nil))
(setq ,key (pop .plist-tail.))
(when (null .plist-tail.)
(error "malformed plist, odd number of elements"))
(setq ,val (pop .plist-tail.))
(progn ,@body))))
(defmacro dolist-carefully ((var list improper-list-handler) &body body)
"Loops over the LIST as in DOLIST, but if the list turns out to be
improper (current head of list isn't a cons calls the handler named by
IMPROPER-LIST-HANDLER"
`(let ((,var nil)
(.dolist-carefully. ,list))
(loop (when (null .dolist-carefully.) (return nil))
(if (consp .dolist-carefully.)
(progn
(setq ,var (pop .dolist-carefully.))
,@body)
(,improper-list-handler)))))
(defmacro dotimes-fixnum ((var count &optional (result nil)) &body body)
`(dotimes (,var (the fixnum ,count) ,result)
(declare (fixnum ,var))
,@body))
(declaim (inline random-fixnum))
(defun random-fixnum ()
(random (1+ most-positive-fixnum)))
(defmacro randomly-punting-lambda (lambda-list &body body)
(with-unique-names (drops drop-pos)
`(let ((,drops (random-fixnum))
(,drop-pos ,n-fixnum-bits))
(declare (fixnum ,drops)
(type (integer 0 ,n-fixnum-bits) ,drop-pos))
(lambda ,lambda-list
(when (logbitp (the unsigned-byte (decf ,drop-pos)) ,drops)
(locally ,@body))
(when (zerop ,drop-pos)
(setf ,drops (random-fixnum)
,drop-pos ,n-fixnum-bits))))))
(defmacro function-funcall (form &rest args)
`(funcall (the function ,form) ,@args))
(defmacro function-apply (form &rest args)
`(apply (the function ,form) ,@args))
This is documented in the CLOS specification .
FIXME : Only compile CL - conflicting stuff to target for now . We
( SB - PCL would n't shadow CL 's symbols , but define them ) . There 's
(defun sb-xc:find-class (symbol &optional (errorp t) environment)
(declare (ignore environment))
#+sb-xc-host
(error "Unimplemented so far")
#+sb-xc
(find-class-from-cell symbol
(find-classoid-cell symbol)
errorp))
(defun (setf sb-xc:find-class) (new-value name &optional errorp environment)
(declare (ignore errorp environment))
#+sb-xc-host
(error "Unimplemented so far")
#+sb-xc
(cond ((legal-class-name-p name)
(with-single-package-locked-error
(:symbol name "Using ~A as the class-name argument in ~
(SETF FIND-CLASS)"))
(with-world-lock ()
(let ((cell (find-classoid-cell name :create new-value)))
(cond (new-value
(setf (classoid-cell-pcl-class cell) new-value)
(when (eq **boot-state** 'complete)
(let ((classoid (class-classoid new-value)))
(setf (find-classoid name) classoid)
(%set-class-type-translation new-value classoid))))
(cell
(%clear-classoid name cell)))
(when (or (eq **boot-state** 'complete)
(eq **boot-state** 'braid))
(update-ctors 'setf-find-class :class new-value :name name))
new-value)))
(t
(error "~S is not a legal class name." name))))
(/show "pcl/macros.lisp 119")
(declaim (inline legal-class-name-p))
(defun legal-class-name-p (x)
(symbolp x))
(defun get-setf-fun-name (name)
`(setf ,name))
(declaim (inline class-classoid))
(defun class-classoid (class)
(layout-classoid (class-wrapper class)))
(defvar *create-classes-from-internal-structure-definitions-p* t)
(defun find-class-from-cell (symbol cell &optional (errorp t))
(or (when cell
(or (classoid-cell-pcl-class cell)
(when *create-classes-from-internal-structure-definitions-p*
(let ((classoid (classoid-cell-classoid cell)))
(when (and classoid
(or (condition-classoid-p classoid)
(defstruct-classoid-p classoid)))
(ensure-non-standard-class symbol classoid))))))
(cond ((null errorp) nil)
((legal-class-name-p symbol)
(error "There is no class named ~S." symbol))
(t
(error "~S is not a legal class name." symbol)))))
(/show "pcl/macros.lisp 187")
FIXME : defining compiler macros for CL forms has unspecified
#+sb-xc
(define-compiler-macro sb-xc:find-class (&whole form
symbol &optional (errorp t) environment)
(declare (ignore environment))
(if (and (constantp symbol)
(legal-class-name-p (setf symbol (constant-form-value symbol)))
(constantp errorp)
(boundp '**boot-state**)
(member **boot-state** '(braid complete)))
(let ((errorp (not (null (constant-form-value errorp))))
(cell (make-symbol "CLASSOID-CELL")))
`(let ((,cell (load-time-value (find-classoid-cell ',symbol :create t))))
(or (classoid-cell-pcl-class ,cell)
,(if errorp
`(find-class-from-cell ',symbol ,cell t)
`(when (classoid-cell-classoid ,cell)
(find-class-from-cell ',symbol ,cell nil))))))
form))
#+sb-xc
(defsetf slot-value set-slot-value)
#+sb-xc-host
(defsetf slot-value-xs set-slot-value)
(/show "finished with pcl/macros.lisp")
|
d357833867589dc3d1b6fb833fa350bd2c0cb7a1d0ba1e11fa762b735ee541db
|
droundy/iolaus-broken
|
Exec.hs
|
Copyright ( C ) 2003
--
-- This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 , 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; see the file COPYING. If not, write to
the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor ,
Boston , , USA .
# OPTIONS_GHC -cpp
# LANGUAGE CPP , ForeignFunctionInterface #
, DeriveDataTypeable # - }
module Iolaus.Exec ( system, exec_interactive,
withoutNonBlock,
Redirects, Redirect(..),
ExecException(..)
) where
import Data.Typeable ( Typeable )
#ifndef WIN32
import Control.Exception ( bracket )
import System.Posix.Env ( setEnv, getEnv, unsetEnv )
import System.Posix.IO ( queryFdOption, setFdOption, FdOption(..), stdInput )
import System.IO ( stdin )
#else
import Control.Exception ( catchJust, Exception(IOException) )
import Data.List ( isInfixOf )
#endif
import System.Exit ( ExitCode (..) )
#ifndef HAVE_REDIRECTS
import System.Cmd ( system )
#else
import System.Process.Redirects ( system )
#endif
A redirection is a three - tuple of values ( in , out , err ) .
The most common values are :
AsIs do n't change it
Null /dev / null on Unix , NUL on Windows
File open a file for reading or writing
There is also the value Stdout , which is only meaningful for
redirection of errors , and is performed AFTER stdout is
redirected so that output and errors mix together . StdIn and
StdErr could be added as well if they are useful .
NOTE : Lots of care must be taken when redirecting stdin , stdout
and stderr to one of EACH OTHER , since the ORDER in which they
are changed have a significant effect on the result .
A redirection is a three-tuple of values (in, out, err).
The most common values are:
AsIs don't change it
Null /dev/null on Unix, NUL on Windows
File open a file for reading or writing
There is also the value Stdout, which is only meaningful for
redirection of errors, and is performed AFTER stdout is
redirected so that output and errors mix together. StdIn and
StdErr could be added as well if they are useful.
NOTE: Lots of care must be taken when redirecting stdin, stdout
and stderr to one of EACH OTHER, since the ORDER in which they
are changed have a significant effect on the result.
-}
type Redirects = (Redirect, Redirect, Redirect)
data Redirect = AsIs | Null | File FilePath
| Stdout | Stderr
deriving Show
ExecException is thrown by exec if any system call fails ,
for example because the executable we 're trying to run
does n't exist .
ExecException is thrown by exec if any system call fails,
for example because the executable we're trying to run
doesn't exist.
-}
ExecException cmd args errorDesc
data ExecException = ExecException String [String] Redirects String
deriving (Typeable,Show)
_dev_null :: FilePath
#ifdef WIN32
_dev_null = "NUL"
#else
_dev_null = "/dev/null"
#endif
exec_interactive :: String -> String -> IO ExitCode
#ifndef WIN32
{-
This should handle arbitrary commands interpreted by the shell on Unix since
that's what people expect. But we don't want to allow the shell to interpret
the argument in any way, so we set an environment variable and call
cmd "$DARCS_ARGUMENT"
-}
exec_interactive cmd arg = do
let var = "DARCS_ARGUMENT"
stdin `seq` return ()
withoutNonBlock $ bracket
(do oldval <- getEnv var
setEnv var arg True
return oldval)
(\oldval ->
do case oldval of
Nothing -> unsetEnv var
Just val -> setEnv var val True)
(\_ -> withExit127 $ system $ cmd++" \"$"++var++"\"")
#else
exec_interactive cmd arg = system $ cmd ++ " " ++ arg
#endif
withoutNonBlock :: IO a -> IO a
#ifndef WIN32
Do IO without NonBlockingRead on stdInput .
This is needed when running unsuspecting external commands with interactive
mode - if read from terminal is non - blocking also write to terminal is
non - blocking .
Do IO without NonBlockingRead on stdInput.
This is needed when running unsuspecting external commands with interactive
mode - if read from terminal is non-blocking also write to terminal is
non-blocking.
-}
withoutNonBlock x =
do nb <- queryFdOption stdInput NonBlockingRead
if nb
then bracket
(do setFdOption stdInput NonBlockingRead False)
(\_ -> setFdOption stdInput NonBlockingRead True)
(\_ -> x)
else do x
#else
withoutNonBlock x = do x
#endif
Ensure that we exit 127 if the thing we are trying to run does not exist
( Only needed under Windows )
Ensure that we exit 127 if the thing we are trying to run does not exist
(Only needed under Windows)
-}
withExit127 :: IO ExitCode -> IO ExitCode
#ifdef WIN32
withExit127 a = catchJust notFoundError a (const $ return $ ExitFailure 127)
notFoundError :: Exception -> Maybe ()
notFoundError (IOException e) | "runProcess: does not exist" `isInfixOf` show e = Just ()
notFoundError _ = Nothing
#else
withExit127 = id
#endif
| null |
https://raw.githubusercontent.com/droundy/iolaus-broken/e40c001f3c5a106bf39f437d6349858e7e9bf51e/Iolaus/Exec.hs
|
haskell
|
This program is free software; you can redistribute it and/or modify
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; see the file COPYING. If not, write to
This should handle arbitrary commands interpreted by the shell on Unix since
that's what people expect. But we don't want to allow the shell to interpret
the argument in any way, so we set an environment variable and call
cmd "$DARCS_ARGUMENT"
|
Copyright ( C ) 2003
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 , or ( at your option )
You should have received a copy of the GNU General Public License
the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor ,
Boston , , USA .
# OPTIONS_GHC -cpp
# LANGUAGE CPP , ForeignFunctionInterface #
, DeriveDataTypeable # - }
module Iolaus.Exec ( system, exec_interactive,
withoutNonBlock,
Redirects, Redirect(..),
ExecException(..)
) where
import Data.Typeable ( Typeable )
#ifndef WIN32
import Control.Exception ( bracket )
import System.Posix.Env ( setEnv, getEnv, unsetEnv )
import System.Posix.IO ( queryFdOption, setFdOption, FdOption(..), stdInput )
import System.IO ( stdin )
#else
import Control.Exception ( catchJust, Exception(IOException) )
import Data.List ( isInfixOf )
#endif
import System.Exit ( ExitCode (..) )
#ifndef HAVE_REDIRECTS
import System.Cmd ( system )
#else
import System.Process.Redirects ( system )
#endif
A redirection is a three - tuple of values ( in , out , err ) .
The most common values are :
AsIs do n't change it
Null /dev / null on Unix , NUL on Windows
File open a file for reading or writing
There is also the value Stdout , which is only meaningful for
redirection of errors , and is performed AFTER stdout is
redirected so that output and errors mix together . StdIn and
StdErr could be added as well if they are useful .
NOTE : Lots of care must be taken when redirecting stdin , stdout
and stderr to one of EACH OTHER , since the ORDER in which they
are changed have a significant effect on the result .
A redirection is a three-tuple of values (in, out, err).
The most common values are:
AsIs don't change it
Null /dev/null on Unix, NUL on Windows
File open a file for reading or writing
There is also the value Stdout, which is only meaningful for
redirection of errors, and is performed AFTER stdout is
redirected so that output and errors mix together. StdIn and
StdErr could be added as well if they are useful.
NOTE: Lots of care must be taken when redirecting stdin, stdout
and stderr to one of EACH OTHER, since the ORDER in which they
are changed have a significant effect on the result.
-}
type Redirects = (Redirect, Redirect, Redirect)
data Redirect = AsIs | Null | File FilePath
| Stdout | Stderr
deriving Show
ExecException is thrown by exec if any system call fails ,
for example because the executable we 're trying to run
does n't exist .
ExecException is thrown by exec if any system call fails,
for example because the executable we're trying to run
doesn't exist.
-}
ExecException cmd args errorDesc
data ExecException = ExecException String [String] Redirects String
deriving (Typeable,Show)
_dev_null :: FilePath
#ifdef WIN32
_dev_null = "NUL"
#else
_dev_null = "/dev/null"
#endif
exec_interactive :: String -> String -> IO ExitCode
#ifndef WIN32
exec_interactive cmd arg = do
let var = "DARCS_ARGUMENT"
stdin `seq` return ()
withoutNonBlock $ bracket
(do oldval <- getEnv var
setEnv var arg True
return oldval)
(\oldval ->
do case oldval of
Nothing -> unsetEnv var
Just val -> setEnv var val True)
(\_ -> withExit127 $ system $ cmd++" \"$"++var++"\"")
#else
exec_interactive cmd arg = system $ cmd ++ " " ++ arg
#endif
withoutNonBlock :: IO a -> IO a
#ifndef WIN32
Do IO without NonBlockingRead on stdInput .
This is needed when running unsuspecting external commands with interactive
mode - if read from terminal is non - blocking also write to terminal is
non - blocking .
Do IO without NonBlockingRead on stdInput.
This is needed when running unsuspecting external commands with interactive
mode - if read from terminal is non-blocking also write to terminal is
non-blocking.
-}
withoutNonBlock x =
do nb <- queryFdOption stdInput NonBlockingRead
if nb
then bracket
(do setFdOption stdInput NonBlockingRead False)
(\_ -> setFdOption stdInput NonBlockingRead True)
(\_ -> x)
else do x
#else
withoutNonBlock x = do x
#endif
Ensure that we exit 127 if the thing we are trying to run does not exist
( Only needed under Windows )
Ensure that we exit 127 if the thing we are trying to run does not exist
(Only needed under Windows)
-}
withExit127 :: IO ExitCode -> IO ExitCode
#ifdef WIN32
withExit127 a = catchJust notFoundError a (const $ return $ ExitFailure 127)
notFoundError :: Exception -> Maybe ()
notFoundError (IOException e) | "runProcess: does not exist" `isInfixOf` show e = Just ()
notFoundError _ = Nothing
#else
withExit127 = id
#endif
|
570df2c3381efd75af2bc08e51a2adf7a82d947dfc6f046023251cd3652652d1
|
softlab-ntua/bencherl
|
pcmark.erl
|
%%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
Author :
Created : 17 Dec 2009 by Björn - Egil Dahlberg
-module(pcmark).
-export([bench_args/2, run/3]).
-define(etstables, [ets1,ets2,ets3,ets4,ets5]).
%% abstract
%%
bench_args(Version, Conf) ->
{_,Cores} = lists:keyfind(number_of_cores, 1, Conf),
[F1, F2, F3] = case Version of
short -> [4, 8, 8];
intermediate -> [4, 19, 19];
long -> [4, 29, 29]
end,
[[A,B,C] || A <- [F1 * Cores], B <- [F2 * Cores], C <- [F3 * Cores]].
run([Size,Ongoing,Total|_], _, _) ->
init_ets(?etstables, Size),
master(init_procs(Ongoing), Total - Ongoing),
[ets:delete(T) || T <- ?etstables],
ok.
master(Pids, 0) ->
[receive {Pid, done} -> ok end || Pid <- Pids],
ok;
master(Pids, N) ->
receive
{Pid, done} -> Me = self(),
New = spawn_link(fun() -> worker(Me) end),
master([New|lists:delete(Pid, Pids)], N - 1)
end.
worker(Parent) ->
S = lists:foldl(fun (T, EA) ->
Ttotal = ets:foldl(fun ({K, V}, TA) ->
ets:insert(T, {K, V + 1 }),
TA + V
end, 0, T),
Ttotal + EA
end, 0, ?etstables),
do(S),
Parent ! {self(), done}.
do(S) -> do(S,0).
do(S, N) when S > 0 ->
do(S - 1, N + S);
do(_,_) -> ok.
init_procs(Ongoing) ->
Me = self(),
lists:foldl(fun (_,Pids) -> [spawn_link(fun() -> worker(Me) end)|Pids] end, [], lists:seq(1, Ongoing)).
init_ets([], _) -> ok;
init_ets([T|Ts], Size) ->
ets:new(T, [public, named_table, ordered_set]),
lists:foreach(fun(I) ->
ets:insert(T, {I, 1})
end, lists:seq(1, Size)),
init_ets(Ts, Size).
| null |
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/bench/pcmark/src/pcmark.erl
|
erlang
|
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
abstract
|
Copyright Ericsson AB 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
Author :
Created : 17 Dec 2009 by Björn - Egil Dahlberg
-module(pcmark).
-export([bench_args/2, run/3]).
-define(etstables, [ets1,ets2,ets3,ets4,ets5]).
bench_args(Version, Conf) ->
{_,Cores} = lists:keyfind(number_of_cores, 1, Conf),
[F1, F2, F3] = case Version of
short -> [4, 8, 8];
intermediate -> [4, 19, 19];
long -> [4, 29, 29]
end,
[[A,B,C] || A <- [F1 * Cores], B <- [F2 * Cores], C <- [F3 * Cores]].
run([Size,Ongoing,Total|_], _, _) ->
init_ets(?etstables, Size),
master(init_procs(Ongoing), Total - Ongoing),
[ets:delete(T) || T <- ?etstables],
ok.
master(Pids, 0) ->
[receive {Pid, done} -> ok end || Pid <- Pids],
ok;
master(Pids, N) ->
receive
{Pid, done} -> Me = self(),
New = spawn_link(fun() -> worker(Me) end),
master([New|lists:delete(Pid, Pids)], N - 1)
end.
worker(Parent) ->
S = lists:foldl(fun (T, EA) ->
Ttotal = ets:foldl(fun ({K, V}, TA) ->
ets:insert(T, {K, V + 1 }),
TA + V
end, 0, T),
Ttotal + EA
end, 0, ?etstables),
do(S),
Parent ! {self(), done}.
do(S) -> do(S,0).
do(S, N) when S > 0 ->
do(S - 1, N + S);
do(_,_) -> ok.
init_procs(Ongoing) ->
Me = self(),
lists:foldl(fun (_,Pids) -> [spawn_link(fun() -> worker(Me) end)|Pids] end, [], lists:seq(1, Ongoing)).
init_ets([], _) -> ok;
init_ets([T|Ts], Size) ->
ets:new(T, [public, named_table, ordered_set]),
lists:foreach(fun(I) ->
ets:insert(T, {I, 1})
end, lists:seq(1, Size)),
init_ets(Ts, Size).
|
706b35f1de60c7623f766317270a285c53a939a4dd14bd196f65d7fca976b5a8
|
flora-pm/flora-server
|
File.hs
|
module Log.Backend.File where
import Data.Aeson qualified as Aeson
import Data.ByteString.Char8 qualified as BS
import Data.ByteString.Lazy qualified as BSL
import Data.Kind (Type)
import Effectful
import Effectful.Log qualified as Log
import GHC.Generics (Generic)
import Log (Logger)
import Log.Internal.Logger (withLogger)
import System.IO (stdout)
data FileBackendConfig = FileBackendConfig
{ destinationFile :: FilePath
}
deriving stock (Eq, Ord, Show, Generic)
withJSONFileBackend
:: forall (es :: [Effect]) (a :: Type)
. IOE :> es
=> FileBackendConfig
-> (Logger -> Eff es a)
-> Eff es a
withJSONFileBackend FileBackendConfig{destinationFile} action = withRunInIO $ \unlift -> do
liftIO $ BS.hPutStrLn stdout $ BS.pack $ "Redirecting logs to " <> destinationFile
logger <- liftIO $ Log.mkLogger "file-json" $ \msg -> liftIO $ do
BS.appendFile destinationFile (BSL.toStrict $ Aeson.encode msg <> "\n")
withLogger logger (unlift . action)
| null |
https://raw.githubusercontent.com/flora-pm/flora-server/c214c0b5d5db71a8330eb69326284be5a4d5e858/src/orphans/Log/Backend/File.hs
|
haskell
|
module Log.Backend.File where
import Data.Aeson qualified as Aeson
import Data.ByteString.Char8 qualified as BS
import Data.ByteString.Lazy qualified as BSL
import Data.Kind (Type)
import Effectful
import Effectful.Log qualified as Log
import GHC.Generics (Generic)
import Log (Logger)
import Log.Internal.Logger (withLogger)
import System.IO (stdout)
data FileBackendConfig = FileBackendConfig
{ destinationFile :: FilePath
}
deriving stock (Eq, Ord, Show, Generic)
withJSONFileBackend
:: forall (es :: [Effect]) (a :: Type)
. IOE :> es
=> FileBackendConfig
-> (Logger -> Eff es a)
-> Eff es a
withJSONFileBackend FileBackendConfig{destinationFile} action = withRunInIO $ \unlift -> do
liftIO $ BS.hPutStrLn stdout $ BS.pack $ "Redirecting logs to " <> destinationFile
logger <- liftIO $ Log.mkLogger "file-json" $ \msg -> liftIO $ do
BS.appendFile destinationFile (BSL.toStrict $ Aeson.encode msg <> "\n")
withLogger logger (unlift . action)
|
|
84adbf1c9959c4d27b013f4b4e08c5b2597fc0dd1d4649d3eeddf838f452cabf
|
DavidAlphaFox/RabbitMQ
|
rabbit_federation_status.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 Federation .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
%%
-module(rabbit_federation_status).
-behaviour(gen_server).
-include_lib("amqp_client/include/amqp_client.hrl").
-include("rabbit_federation.hrl").
-export([start_link/0]).
-export([report/4, remove_exchange_or_queue/1, remove/2, status/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-import(rabbit_federation_util, [name/1]).
-define(SERVER, ?MODULE).
-define(ETS_NAME, ?MODULE).
-record(state, {}).
-record(entry, {key, uri, status, timestamp}).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
report(Upstream, UParams, XorQName, Status) ->
gen_server:cast(?SERVER, {report, Upstream, UParams, XorQName, Status,
calendar:local_time()}).
remove_exchange_or_queue(XorQName) ->
gen_server:call(?SERVER, {remove_exchange_or_queue, XorQName}, infinity).
remove(Upstream, XorQName) ->
gen_server:call(?SERVER, {remove, Upstream, XorQName}, infinity).
status() ->
gen_server:call(?SERVER, status, infinity).
init([]) ->
?ETS_NAME = ets:new(?ETS_NAME,
[named_table, {keypos, #entry.key}, private]),
{ok, #state{}}.
handle_call({remove_exchange_or_queue, XorQName}, _From, State) ->
[link_gone(Entry)
|| Entry <- ets:match_object(?ETS_NAME, match_entry(xorqkey(XorQName)))],
{reply, ok, State};
handle_call({remove, Upstream, XorQName}, _From, State) ->
case ets:match_object(?ETS_NAME, match_entry(key(XorQName, Upstream))) of
[Entry] -> link_gone(Entry);
[] -> ok
end,
{reply, ok, State};
handle_call(status, _From, State) ->
Entries = ets:tab2list(?ETS_NAME),
{reply, [format(Entry) || Entry <- Entries], State}.
handle_cast({report, Upstream, #upstream_params{safe_uri = URI},
XorQName, Status, Timestamp}, State) ->
Entry = #entry{key = key(XorQName, Upstream),
status = Status,
uri = URI,
timestamp = Timestamp},
true = ets:insert(?ETS_NAME, Entry),
rabbit_event:notify(federation_link_status, format(Entry)),
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
format(#entry{status = Status,
uri = URI,
timestamp = Timestamp} = Entry) ->
identity(Entry) ++ split_status(Status) ++ [{uri, URI},
{timestamp, Timestamp}].
identity(#entry{key = {#resource{virtual_host = VHost,
kind = Type,
name = XorQNameBin},
UpstreamName, UXorQNameBin}}) ->
case Type of
exchange -> [{exchange, XorQNameBin},
{upstream_exchange, UXorQNameBin}];
queue -> [{queue, XorQNameBin},
{upstream_queue, UXorQNameBin}]
end ++ [{type, Type},
{vhost, VHost},
{upstream, UpstreamName}].
split_status({running, ConnName}) -> [{status, running},
{local_connection, ConnName}];
split_status({Status, Error}) -> [{status, Status},
{error, Error}];
split_status(Status) when is_atom(Status) -> [{status, Status}].
link_gone(Entry) ->
rabbit_event:notify(federation_link_removed, identity(Entry)),
true = ets:delete_object(?ETS_NAME, Entry).
%% We don't want to key off the entire upstream, bits of it may change
key(XName = #resource{kind = exchange}, #upstream{name = UpstreamName,
exchange_name = UXNameBin}) ->
{XName, UpstreamName, UXNameBin};
key(QName = #resource{kind = queue}, #upstream{name = UpstreamName,
queue_name = UQNameBin}) ->
{QName, UpstreamName, UQNameBin}.
xorqkey(XorQName) ->
{XorQName, '_', '_'}.
match_entry(Key) ->
#entry{key = Key,
uri = '_',
status = '_',
timestamp = '_'}.
| null |
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/rabbitmq-federation/src/rabbit_federation_status.erl
|
erlang
|
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
We don't want to key off the entire upstream, bits of it may change
|
The contents of this file are subject to the Mozilla Public License
Version 1.1 ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ Federation .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
-module(rabbit_federation_status).
-behaviour(gen_server).
-include_lib("amqp_client/include/amqp_client.hrl").
-include("rabbit_federation.hrl").
-export([start_link/0]).
-export([report/4, remove_exchange_or_queue/1, remove/2, status/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-import(rabbit_federation_util, [name/1]).
-define(SERVER, ?MODULE).
-define(ETS_NAME, ?MODULE).
-record(state, {}).
-record(entry, {key, uri, status, timestamp}).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
report(Upstream, UParams, XorQName, Status) ->
gen_server:cast(?SERVER, {report, Upstream, UParams, XorQName, Status,
calendar:local_time()}).
remove_exchange_or_queue(XorQName) ->
gen_server:call(?SERVER, {remove_exchange_or_queue, XorQName}, infinity).
remove(Upstream, XorQName) ->
gen_server:call(?SERVER, {remove, Upstream, XorQName}, infinity).
status() ->
gen_server:call(?SERVER, status, infinity).
init([]) ->
?ETS_NAME = ets:new(?ETS_NAME,
[named_table, {keypos, #entry.key}, private]),
{ok, #state{}}.
handle_call({remove_exchange_or_queue, XorQName}, _From, State) ->
[link_gone(Entry)
|| Entry <- ets:match_object(?ETS_NAME, match_entry(xorqkey(XorQName)))],
{reply, ok, State};
handle_call({remove, Upstream, XorQName}, _From, State) ->
case ets:match_object(?ETS_NAME, match_entry(key(XorQName, Upstream))) of
[Entry] -> link_gone(Entry);
[] -> ok
end,
{reply, ok, State};
handle_call(status, _From, State) ->
Entries = ets:tab2list(?ETS_NAME),
{reply, [format(Entry) || Entry <- Entries], State}.
handle_cast({report, Upstream, #upstream_params{safe_uri = URI},
XorQName, Status, Timestamp}, State) ->
Entry = #entry{key = key(XorQName, Upstream),
status = Status,
uri = URI,
timestamp = Timestamp},
true = ets:insert(?ETS_NAME, Entry),
rabbit_event:notify(federation_link_status, format(Entry)),
{noreply, State}.
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
format(#entry{status = Status,
uri = URI,
timestamp = Timestamp} = Entry) ->
identity(Entry) ++ split_status(Status) ++ [{uri, URI},
{timestamp, Timestamp}].
identity(#entry{key = {#resource{virtual_host = VHost,
kind = Type,
name = XorQNameBin},
UpstreamName, UXorQNameBin}}) ->
case Type of
exchange -> [{exchange, XorQNameBin},
{upstream_exchange, UXorQNameBin}];
queue -> [{queue, XorQNameBin},
{upstream_queue, UXorQNameBin}]
end ++ [{type, Type},
{vhost, VHost},
{upstream, UpstreamName}].
split_status({running, ConnName}) -> [{status, running},
{local_connection, ConnName}];
split_status({Status, Error}) -> [{status, Status},
{error, Error}];
split_status(Status) when is_atom(Status) -> [{status, Status}].
link_gone(Entry) ->
rabbit_event:notify(federation_link_removed, identity(Entry)),
true = ets:delete_object(?ETS_NAME, Entry).
key(XName = #resource{kind = exchange}, #upstream{name = UpstreamName,
exchange_name = UXNameBin}) ->
{XName, UpstreamName, UXNameBin};
key(QName = #resource{kind = queue}, #upstream{name = UpstreamName,
queue_name = UQNameBin}) ->
{QName, UpstreamName, UQNameBin}.
xorqkey(XorQName) ->
{XorQName, '_', '_'}.
match_entry(Key) ->
#entry{key = Key,
uri = '_',
status = '_',
timestamp = '_'}.
|
7753929492dd683c0d73aaee4f2f44a7e1c34796fd297a368850dd78f07ec1b5
|
SKA-ScienceDataProcessor/RC
|
Namespace.hs
|
module Namespace where
import Control.Monad ( liftM, filterM )
import System.Directory
import System.FilePath
data NSType = RAM | Persistent
isRam :: NSType -> Bool
isRam RAM = True
isRam _ = False
createNameSpace :: NSType -> FilePath -> IO FilePath
createNameSpace nstyp fp = do
let dirs = case nstyp of
RAM -> ["/ramdisks", "/tmp", "."]
Persistent -> ["."]
dir <- head `liftM` filterM doesDirectoryExist dirs
let fn = dir </> takeBaseName fp
createDirectoryIfMissing True fn
return fn
addNameSpace :: FilePath -> FilePath -> IO FilePath
addNameSpace outer inner = createDirectoryIfMissing True d >> return d
where d = outer </> inner
| null |
https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS3/Sketches/Utils/Namespace.hs
|
haskell
|
module Namespace where
import Control.Monad ( liftM, filterM )
import System.Directory
import System.FilePath
data NSType = RAM | Persistent
isRam :: NSType -> Bool
isRam RAM = True
isRam _ = False
createNameSpace :: NSType -> FilePath -> IO FilePath
createNameSpace nstyp fp = do
let dirs = case nstyp of
RAM -> ["/ramdisks", "/tmp", "."]
Persistent -> ["."]
dir <- head `liftM` filterM doesDirectoryExist dirs
let fn = dir </> takeBaseName fp
createDirectoryIfMissing True fn
return fn
addNameSpace :: FilePath -> FilePath -> IO FilePath
addNameSpace outer inner = createDirectoryIfMissing True d >> return d
where d = outer </> inner
|
|
4ee652e0ce367c65420a96d7522f1258c00bfa73c54198479ca4ef44fa66f9e9
|
fp-works/2019-winter-Haskell-school
|
HomeworkSpec.hs
|
module HomeworkSpec where
import Homework
import Test.Hspec
spec :: Spec
spec = do
describe "toDigits" $ do
it "returns an empty list for a negative integer" $ do
toDigits (-1) `shouldBe` []
it "returns an empty list for 0" $ do
toDigits 0 `shouldBe` []
it "returns al ist for an integer" $ do
toDigits 2341 `shouldBe` [2,3,4,1]
describe "toDigitsRev" $ do
it "returns reversed list" $ do
toDigitsRev 1234 `shouldBe` [4,3,2,1]
describe "doubleEveryOther" $ do
it "returns an empty list for an empty string" $
doubleEveryOther [] `shouldBe` []
it "returns the same list itself for a single element list" $
doubleEveryOther [1] `shouldBe` [1]
it "returns the expected list for a multiple elements list" $ do
doubleEveryOther [1, 2, 3, 4] `shouldBe` [2, 2, 6, 4]
doubleEveryOther [1, 2, 3, 4, 5] `shouldBe` [1, 4, 3, 8, 5]
describe "sumDigits" $ do
it "returns 0 for an empty string" $
sumDigits [] `shouldBe` 0
it "returns the element value for a single element list" $
sumDigits [1] `shouldBe` 1
it "returns the expected result for a list of single digit numbers" $
sumDigits [1, 2, 3, 4] `shouldBe` 10
it "returns the expected result for a list of multi digit numbers" $
sumDigits [16,7,12,5] `shouldBe` 22
describe "validate" $ do
it "returns true if is valid credit card number" $
validate 4012888888881881 `shouldBe` True
it "returns true if is valid credit card number" $
validate 4012888888881882 `shouldBe` False
describe "hanoi" $ do
it "returns correct moves with 0 disc" $ do
hanoi 0 "a" "b" "c" `shouldBe` []
it "returns correct moves with 1 disc" $ do
hanoi 1 "a" "b" "c" `shouldBe` [("a", "b")]
it "returns correct moves with 2 disc" $ do
hanoi 2 "a" "b" "c" `shouldBe` [("a","c"), ("a","b"), ("c","b")]
it "returns correct moves with 3 disc" $ do
hanoi 3 "a" "b" "c" `shouldBe` [("a", "b"), ("a", "c"), ("b", "c"),
("a", "b"), ("c", "a"), ("c", "b"),
("a", "b")]
describe "hanoi4" $ do
it "returns correct moves with 0 disc" $ do
hanoi4 0 "a" "b" "c" "d" `shouldBe` []
it "returns correct moves with 1 disc" $ do
hanoi4 1 "a" "b" "c" "d" `shouldBe` [("a", "b")]
it "returns correct number of moves with 2 disc" $ do
length (hanoi4 2 "a" "b" "c" "d") `shouldBe` 3
it "returns correct number of moves with 3 disc" $ do
length (hanoi4 3 "a" "b" "c" "d") `shouldBe` 5
it "returns correct number of moves with 15 disc" $ do
length (hanoi4 15 "a" "b" "c" "d") `shouldBe` 129
| null |
https://raw.githubusercontent.com/fp-works/2019-winter-Haskell-school/823b67f019b9e7bc0d3be36711c0cc7da4eba7d2/cis194/week1/stevemao/test/HomeworkSpec.hs
|
haskell
|
module HomeworkSpec where
import Homework
import Test.Hspec
spec :: Spec
spec = do
describe "toDigits" $ do
it "returns an empty list for a negative integer" $ do
toDigits (-1) `shouldBe` []
it "returns an empty list for 0" $ do
toDigits 0 `shouldBe` []
it "returns al ist for an integer" $ do
toDigits 2341 `shouldBe` [2,3,4,1]
describe "toDigitsRev" $ do
it "returns reversed list" $ do
toDigitsRev 1234 `shouldBe` [4,3,2,1]
describe "doubleEveryOther" $ do
it "returns an empty list for an empty string" $
doubleEveryOther [] `shouldBe` []
it "returns the same list itself for a single element list" $
doubleEveryOther [1] `shouldBe` [1]
it "returns the expected list for a multiple elements list" $ do
doubleEveryOther [1, 2, 3, 4] `shouldBe` [2, 2, 6, 4]
doubleEveryOther [1, 2, 3, 4, 5] `shouldBe` [1, 4, 3, 8, 5]
describe "sumDigits" $ do
it "returns 0 for an empty string" $
sumDigits [] `shouldBe` 0
it "returns the element value for a single element list" $
sumDigits [1] `shouldBe` 1
it "returns the expected result for a list of single digit numbers" $
sumDigits [1, 2, 3, 4] `shouldBe` 10
it "returns the expected result for a list of multi digit numbers" $
sumDigits [16,7,12,5] `shouldBe` 22
describe "validate" $ do
it "returns true if is valid credit card number" $
validate 4012888888881881 `shouldBe` True
it "returns true if is valid credit card number" $
validate 4012888888881882 `shouldBe` False
describe "hanoi" $ do
it "returns correct moves with 0 disc" $ do
hanoi 0 "a" "b" "c" `shouldBe` []
it "returns correct moves with 1 disc" $ do
hanoi 1 "a" "b" "c" `shouldBe` [("a", "b")]
it "returns correct moves with 2 disc" $ do
hanoi 2 "a" "b" "c" `shouldBe` [("a","c"), ("a","b"), ("c","b")]
it "returns correct moves with 3 disc" $ do
hanoi 3 "a" "b" "c" `shouldBe` [("a", "b"), ("a", "c"), ("b", "c"),
("a", "b"), ("c", "a"), ("c", "b"),
("a", "b")]
describe "hanoi4" $ do
it "returns correct moves with 0 disc" $ do
hanoi4 0 "a" "b" "c" "d" `shouldBe` []
it "returns correct moves with 1 disc" $ do
hanoi4 1 "a" "b" "c" "d" `shouldBe` [("a", "b")]
it "returns correct number of moves with 2 disc" $ do
length (hanoi4 2 "a" "b" "c" "d") `shouldBe` 3
it "returns correct number of moves with 3 disc" $ do
length (hanoi4 3 "a" "b" "c" "d") `shouldBe` 5
it "returns correct number of moves with 15 disc" $ do
length (hanoi4 15 "a" "b" "c" "d") `shouldBe` 129
|
|
afee60d041733fca516b92f3b67ad6107cca356756dc2e77c4fa37244842a265
|
cruxlang/crux
|
Pos.hs
|
module Crux.Pos where
data ParsePos = ParsePos
{ ppLineStart :: Int
, ppLine :: Int
, ppColumn :: Int
}
deriving (Show)
-- TODO: we should record the start and end positions of tokens
All of these numbers are one - based , because that 's how editors standardized .
( Except emacs . Emacs users will have to deal with column numbers being off
-- by one.)
data PosRec = PosRec
{ posFileName :: FilePath
, posLine :: Int
, posColumn :: Int
}
deriving (Show, Eq)
data Pos
= Pos PosRec
| SyntaxDependency FilePath
| GeneratedMainCall FilePath
| InternalErrorPos FilePath
deriving (Show, Eq)
-- TODO: eliminate references to dummyPos
dummyPos :: Pos
dummyPos = Pos $ PosRec
{ posFileName = "<dummy>"
, posLine = 0
, posColumn = 0
}
| null |
https://raw.githubusercontent.com/cruxlang/crux/883f642d15fb85ce17d9c485ee91158d9e826a2f/Crux/Pos.hs
|
haskell
|
TODO: we should record the start and end positions of tokens
by one.)
TODO: eliminate references to dummyPos
|
module Crux.Pos where
data ParsePos = ParsePos
{ ppLineStart :: Int
, ppLine :: Int
, ppColumn :: Int
}
deriving (Show)
All of these numbers are one - based , because that 's how editors standardized .
( Except emacs . Emacs users will have to deal with column numbers being off
data PosRec = PosRec
{ posFileName :: FilePath
, posLine :: Int
, posColumn :: Int
}
deriving (Show, Eq)
data Pos
= Pos PosRec
| SyntaxDependency FilePath
| GeneratedMainCall FilePath
| InternalErrorPos FilePath
deriving (Show, Eq)
dummyPos :: Pos
dummyPos = Pos $ PosRec
{ posFileName = "<dummy>"
, posLine = 0
, posColumn = 0
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.