_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 |
|---|---|---|---|---|---|---|---|---|
1f4504a391698399c2759fff4bc577abf073ecc00ea67f01a03f7557e35c9bb7 | linuxscout/festival-tts-arabic-voices | build_prosody.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
Carnegie Mellon University ; ; ;
and and ; ; ;
Copyright ( c ) 1998 - 2000 ; ; ;
All Rights Reserved . ; ; ;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
1 . The code must retain the above copyright notice , this list of ; ; ;
;;; conditions and the following disclaimer. ;;;
2 . Any modifications must be clearly marked as such . ; ; ;
3 . Original authors ' names are not deleted . ; ; ;
4 . The authors ' names are not used to endorse or promote products ; ; ;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
;;; Support Code for building prosody models ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar feat_float_types
'(segment_duration
lisp_zscore_dur
R:SylStructure.parent.syl_onsetsize
R:SylStructure.parent.syl_codasize
R:SylStructure.parent.R:Syllable.n.syl_onsetsize
R:SylStructure.parent.R:Syllable.p.syl_codasize
R:SylStructure.parent.parent.word_numsyls
pos_in_syl
R:SylStructure.parent.pos_in_word
R:SylStructure.parent.syl_in
R:SylStructure.parent.syl_out
R:SylStructure.parent.ssyl_in
R:SylStructure.parent.ssyl_out
R:SylStructure.parent.asyl_in
R:SylStructure.parent.asyl_out
R:SylStructure.parent.last_accent
R:SylStructure.parent.next_accent
R:SylStructure.parent.sub_phrases
syl_startpitch
syl_midpitch
syl_endpitch
syl_numphones
pos_in_word
syl_in
syl_out
ssyl_in
ssyl_out
sub_phrases
R:segstate.parent.R:SylStructure.parent.syl_onsetsize
R:segstate.parent.R:SylStructure.parent.syl_codasize
R:segstate.parent.R:SylStructure.parent.R:Syllable.n.syl_onsetsize
R:segstate.parent.R:SylStructure.parent.R:Syllable.p.syl_codasize
R:segstate.parent.R:SylStructure.parent.parent.word_numsyls
R:segstate.parent.R:SylStructure.parent.pos_in_word
R:segstate.parent.R:SylStructure.parent.syl_in
R:segstate.parent.R:SylStructure.parent.syl_out
R:segstate.parent.R:SylStructure.parent.ssyl_in
R:segstate.parent.R:SylStructure.parent.ssyl_out
R:segstate.parent.R:SylStructure.parent.asyl_in
R:segstate.parent.R:SylStructure.parent.asyl_out
R:segstate.parent.R:SylStructure.parent.last_accent
R:segstate.parent.R:SylStructure.parent.next_accent
R:segstate.parent.R:SylStructure.parent.sub_phrases
R:segstate.parent.R:SylStructure.parent.R:Syllable.pp.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.R:Syllable.p.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.R:Syllable.n.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.R:Syllable.nn.lisp_cg_break
))
(defvar feat_int_types
'())
(define (build_dur_feats_desc)
"(build_dur_feats_desc)
Replaces the huge list of numbers in the dur.desc file with
floats as appropriate."
(build_fix_desc_file "festival/dur/etc/dur.desc"))
(define (build_f0_feats_desc)
"(build_f0_feats_desc)
Replaces the huge list of numbers in the f0.desc file with
floats as appropriate."
(build_fix_desc_file "festival/f0/etc/f0.desc"))
(define (build_fix_desc_file descfile)
(let ((desc (car (load descfile t)))
(ofd (fopen descfile "w")))
(format ofd "(\n")
(mapcar
(lambda (fd)
(if (not (cddr fd))
(set-cdr! fd (cons 'ignore)))
(cond
((member_string (car fd) feat_float_types)
(set-cdr! fd (cons 'float)))
((member_string (car fd) feat_int_types)
(set-cdr! fd (cons 'float)))
)
(format ofd "%l\n" fd)
t)
desc)
(format ofd ")\n")
(fclose ofd)))
(define (build_dur_vec_feats_desc)
"(build_dur_feats_desc)
Replaces the huge list of numbers in the dur.desc file with
floats as appropriate."
(build_fix_desc_vec_file "festival/dur/etc/dur.desc"))
(define (build_fix_desc_vec_file descfile)
(let ((desc (car (load descfile t)))
(ofd (fopen descfile "w")))
(format ofd "(\n")
(format ofd "(durvec vector)\n")
(mapcar
(lambda (fd)
(if (not (cddr fd))
(set-cdr! fd (cons 'ignore)))
(cond
((member_string (car fd) feat_float_types)
(set-cdr! fd (cons 'float)))
((member_string (car fd) feat_int_types)
(set-cdr! fd (cons 'float)))
)
(format ofd "%l\n" fd)
t)
(cdr desc))
(format ofd ")\n")
(fclose ofd)))
(define (finalize_dur_model modelname treename)
"(finalize_dur_model modelname treename)
Take the tree and means/dur and create a scheme file which can
be useds as a duration model."
(let ((ofd (fopen (format nil "festvox/%s_dur.scm" modelname) "w"))
(silence (car (cadr (car (PhoneSet.description '(silences)))))))
(if (string-matches modelname "^(.*")
(set! modelname (string-after modelname "(")))
(if (string-matches modelname ".*)$")
(set! modelname (string-before modelname ")")))
(format ofd ";; Duration models autotrained by festvox\n")
(format ofd ";; %s\n" treename)
(format ofd "(set! %s::phone_durs '\n" modelname)
(pprintf
(cons
(list silence 0.200 0.100)
(mapcar
(lambda (x)
(if (string-equal (car (cddr x)) "nan")
(list (car x) (cadr x) 0.001)
x)
)
(load "festival/dur/etc/durs.meanstd" t)))
ofd)
(format ofd ")\n")
(format ofd "\n\n")
;; The tree wasn't trained with silence so we need to add that
(format ofd "(set! %s::zdur_tree '\n" modelname)
(format ofd "((name is %s)\n" silence)
(format ofd " ((p.R:SylStructure.parent.parent.pbreak is BB)\n")
(format ofd " ((0.0 2.0))\n")
(format ofd " ((0.0 0.0)))\n")
(pprintf
(car (load (format nil "festival/dur/tree/%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(provide '%s)\n" (string-append modelname "_dur"))
(format ofd "\n\n")
(fclose ofd)
)
)
(define (finalize_f0_model modelname treename)
"(finalize_f0_model modelname treename)
Take the F0 trees and create a scheme file which can
be used as a F0 model."
(let ((ofd (fopen (format nil "festvox/%s_f0.scm" modelname) "w")))
(format ofd ";; F0 models autotrained by festvox\n")
(format ofd ";; %s\n" treename)
(format ofd "(set! %s::start_f0 '\n" modelname)
(pprintf
(car (load (format nil "festival/f0/tree/start.%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(set! %s::mid_f0 '\n" modelname)
(pprintf
(car (load (format nil "festival/f0/tree/mid.%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(set! %s::end_f0 '\n" modelname)
(pprintf
(car (load (format nil "festival/f0/tree/end.%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(provide '%s)\n" (string-append modelname "_f0"))
(format ofd "\n\n")
(fclose ofd)
)
)
(provide 'build_prosody) | null | https://raw.githubusercontent.com/linuxscout/festival-tts-arabic-voices/ab9fe26120bf6cf3079afa2484b985cfd6ecd56a/voices/ara_norm_ziad_hts/festvox/build_prosody.scm | scheme |
;;;
; ;
; ;
; ;
; ;
;;;
Permission is hereby granted, free of charge, to use and distribute ;;;
this software and its documentation without restriction, including ;;;
without limitation the rights to use, copy, modify, merge, publish, ;;;
distribute, sublicense, and/or sell copies of this work, and to ;;;
permit persons to whom this work is furnished to do so, subject to ;;;
the following conditions: ;;;
; ;
conditions and the following disclaimer. ;;;
; ;
; ;
; ;
derived from this software without specific prior written ;;;
permission. ;;;
;;;
; ;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
; ;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
; ;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
THIS SOFTWARE. ;;;
;;;
;;;
Support Code for building prosody models ;;;
;;;
The tree wasn't trained with silence so we need to add that |
(defvar feat_float_types
'(segment_duration
lisp_zscore_dur
R:SylStructure.parent.syl_onsetsize
R:SylStructure.parent.syl_codasize
R:SylStructure.parent.R:Syllable.n.syl_onsetsize
R:SylStructure.parent.R:Syllable.p.syl_codasize
R:SylStructure.parent.parent.word_numsyls
pos_in_syl
R:SylStructure.parent.pos_in_word
R:SylStructure.parent.syl_in
R:SylStructure.parent.syl_out
R:SylStructure.parent.ssyl_in
R:SylStructure.parent.ssyl_out
R:SylStructure.parent.asyl_in
R:SylStructure.parent.asyl_out
R:SylStructure.parent.last_accent
R:SylStructure.parent.next_accent
R:SylStructure.parent.sub_phrases
syl_startpitch
syl_midpitch
syl_endpitch
syl_numphones
pos_in_word
syl_in
syl_out
ssyl_in
ssyl_out
sub_phrases
R:segstate.parent.R:SylStructure.parent.syl_onsetsize
R:segstate.parent.R:SylStructure.parent.syl_codasize
R:segstate.parent.R:SylStructure.parent.R:Syllable.n.syl_onsetsize
R:segstate.parent.R:SylStructure.parent.R:Syllable.p.syl_codasize
R:segstate.parent.R:SylStructure.parent.parent.word_numsyls
R:segstate.parent.R:SylStructure.parent.pos_in_word
R:segstate.parent.R:SylStructure.parent.syl_in
R:segstate.parent.R:SylStructure.parent.syl_out
R:segstate.parent.R:SylStructure.parent.ssyl_in
R:segstate.parent.R:SylStructure.parent.ssyl_out
R:segstate.parent.R:SylStructure.parent.asyl_in
R:segstate.parent.R:SylStructure.parent.asyl_out
R:segstate.parent.R:SylStructure.parent.last_accent
R:segstate.parent.R:SylStructure.parent.next_accent
R:segstate.parent.R:SylStructure.parent.sub_phrases
R:segstate.parent.R:SylStructure.parent.R:Syllable.pp.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.R:Syllable.p.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.R:Syllable.n.lisp_cg_break
R:segstate.parent.R:SylStructure.parent.R:Syllable.nn.lisp_cg_break
))
(defvar feat_int_types
'())
(define (build_dur_feats_desc)
"(build_dur_feats_desc)
Replaces the huge list of numbers in the dur.desc file with
floats as appropriate."
(build_fix_desc_file "festival/dur/etc/dur.desc"))
(define (build_f0_feats_desc)
"(build_f0_feats_desc)
Replaces the huge list of numbers in the f0.desc file with
floats as appropriate."
(build_fix_desc_file "festival/f0/etc/f0.desc"))
(define (build_fix_desc_file descfile)
(let ((desc (car (load descfile t)))
(ofd (fopen descfile "w")))
(format ofd "(\n")
(mapcar
(lambda (fd)
(if (not (cddr fd))
(set-cdr! fd (cons 'ignore)))
(cond
((member_string (car fd) feat_float_types)
(set-cdr! fd (cons 'float)))
((member_string (car fd) feat_int_types)
(set-cdr! fd (cons 'float)))
)
(format ofd "%l\n" fd)
t)
desc)
(format ofd ")\n")
(fclose ofd)))
(define (build_dur_vec_feats_desc)
"(build_dur_feats_desc)
Replaces the huge list of numbers in the dur.desc file with
floats as appropriate."
(build_fix_desc_vec_file "festival/dur/etc/dur.desc"))
(define (build_fix_desc_vec_file descfile)
(let ((desc (car (load descfile t)))
(ofd (fopen descfile "w")))
(format ofd "(\n")
(format ofd "(durvec vector)\n")
(mapcar
(lambda (fd)
(if (not (cddr fd))
(set-cdr! fd (cons 'ignore)))
(cond
((member_string (car fd) feat_float_types)
(set-cdr! fd (cons 'float)))
((member_string (car fd) feat_int_types)
(set-cdr! fd (cons 'float)))
)
(format ofd "%l\n" fd)
t)
(cdr desc))
(format ofd ")\n")
(fclose ofd)))
(define (finalize_dur_model modelname treename)
"(finalize_dur_model modelname treename)
Take the tree and means/dur and create a scheme file which can
be useds as a duration model."
(let ((ofd (fopen (format nil "festvox/%s_dur.scm" modelname) "w"))
(silence (car (cadr (car (PhoneSet.description '(silences)))))))
(if (string-matches modelname "^(.*")
(set! modelname (string-after modelname "(")))
(if (string-matches modelname ".*)$")
(set! modelname (string-before modelname ")")))
(format ofd ";; Duration models autotrained by festvox\n")
(format ofd ";; %s\n" treename)
(format ofd "(set! %s::phone_durs '\n" modelname)
(pprintf
(cons
(list silence 0.200 0.100)
(mapcar
(lambda (x)
(if (string-equal (car (cddr x)) "nan")
(list (car x) (cadr x) 0.001)
x)
)
(load "festival/dur/etc/durs.meanstd" t)))
ofd)
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(set! %s::zdur_tree '\n" modelname)
(format ofd "((name is %s)\n" silence)
(format ofd " ((p.R:SylStructure.parent.parent.pbreak is BB)\n")
(format ofd " ((0.0 2.0))\n")
(format ofd " ((0.0 0.0)))\n")
(pprintf
(car (load (format nil "festival/dur/tree/%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(provide '%s)\n" (string-append modelname "_dur"))
(format ofd "\n\n")
(fclose ofd)
)
)
(define (finalize_f0_model modelname treename)
"(finalize_f0_model modelname treename)
Take the F0 trees and create a scheme file which can
be used as a F0 model."
(let ((ofd (fopen (format nil "festvox/%s_f0.scm" modelname) "w")))
(format ofd ";; F0 models autotrained by festvox\n")
(format ofd ";; %s\n" treename)
(format ofd "(set! %s::start_f0 '\n" modelname)
(pprintf
(car (load (format nil "festival/f0/tree/start.%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(set! %s::mid_f0 '\n" modelname)
(pprintf
(car (load (format nil "festival/f0/tree/mid.%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(set! %s::end_f0 '\n" modelname)
(pprintf
(car (load (format nil "festival/f0/tree/end.%s" treename) t)) ofd)
(format ofd ")\n")
(format ofd "\n\n")
(format ofd "(provide '%s)\n" (string-append modelname "_f0"))
(format ofd "\n\n")
(fclose ofd)
)
)
(provide 'build_prosody) |
21a40e1175b6dbc3cbe7096b2e91b76a806c8f01b9eb5060fd2ec05b666f1536 | fraimondi/racket-asip | AsipTestBlink3.rkt | #lang racket/base
(require "AsipMain.rkt")
A simple example with 3 LEDs in a loop
(define led1 11)
(define led2 12)
(define led3 13)
(define setup
(λ ()
(open-asip)
Setting 3 pins to OUTPUT_MODE
(set-pin-mode led1 OUTPUT_MODE)
(set-pin-mode led2 OUTPUT_MODE)
(set-pin-mode led3 OUTPUT_MODE)
Turning the three pins off
(map (λ (x) (digital-write x LOW)) (list led1 led2 led3))
) ;; end of lambda
) ;; end of setup
(define lightLoop
(λ ()
(digital-write led1 HIGH)
(sleep 1)
(digital-write led1 LOW)
(digital-write led2 HIGH)
(sleep 1)
(digital-write led2 LOW)
(digital-write led3 HIGH)
(sleep 1)
(digital-write led3 LOW)
(lightLoop)
)
)
(setup)
(lightLoop) | null | https://raw.githubusercontent.com/fraimondi/racket-asip/27c67c7d5ce9537ad38cba1da03402b97cc7a7c5/AsipTestBlink3.rkt | racket | end of lambda
end of setup | #lang racket/base
(require "AsipMain.rkt")
A simple example with 3 LEDs in a loop
(define led1 11)
(define led2 12)
(define led3 13)
(define setup
(λ ()
(open-asip)
Setting 3 pins to OUTPUT_MODE
(set-pin-mode led1 OUTPUT_MODE)
(set-pin-mode led2 OUTPUT_MODE)
(set-pin-mode led3 OUTPUT_MODE)
Turning the three pins off
(map (λ (x) (digital-write x LOW)) (list led1 led2 led3))
(define lightLoop
(λ ()
(digital-write led1 HIGH)
(sleep 1)
(digital-write led1 LOW)
(digital-write led2 HIGH)
(sleep 1)
(digital-write led2 LOW)
(digital-write led3 HIGH)
(sleep 1)
(digital-write led3 LOW)
(lightLoop)
)
)
(setup)
(lightLoop) |
d09406affca21123acc74a45dd833a16cfedb84e57f6830e54238a222d12388c | fetburner/Coq2SML | classops.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
open Decl_kinds
open Term
open Evd
open Environ
open Nametab
open Mod_subst
* { 6 This is the type of class kinds }
type cl_typ =
| CL_SORT
| CL_FUN
| CL_SECVAR of variable
| CL_CONST of constant
| CL_IND of inductive
val subst_cl_typ : substitution -> cl_typ -> cl_typ
(** This is the type of infos for declared classes *)
type cl_info_typ = {
cl_param : int }
(** This is the type of coercion kinds *)
type coe_typ = Libnames.global_reference
(** This is the type of infos for declared coercions *)
type coe_info_typ
(** [cl_index] is the type of class keys *)
type cl_index
(** [coe_index] is the type of coercion keys *)
type coe_index
(** This is the type of paths from a class to another *)
type inheritance_path = coe_index list
* { 6 Access to classes infos }
val class_info : cl_typ -> (cl_index * cl_info_typ)
val class_exists : cl_typ -> bool
val class_info_from_index : cl_index -> cl_typ * cl_info_typ
(** [find_class_type env sigma c] returns the head reference of [c] and its
arguments *)
val find_class_type : evar_map -> types -> cl_typ * constr list
(** raises [Not_found] if not convertible to a class *)
val class_of : env -> evar_map -> types -> types * cl_index
(** raises [Not_found] if not mapped to a class *)
val inductive_class_of : inductive -> cl_index
val class_args_of : env -> evar_map -> types -> constr list
* { 6 [ declare_coercion ] adds a coercion in the graph of coercion paths }
val declare_coercion :
coe_typ -> locality -> isid:bool ->
src:cl_typ -> target:cl_typ -> params:int -> unit
* { 6 Access to coercions infos }
val coercion_exists : coe_typ -> bool
val coercion_value : coe_index -> (unsafe_judgment * bool)
* { 6 Lookup functions for coercion paths }
val lookup_path_between_class : cl_index * cl_index -> inheritance_path
val lookup_path_between : env -> evar_map -> types * types ->
types * types * inheritance_path
val lookup_path_to_fun_from : env -> evar_map -> types ->
types * inheritance_path
val lookup_path_to_sort_from : env -> evar_map -> types ->
types * inheritance_path
val lookup_pattern_path_between :
inductive * inductive -> (constructor * int) list
(**/**)
(* Crade *)
open Pp
val install_path_printer :
((cl_index * cl_index) * inheritance_path -> std_ppcmds) -> unit
(**/**)
* { 6 This is for printing purpose }
val string_of_class : cl_typ -> string
val pr_class : cl_typ -> std_ppcmds
val pr_cl_index : cl_index -> std_ppcmds
val get_coercion_value : coe_index -> constr
val inheritance_graph : unit -> ((cl_index * cl_index) * inheritance_path) list
val classes : unit -> cl_typ list
val coercions : unit -> coe_index list
(** [hide_coercion] returns the number of params to skip if the coercion must
be hidden, [None] otherwise; it raises [Not_found] if not a coercion *)
val hide_coercion : coe_typ -> int option
| null | https://raw.githubusercontent.com/fetburner/Coq2SML/322d613619edbb62edafa999bff24b1993f37612/coq-8.4pl4/pretyping/classops.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* This is the type of infos for declared classes
* This is the type of coercion kinds
* This is the type of infos for declared coercions
* [cl_index] is the type of class keys
* [coe_index] is the type of coercion keys
* This is the type of paths from a class to another
* [find_class_type env sigma c] returns the head reference of [c] and its
arguments
* raises [Not_found] if not convertible to a class
* raises [Not_found] if not mapped to a class
*/*
Crade
*/*
* [hide_coercion] returns the number of params to skip if the coercion must
be hidden, [None] otherwise; it raises [Not_found] if not a coercion | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Decl_kinds
open Term
open Evd
open Environ
open Nametab
open Mod_subst
* { 6 This is the type of class kinds }
type cl_typ =
| CL_SORT
| CL_FUN
| CL_SECVAR of variable
| CL_CONST of constant
| CL_IND of inductive
val subst_cl_typ : substitution -> cl_typ -> cl_typ
type cl_info_typ = {
cl_param : int }
type coe_typ = Libnames.global_reference
type coe_info_typ
type cl_index
type coe_index
type inheritance_path = coe_index list
* { 6 Access to classes infos }
val class_info : cl_typ -> (cl_index * cl_info_typ)
val class_exists : cl_typ -> bool
val class_info_from_index : cl_index -> cl_typ * cl_info_typ
val find_class_type : evar_map -> types -> cl_typ * constr list
val class_of : env -> evar_map -> types -> types * cl_index
val inductive_class_of : inductive -> cl_index
val class_args_of : env -> evar_map -> types -> constr list
* { 6 [ declare_coercion ] adds a coercion in the graph of coercion paths }
val declare_coercion :
coe_typ -> locality -> isid:bool ->
src:cl_typ -> target:cl_typ -> params:int -> unit
* { 6 Access to coercions infos }
val coercion_exists : coe_typ -> bool
val coercion_value : coe_index -> (unsafe_judgment * bool)
* { 6 Lookup functions for coercion paths }
val lookup_path_between_class : cl_index * cl_index -> inheritance_path
val lookup_path_between : env -> evar_map -> types * types ->
types * types * inheritance_path
val lookup_path_to_fun_from : env -> evar_map -> types ->
types * inheritance_path
val lookup_path_to_sort_from : env -> evar_map -> types ->
types * inheritance_path
val lookup_pattern_path_between :
inductive * inductive -> (constructor * int) list
open Pp
val install_path_printer :
((cl_index * cl_index) * inheritance_path -> std_ppcmds) -> unit
* { 6 This is for printing purpose }
val string_of_class : cl_typ -> string
val pr_class : cl_typ -> std_ppcmds
val pr_cl_index : cl_index -> std_ppcmds
val get_coercion_value : coe_index -> constr
val inheritance_graph : unit -> ((cl_index * cl_index) * inheritance_path) list
val classes : unit -> cl_typ list
val coercions : unit -> coe_index list
val hide_coercion : coe_typ -> int option
|
2d6081fb54022f9e6548de1ef3c1f16521740f2a09f728b88dae47430f9f76d0 | Compositional/reflex-servant | Product.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
-- | Some product types to choose from
--
> > > example = ( \cfg - > productCons cfg ( Proxy : : Proxy ( Cons ) ) False $ productCons cfg ( Proxy : : Proxy ( Nil ) ) True $ productNil cfg )
-- >>> example Fish
-- False :<|> True
-- >>> example Tuple
-- (False, True)
> > > example InductivePair
-- (False, (True, ()))
--
module Reflex.Servant.Internal.Product where
import Servant.API
import Data.Proxy
import GHC.Exts(Constraint)
class ProductConfig config where
type ProductOf config (ts :: [*]) :: * -- ts: Cons a b | Nil
type ProductConstraint config :: [*] -> Constraint
productNil :: config -> ProductOf config '[]
productCons :: ProductConstraint config tl => config -> Proxy tl -> hd -> ProductOf config tl -> ProductOf config (hd ': tl)
productHead :: ProductConstraint config tl => config -> Proxy tl -> ProductOf config (hd ': tl) -> hd
productTail :: ProductConstraint config tl => config -> Proxy tl -> Proxy hd -> ProductOf config (hd ': tl) -> ProductOf config tl
type ProductConstr config prod = (ProductConstraint config prod, ProductConfig config)
uncons :: forall config hd tl. ProductConstr config tl => config -> Proxy tl -> ProductOf config (hd ': tl) -> (hd, ProductOf config tl)
uncons config _p x = ( productHead config (Proxy @tl) x
, productTail config (Proxy @tl) (Proxy @hd) x
)
------------------------------------------------------------------------
class Trivial (a :: k)
instance Trivial (a :: k)
------------------------------------------------------------------------
| Using nested 2 - tuples , terminated with @()@
--
-- @
-- ()
-- (a, ())
-- (b, (a, ()))
--
-- ...
--
-- @
data InductivePair = InductivePair
type family InductivePairProduct ts where
InductivePairProduct (hd ': tl) = (hd, InductivePairProduct tl)
InductivePairProduct '[] = ()
instance ProductConfig InductivePair where
type ProductOf InductivePair ts = InductivePairProduct ts
type ProductConstraint InductivePair = Trivial
productNil _ = ()
productCons _ _ = (,)
productHead _ _ = fst
productTail _ _ _ = snd
------------------------------------------------------------------------
-- Or is it simply 'Inducktive'...
| Using servant 's ' : < | > ' , always terminating with @()@
--
-- @
-- ()
-- a ':<|>' ()
-- b ':<|>' a ':<|>' ()
--
-- ...
--
-- @
data InductiveFish = InductiveFish
type family InductiveFishProduct ts where
InductiveFishProduct (hd ': tl) = hd :<|> InductiveFishProduct tl
InductiveFishProduct '[] = ()
instance ProductConfig InductiveFish where
type ProductOf InductiveFish ts = InductiveFishProduct ts
type ProductConstraint InductiveFish = Trivial
productNil _ = ()
productCons _ _ = (:<|>)
productHead _ _ (hd :<|> _) = hd
productTail _ _ _ (_ :<|> tl) = tl
------------------------------------------------------------------------
-- | Using servant's ':<|>' operator, but without terminating with @':<|>' ()@
--
-- @
-- ()
-- a
-- b ':<|>' a
-- c ':<|>' b ':<|>' a
--
-- ...
--
-- @
data Fish = Fish
instance ProductConfig Fish where
type ProductOf Fish ts = FishProductOf ts
type ProductConstraint Fish = FishProduct
productNil _fish = ()
productCons _fish proxy hd tl = fishCons proxy hd tl
productHead _fish proxy = fishHead proxy
productTail _fish proxy = fishTail proxy
class FishProduct ts where
type FishProductOf (ts :: [*]) :: *
fishCons :: Proxy ts -> hd -> FishProductOf ts -> FishProductOf (hd ': ts)
fishHead :: Proxy ts -> FishProductOf (hd ': ts) -> hd
fishTail :: Proxy ts -> Proxy hd -> FishProductOf (hd ': ts) -> FishProductOf ts
instance FishProduct (a ': a' ': as) where
type FishProductOf (a ': a' ': as) = a :<|> FishProductOf (a' ': as)
fishCons _ hd tl = hd :<|> tl
fishHead _ (hd :<|> _h) = hd
fishTail _ _ (_t :<|> tl) = tl
instance FishProduct '[a] where
type FishProductOf '[a] = a
fishCons _ hd tl = hd :<|> tl
fishHead _ (hd :<|> _h) = hd
fishTail _ _ (_t :<|> tl) = tl
instance FishProduct '[] where
type FishProductOf '[] = ()
fishCons _ hd nil = hd
fishHead _ hd = hd
fishTail _ _ _h = ()
------------------------------------------------------------------------
-- | Using n-arity tuples then switching to nested pairs terminated by an n-arity tuple
--
-- @
-- ()
-- a
-- (b, a)
-- (c, b, a)
--
-- ...
--
-- (g, f, e, d, c, b, a)
( h , ( g , f , e , d , c , b , a ) )
( i , ( h , ( g , f , e , d , c , b , a ) ) ) ,
--
-- ...
--
-- @
data Tuple = Tuple
instance ProductConfig Tuple where
type ProductOf Tuple ts = TupleProductOf ts
type ProductConstraint Tuple = TupleProduct
productNil _ = ()
productCons _ proxy hd tl = tupleCons proxy hd tl
productHead _ proxy = tupleHead proxy
productTail _ proxy = tupleTail proxy
class TupleProduct ts where
type TupleProductOf (ts :: [*]) :: *
tupleCons :: Proxy ts -> hd -> TupleProductOf ts -> TupleProductOf (hd ': ts)
tupleHead :: Proxy ts -> TupleProductOf (hd ': ts) -> hd
tupleTail :: Proxy ts -> Proxy hd -> TupleProductOf (hd ': ts) -> TupleProductOf ts
-- | Base case 0
instance TupleProduct '[] where
type TupleProductOf '[] = ()
tupleCons _ hd _ = hd
tupleHead _ hd = hd
tupleTail _ _ _ = ()
| Base case 1
instance TupleProduct '[a0] where
type TupleProductOf '[a0] = a0
tupleCons _ hd tl = (hd, tl)
tupleHead _ (a, _) = a
tupleTail _ _ (_, a) = a
| Base case 2
instance TupleProduct '[a1, a0] where
type TupleProductOf '[a1, a0] = (a1, a0)
tupleCons _ hd (a1, a0) = (hd, a1, a0)
tupleHead _ (a, _, _) = a
tupleTail _ _ (_, a1, a0) = (a1, a0)
| Base case 3
instance TupleProduct '[a2, a1, a0] where
type TupleProductOf '[a2, a1, a0] = (a2, a1, a0)
tupleCons _ hd (a2, a1, a0) = (hd, a2, a1, a0)
tupleHead _ (a, _, _, _) = a
tupleTail _ _ (_, a2, a1, a0) = (a2, a1, a0)
| Base case 4
instance TupleProduct '[a3, a2, a1, a0] where
type TupleProductOf '[a3, a2, a1, a0] = (a3, a2, a1, a0)
tupleCons _ hd (a3, a2, a1, a0) = (hd, a3, a2, a1, a0)
tupleHead _ (a, _, _, _, _) = a
tupleTail _ _ (_, a3, a2, a1, a0) = (a3, a2, a1, a0)
| Base case 5
instance TupleProduct '[a4, a3, a2, a1, a0] where
type TupleProductOf '[a4, a3, a2, a1, a0] = (a4, a3, a2, a1, a0)
tupleCons _ hd (a4, a3, a2, a1, a0) = (hd, a4, a3, a2, a1, a0)
tupleHead _ (a, _, _, _, _, _) = a
tupleTail _ _ (_, a4, a3, a2, a1, a0) = (a4, a3, a2, a1, a0)
| Base case 6
instance TupleProduct '[a5, a4, a3, a2, a1, a0] where
type TupleProductOf '[a5, a4, a3, a2, a1, a0] = (a5, a4, a3, a2, a1, a0)
tupleCons _ hd (a5, a4, a3, a2, a1, a0) = (hd, a5, a4, a3, a2, a1, a0)
tupleHead _ (a, _, _, _, _, _, _) = a
tupleTail _ _ (_, a5, a4, a3, a2, a1, a0) = (a5, a4, a3, a2, a1, a0)
| Base case 7
instance TupleProduct '[a6, a5, a4, a3, a2, a1, a0] where
type TupleProductOf '[a6, a5, a4, a3, a2, a1, a0] = (a6, a5, a4, a3, a2, a1, a0)
7 should be enough for most , let 's switch to inductive pairs
tupleHead _ (a, _) = a
tupleTail _ _ (_, tl) = tl
-- | Inductive step, using nesting
instance ( TupleProduct (a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more)
) => TupleProduct (a7 ': a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more) where
type TupleProductOf (a7 ': a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more) =
(a7, TupleProductOf (a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more))
tupleCons _ hd tl = (hd, tl)
tupleHead _ (a, _) = a
tupleTail _ _ (_, tl) = tl
| null | https://raw.githubusercontent.com/Compositional/reflex-servant/ab29626d9643ede881572c35b8ae08f93cefe1d7/src/Reflex/Servant/Internal/Product.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE RankNTypes #
| Some product types to choose from
>>> example Fish
False :<|> True
>>> example Tuple
(False, True)
(False, (True, ()))
ts: Cons a b | Nil
----------------------------------------------------------------------
----------------------------------------------------------------------
@
()
(a, ())
(b, (a, ()))
...
@
----------------------------------------------------------------------
Or is it simply 'Inducktive'...
@
()
a ':<|>' ()
b ':<|>' a ':<|>' ()
...
@
----------------------------------------------------------------------
| Using servant's ':<|>' operator, but without terminating with @':<|>' ()@
@
()
a
b ':<|>' a
c ':<|>' b ':<|>' a
...
@
----------------------------------------------------------------------
| Using n-arity tuples then switching to nested pairs terminated by an n-arity tuple
@
()
a
(b, a)
(c, b, a)
...
(g, f, e, d, c, b, a)
...
@
| Base case 0
| Inductive step, using nesting | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
> > > example = ( \cfg - > productCons cfg ( Proxy : : Proxy ( Cons ) ) False $ productCons cfg ( Proxy : : Proxy ( Nil ) ) True $ productNil cfg )
> > > example InductivePair
module Reflex.Servant.Internal.Product where
import Servant.API
import Data.Proxy
import GHC.Exts(Constraint)
class ProductConfig config where
type ProductConstraint config :: [*] -> Constraint
productNil :: config -> ProductOf config '[]
productCons :: ProductConstraint config tl => config -> Proxy tl -> hd -> ProductOf config tl -> ProductOf config (hd ': tl)
productHead :: ProductConstraint config tl => config -> Proxy tl -> ProductOf config (hd ': tl) -> hd
productTail :: ProductConstraint config tl => config -> Proxy tl -> Proxy hd -> ProductOf config (hd ': tl) -> ProductOf config tl
type ProductConstr config prod = (ProductConstraint config prod, ProductConfig config)
uncons :: forall config hd tl. ProductConstr config tl => config -> Proxy tl -> ProductOf config (hd ': tl) -> (hd, ProductOf config tl)
uncons config _p x = ( productHead config (Proxy @tl) x
, productTail config (Proxy @tl) (Proxy @hd) x
)
class Trivial (a :: k)
instance Trivial (a :: k)
| Using nested 2 - tuples , terminated with @()@
data InductivePair = InductivePair
type family InductivePairProduct ts where
InductivePairProduct (hd ': tl) = (hd, InductivePairProduct tl)
InductivePairProduct '[] = ()
instance ProductConfig InductivePair where
type ProductOf InductivePair ts = InductivePairProduct ts
type ProductConstraint InductivePair = Trivial
productNil _ = ()
productCons _ _ = (,)
productHead _ _ = fst
productTail _ _ _ = snd
| Using servant 's ' : < | > ' , always terminating with @()@
data InductiveFish = InductiveFish
type family InductiveFishProduct ts where
InductiveFishProduct (hd ': tl) = hd :<|> InductiveFishProduct tl
InductiveFishProduct '[] = ()
instance ProductConfig InductiveFish where
type ProductOf InductiveFish ts = InductiveFishProduct ts
type ProductConstraint InductiveFish = Trivial
productNil _ = ()
productCons _ _ = (:<|>)
productHead _ _ (hd :<|> _) = hd
productTail _ _ _ (_ :<|> tl) = tl
data Fish = Fish
instance ProductConfig Fish where
type ProductOf Fish ts = FishProductOf ts
type ProductConstraint Fish = FishProduct
productNil _fish = ()
productCons _fish proxy hd tl = fishCons proxy hd tl
productHead _fish proxy = fishHead proxy
productTail _fish proxy = fishTail proxy
class FishProduct ts where
type FishProductOf (ts :: [*]) :: *
fishCons :: Proxy ts -> hd -> FishProductOf ts -> FishProductOf (hd ': ts)
fishHead :: Proxy ts -> FishProductOf (hd ': ts) -> hd
fishTail :: Proxy ts -> Proxy hd -> FishProductOf (hd ': ts) -> FishProductOf ts
instance FishProduct (a ': a' ': as) where
type FishProductOf (a ': a' ': as) = a :<|> FishProductOf (a' ': as)
fishCons _ hd tl = hd :<|> tl
fishHead _ (hd :<|> _h) = hd
fishTail _ _ (_t :<|> tl) = tl
instance FishProduct '[a] where
type FishProductOf '[a] = a
fishCons _ hd tl = hd :<|> tl
fishHead _ (hd :<|> _h) = hd
fishTail _ _ (_t :<|> tl) = tl
instance FishProduct '[] where
type FishProductOf '[] = ()
fishCons _ hd nil = hd
fishHead _ hd = hd
fishTail _ _ _h = ()
( h , ( g , f , e , d , c , b , a ) )
( i , ( h , ( g , f , e , d , c , b , a ) ) ) ,
data Tuple = Tuple
instance ProductConfig Tuple where
type ProductOf Tuple ts = TupleProductOf ts
type ProductConstraint Tuple = TupleProduct
productNil _ = ()
productCons _ proxy hd tl = tupleCons proxy hd tl
productHead _ proxy = tupleHead proxy
productTail _ proxy = tupleTail proxy
class TupleProduct ts where
type TupleProductOf (ts :: [*]) :: *
tupleCons :: Proxy ts -> hd -> TupleProductOf ts -> TupleProductOf (hd ': ts)
tupleHead :: Proxy ts -> TupleProductOf (hd ': ts) -> hd
tupleTail :: Proxy ts -> Proxy hd -> TupleProductOf (hd ': ts) -> TupleProductOf ts
instance TupleProduct '[] where
type TupleProductOf '[] = ()
tupleCons _ hd _ = hd
tupleHead _ hd = hd
tupleTail _ _ _ = ()
| Base case 1
instance TupleProduct '[a0] where
type TupleProductOf '[a0] = a0
tupleCons _ hd tl = (hd, tl)
tupleHead _ (a, _) = a
tupleTail _ _ (_, a) = a
| Base case 2
instance TupleProduct '[a1, a0] where
type TupleProductOf '[a1, a0] = (a1, a0)
tupleCons _ hd (a1, a0) = (hd, a1, a0)
tupleHead _ (a, _, _) = a
tupleTail _ _ (_, a1, a0) = (a1, a0)
| Base case 3
instance TupleProduct '[a2, a1, a0] where
type TupleProductOf '[a2, a1, a0] = (a2, a1, a0)
tupleCons _ hd (a2, a1, a0) = (hd, a2, a1, a0)
tupleHead _ (a, _, _, _) = a
tupleTail _ _ (_, a2, a1, a0) = (a2, a1, a0)
| Base case 4
instance TupleProduct '[a3, a2, a1, a0] where
type TupleProductOf '[a3, a2, a1, a0] = (a3, a2, a1, a0)
tupleCons _ hd (a3, a2, a1, a0) = (hd, a3, a2, a1, a0)
tupleHead _ (a, _, _, _, _) = a
tupleTail _ _ (_, a3, a2, a1, a0) = (a3, a2, a1, a0)
| Base case 5
instance TupleProduct '[a4, a3, a2, a1, a0] where
type TupleProductOf '[a4, a3, a2, a1, a0] = (a4, a3, a2, a1, a0)
tupleCons _ hd (a4, a3, a2, a1, a0) = (hd, a4, a3, a2, a1, a0)
tupleHead _ (a, _, _, _, _, _) = a
tupleTail _ _ (_, a4, a3, a2, a1, a0) = (a4, a3, a2, a1, a0)
| Base case 6
instance TupleProduct '[a5, a4, a3, a2, a1, a0] where
type TupleProductOf '[a5, a4, a3, a2, a1, a0] = (a5, a4, a3, a2, a1, a0)
tupleCons _ hd (a5, a4, a3, a2, a1, a0) = (hd, a5, a4, a3, a2, a1, a0)
tupleHead _ (a, _, _, _, _, _, _) = a
tupleTail _ _ (_, a5, a4, a3, a2, a1, a0) = (a5, a4, a3, a2, a1, a0)
| Base case 7
instance TupleProduct '[a6, a5, a4, a3, a2, a1, a0] where
type TupleProductOf '[a6, a5, a4, a3, a2, a1, a0] = (a6, a5, a4, a3, a2, a1, a0)
7 should be enough for most , let 's switch to inductive pairs
tupleHead _ (a, _) = a
tupleTail _ _ (_, tl) = tl
instance ( TupleProduct (a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more)
) => TupleProduct (a7 ': a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more) where
type TupleProductOf (a7 ': a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more) =
(a7, TupleProductOf (a6 ': a5 ': a4 ': a3 ': a2 ': a1 ': a0 ': more))
tupleCons _ hd tl = (hd, tl)
tupleHead _ (a, _) = a
tupleTail _ _ (_, tl) = tl
|
585cd696f310a6e170fa2562f887949bab5a1e80650562810b6ea0681b11a7be | lspitzner/brittany | Test201.hs | instance MyClass Int where
type MyType = String
myMethod :: MyType -> Int
myMethod x = x + 1
type MyType = Int
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test201.hs | haskell | instance MyClass Int where
type MyType = String
myMethod :: MyType -> Int
myMethod x = x + 1
type MyType = Int
| |
000febb402c3914543a3ff035c39faf7177f49255ce1ceabf3c4686fd4103791 | helium/blockchain-node | helium_follower_service.erl | %%%-------------------------------------------------------------------
%%
Handler module for the follower service 's streaming API / RPC
%%
%%%-------------------------------------------------------------------
-module(helium_follower_service).
-behaviour(helium_follower_follower_bhvr).
-include("grpc/autogen/server/follower_pb.hrl").
-include_lib("blockchain/include/blockchain.hrl").
-include_lib("blockchain/include/blockchain_vars.hrl").
-export([
txn_stream/2,
find_gateway/2,
subnetwork_last_reward_height/2,
active_gateways/2
]).
-export([init/2, handle_info/2]).
-type handler_state() :: #{
chain => blockchain:blockchain(),
streaming_initialized => boolean(),
txn_types => [atom()]
}.
-export_type([handler_state/0]).
-define(GW_STREAM_BATCH_SIZE, 5000).
%% -------------------------------------------------------------------
helium_follower_bhvr callback functions
%% -------------------------------------------------------------------
-spec txn_stream(follower_pb:follower_txn_stream_req_v1_pb(), grpcbox_stream:t()) ->
{ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response().
txn_stream(#follower_txn_stream_req_v1_pb{} = Msg, StreamState) ->
#{chain := Chain, streaming_initialized := StreamInitialized} =
grpcbox_stream:stream_handler_state(StreamState),
txn_stream(Chain, StreamInitialized, Msg, StreamState);
txn_stream(_Msg, StreamState) ->
lager:warning("unhandled grpc msg ~p", [_Msg]),
{ok, StreamState}.
-spec find_gateway(ctx:ctx(), follower_pb:follower_gateway_req_v1_pb()) ->
{ok, follower_pb:follower_gateway_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
find_gateway(Ctx, Req) ->
Chain = blockchain_worker:cached_blockchain(),
find_gateway(Chain, Ctx, Req).
-spec subnetwork_last_reward_height(
ctx:ctx(), follower_pb:follower_subnetwork_last_reward_height_req_v1_pb()
) ->
{ok, follower_pb:follower_subnetwork_last_reward_height_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
subnetwork_last_reward_height(Ctx, Req) ->
Chain = blockchain_worker:cached_blockchain(),
subnetwork_last_reward_height(Chain, Ctx, Req).
-spec active_gateways(follower_pb:follower_gateway_stream_req_v1_pb(), grpcbox_stream:t()) ->
{ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response().
active_gateways(#follower_gateway_stream_req_v1_pb{batch_size = BatchSize} = _Msg, StreamState) when BatchSize =< ?GW_STREAM_BATCH_SIZE ->
#{chain := Chain} = grpcbox_stream:stream_handler_state(StreamState),
case Chain of
undefined ->
lager:debug("chain not ready, returning error response for msg ~p", [_Msg]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
_ ->
Ledger = blockchain:ledger(Chain),
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
{NumGateways, FinalGws, StreamState1} =
blockchain_ledger_v1:cf_fold(
active_gateways,
fun({Addr, BinGw}, {CountAcc, GwAcc, StreamAcc}) ->
Gw = blockchain_ledger_gateway_v2:deserialize(BinGw),
Loc = blockchain_ledger_gateway_v2:location(Gw),
case Loc /= undefined of
true ->
Region = case blockchain_region_v1:h3_to_region(Loc, Ledger) of
{ok, R} -> normalize_region(R);
_ -> undefined
end,
GwResp = #follower_gateway_resp_v1_pb{
height = Height,
result = {info, #gateway_info_pb{
address = Addr,
location = h3:to_string(Loc),
owner = blockchain_ledger_gateway_v2:owner_address(Gw),
staking_mode = blockchain_ledger_gateway_v2:mode(Gw),
gain = blockchain_ledger_gateway_v2:gain(Gw),
region = Region,
%% we dont need region params in the active gw resp
%% default to empty list
region_params = #blockchain_region_params_v1_pb{
region_params = []
}
}}},
GwAcc1 = [GwResp | GwAcc],
RespLen = length(GwAcc1),
case RespLen >= BatchSize of
true ->
Resp = #follower_gateway_stream_resp_v1_pb{ gateways = GwAcc1 },
StreamAcc1 = grpcbox_stream:send(false, Resp, StreamAcc),
{CountAcc + RespLen, [], StreamAcc1};
_ ->
{CountAcc, GwAcc1, StreamAcc}
end;
_ -> {CountAcc, GwAcc, StreamAcc}
end
end, {0, [], StreamState}, Ledger),
FinalGwLen = length(FinalGws),
{FinalGwCount, StreamState3} =
case FinalGwLen > 0 of
true ->
Resp = #follower_gateway_stream_resp_v1_pb{ gateways = FinalGws },
StreamState2 = grpcbox_stream:send(false, Resp, StreamState1),
{NumGateways + FinalGwLen, StreamState2};
_ ->
{NumGateways, StreamState1}
end,
StreamState4 = grpcbox_stream:update_trailers([{<<"num_gateways">>, integer_to_binary(FinalGwCount)}], StreamState3),
{stop, StreamState4}
end;
active_gateways(#follower_gateway_stream_req_v1_pb{batch_size = BatchSize} = _Msg, _StreamState) ->
lager:info("Requested batch size exceeds maximum allowed batch count: ~p", [BatchSize]),
{grpc_error, {grpcbox_stream:code_to_status(3), <<"maximum batch size exceeded">>}};
active_gateways(_Msg, StreamState) ->
lager:warning("unhandled grpc msg ~p", [_Msg]),
{ok, StreamState}.
-spec init(atom(), grpcbox_stream:t()) -> grpcbox_stream:t().
init(_RPC, StreamState) ->
lager:debug("handler init, stream state ~p", [StreamState]),
Chain = blockchain_worker:blockchain(),
_NewStreamState = grpcbox_stream:stream_handler_state(
StreamState,
#{chain => Chain, streaming_initialized => false}
).
handle_info({blockchain_event, {add_block, BlockHash, _Sync, _Ledger}}, StreamState) ->
#{chain := Chain, txn_types := TxnTypes} = grpcbox_stream:stream_handler_state(StreamState),
case blockchain:get_block(BlockHash, Chain) of
{ok, Block} ->
Height = blockchain_block:height(Block),
Timestamp = blockchain_block:time(Block),
SortedTxns = filter_hash_sort_txns(Block, TxnTypes),
_NewStreamState = send_txn_sequence(SortedTxns, Height, Timestamp, StreamState);
_ ->
lager:error("failed to find block with hash: ~p", [BlockHash]),
StreamState
end;
handle_info(_Msg, StreamState) ->
lager:warning("unhandled info msg: ~p", [_Msg]),
StreamState.
%% -------------------------------------------------------------------
%% internal and callback breakdown functions
%% -------------------------------------------------------------------
-spec txn_stream(
blockchain:blockchain() | undefined,
boolean(),
follower_pb:follower_txn_stream_req_v1_pb(),
grpcbox_stream:t()
) ->
{ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response().
txn_stream(undefined = _Chain, _StreamInitialized, _Msg, _StreamState) ->
lager:debug("chain not ready, returning error response for msg ~p", [_Msg]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
txn_stream(_Chain, true = _StreamInitialized, _Msg, StreamState) ->
{ok, StreamState};
txn_stream(
Chain,
false = _StreamInitialized,
#follower_txn_stream_req_v1_pb{height = Height, txn_hash = Hash, txn_types = TxnTypes0} = _Msg,
StreamState
) ->
lager:debug("subscribing client to txn stream with msg ~p", [_Msg]),
ok = blockchain_event:add_handler(self()),
case validate_txn_filters(TxnTypes0) of
{error, invalid_filters} ->
{grpc_error, {grpcbox_stream:code_to_status(3), <<"invalid txn filter">>}};
{ok, TxnTypes} ->
case process_past_blocks(Height, Hash, TxnTypes, Chain, StreamState) of
{ok, StreamState1} ->
HandlerState = grpcbox_stream:stream_handler_state(StreamState1),
StreamState2 = grpcbox_stream:stream_handler_state(
StreamState1,
HandlerState#{streaming_initialized => true, txn_types => TxnTypes}
),
{ok, StreamState2};
{error, invalid_req_params} ->
{grpc_error, {
grpcbox_stream:code_to_status(3),
<<"invalid starting height, txn hash, or filter">>
}};
{error, _} ->
{grpc_error, {
grpcbox_stream:code_to_status(5), <<"requested block not found">>
}}
end
end.
-spec find_gateway(
blockchain:chain() | undefined, ctx:ctx(), follower_pb:follower_gateway_req_v1_pb()
) ->
{ok, follower_pb:follower_gateway_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
find_gateway(undefined = _Chain, _Ctx, _Req) ->
lager:debug("chain not ready, returning error response for msg ~p", [_Req]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
find_gateway(Chain, Ctx, Req) ->
Ledger = blockchain:ledger(Chain),
PubKeyBin = Req#follower_gateway_req_v1_pb.address,
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
case blockchain_ledger_v1:find_gateway_info(PubKeyBin, Ledger) of
{ok, GwInfo} ->
{Location, Region} =
case blockchain_ledger_gateway_v2:location(GwInfo) of
undefined -> {<<>>, undefined};
H3 ->
case blockchain_region_v1:h3_to_region(H3, Ledger) of
{ok, R} -> {h3:to_string(H3), normalize_region(R)};
_ -> {h3:to_string(H3), undefined}
end
end,
RegionParams =
case region_params_for_region(Region, Ledger) of
{ok, Params} -> Params;
{error, _} -> []
end,
{ok,
#follower_gateway_resp_v1_pb{
height = Height,
result = {info, #gateway_info_pb{
address = PubKeyBin,
location = Location,
owner = blockchain_ledger_gateway_v2:owner_address(GwInfo),
staking_mode = blockchain_ledger_gateway_v2:mode(GwInfo),
gain = blockchain_ledger_gateway_v2:gain(GwInfo),
region = Region,
region_params = #blockchain_region_params_v1_pb{
region_params = RegionParams
}
}}
},
Ctx};
_ ->
ErrorResult = {error, #follower_error_pb{type = {not_found, #gateway_not_found_pb{address = PubKeyBin}}}},
{ok, #follower_gateway_resp_v1_pb{height = Height, result = ErrorResult}, Ctx}
end.
-spec subnetwork_last_reward_height(
blockchain:chain() | undefined,
ctx:ctx(),
follower_pb:follower_subnetwork_last_reward_height_req_v1_pb()
) ->
{ok, follower_pb:follower_subnetwork_last_reward_height_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
subnetwork_last_reward_height(undefined = _Chain, _Ctx, _Req) ->
lager:debug("chain not ready, returning error response for msg ~p", [_Req]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
subnetwork_last_reward_height(Chain, Ctx, Req) ->
Ledger = blockchain:ledger(Chain),
TokenType = Req#follower_subnetwork_last_reward_height_req_v1_pb.token_type,
{ok, CurrentHeight} = blockchain_ledger_v1:current_height(Ledger),
case blockchain_ledger_v1:find_subnetwork_v1(TokenType, Ledger) of
{ok, SubnetworkLedger} ->
LastRewardHt = blockchain_ledger_subnetwork_v1:last_rewarded_block(SubnetworkLedger),
{ok, #follower_subnetwork_last_reward_height_resp_v1_pb{height = CurrentHeight, reward_height = LastRewardHt}, Ctx};
_ -> {grpc_error, {grpcbox_stream:code_to_status(3), <<"unable to get retrieve subnetwork for requested token">>}}
end.
-spec process_past_blocks(Height :: pos_integer(),
TxnHash :: binary(),
TxnTypes :: [atom()],
Chain :: blockchain:blockchain(),
StreamState :: grpcbox_stream:t()) -> {ok, grpcbox_stream:t()} | {error, term()}.
process_past_blocks(Height, TxnHash, TxnTypes, Chain, StreamState) when is_integer(Height) andalso Height > 0 ->
{ok, #block_info_v2{height = HeadHeight}} = blockchain:head_block_info(Chain),
case Height > HeadHeight of
%% requested a future block; nothing to do but wait
true -> {ok, StreamState};
false ->
case blockchain:get_block(Height, Chain) of
{ok, SubscribeBlock} ->
process_past_blocks_(SubscribeBlock, TxnHash, TxnTypes, HeadHeight, Chain, StreamState);
{error, not_found} ->
case blockchain:find_first_block_after(Height, Chain) of
{ok, _Height, ClosestBlock} ->
process_past_blocks_(ClosestBlock, <<>>, TxnTypes, HeadHeight, Chain, StreamState);
{error, _} = Error -> Error
end
end
end;
process_past_blocks(_Height, _TxnHash, _TxnTypes, _Chain, _StreamState) -> {error, invalid_req_params}.
-spec process_past_blocks_(StartBlock :: blockchain_block:block(),
TxnHash :: binary(),
TxnTypes :: [atom()],
HeadHeight :: pos_integer(),
Chain :: blockchain:blockchain(),
StreamState :: grpcbox_stream:t()) -> {ok, grpcbox_stream:t()}.
process_past_blocks_(StartBlock, TxnHash, TxnTypes, HeadHeight, Chain, StreamState) ->
StartHeight = blockchain_block:height(StartBlock),
StartBlockTimestamp = blockchain_block:time(StartBlock),
SortedStartTxns = filter_hash_sort_txns(StartBlock, TxnTypes),
{UnhandledTxns, _} = lists:partition(fun({H, _T}) -> H > TxnHash end, SortedStartTxns),
StreamState1 = send_txn_sequence(UnhandledTxns, StartHeight, StartBlockTimestamp, StreamState),
BlockSeq = lists:seq(StartHeight + 1, HeadHeight),
StreamState2 = lists:foldl(fun(HeightX, StateAcc) ->
{ok, BlockX} = blockchain:get_block(HeightX, Chain),
BlockXTimestamp = blockchain_block:time(BlockX),
SortedTxnsX = filter_hash_sort_txns(BlockX, TxnTypes),
_NewStateAcc = send_txn_sequence(SortedTxnsX, HeightX, BlockXTimestamp, StateAcc)
end, StreamState1, BlockSeq),
{ok, StreamState2}.
-spec filter_hash_sort_txns(blockchain_block:block(), [atom()]) -> [{binary(), blockchain_txn:txn()}].
filter_hash_sort_txns(Block, TxnTypes) ->
Txns = blockchain_block:transactions(Block),
FilteredTxns = lists:filter(fun(Txn) -> subscribed_type(blockchain_txn:type(Txn), TxnTypes) end, Txns),
HashKeyedTxns = lists:map(fun(Txn) -> {blockchain_txn:hash(Txn), Txn} end, FilteredTxns),
lists:sort(fun({H1, _T1}, {H2, _T2}) -> H1 < H2 end, HashKeyedTxns).
-spec send_txn_sequence(SortedTxns :: [{binary(), blockchain_txn:txn()}],
Height :: pos_integer(),
Timestamp :: pos_integer(),
StreamState :: grpcbox_stream:t()) -> grpcbox_stream:t().
send_txn_sequence(SortedTxns, Height, Timestamp, StreamState) ->
lists:foldl(fun({TxnHash, Txn}, StateAcc) ->
Msg = encode_follower_resp(TxnHash, Txn, Height, Timestamp),
grpcbox_stream:send(false, Msg, StateAcc)
end, StreamState, SortedTxns).
-spec encode_follower_resp(TxnHash :: binary(),
Txn :: blockchain_txn:txn(),
TxnHeight :: pos_integer(),
Timestamp :: pos_integer()) -> follower_pb:follower_resp_v1_pb().
encode_follower_resp(TxnHash, Txn, TxnHeight, Timestamp) ->
#follower_txn_stream_resp_v1_pb{
height = TxnHeight,
txn_hash = TxnHash,
txn = blockchain_txn:wrap_txn(Txn),
timestamp = Timestamp
}.
subscribed_type(_Type, []) -> true;
subscribed_type(Type, FilterTypes) -> lists:member(Type, FilterTypes).
validate_txn_filters(TxnFilters0) ->
case
(catch lists:foldl(
fun
(BinType, AtomTypes) when is_binary(BinType) ->
[binary_to_existing_atom(BinType, utf8) | AtomTypes];
(BinType, AtomTypes) when is_list(BinType) ->
[list_to_existing_atom(BinType) | AtomTypes]
end,
[],
TxnFilters0
))
of
{'EXIT', _} ->
{error, invalid_filter};
TxnFilters when is_list(TxnFilters) ->
case lists:all(fun is_blockchain_txn/1, TxnFilters) of
true -> {ok, TxnFilters};
false -> {error, invalid_filters}
end
end.
is_blockchain_txn(Module) ->
ModInfo = Module:module_info(attributes),
lists:any(fun({behavior, [blockchain_txn]}) -> true; (_) -> false end, ModInfo).
%% blockchain_region_v1 returns region as an atom with a 'region_' prefix, ie
' region_us915 ' etc , we need it without the prefix and capitalised to
%% be compatible with the proto
normalize_region(V) ->
list_to_atom(string:to_upper(string:slice(atom_to_list(V), 7))).
-spec region_params_for_region(atom(), blockchain_ledger_v1:ledger()) ->
{ok, [blockchain_region_param_v1:region_param_v1()]} | {error, no_params_for_region}.
region_params_for_region(Region, Ledger) ->
case blockchain_region_params_v1:for_region(Region, Ledger) of
{error, Reason} ->
lager:error(
"Could not get params for region: ~p, reason: ~p",
[Region, Reason]
),
{error, no_params_for_region};
{ok, Params} ->
{ok, Params}
end.
| null | https://raw.githubusercontent.com/helium/blockchain-node/6e7b470ffd2622be867e9002da99bbdc7cefb80a/src/helium_follower_service.erl | erlang | -------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
we dont need region params in the active gw resp
default to empty list
-------------------------------------------------------------------
internal and callback breakdown functions
-------------------------------------------------------------------
requested a future block; nothing to do but wait
blockchain_region_v1 returns region as an atom with a 'region_' prefix, ie
be compatible with the proto | Handler module for the follower service 's streaming API / RPC
-module(helium_follower_service).
-behaviour(helium_follower_follower_bhvr).
-include("grpc/autogen/server/follower_pb.hrl").
-include_lib("blockchain/include/blockchain.hrl").
-include_lib("blockchain/include/blockchain_vars.hrl").
-export([
txn_stream/2,
find_gateway/2,
subnetwork_last_reward_height/2,
active_gateways/2
]).
-export([init/2, handle_info/2]).
-type handler_state() :: #{
chain => blockchain:blockchain(),
streaming_initialized => boolean(),
txn_types => [atom()]
}.
-export_type([handler_state/0]).
-define(GW_STREAM_BATCH_SIZE, 5000).
helium_follower_bhvr callback functions
-spec txn_stream(follower_pb:follower_txn_stream_req_v1_pb(), grpcbox_stream:t()) ->
{ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response().
txn_stream(#follower_txn_stream_req_v1_pb{} = Msg, StreamState) ->
#{chain := Chain, streaming_initialized := StreamInitialized} =
grpcbox_stream:stream_handler_state(StreamState),
txn_stream(Chain, StreamInitialized, Msg, StreamState);
txn_stream(_Msg, StreamState) ->
lager:warning("unhandled grpc msg ~p", [_Msg]),
{ok, StreamState}.
-spec find_gateway(ctx:ctx(), follower_pb:follower_gateway_req_v1_pb()) ->
{ok, follower_pb:follower_gateway_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
find_gateway(Ctx, Req) ->
Chain = blockchain_worker:cached_blockchain(),
find_gateway(Chain, Ctx, Req).
-spec subnetwork_last_reward_height(
ctx:ctx(), follower_pb:follower_subnetwork_last_reward_height_req_v1_pb()
) ->
{ok, follower_pb:follower_subnetwork_last_reward_height_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
subnetwork_last_reward_height(Ctx, Req) ->
Chain = blockchain_worker:cached_blockchain(),
subnetwork_last_reward_height(Chain, Ctx, Req).
-spec active_gateways(follower_pb:follower_gateway_stream_req_v1_pb(), grpcbox_stream:t()) ->
{ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response().
active_gateways(#follower_gateway_stream_req_v1_pb{batch_size = BatchSize} = _Msg, StreamState) when BatchSize =< ?GW_STREAM_BATCH_SIZE ->
#{chain := Chain} = grpcbox_stream:stream_handler_state(StreamState),
case Chain of
undefined ->
lager:debug("chain not ready, returning error response for msg ~p", [_Msg]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
_ ->
Ledger = blockchain:ledger(Chain),
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
{NumGateways, FinalGws, StreamState1} =
blockchain_ledger_v1:cf_fold(
active_gateways,
fun({Addr, BinGw}, {CountAcc, GwAcc, StreamAcc}) ->
Gw = blockchain_ledger_gateway_v2:deserialize(BinGw),
Loc = blockchain_ledger_gateway_v2:location(Gw),
case Loc /= undefined of
true ->
Region = case blockchain_region_v1:h3_to_region(Loc, Ledger) of
{ok, R} -> normalize_region(R);
_ -> undefined
end,
GwResp = #follower_gateway_resp_v1_pb{
height = Height,
result = {info, #gateway_info_pb{
address = Addr,
location = h3:to_string(Loc),
owner = blockchain_ledger_gateway_v2:owner_address(Gw),
staking_mode = blockchain_ledger_gateway_v2:mode(Gw),
gain = blockchain_ledger_gateway_v2:gain(Gw),
region = Region,
region_params = #blockchain_region_params_v1_pb{
region_params = []
}
}}},
GwAcc1 = [GwResp | GwAcc],
RespLen = length(GwAcc1),
case RespLen >= BatchSize of
true ->
Resp = #follower_gateway_stream_resp_v1_pb{ gateways = GwAcc1 },
StreamAcc1 = grpcbox_stream:send(false, Resp, StreamAcc),
{CountAcc + RespLen, [], StreamAcc1};
_ ->
{CountAcc, GwAcc1, StreamAcc}
end;
_ -> {CountAcc, GwAcc, StreamAcc}
end
end, {0, [], StreamState}, Ledger),
FinalGwLen = length(FinalGws),
{FinalGwCount, StreamState3} =
case FinalGwLen > 0 of
true ->
Resp = #follower_gateway_stream_resp_v1_pb{ gateways = FinalGws },
StreamState2 = grpcbox_stream:send(false, Resp, StreamState1),
{NumGateways + FinalGwLen, StreamState2};
_ ->
{NumGateways, StreamState1}
end,
StreamState4 = grpcbox_stream:update_trailers([{<<"num_gateways">>, integer_to_binary(FinalGwCount)}], StreamState3),
{stop, StreamState4}
end;
active_gateways(#follower_gateway_stream_req_v1_pb{batch_size = BatchSize} = _Msg, _StreamState) ->
lager:info("Requested batch size exceeds maximum allowed batch count: ~p", [BatchSize]),
{grpc_error, {grpcbox_stream:code_to_status(3), <<"maximum batch size exceeded">>}};
active_gateways(_Msg, StreamState) ->
lager:warning("unhandled grpc msg ~p", [_Msg]),
{ok, StreamState}.
-spec init(atom(), grpcbox_stream:t()) -> grpcbox_stream:t().
init(_RPC, StreamState) ->
lager:debug("handler init, stream state ~p", [StreamState]),
Chain = blockchain_worker:blockchain(),
_NewStreamState = grpcbox_stream:stream_handler_state(
StreamState,
#{chain => Chain, streaming_initialized => false}
).
handle_info({blockchain_event, {add_block, BlockHash, _Sync, _Ledger}}, StreamState) ->
#{chain := Chain, txn_types := TxnTypes} = grpcbox_stream:stream_handler_state(StreamState),
case blockchain:get_block(BlockHash, Chain) of
{ok, Block} ->
Height = blockchain_block:height(Block),
Timestamp = blockchain_block:time(Block),
SortedTxns = filter_hash_sort_txns(Block, TxnTypes),
_NewStreamState = send_txn_sequence(SortedTxns, Height, Timestamp, StreamState);
_ ->
lager:error("failed to find block with hash: ~p", [BlockHash]),
StreamState
end;
handle_info(_Msg, StreamState) ->
lager:warning("unhandled info msg: ~p", [_Msg]),
StreamState.
-spec txn_stream(
blockchain:blockchain() | undefined,
boolean(),
follower_pb:follower_txn_stream_req_v1_pb(),
grpcbox_stream:t()
) ->
{ok, grpcbox_stream:t()} | grpcbox_stream:grpc_error_response().
txn_stream(undefined = _Chain, _StreamInitialized, _Msg, _StreamState) ->
lager:debug("chain not ready, returning error response for msg ~p", [_Msg]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
txn_stream(_Chain, true = _StreamInitialized, _Msg, StreamState) ->
{ok, StreamState};
txn_stream(
Chain,
false = _StreamInitialized,
#follower_txn_stream_req_v1_pb{height = Height, txn_hash = Hash, txn_types = TxnTypes0} = _Msg,
StreamState
) ->
lager:debug("subscribing client to txn stream with msg ~p", [_Msg]),
ok = blockchain_event:add_handler(self()),
case validate_txn_filters(TxnTypes0) of
{error, invalid_filters} ->
{grpc_error, {grpcbox_stream:code_to_status(3), <<"invalid txn filter">>}};
{ok, TxnTypes} ->
case process_past_blocks(Height, Hash, TxnTypes, Chain, StreamState) of
{ok, StreamState1} ->
HandlerState = grpcbox_stream:stream_handler_state(StreamState1),
StreamState2 = grpcbox_stream:stream_handler_state(
StreamState1,
HandlerState#{streaming_initialized => true, txn_types => TxnTypes}
),
{ok, StreamState2};
{error, invalid_req_params} ->
{grpc_error, {
grpcbox_stream:code_to_status(3),
<<"invalid starting height, txn hash, or filter">>
}};
{error, _} ->
{grpc_error, {
grpcbox_stream:code_to_status(5), <<"requested block not found">>
}}
end
end.
-spec find_gateway(
blockchain:chain() | undefined, ctx:ctx(), follower_pb:follower_gateway_req_v1_pb()
) ->
{ok, follower_pb:follower_gateway_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
find_gateway(undefined = _Chain, _Ctx, _Req) ->
lager:debug("chain not ready, returning error response for msg ~p", [_Req]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
find_gateway(Chain, Ctx, Req) ->
Ledger = blockchain:ledger(Chain),
PubKeyBin = Req#follower_gateway_req_v1_pb.address,
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
case blockchain_ledger_v1:find_gateway_info(PubKeyBin, Ledger) of
{ok, GwInfo} ->
{Location, Region} =
case blockchain_ledger_gateway_v2:location(GwInfo) of
undefined -> {<<>>, undefined};
H3 ->
case blockchain_region_v1:h3_to_region(H3, Ledger) of
{ok, R} -> {h3:to_string(H3), normalize_region(R)};
_ -> {h3:to_string(H3), undefined}
end
end,
RegionParams =
case region_params_for_region(Region, Ledger) of
{ok, Params} -> Params;
{error, _} -> []
end,
{ok,
#follower_gateway_resp_v1_pb{
height = Height,
result = {info, #gateway_info_pb{
address = PubKeyBin,
location = Location,
owner = blockchain_ledger_gateway_v2:owner_address(GwInfo),
staking_mode = blockchain_ledger_gateway_v2:mode(GwInfo),
gain = blockchain_ledger_gateway_v2:gain(GwInfo),
region = Region,
region_params = #blockchain_region_params_v1_pb{
region_params = RegionParams
}
}}
},
Ctx};
_ ->
ErrorResult = {error, #follower_error_pb{type = {not_found, #gateway_not_found_pb{address = PubKeyBin}}}},
{ok, #follower_gateway_resp_v1_pb{height = Height, result = ErrorResult}, Ctx}
end.
-spec subnetwork_last_reward_height(
blockchain:chain() | undefined,
ctx:ctx(),
follower_pb:follower_subnetwork_last_reward_height_req_v1_pb()
) ->
{ok, follower_pb:follower_subnetwork_last_reward_height_resp_v1_pb(), ctx:ctx()}
| grpcbox_stream:grpc_error_response().
subnetwork_last_reward_height(undefined = _Chain, _Ctx, _Req) ->
lager:debug("chain not ready, returning error response for msg ~p", [_Req]),
{grpc_error, {grpcbox_stream:code_to_status(14), <<"temporarily unavailable">>}};
subnetwork_last_reward_height(Chain, Ctx, Req) ->
Ledger = blockchain:ledger(Chain),
TokenType = Req#follower_subnetwork_last_reward_height_req_v1_pb.token_type,
{ok, CurrentHeight} = blockchain_ledger_v1:current_height(Ledger),
case blockchain_ledger_v1:find_subnetwork_v1(TokenType, Ledger) of
{ok, SubnetworkLedger} ->
LastRewardHt = blockchain_ledger_subnetwork_v1:last_rewarded_block(SubnetworkLedger),
{ok, #follower_subnetwork_last_reward_height_resp_v1_pb{height = CurrentHeight, reward_height = LastRewardHt}, Ctx};
_ -> {grpc_error, {grpcbox_stream:code_to_status(3), <<"unable to get retrieve subnetwork for requested token">>}}
end.
-spec process_past_blocks(Height :: pos_integer(),
TxnHash :: binary(),
TxnTypes :: [atom()],
Chain :: blockchain:blockchain(),
StreamState :: grpcbox_stream:t()) -> {ok, grpcbox_stream:t()} | {error, term()}.
process_past_blocks(Height, TxnHash, TxnTypes, Chain, StreamState) when is_integer(Height) andalso Height > 0 ->
{ok, #block_info_v2{height = HeadHeight}} = blockchain:head_block_info(Chain),
case Height > HeadHeight of
true -> {ok, StreamState};
false ->
case blockchain:get_block(Height, Chain) of
{ok, SubscribeBlock} ->
process_past_blocks_(SubscribeBlock, TxnHash, TxnTypes, HeadHeight, Chain, StreamState);
{error, not_found} ->
case blockchain:find_first_block_after(Height, Chain) of
{ok, _Height, ClosestBlock} ->
process_past_blocks_(ClosestBlock, <<>>, TxnTypes, HeadHeight, Chain, StreamState);
{error, _} = Error -> Error
end
end
end;
process_past_blocks(_Height, _TxnHash, _TxnTypes, _Chain, _StreamState) -> {error, invalid_req_params}.
-spec process_past_blocks_(StartBlock :: blockchain_block:block(),
TxnHash :: binary(),
TxnTypes :: [atom()],
HeadHeight :: pos_integer(),
Chain :: blockchain:blockchain(),
StreamState :: grpcbox_stream:t()) -> {ok, grpcbox_stream:t()}.
process_past_blocks_(StartBlock, TxnHash, TxnTypes, HeadHeight, Chain, StreamState) ->
StartHeight = blockchain_block:height(StartBlock),
StartBlockTimestamp = blockchain_block:time(StartBlock),
SortedStartTxns = filter_hash_sort_txns(StartBlock, TxnTypes),
{UnhandledTxns, _} = lists:partition(fun({H, _T}) -> H > TxnHash end, SortedStartTxns),
StreamState1 = send_txn_sequence(UnhandledTxns, StartHeight, StartBlockTimestamp, StreamState),
BlockSeq = lists:seq(StartHeight + 1, HeadHeight),
StreamState2 = lists:foldl(fun(HeightX, StateAcc) ->
{ok, BlockX} = blockchain:get_block(HeightX, Chain),
BlockXTimestamp = blockchain_block:time(BlockX),
SortedTxnsX = filter_hash_sort_txns(BlockX, TxnTypes),
_NewStateAcc = send_txn_sequence(SortedTxnsX, HeightX, BlockXTimestamp, StateAcc)
end, StreamState1, BlockSeq),
{ok, StreamState2}.
-spec filter_hash_sort_txns(blockchain_block:block(), [atom()]) -> [{binary(), blockchain_txn:txn()}].
filter_hash_sort_txns(Block, TxnTypes) ->
Txns = blockchain_block:transactions(Block),
FilteredTxns = lists:filter(fun(Txn) -> subscribed_type(blockchain_txn:type(Txn), TxnTypes) end, Txns),
HashKeyedTxns = lists:map(fun(Txn) -> {blockchain_txn:hash(Txn), Txn} end, FilteredTxns),
lists:sort(fun({H1, _T1}, {H2, _T2}) -> H1 < H2 end, HashKeyedTxns).
-spec send_txn_sequence(SortedTxns :: [{binary(), blockchain_txn:txn()}],
Height :: pos_integer(),
Timestamp :: pos_integer(),
StreamState :: grpcbox_stream:t()) -> grpcbox_stream:t().
send_txn_sequence(SortedTxns, Height, Timestamp, StreamState) ->
lists:foldl(fun({TxnHash, Txn}, StateAcc) ->
Msg = encode_follower_resp(TxnHash, Txn, Height, Timestamp),
grpcbox_stream:send(false, Msg, StateAcc)
end, StreamState, SortedTxns).
-spec encode_follower_resp(TxnHash :: binary(),
Txn :: blockchain_txn:txn(),
TxnHeight :: pos_integer(),
Timestamp :: pos_integer()) -> follower_pb:follower_resp_v1_pb().
encode_follower_resp(TxnHash, Txn, TxnHeight, Timestamp) ->
#follower_txn_stream_resp_v1_pb{
height = TxnHeight,
txn_hash = TxnHash,
txn = blockchain_txn:wrap_txn(Txn),
timestamp = Timestamp
}.
subscribed_type(_Type, []) -> true;
subscribed_type(Type, FilterTypes) -> lists:member(Type, FilterTypes).
validate_txn_filters(TxnFilters0) ->
case
(catch lists:foldl(
fun
(BinType, AtomTypes) when is_binary(BinType) ->
[binary_to_existing_atom(BinType, utf8) | AtomTypes];
(BinType, AtomTypes) when is_list(BinType) ->
[list_to_existing_atom(BinType) | AtomTypes]
end,
[],
TxnFilters0
))
of
{'EXIT', _} ->
{error, invalid_filter};
TxnFilters when is_list(TxnFilters) ->
case lists:all(fun is_blockchain_txn/1, TxnFilters) of
true -> {ok, TxnFilters};
false -> {error, invalid_filters}
end
end.
is_blockchain_txn(Module) ->
ModInfo = Module:module_info(attributes),
lists:any(fun({behavior, [blockchain_txn]}) -> true; (_) -> false end, ModInfo).
' region_us915 ' etc , we need it without the prefix and capitalised to
normalize_region(V) ->
list_to_atom(string:to_upper(string:slice(atom_to_list(V), 7))).
-spec region_params_for_region(atom(), blockchain_ledger_v1:ledger()) ->
{ok, [blockchain_region_param_v1:region_param_v1()]} | {error, no_params_for_region}.
region_params_for_region(Region, Ledger) ->
case blockchain_region_params_v1:for_region(Region, Ledger) of
{error, Reason} ->
lager:error(
"Could not get params for region: ~p, reason: ~p",
[Region, Reason]
),
{error, no_params_for_region};
{ok, Params} ->
{ok, Params}
end.
|
b7727603a4500bc88e8be2e04d58429a4e63a3a55e341646b92e8acef4cda021 | clojurians-org/haskell-example | Class.hs | module Class where
import Types
import Control.Applicative (empty)
import Data.Aeson (Value(Object, String, Number), (.:), (.:?), (.=), FromJSON, ToJSON, object)
import qualified Data.Aeson as J
instance FromJSON Contact where
parseJSON (Object v) = do
userName <- v .: "UserName"
nickName <- v .: "NickName"
remarkName <- v .: "RemarkName"
sex <- v .: "Sex"
signature <- v .: "Signature"
return $ Contact userName nickName remarkName sex signature
parseJSON _ = empty
instance FromJSON HttpContacts where
parseJSON (Object v) = do
count <- v .: "MemberCount"
contacts <- v .: "MemberList"
return $ HttpContacts count contacts
parseJSON _ = empty
instance FromJSON SyncKey where
parseJSON (Object v) = do
count <- v .: "Count"
list <- v .: "List"
return $ SyncKey count list
instance ToJSON SyncKey where
toJSON (SyncKey count list) =
object [ "Count" .= count, "List" .= list ]
instance FromJSON HttpWxInitST where
parseJSON (Object v) = do
contact <- v .: "User"
syncKey <- v .: "SyncKey"
return $ HttpWxInitST contact syncKey
instance FromJSON Msg where
parseJSON (Object v) = do
fromUserName <- v .: "FromUserName"
toUserName <- v .: "ToUserName"
msgType <- v .: "MsgType"
content <- v .:? "Content"
url <- v .:? "Url"
fileName <- v .:? "FileName"
fileSize <- v .:? "FileSize"
recommandInfo <- v .:? "RecommandInfo"
return (Msg fromUserName toUserName msgType content url fileName fileSize recommandInfo)
instance FromJSON HttpMsgs where
parseJSON (Object v) = do
addMsgList <- v .: "AddMsgList"
syncKey <- v .: "SyncKey"
syncCheckKey <- v .: "SyncCheckKey"
return (HttpMsgs addMsgList syncKey syncCheckKey)
| null | https://raw.githubusercontent.com/clojurians-org/haskell-example/c96b021bdef52a121e04ea203c8c3e458770a25a/hweixin/app/Class.hs | haskell | module Class where
import Types
import Control.Applicative (empty)
import Data.Aeson (Value(Object, String, Number), (.:), (.:?), (.=), FromJSON, ToJSON, object)
import qualified Data.Aeson as J
instance FromJSON Contact where
parseJSON (Object v) = do
userName <- v .: "UserName"
nickName <- v .: "NickName"
remarkName <- v .: "RemarkName"
sex <- v .: "Sex"
signature <- v .: "Signature"
return $ Contact userName nickName remarkName sex signature
parseJSON _ = empty
instance FromJSON HttpContacts where
parseJSON (Object v) = do
count <- v .: "MemberCount"
contacts <- v .: "MemberList"
return $ HttpContacts count contacts
parseJSON _ = empty
instance FromJSON SyncKey where
parseJSON (Object v) = do
count <- v .: "Count"
list <- v .: "List"
return $ SyncKey count list
instance ToJSON SyncKey where
toJSON (SyncKey count list) =
object [ "Count" .= count, "List" .= list ]
instance FromJSON HttpWxInitST where
parseJSON (Object v) = do
contact <- v .: "User"
syncKey <- v .: "SyncKey"
return $ HttpWxInitST contact syncKey
instance FromJSON Msg where
parseJSON (Object v) = do
fromUserName <- v .: "FromUserName"
toUserName <- v .: "ToUserName"
msgType <- v .: "MsgType"
content <- v .:? "Content"
url <- v .:? "Url"
fileName <- v .:? "FileName"
fileSize <- v .:? "FileSize"
recommandInfo <- v .:? "RecommandInfo"
return (Msg fromUserName toUserName msgType content url fileName fileSize recommandInfo)
instance FromJSON HttpMsgs where
parseJSON (Object v) = do
addMsgList <- v .: "AddMsgList"
syncKey <- v .: "SyncKey"
syncCheckKey <- v .: "SyncCheckKey"
return (HttpMsgs addMsgList syncKey syncCheckKey)
| |
d394ecbaca4c77a48a75d298eeea06f78b13dbe412146369e4ff37571a2e2743 | russmatney/ralphie | clipboard.clj | (ns ralphie.clipboard
(:require
[clojure.string :as string]
[babashka.process :as p]
[clojure.java.shell :as sh]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Read the clipboard
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-clip [clipboard-name]
(-> (sh/sh "xclip" "-o" "-selection" clipboard-name)
:out))
(defn get-all
"Returns a list of things on available clipboards."
[]
{:clipboard (get-clip "clipboard")
:primary (get-clip "primary")
: secondary ( get - clip " secondary " )
;; :buffer-cut (get-clip "buffer-cut")
})
(defn values []
(->> (get-all)
vals
(map string/trim)
(remove empty?)))
(comment
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Write to the clipboard
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-clip [s]
(-> (p/process '[xclip -i -selection clipboard]
{:in s})
p/check
:out
slurp))
(comment
(set-clip "hello\ngoodbye")
(set-clip "siyanora")
(get-clip "primary")
(sh/sh "xclip" "-o" "-selection" "primary")
(get-all)
)
| null | https://raw.githubusercontent.com/russmatney/ralphie/3b7af4a9ec2dc2b9e59036d67a66f365691f171d/src/ralphie/clipboard.clj | clojure |
Read the clipboard
:buffer-cut (get-clip "buffer-cut")
Write to the clipboard
| (ns ralphie.clipboard
(:require
[clojure.string :as string]
[babashka.process :as p]
[clojure.java.shell :as sh]))
(defn get-clip [clipboard-name]
(-> (sh/sh "xclip" "-o" "-selection" clipboard-name)
:out))
(defn get-all
"Returns a list of things on available clipboards."
[]
{:clipboard (get-clip "clipboard")
:primary (get-clip "primary")
: secondary ( get - clip " secondary " )
})
(defn values []
(->> (get-all)
vals
(map string/trim)
(remove empty?)))
(comment
(values))
(defn set-clip [s]
(-> (p/process '[xclip -i -selection clipboard]
{:in s})
p/check
:out
slurp))
(comment
(set-clip "hello\ngoodbye")
(set-clip "siyanora")
(get-clip "primary")
(sh/sh "xclip" "-o" "-selection" "primary")
(get-all)
)
|
027f730b5af58aa0c793d560144c1b29de02e4f9fc7bf2d53577c845d19eeca5 | ml4tp/tcoq | subtyping.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Univ
open Declarations
open Environ
val check_subtypes : env -> module_type_body -> module_type_body -> constraints
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/kernel/subtyping.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Univ
open Declarations
open Environ
val check_subtypes : env -> module_type_body -> module_type_body -> constraints
|
7c7c6cf019aa1c5c778f123cc7fd2572857e8b463b22198f5412e512f06ab95b | equill/restagraph | utilities.lisp | Copyright 2020 < >
;
Licensed under the GNU General Public License
- for details , see LICENSE.txt in the top - level directory
(in-package #:restagraph)
(declaim (optimize (compilation-speed 0)
(speed 2)
(safety 3)
(debug 3)))
;;; Utility functions
Handy reference of definitions from RFC 3986
( defvar unreserved ( list # \- # \. # \ _ # \~ ) )
( defvar delimiters ( list # \ : # \/ # \ ? # \ # # \ [ # \ ] # \@ ) )
( defvar sub - delimiters ( list # \ ! # \$ # \ & # \ ' # \ ( # \ ) # \ * # \+ # \ , # \ ; # \= ) )
(defun unreserved-char-p (c)
"Test whether a character is unreserved, per section 2.3 of RFC 3986."
(or (alphanumericp c)
(char= #\- c)
(char= #\. c)
(char= #\_ c)
(char= #\~ c)))
;; Design-decision note
;;
Two options here :
;; - Replace unfriendly characters with something neutral, like an underscore.
;; - Remove unfriendly characters altogether.
;;
;; For almost all cases, replacing them will make for a crappy-looking URL with very little gain.
;; However, preserving some kind of separation between words can improve URL readability at low cost.
;;
;; Even though the API itself is unlikely to actually be used directly by humans,
;; URIs do get reflected in user interfaces in various ways, such as in the URL of a web GUI,
;; which people sometimes need to transcribe or communicate verbally.
;; Because of that, human-friendliness of identifiers is important in a way that
;; compactness in _paths_ is not.
(defun sanitise-uid (uid)
"Strip out UID-unfriendly characters, after replacing whitespace with underscores.
UID-friendly means being an unreserved character as defined in RFC 3986."
(declare (type (string) uid))
(remove-if-not #'unreserved-char-p
(substitute #\_ #\Space uid)))
(defun get-sub-uri (uri base-uri)
(declare (type (string) uri base-uri))
"Extract the URI from the full request string,
excluding the base URL and any GET parameters."
The ( or ) is to prevent breakage when the URI matches the base - uri ,
;; which would return NIL instead of a string.
(or (first (cl-ppcre:split
"\\?"
(cl-ppcre:regex-replace base-uri uri "")))
""))
(defun get-uri-parts (uri)
"Break the URI into parts for processing by uri-node-helper.
Assumes the base-uri and trailing parameters have already been removed.
Expects a leading forward-slash before the first element;
anything *before and including* the first forward slash will be discarded."
(declare (type (string) uri))
(mapcar #'sanitise-uid
(cdr (ppcre:split "/" uri))))
(defun regex-p (str)
"Test whether a string contains a Java-style regex."
(cl-ppcre:all-matches "[\\.\\*\\+[]" str))
(defun uri-node-helper (uri-parts &key (path "") (marker "n"))
"Build a Cypher path ending in a node variable, which defaults to 'n'.
Accepts a list of strings and returns a single string."
(declare (type (or null cons) uri-parts)
(type (string) path marker))
(cond
;; End of the list; terminate the path with the marker.
((null uri-parts)
(format nil "~A(~A)" path marker))
1 - element URI ; terminate the path with the marker identifying a resourcetype .
((equal (length uri-parts) 1)
(format nil "~A(~A:~A)" path marker (first uri-parts)))
2 - element URI ; terminate the path with the marker identifying a specific resource .
((equal (length uri-parts) 2)
(format nil "~A(~A:~A { uid: '~A' })"
path marker (first uri-parts) (second uri-parts)))
3 - element URI ; terminate the path with a relationship from a resource to the marker .
((equal (length uri-parts) 3)
(format nil "~A(:~A~A)-[:~A]->(~A)"
path
Resourcetype
(sanitise-uid (first uri-parts))
UID
;; Allow for a wildcard.
(if (equal "*" (second uri-parts))
""
(format nil " { uid: '~A' }" (sanitise-uid (second uri-parts))))
;; Relationship to target
(sanitise-uid (third uri-parts))
Target
marker))
The URI is longer than 3 elements .
Extend the path with its first 3 elements , then recurse through this function
;; with whatever is left over.
(t
(uri-node-helper
(cdddr uri-parts)
:path (format nil "~A(:~A { uid: '~A' })-[:~A]->"
path
(sanitise-uid (first uri-parts))
(sanitise-uid (second uri-parts))
(sanitise-uid (third uri-parts)))
:marker marker))))
(defun build-cypher-path (uri-parts &optional (path "") (marker "m"))
"Build a Cypher path from the list of strings supplied.
Attach a marker variable to the last node in the list, defaulting to 'm'."
(declare (type (or null cons) uri-parts)
(type (string) path)
(type (string) marker))
;; sep == separator
(let ((sep (if (equal path "") "" "->")))
(cond
((null uri-parts)
path)
((equal (length uri-parts) 1)
(format nil "~A~A(~A:~A)" path sep marker (first uri-parts)))
((equal (length uri-parts) 2)
(format nil "~A~A(~A:~A { uid: '~A' })"
path sep marker (first uri-parts) (second uri-parts)))
((equal (length uri-parts) 3)
(format nil "~A~A(~A:~A { uid: '~A' })-[:~A]"
path sep marker (first uri-parts) (second uri-parts) (third uri-parts)))
(t
(build-cypher-path
(cdddr uri-parts)
(format nil "~A~A(:~A { uid: '~A' })-[:~A]"
path sep (first uri-parts) (second uri-parts) (third uri-parts)))))))
(defun hash-file (filepath &optional (digest 'ironclad:sha3/256))
"Return the hash-digest of a file, as a string."
(declare (type pathname filepath))
(log-message :debug (format nil "Producing a hash digest of file '~A'" filepath))
;; Convert the digest back into a string
(format nil "~{~2,'0X~}"
(loop for b across
Digest the file
(with-open-file (filestream filepath :element-type '(unsigned-byte 8))
(ironclad:digest-stream digest filestream))
;; Accumulator for the string to return
collecting b)))
(defun digest-to-filepath (basedir digest)
"Take a 64-bit digest string and the basedir, and return the target path to the file
as a cons of two strings: the directory path and the filename"
(declare (type pathname basedir)
(type string digest))
(log-message :debug (format nil "Generating a filepath from base-dir '~A' and digest '~A'" basedir digest))
(merge-pathnames (make-pathname :directory `(:relative
,(format nil "~A/~A/~A" (subseq digest 0 2)
(subseq digest 2 4)
(subseq digest 4 6)))
:name (subseq digest 6))
(make-pathname :defaults basedir)))
(defun get-file-mime-type (filepath)
"Return the MIME-type of a file, as a string.
The path argument must be a string, as it's passed verbatim to the Unix shell."
(declare (type string filepath))
(log-message :debug (format nil "Identifying MIME-type for file '~A'" filepath))
(log-message :debug (format nil "PATH value: ~A" (sb-ext:posix-getenv "PATH")))
(string-right-trim
'(#\NewLine)
(with-output-to-string (str)
(sb-ext:run-program "file" (list "-b" "--mime-type" filepath) :search t :output str)
str)))
(defun move-file (old-path new-path)
"Move a file by calling out to the Unix 'mv' utility.
Do this because rename-file doesn't work across filesystem boundaries."
(let ((oldpath (format nil "~A" old-path))
(newpath (format nil "~A" new-path)))
(log-message :debug (format nil "Moving file '~A' to new location '~A'" oldpath newpath))
(log-message :debug (format nil "Result of file move: ~A"
(with-output-to-string (outstr)
(sb-ext:run-program "mv"
(list oldpath newpath)
:search t
:output outstr)
outstr)))))
(defun confirm-db-is-running (server &key (counter 1) (max-count 5) (sleep-time 5))
"Check whether the database server is running by polling the discovery endpoint."
(declare (type neo4cl:bolt-server server)
(type integer counter max-count sleep-time))
(log-message :debug (format nil "Checking whether the database is running on ~A:~A"
(neo4cl:hostname server) (neo4cl:port server)))
(handler-case
;; Try to run a non-destructive transaction
(let ((session (neo4cl:establish-bolt-session server)))
(neo4cl:bolt-transaction-autocommit session "RETURN 'hello'")
(neo4cl:disconnect session))
If the port is n't open , pause for a few seconds before trying again .
(USOCKET:CONNECTION-REFUSED-ERROR
(e)
(declare (ignore e))
(if (>= counter max-count)
;; Timed out.
;; Leave a message, then exit this whole thing.
(progn
(log-message :crit "Timed out trying to connect to the database. Exiting.")
(sb-ext:exit))
;; Still isn't responding, but we haven't yet hit timeout.
;; Leave a message, pause, then try again.
(progn
(log-message :warn (format nil "Connection refused. Pausing for ~A seconds before retrying" sleep-time))
(sleep sleep-time)
(confirm-db-is-running server
:counter (+ counter 1)
:max-count max-count
:sleep-time sleep-time))))))
(defun replace-all (string part replacement &key (test #'char=))
"Returns a new string in which all the occurences of the part is replaced with replacement.
Swiped from the Common Lisp cookbook."
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string
:start2 old-pos
:test test)
do (write-string string out
:start old-pos
:end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
| null | https://raw.githubusercontent.com/equill/restagraph/b6a135cdd212ec94d5ad7e06af8c95f82c272f12/src/utilities.lisp | lisp |
Utility functions
# \= ) )
Design-decision note
- Replace unfriendly characters with something neutral, like an underscore.
- Remove unfriendly characters altogether.
For almost all cases, replacing them will make for a crappy-looking URL with very little gain.
However, preserving some kind of separation between words can improve URL readability at low cost.
Even though the API itself is unlikely to actually be used directly by humans,
URIs do get reflected in user interfaces in various ways, such as in the URL of a web GUI,
which people sometimes need to transcribe or communicate verbally.
Because of that, human-friendliness of identifiers is important in a way that
compactness in _paths_ is not.
which would return NIL instead of a string.
End of the list; terminate the path with the marker.
terminate the path with the marker identifying a resourcetype .
terminate the path with the marker identifying a specific resource .
terminate the path with a relationship from a resource to the marker .
Allow for a wildcard.
Relationship to target
with whatever is left over.
sep == separator
Convert the digest back into a string
Accumulator for the string to return
Try to run a non-destructive transaction
Timed out.
Leave a message, then exit this whole thing.
Still isn't responding, but we haven't yet hit timeout.
Leave a message, pause, then try again. | Copyright 2020 < >
Licensed under the GNU General Public License
- for details , see LICENSE.txt in the top - level directory
(in-package #:restagraph)
(declaim (optimize (compilation-speed 0)
(speed 2)
(safety 3)
(debug 3)))
Handy reference of definitions from RFC 3986
( defvar unreserved ( list # \- # \. # \ _ # \~ ) )
( defvar delimiters ( list # \ : # \/ # \ ? # \ # # \ [ # \ ] # \@ ) )
(defun unreserved-char-p (c)
"Test whether a character is unreserved, per section 2.3 of RFC 3986."
(or (alphanumericp c)
(char= #\- c)
(char= #\. c)
(char= #\_ c)
(char= #\~ c)))
Two options here :
(defun sanitise-uid (uid)
"Strip out UID-unfriendly characters, after replacing whitespace with underscores.
UID-friendly means being an unreserved character as defined in RFC 3986."
(declare (type (string) uid))
(remove-if-not #'unreserved-char-p
(substitute #\_ #\Space uid)))
(defun get-sub-uri (uri base-uri)
(declare (type (string) uri base-uri))
"Extract the URI from the full request string,
excluding the base URL and any GET parameters."
The ( or ) is to prevent breakage when the URI matches the base - uri ,
(or (first (cl-ppcre:split
"\\?"
(cl-ppcre:regex-replace base-uri uri "")))
""))
(defun get-uri-parts (uri)
"Break the URI into parts for processing by uri-node-helper.
Assumes the base-uri and trailing parameters have already been removed.
anything *before and including* the first forward slash will be discarded."
(declare (type (string) uri))
(mapcar #'sanitise-uid
(cdr (ppcre:split "/" uri))))
(defun regex-p (str)
"Test whether a string contains a Java-style regex."
(cl-ppcre:all-matches "[\\.\\*\\+[]" str))
(defun uri-node-helper (uri-parts &key (path "") (marker "n"))
"Build a Cypher path ending in a node variable, which defaults to 'n'.
Accepts a list of strings and returns a single string."
(declare (type (or null cons) uri-parts)
(type (string) path marker))
(cond
((null uri-parts)
(format nil "~A(~A)" path marker))
((equal (length uri-parts) 1)
(format nil "~A(~A:~A)" path marker (first uri-parts)))
((equal (length uri-parts) 2)
(format nil "~A(~A:~A { uid: '~A' })"
path marker (first uri-parts) (second uri-parts)))
((equal (length uri-parts) 3)
(format nil "~A(:~A~A)-[:~A]->(~A)"
path
Resourcetype
(sanitise-uid (first uri-parts))
UID
(if (equal "*" (second uri-parts))
""
(format nil " { uid: '~A' }" (sanitise-uid (second uri-parts))))
(sanitise-uid (third uri-parts))
Target
marker))
The URI is longer than 3 elements .
Extend the path with its first 3 elements , then recurse through this function
(t
(uri-node-helper
(cdddr uri-parts)
:path (format nil "~A(:~A { uid: '~A' })-[:~A]->"
path
(sanitise-uid (first uri-parts))
(sanitise-uid (second uri-parts))
(sanitise-uid (third uri-parts)))
:marker marker))))
(defun build-cypher-path (uri-parts &optional (path "") (marker "m"))
"Build a Cypher path from the list of strings supplied.
Attach a marker variable to the last node in the list, defaulting to 'm'."
(declare (type (or null cons) uri-parts)
(type (string) path)
(type (string) marker))
(let ((sep (if (equal path "") "" "->")))
(cond
((null uri-parts)
path)
((equal (length uri-parts) 1)
(format nil "~A~A(~A:~A)" path sep marker (first uri-parts)))
((equal (length uri-parts) 2)
(format nil "~A~A(~A:~A { uid: '~A' })"
path sep marker (first uri-parts) (second uri-parts)))
((equal (length uri-parts) 3)
(format nil "~A~A(~A:~A { uid: '~A' })-[:~A]"
path sep marker (first uri-parts) (second uri-parts) (third uri-parts)))
(t
(build-cypher-path
(cdddr uri-parts)
(format nil "~A~A(:~A { uid: '~A' })-[:~A]"
path sep (first uri-parts) (second uri-parts) (third uri-parts)))))))
(defun hash-file (filepath &optional (digest 'ironclad:sha3/256))
"Return the hash-digest of a file, as a string."
(declare (type pathname filepath))
(log-message :debug (format nil "Producing a hash digest of file '~A'" filepath))
(format nil "~{~2,'0X~}"
(loop for b across
Digest the file
(with-open-file (filestream filepath :element-type '(unsigned-byte 8))
(ironclad:digest-stream digest filestream))
collecting b)))
(defun digest-to-filepath (basedir digest)
"Take a 64-bit digest string and the basedir, and return the target path to the file
as a cons of two strings: the directory path and the filename"
(declare (type pathname basedir)
(type string digest))
(log-message :debug (format nil "Generating a filepath from base-dir '~A' and digest '~A'" basedir digest))
(merge-pathnames (make-pathname :directory `(:relative
,(format nil "~A/~A/~A" (subseq digest 0 2)
(subseq digest 2 4)
(subseq digest 4 6)))
:name (subseq digest 6))
(make-pathname :defaults basedir)))
(defun get-file-mime-type (filepath)
"Return the MIME-type of a file, as a string.
The path argument must be a string, as it's passed verbatim to the Unix shell."
(declare (type string filepath))
(log-message :debug (format nil "Identifying MIME-type for file '~A'" filepath))
(log-message :debug (format nil "PATH value: ~A" (sb-ext:posix-getenv "PATH")))
(string-right-trim
'(#\NewLine)
(with-output-to-string (str)
(sb-ext:run-program "file" (list "-b" "--mime-type" filepath) :search t :output str)
str)))
(defun move-file (old-path new-path)
"Move a file by calling out to the Unix 'mv' utility.
Do this because rename-file doesn't work across filesystem boundaries."
(let ((oldpath (format nil "~A" old-path))
(newpath (format nil "~A" new-path)))
(log-message :debug (format nil "Moving file '~A' to new location '~A'" oldpath newpath))
(log-message :debug (format nil "Result of file move: ~A"
(with-output-to-string (outstr)
(sb-ext:run-program "mv"
(list oldpath newpath)
:search t
:output outstr)
outstr)))))
(defun confirm-db-is-running (server &key (counter 1) (max-count 5) (sleep-time 5))
"Check whether the database server is running by polling the discovery endpoint."
(declare (type neo4cl:bolt-server server)
(type integer counter max-count sleep-time))
(log-message :debug (format nil "Checking whether the database is running on ~A:~A"
(neo4cl:hostname server) (neo4cl:port server)))
(handler-case
(let ((session (neo4cl:establish-bolt-session server)))
(neo4cl:bolt-transaction-autocommit session "RETURN 'hello'")
(neo4cl:disconnect session))
If the port is n't open , pause for a few seconds before trying again .
(USOCKET:CONNECTION-REFUSED-ERROR
(e)
(declare (ignore e))
(if (>= counter max-count)
(progn
(log-message :crit "Timed out trying to connect to the database. Exiting.")
(sb-ext:exit))
(progn
(log-message :warn (format nil "Connection refused. Pausing for ~A seconds before retrying" sleep-time))
(sleep sleep-time)
(confirm-db-is-running server
:counter (+ counter 1)
:max-count max-count
:sleep-time sleep-time))))))
(defun replace-all (string part replacement &key (test #'char=))
"Returns a new string in which all the occurences of the part is replaced with replacement.
Swiped from the Common Lisp cookbook."
(with-output-to-string (out)
(loop with part-length = (length part)
for old-pos = 0 then (+ pos part-length)
for pos = (search part string
:start2 old-pos
:test test)
do (write-string string out
:start old-pos
:end (or pos (length string)))
when pos do (write-string replacement out)
while pos)))
|
60ee81db2d499cdd99400ea454e39b6c21db18870203ef3a33b6a4f9ebfca63b | manuel-serrano/bigloo | server.scm | ;*=====================================================================*/
* ... /prgm / project / bigloo / bigloo / api / mqtt / src / Llib / server.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Sun Mar 13 06:41:15 2022 * /
* Last change : We d Apr 27 18:06:08 2022 ( serrano ) * /
* Copyright : 2022 * /
;* ------------------------------------------------------------- */
;* MQTT server side */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module __mqtt_server
(library pthread)
(import __mqtt_common)
(export (class mqtt-server
(lock read-only (default (make-mutex "mqtt-server")))
(socket::socket read-only)
(subscriptions::pair-nil (default '()))
(retains::pair-nil (default '()))
(debug::long (default 0)))
(class mqtt-client-conn
(sock::socket read-only)
(lock read-only (default (make-mutex "mqtt-server-conn")))
(version::long read-only)
(connpk::mqtt-connect-packet read-only))
(mqtt-make-server ::obj #!key (debug 0))
(mqtt-server-loop ::mqtt-server ::procedure)
(mqtt-read-server-packet ip::input-port ::long)))
;*---------------------------------------------------------------------*/
;* topic ... */
;*---------------------------------------------------------------------*/
(define-struct topic name regexp qos)
;*---------------------------------------------------------------------*/
;* conn-id ... */
;*---------------------------------------------------------------------*/
(define (conn-id conn::mqtt-client-conn)
(with-access::mqtt-client-conn conn (sock lock version connpk)
(with-access::mqtt-connect-packet connpk (client-id)
client-id)))
;*---------------------------------------------------------------------*/
;* flag? ... */
;*---------------------------------------------------------------------*/
(define (flag? flags flag)
(=fx (bit-and flags flag) flag))
;*---------------------------------------------------------------------*/
;* mqtt-make-server ... */
;*---------------------------------------------------------------------*/
(define (mqtt-make-server socket #!key (debug 0))
(instantiate::mqtt-server
(socket socket)
(debug debug)))
;*---------------------------------------------------------------------*/
;* mqtt-server-loop ... */
;*---------------------------------------------------------------------*/
(define (mqtt-server-loop srv::mqtt-server on)
(unless (correct-arity? on 2)
(error "mqtt-server-loop" "wrong procedure" on))
(with-access::mqtt-server srv (socket)
(unwind-protect
(let loop ()
(let* ((sock (socket-accept socket))
(pk (mqtt-read-connect-packet (socket-input sock))))
(when (isa? pk mqtt-connect-packet)
(with-access::mqtt-connect-packet pk (version client-id flags)
(let ((conn (instantiate::mqtt-client-conn
(sock sock)
(version version)
(connpk pk))))
(on 'connect client-id)
(mqtt-conn-loop srv conn on))))
(loop)))
(mqtt-server-close srv))))
;*---------------------------------------------------------------------*/
;* mqtt-server-close ... */
;*---------------------------------------------------------------------*/
(define (mqtt-server-close srv::mqtt-server)
(with-access::mqtt-server srv (socket lock)
#f))
;*---------------------------------------------------------------------*/
;* mqtt-server-debug ... */
;*---------------------------------------------------------------------*/
(define-macro (mqtt-server-debug srv thunk)
`(with-access::mqtt-server ,srv (debug)
(when (>fx debug 0)
(,thunk))))
;*---------------------------------------------------------------------*/
;* mqtt-conn-loop ... */
;*---------------------------------------------------------------------*/
(define (mqtt-conn-loop srv::mqtt-server conn::mqtt-client-conn on)
(with-access::mqtt-client-conn conn (sock lock version connpk)
(mqtt-server-debug srv
(lambda ()
(tprint "New client connected as " (conn-id conn))
(tprint "sending CONNACK to " (conn-id conn))))
(mqtt-write-connack-packet (socket-output sock) 0)
(thread-start!
(instantiate::pthread
(name "mqtt-server-loop")
(body (lambda ()
(with-trace 'mqtt "mqtt-connloop"
(trace-item "connid=" (conn-id conn))
(let ((ip (socket-input sock))
(op (socket-output sock)))
(let loop ()
(let ((pk (mqtt-read-server-packet ip version)))
(if (not (isa? pk mqtt-control-packet))
(mqtt-server-will srv on conn)
(with-access::mqtt-control-packet pk (type)
(on 'packet pk)
(cond
((=fx type (MQTT-CPT-CONNECT))
3.1 , error
(mqtt-server-will srv on conn)
#f)
((=fx type (MQTT-CPT-PUBLISH))
3.3
(mqtt-server-publish srv conn on pk)
(loop))
((=fx type (MQTT-CPT-PUBACK))
3.4
(loop))
((=fx type (MQTT-CPT-PUBREC))
3.5
(loop))
((=fx type (MQTT-CPT-SUBSCRIBE))
3.8
(mqtt-server-subscribe srv on conn pk)
(loop))
((=fx type (MQTT-CPT-UNSUBSCRIBE))
3.10
(mqtt-server-unsubscribe srv conn pk)
(loop))
((=fx type (MQTT-CPT-PINGREQ))
3.12
(mqtt-write-pingresp-packet op)
(loop))
((=fx type (MQTT-CPT-DISCONNECT))
3.14
#unspecified)
(else
(loop)))))))
(trace-item "closing " (conn-id conn))
(with-access::mqtt-server srv (lock subscriptions retains)
(synchronize lock
(set! subscriptions
(filter (lambda (sub)
(not (eq? (car sub) conn)))
subscriptions))
(set! retains
(filter (lambda (pub)
(not (eq? (car pub) conn)))
retains))))
(on 'disconnect (conn-id conn))
;; remove all connection subscriptions
(socket-close sock)))))))))
;*---------------------------------------------------------------------*/
;* mqtt-server-will ... */
;*---------------------------------------------------------------------*/
(define (mqtt-server-will srv::mqtt-server on conn::mqtt-client-conn)
(with-access::mqtt-client-conn conn (connpk)
(with-access::mqtt-connect-packet connpk (flags will-topic will-message)
(when (flag? flags (MQTT-CONFLAG-WILL-FLAG))
(let* ((flags (if (flag? flags (MQTT-CONFLAG-WILL-RETAIN))
1 0))
(qos (bit-rsh
(bit-or
(bit-and flags (MQTT-CONFLAG-WILL-QOSL))
(bit-and flags (MQTT-CONFLAG-WILL-QOSH)))
3))
(pk (instantiate::mqtt-publish-packet
(type (MQTT-CPT-PUBLISH))
(topic will-topic)
(flags flags)
(qos qos)
(payload will-message))))
(mqtt-server-publish srv conn on pk))))))
;*---------------------------------------------------------------------*/
;* mqtt-server-publish ... */
;*---------------------------------------------------------------------*/
(define (mqtt-server-publish srv::mqtt-server conn on pk::mqtt-publish-packet)
(with-trace 'mqtt "mqtt-server-publish"
(with-access::mqtt-server srv (lock subscriptions retains)
(with-access::mqtt-publish-packet pk (flags topic pid)
(trace-item "topic=" topic " retain=" (=fx (bit-and flags 1) 1))
(when (=fx (bit-and flags 1) 1)
;; 3.3.1.3 RETAIN
(synchronize lock
(cond
((null? retains)
(set! retains (list (cons conn pk))))
((find (lambda (p)
(and (eq? (car p) conn)
(with-access::mqtt-publish-packet (cdr p) ((t topic))
(string=? t topic))))
retains)
=>
(lambda (p)
(set-cdr! p pk)))
(else
(set! retains (cons (cons conn pk) retains))))))
;; qos
(with-access::mqtt-client-conn conn (sock)
(cond
((=fx (bit-and flags 2) 2)
(mqtt-write-puback-packet (socket-output sock) pid -1 '()))
((=fx (bit-and flags 4) 4)
(mqtt-write-pubrec-packet (socket-output sock) pid -1 '()))))
(for-each (lambda (subscription)
(let ((connsub (car subscription))
(topics (cdr subscription)))
(unless (eq? connsub conn)
(mqtt-conn-publish connsub topics on pk))))
subscriptions)))))
;*---------------------------------------------------------------------*/
;* mqtt-conn-publish ... */
;*---------------------------------------------------------------------*/
(define (mqtt-conn-publish conn topics on pk::mqtt-publish-packet)
(with-trace 'mqtt "mqtt-conn-publish"
(with-access::mqtt-publish-packet pk (topic payload)
(trace-item "conn=" (conn-id conn))
(trace-item "topics=" topics)
(trace-item "retain=" topic)
(for-each (lambda (t)
(when (mqtt-topic-match? (topic-regexp t) topic)
(with-access::mqtt-client-conn conn (sock connpk)
(with-handler
(lambda (e)
(with-access::mqtt-connect-packet connpk (client-id)
(fprintf (current-error-port)
"Could not publish ~s to client ~a"
topic
client-id))
(exception-notify e))
(begin
(mqtt-write-publish-packet
(socket-output sock)
#f 0 #f topic 0 payload)
(when on (on 'publish (cons (conn-id conn) topic))))))))
topics))))
;*---------------------------------------------------------------------*/
;* mqtt-server-subscribe ... */
;*---------------------------------------------------------------------*/
(define (mqtt-server-subscribe srv::mqtt-server on conn pk::mqtt-control-packet)
(define (payload->topic payload)
(topic (car payload)
(topic-filter->regexp (car payload))
(cdr payload)))
(with-trace 'mqtt "mqtt-server-subscribe"
(with-access::mqtt-server srv (lock subscriptions retains)
(with-access::mqtt-control-packet pk (payload pid qos)
(let ((subtopics (map payload->topic payload)))
;; add the subscription
(synchronize lock
(trace-item "subscribe=" payload)
(trace-item "conn=" (conn-id conn))
(let ((cell (assq conn subscriptions)))
(if (not cell)
(set! subscriptions
(cons (cons conn subtopics)
subscriptions))
(for-each (lambda (payload)
(unless (find (lambda (t)
(string=? (topic-name t)
(car payload)))
(cdr cell))
(set-cdr! cell
(cons (payload->topic payload)
(cdr cell)))))
payload))))
(with-access::mqtt-client-conn conn (sock)
(mqtt-write-suback-packet (socket-output sock) pid '()))
(for-each (lambda (rt)
(mqtt-conn-publish conn subtopics on (cdr rt)))
retains))))))
;*---------------------------------------------------------------------*/
;* mqtt-server-unsubscribe ... */
;*---------------------------------------------------------------------*/
(define (mqtt-server-unsubscribe srv::mqtt-server conn pk::mqtt-control-packet)
(with-trace 'mqtt "mqtt-server-unsubscribe"
(with-access::mqtt-server srv (lock subscriptions)
(with-access::mqtt-control-packet pk (payload pid)
(synchronize lock
(let ((cell (assq conn subscriptions)))
(when (pair? cell)
(set-cdr! cell
(filter! (lambda (topic)
(not (member (topic-name topic) payload)))
(cdr cell))))))
(with-access::mqtt-client-conn conn (sock)
3.10.4 Response
(mqtt-write-unsuback-packet (socket-output sock) pid))))))
;*---------------------------------------------------------------------*/
;* mqtt-read-server-packet ... */
;*---------------------------------------------------------------------*/
(define (mqtt-read-server-packet ip::input-port version::long)
(with-trace 'mqtt "mqtt-read-server-packet"
(let ((header (read-byte ip)))
(if (eof-object? header)
header
(let ((ptype (bit-rsh header 4)))
(trace-item "type=" (mqtt-control-packet-type-name ptype))
(unread-char! (integer->char header) ip)
(cond
((=fx ptype (MQTT-CPT-CONNECT))
(mqtt-read-connect-packet ip))
((=fx ptype (MQTT-CPT-PUBLISH))
(mqtt-read-publish-packet ip version))
((=fx ptype (MQTT-CPT-SUBSCRIBE))
(mqtt-read-subscribe-packet ip version))
((=fx ptype (MQTT-CPT-UNSUBSCRIBE))
(mqtt-read-unsubscribe-packet ip version))
((=fx ptype (MQTT-CPT-PUBREC))
(mqtt-read-pubrec-packet ip version))
((=fx ptype (MQTT-CPT-PINGREQ))
(mqtt-read-pingreq-packet ip version))
((=fx ptype (MQTT-CPT-DISCONNECT))
(mqtt-read-disconnect-packet ip version))
(else
(error "mqtt:server" "Illegal packet type"
(mqtt-control-packet-type-name ptype)))))))))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/16e397e187fa85d8949a0285bfb43d4ab4ed8839/api/mqtt/src/Llib/server.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* MQTT server side */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* topic ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* conn-id ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* flag? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-make-server ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-server-loop ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-server-close ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-server-debug ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-conn-loop ... */
*---------------------------------------------------------------------*/
remove all connection subscriptions
*---------------------------------------------------------------------*/
* mqtt-server-will ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-server-publish ... */
*---------------------------------------------------------------------*/
3.3.1.3 RETAIN
qos
*---------------------------------------------------------------------*/
* mqtt-conn-publish ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-server-subscribe ... */
*---------------------------------------------------------------------*/
add the subscription
*---------------------------------------------------------------------*/
* mqtt-server-unsubscribe ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mqtt-read-server-packet ... */
*---------------------------------------------------------------------*/ | * ... /prgm / project / bigloo / bigloo / api / mqtt / src / Llib / server.scm * /
* Author : * /
* Creation : Sun Mar 13 06:41:15 2022 * /
* Last change : We d Apr 27 18:06:08 2022 ( serrano ) * /
* Copyright : 2022 * /
(module __mqtt_server
(library pthread)
(import __mqtt_common)
(export (class mqtt-server
(lock read-only (default (make-mutex "mqtt-server")))
(socket::socket read-only)
(subscriptions::pair-nil (default '()))
(retains::pair-nil (default '()))
(debug::long (default 0)))
(class mqtt-client-conn
(sock::socket read-only)
(lock read-only (default (make-mutex "mqtt-server-conn")))
(version::long read-only)
(connpk::mqtt-connect-packet read-only))
(mqtt-make-server ::obj #!key (debug 0))
(mqtt-server-loop ::mqtt-server ::procedure)
(mqtt-read-server-packet ip::input-port ::long)))
(define-struct topic name regexp qos)
(define (conn-id conn::mqtt-client-conn)
(with-access::mqtt-client-conn conn (sock lock version connpk)
(with-access::mqtt-connect-packet connpk (client-id)
client-id)))
(define (flag? flags flag)
(=fx (bit-and flags flag) flag))
(define (mqtt-make-server socket #!key (debug 0))
(instantiate::mqtt-server
(socket socket)
(debug debug)))
(define (mqtt-server-loop srv::mqtt-server on)
(unless (correct-arity? on 2)
(error "mqtt-server-loop" "wrong procedure" on))
(with-access::mqtt-server srv (socket)
(unwind-protect
(let loop ()
(let* ((sock (socket-accept socket))
(pk (mqtt-read-connect-packet (socket-input sock))))
(when (isa? pk mqtt-connect-packet)
(with-access::mqtt-connect-packet pk (version client-id flags)
(let ((conn (instantiate::mqtt-client-conn
(sock sock)
(version version)
(connpk pk))))
(on 'connect client-id)
(mqtt-conn-loop srv conn on))))
(loop)))
(mqtt-server-close srv))))
(define (mqtt-server-close srv::mqtt-server)
(with-access::mqtt-server srv (socket lock)
#f))
(define-macro (mqtt-server-debug srv thunk)
`(with-access::mqtt-server ,srv (debug)
(when (>fx debug 0)
(,thunk))))
(define (mqtt-conn-loop srv::mqtt-server conn::mqtt-client-conn on)
(with-access::mqtt-client-conn conn (sock lock version connpk)
(mqtt-server-debug srv
(lambda ()
(tprint "New client connected as " (conn-id conn))
(tprint "sending CONNACK to " (conn-id conn))))
(mqtt-write-connack-packet (socket-output sock) 0)
(thread-start!
(instantiate::pthread
(name "mqtt-server-loop")
(body (lambda ()
(with-trace 'mqtt "mqtt-connloop"
(trace-item "connid=" (conn-id conn))
(let ((ip (socket-input sock))
(op (socket-output sock)))
(let loop ()
(let ((pk (mqtt-read-server-packet ip version)))
(if (not (isa? pk mqtt-control-packet))
(mqtt-server-will srv on conn)
(with-access::mqtt-control-packet pk (type)
(on 'packet pk)
(cond
((=fx type (MQTT-CPT-CONNECT))
3.1 , error
(mqtt-server-will srv on conn)
#f)
((=fx type (MQTT-CPT-PUBLISH))
3.3
(mqtt-server-publish srv conn on pk)
(loop))
((=fx type (MQTT-CPT-PUBACK))
3.4
(loop))
((=fx type (MQTT-CPT-PUBREC))
3.5
(loop))
((=fx type (MQTT-CPT-SUBSCRIBE))
3.8
(mqtt-server-subscribe srv on conn pk)
(loop))
((=fx type (MQTT-CPT-UNSUBSCRIBE))
3.10
(mqtt-server-unsubscribe srv conn pk)
(loop))
((=fx type (MQTT-CPT-PINGREQ))
3.12
(mqtt-write-pingresp-packet op)
(loop))
((=fx type (MQTT-CPT-DISCONNECT))
3.14
#unspecified)
(else
(loop)))))))
(trace-item "closing " (conn-id conn))
(with-access::mqtt-server srv (lock subscriptions retains)
(synchronize lock
(set! subscriptions
(filter (lambda (sub)
(not (eq? (car sub) conn)))
subscriptions))
(set! retains
(filter (lambda (pub)
(not (eq? (car pub) conn)))
retains))))
(on 'disconnect (conn-id conn))
(socket-close sock)))))))))
(define (mqtt-server-will srv::mqtt-server on conn::mqtt-client-conn)
(with-access::mqtt-client-conn conn (connpk)
(with-access::mqtt-connect-packet connpk (flags will-topic will-message)
(when (flag? flags (MQTT-CONFLAG-WILL-FLAG))
(let* ((flags (if (flag? flags (MQTT-CONFLAG-WILL-RETAIN))
1 0))
(qos (bit-rsh
(bit-or
(bit-and flags (MQTT-CONFLAG-WILL-QOSL))
(bit-and flags (MQTT-CONFLAG-WILL-QOSH)))
3))
(pk (instantiate::mqtt-publish-packet
(type (MQTT-CPT-PUBLISH))
(topic will-topic)
(flags flags)
(qos qos)
(payload will-message))))
(mqtt-server-publish srv conn on pk))))))
(define (mqtt-server-publish srv::mqtt-server conn on pk::mqtt-publish-packet)
(with-trace 'mqtt "mqtt-server-publish"
(with-access::mqtt-server srv (lock subscriptions retains)
(with-access::mqtt-publish-packet pk (flags topic pid)
(trace-item "topic=" topic " retain=" (=fx (bit-and flags 1) 1))
(when (=fx (bit-and flags 1) 1)
(synchronize lock
(cond
((null? retains)
(set! retains (list (cons conn pk))))
((find (lambda (p)
(and (eq? (car p) conn)
(with-access::mqtt-publish-packet (cdr p) ((t topic))
(string=? t topic))))
retains)
=>
(lambda (p)
(set-cdr! p pk)))
(else
(set! retains (cons (cons conn pk) retains))))))
(with-access::mqtt-client-conn conn (sock)
(cond
((=fx (bit-and flags 2) 2)
(mqtt-write-puback-packet (socket-output sock) pid -1 '()))
((=fx (bit-and flags 4) 4)
(mqtt-write-pubrec-packet (socket-output sock) pid -1 '()))))
(for-each (lambda (subscription)
(let ((connsub (car subscription))
(topics (cdr subscription)))
(unless (eq? connsub conn)
(mqtt-conn-publish connsub topics on pk))))
subscriptions)))))
(define (mqtt-conn-publish conn topics on pk::mqtt-publish-packet)
(with-trace 'mqtt "mqtt-conn-publish"
(with-access::mqtt-publish-packet pk (topic payload)
(trace-item "conn=" (conn-id conn))
(trace-item "topics=" topics)
(trace-item "retain=" topic)
(for-each (lambda (t)
(when (mqtt-topic-match? (topic-regexp t) topic)
(with-access::mqtt-client-conn conn (sock connpk)
(with-handler
(lambda (e)
(with-access::mqtt-connect-packet connpk (client-id)
(fprintf (current-error-port)
"Could not publish ~s to client ~a"
topic
client-id))
(exception-notify e))
(begin
(mqtt-write-publish-packet
(socket-output sock)
#f 0 #f topic 0 payload)
(when on (on 'publish (cons (conn-id conn) topic))))))))
topics))))
(define (mqtt-server-subscribe srv::mqtt-server on conn pk::mqtt-control-packet)
(define (payload->topic payload)
(topic (car payload)
(topic-filter->regexp (car payload))
(cdr payload)))
(with-trace 'mqtt "mqtt-server-subscribe"
(with-access::mqtt-server srv (lock subscriptions retains)
(with-access::mqtt-control-packet pk (payload pid qos)
(let ((subtopics (map payload->topic payload)))
(synchronize lock
(trace-item "subscribe=" payload)
(trace-item "conn=" (conn-id conn))
(let ((cell (assq conn subscriptions)))
(if (not cell)
(set! subscriptions
(cons (cons conn subtopics)
subscriptions))
(for-each (lambda (payload)
(unless (find (lambda (t)
(string=? (topic-name t)
(car payload)))
(cdr cell))
(set-cdr! cell
(cons (payload->topic payload)
(cdr cell)))))
payload))))
(with-access::mqtt-client-conn conn (sock)
(mqtt-write-suback-packet (socket-output sock) pid '()))
(for-each (lambda (rt)
(mqtt-conn-publish conn subtopics on (cdr rt)))
retains))))))
(define (mqtt-server-unsubscribe srv::mqtt-server conn pk::mqtt-control-packet)
(with-trace 'mqtt "mqtt-server-unsubscribe"
(with-access::mqtt-server srv (lock subscriptions)
(with-access::mqtt-control-packet pk (payload pid)
(synchronize lock
(let ((cell (assq conn subscriptions)))
(when (pair? cell)
(set-cdr! cell
(filter! (lambda (topic)
(not (member (topic-name topic) payload)))
(cdr cell))))))
(with-access::mqtt-client-conn conn (sock)
3.10.4 Response
(mqtt-write-unsuback-packet (socket-output sock) pid))))))
(define (mqtt-read-server-packet ip::input-port version::long)
(with-trace 'mqtt "mqtt-read-server-packet"
(let ((header (read-byte ip)))
(if (eof-object? header)
header
(let ((ptype (bit-rsh header 4)))
(trace-item "type=" (mqtt-control-packet-type-name ptype))
(unread-char! (integer->char header) ip)
(cond
((=fx ptype (MQTT-CPT-CONNECT))
(mqtt-read-connect-packet ip))
((=fx ptype (MQTT-CPT-PUBLISH))
(mqtt-read-publish-packet ip version))
((=fx ptype (MQTT-CPT-SUBSCRIBE))
(mqtt-read-subscribe-packet ip version))
((=fx ptype (MQTT-CPT-UNSUBSCRIBE))
(mqtt-read-unsubscribe-packet ip version))
((=fx ptype (MQTT-CPT-PUBREC))
(mqtt-read-pubrec-packet ip version))
((=fx ptype (MQTT-CPT-PINGREQ))
(mqtt-read-pingreq-packet ip version))
((=fx ptype (MQTT-CPT-DISCONNECT))
(mqtt-read-disconnect-packet ip version))
(else
(error "mqtt:server" "Illegal packet type"
(mqtt-control-packet-type-name ptype)))))))))
|
20940a8188eecd731bfa95cf66234e342c3dd77304956aa081c3ef2d693159c0 | tebeka/popen | popen.clj | (ns ^{:doc "Subprocess library"
:author "Miki Tebeka <>"}
popen
(:require [clojure.java.io :as io]))
(defn popen
"Open a sub process, return the subprocess
args - List of command line arguments
:redirect - Redirect stderr to stdout
:dir - Set initial directory
:env - Set environment variables"
[args &{:keys [redirect dir env]}]
(let [pb (ProcessBuilder. args)
environment (.environment pb)]
(doseq [[k v] env] (.put environment k v))
(-> pb
(.directory (if (nil? dir) nil (io/file dir)))
(.redirectErrorStream (boolean redirect))
(.start))))
(defprotocol Popen
(stdout [this] "Process standard output (read from)")
(stdin [this] "Process standard input (write to)")
(stderr [this] "Process standard error (read from)")
(join [this] "Wait for process to terminate, return exit code")
(exit-code [this] "Process exit code (will wait for termination)")
(running? [this] "Return true if process still running")
(kill [this] "Kill process"))
(defn- exit-code- [p]
(try
(.exitValue p)
(catch IllegalThreadStateException e)))
(extend-type java.lang.Process
Popen
(stdout [this] (io/reader (.getInputStream this)))
(stdin [this] (io/writer (.getOutputStream this)))
(stderr [this] (io/reader (.getErrorStream this)))
(join [this] (.waitFor this))
(exit-code [this] (join this) (exit-code- this))
(running? [this] (nil? (exit-code- this)))
(kill [this] (.destroy this)))
(defn popen*
"Open a sub process, return the subprocess stdout
args - List of command line arguments
:redirect - Redirect stderr to stdout
:dir - Set initial directory"
[args &{:keys [redirect dir]}]
(stdout (popen args :redirect redirect :dir dir)))
| null | https://raw.githubusercontent.com/tebeka/popen/91cc8b16426e2db025c361888a8b9322e37808d9/src/popen.clj | clojure | (ns ^{:doc "Subprocess library"
:author "Miki Tebeka <>"}
popen
(:require [clojure.java.io :as io]))
(defn popen
"Open a sub process, return the subprocess
args - List of command line arguments
:redirect - Redirect stderr to stdout
:dir - Set initial directory
:env - Set environment variables"
[args &{:keys [redirect dir env]}]
(let [pb (ProcessBuilder. args)
environment (.environment pb)]
(doseq [[k v] env] (.put environment k v))
(-> pb
(.directory (if (nil? dir) nil (io/file dir)))
(.redirectErrorStream (boolean redirect))
(.start))))
(defprotocol Popen
(stdout [this] "Process standard output (read from)")
(stdin [this] "Process standard input (write to)")
(stderr [this] "Process standard error (read from)")
(join [this] "Wait for process to terminate, return exit code")
(exit-code [this] "Process exit code (will wait for termination)")
(running? [this] "Return true if process still running")
(kill [this] "Kill process"))
(defn- exit-code- [p]
(try
(.exitValue p)
(catch IllegalThreadStateException e)))
(extend-type java.lang.Process
Popen
(stdout [this] (io/reader (.getInputStream this)))
(stdin [this] (io/writer (.getOutputStream this)))
(stderr [this] (io/reader (.getErrorStream this)))
(join [this] (.waitFor this))
(exit-code [this] (join this) (exit-code- this))
(running? [this] (nil? (exit-code- this)))
(kill [this] (.destroy this)))
(defn popen*
"Open a sub process, return the subprocess stdout
args - List of command line arguments
:redirect - Redirect stderr to stdout
:dir - Set initial directory"
[args &{:keys [redirect dir]}]
(stdout (popen args :redirect redirect :dir dir)))
| |
8d7df251ebfecb8c63823c64b35e2ac6a3a79f50745d07f93d16d10164edbc05 | zenunomacedo/Tetris | types.hs | module Types where
import Graphics.UI.GLUT (GLfloat)
import GHC.IO.Handle (Handle)
import System.Random
type Lado = GLfloat
type Centro = (GLfloat, GLfloat)
type Linha = [Piece]
type Grelha = [Linha]
type Falling = (Char, Colour, [(Int, Int)])
data Piece = Piece Colour | Empty deriving (Eq, Show, Read)
data Everything = Everything {grelha :: Grelha,
falling :: Falling,
next :: Falling,
getGhost :: [(Int, Int)],
isFalling :: Bool,
interval :: Int,
score :: Int,
stored :: Falling,
alreadyStored :: Bool,
gameMode :: GameMode
} deriving (Show)
data Enemy = Enemy { enemyGrelha :: Grelha,
enemyFalling :: Falling,
enemyScore :: Int,
scrapLines :: [Linha],
getHandle :: Handle
}
stat0 :: IO Everything
stat0 = do
piece0 <- newFalling
piece1 <- newFalling
return (Everything newGrelha piece0 piece1 [] False interval0 0 dummy False Menu)
where dummy = ('F', Red, [])
enemy0 :: Enemy
enemy0 = Enemy newGrelha dummy 0 noScrap handle
where dummy = ('F', Red, [])
noScrap = []
handle = undefined
interval0 :: Int
tempo que demora uma peça a descer em ms
newGrelha = replicate 20 $ replicate 10 Empty
emptyLine = replicate 10 Empty
testLine = [Piece Red, Empty, Piece Green, Empty, Piece Blue, Piece Blue, Empty, Piece Green, Empty, Piece Red]
testGrelha = testLine : (init newGrelha)
randomColour :: IO Colour
randomColour = do
n <- randomRIO (1, length colours)
return $ colours!!(n-1)
newFalling :: IO Falling
newFalling = do
n <- randomRIO(1,7) :: IO Int
c <- randomColour
return $ matchPiece c ("SLlT|48"!!(n-1))
matchPiece :: Colour -> Char -> Falling
matchPiece c t = case t of
'S' -> ('S', c, [(6,19), (5,19), (5,20), (6,20)])
'L' -> ('L', c, [(6,19), (5,19), (5,20), (5,21)])
'l' -> ('l', c, [(5,19), (6,19), (6,20), (6,21)])
'T' -> ('T', c, [(6,20), (5,19), (5,20), (5,21)])
'|' -> ('|', c, [(5,19), (5,20), (5,21), (5,22)])
'4' -> ('4', c, [(6,19), (6,20), (5,20), (5,21)])
'8' -> ('8', c, [(5,19), (5,20), (6,20), (6,21)])
_ -> ('F', c, [])
data GameMode = Menu | SinglePlayer | MultiPlayer | GameOver deriving (Show, Eq)
data Colour = Red | Green | Blue | Orange | Purple | Yellow | Cyan | Pink | Gray deriving (Eq, Show, Read)
colours :: [Colour]
colours = [Red, Green, Blue, Orange, Purple, Yellow, Cyan, Pink]
getColour :: Colour -> (GLfloat, GLfloat, GLfloat)
getColour Red = (255,0,0)
getColour Green = (0, 204,0)
getColour Blue = (0,0,255)
getColour Orange = (255, 128, 0)
getColour Purple = (127, 0, 255)
getColour Yellow = (255, 255, 56)
getColour Cyan = (0,255,255)
getColour Pink = (255,0,127)
getColour Gray = (96,96,96)
| null | https://raw.githubusercontent.com/zenunomacedo/Tetris/2b9c660bb79001d553b592d80aa75dbb191b5baf/Tetris/types.hs | haskell | module Types where
import Graphics.UI.GLUT (GLfloat)
import GHC.IO.Handle (Handle)
import System.Random
type Lado = GLfloat
type Centro = (GLfloat, GLfloat)
type Linha = [Piece]
type Grelha = [Linha]
type Falling = (Char, Colour, [(Int, Int)])
data Piece = Piece Colour | Empty deriving (Eq, Show, Read)
data Everything = Everything {grelha :: Grelha,
falling :: Falling,
next :: Falling,
getGhost :: [(Int, Int)],
isFalling :: Bool,
interval :: Int,
score :: Int,
stored :: Falling,
alreadyStored :: Bool,
gameMode :: GameMode
} deriving (Show)
data Enemy = Enemy { enemyGrelha :: Grelha,
enemyFalling :: Falling,
enemyScore :: Int,
scrapLines :: [Linha],
getHandle :: Handle
}
stat0 :: IO Everything
stat0 = do
piece0 <- newFalling
piece1 <- newFalling
return (Everything newGrelha piece0 piece1 [] False interval0 0 dummy False Menu)
where dummy = ('F', Red, [])
enemy0 :: Enemy
enemy0 = Enemy newGrelha dummy 0 noScrap handle
where dummy = ('F', Red, [])
noScrap = []
handle = undefined
interval0 :: Int
tempo que demora uma peça a descer em ms
newGrelha = replicate 20 $ replicate 10 Empty
emptyLine = replicate 10 Empty
testLine = [Piece Red, Empty, Piece Green, Empty, Piece Blue, Piece Blue, Empty, Piece Green, Empty, Piece Red]
testGrelha = testLine : (init newGrelha)
randomColour :: IO Colour
randomColour = do
n <- randomRIO (1, length colours)
return $ colours!!(n-1)
newFalling :: IO Falling
newFalling = do
n <- randomRIO(1,7) :: IO Int
c <- randomColour
return $ matchPiece c ("SLlT|48"!!(n-1))
matchPiece :: Colour -> Char -> Falling
matchPiece c t = case t of
'S' -> ('S', c, [(6,19), (5,19), (5,20), (6,20)])
'L' -> ('L', c, [(6,19), (5,19), (5,20), (5,21)])
'l' -> ('l', c, [(5,19), (6,19), (6,20), (6,21)])
'T' -> ('T', c, [(6,20), (5,19), (5,20), (5,21)])
'|' -> ('|', c, [(5,19), (5,20), (5,21), (5,22)])
'4' -> ('4', c, [(6,19), (6,20), (5,20), (5,21)])
'8' -> ('8', c, [(5,19), (5,20), (6,20), (6,21)])
_ -> ('F', c, [])
data GameMode = Menu | SinglePlayer | MultiPlayer | GameOver deriving (Show, Eq)
data Colour = Red | Green | Blue | Orange | Purple | Yellow | Cyan | Pink | Gray deriving (Eq, Show, Read)
colours :: [Colour]
colours = [Red, Green, Blue, Orange, Purple, Yellow, Cyan, Pink]
getColour :: Colour -> (GLfloat, GLfloat, GLfloat)
getColour Red = (255,0,0)
getColour Green = (0, 204,0)
getColour Blue = (0,0,255)
getColour Orange = (255, 128, 0)
getColour Purple = (127, 0, 255)
getColour Yellow = (255, 255, 56)
getColour Cyan = (0,255,255)
getColour Pink = (255,0,127)
getColour Gray = (96,96,96)
| |
707127ef89222b378e9d15a4f94d7ec3b586cdd803a5a849b54602dc7c9b3b38 | puppetlabs/pcp-broker | server.clj | (ns puppetlabs.pcp.testutils.server
(:require [puppetlabs.experimental.websockets.client :as websockets-client]
[puppetlabs.trapperkeeper.core :as trapperkeeper]
[puppetlabs.trapperkeeper.services :refer [service-context]]
[puppetlabs.trapperkeeper.services.scheduler.scheduler-service :refer [scheduler-service]]
[puppetlabs.trapperkeeper.services.webrouting.webrouting-service :refer [webrouting-service]]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer [jetty9-service]]
[puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]]))
;; These handlers exist to be redefined.
(defn on-connect [server ws])
(defn on-error [server ws e])
(defn on-close [server ws status-code reason])
(defn on-text [server ws text])
(defn on-bytes [server ws bytes offset len])
(defprotocol MockServer)
(trapperkeeper/defservice mock-server
MockServer
[[:WebroutingService add-websocket-handler]]
(init [this context]
(let [inventory (atom [])]
(doseq [server [:mock-server-1
:mock-server-2
:mock-server-3]]
(add-websocket-handler this
{:on-connect (fn [ws]
(swap! inventory conj ws)
(on-connect server ws))
:on-error (partial on-error server)
:on-close (partial on-close server)
:on-text (partial on-text server)
:on-bytes (partial on-bytes server)}
{:route-id server
:server-id server}))
(assoc context :inventory inventory)))
(stop [this context]
(doseq [ws @(:inventory context)]
(try
;; Close may encounter a null pointer if the underlying session has already closed.
(websockets-client/close! ws)
(catch NullPointerException _)))
;; TODO: this pause is necessary to allow a successful reconnection
;; from the broker. We need to understand why and eliminate the
;; problem. This is covered in PCP-720.
(Thread/sleep 200)
(dissoc context :inventory)))
(def mock-server-services
[mock-server webrouting-service jetty9-service])
(defn wait-for-inbound-connection
[svc-context]
(loop [i 0]
(when (empty? @(:inventory svc-context))
(if (> i 50)
(throw (Exception. "Test timed out waiting for inbound connection"))
(do
(Thread/sleep 100)
(recur (inc i)))))))
| null | https://raw.githubusercontent.com/puppetlabs/pcp-broker/7806c6a6045c406c256b2c9d6129382923ba3d03/test/utils/puppetlabs/pcp/testutils/server.clj | clojure | These handlers exist to be redefined.
Close may encounter a null pointer if the underlying session has already closed.
TODO: this pause is necessary to allow a successful reconnection
from the broker. We need to understand why and eliminate the
problem. This is covered in PCP-720. | (ns puppetlabs.pcp.testutils.server
(:require [puppetlabs.experimental.websockets.client :as websockets-client]
[puppetlabs.trapperkeeper.core :as trapperkeeper]
[puppetlabs.trapperkeeper.services :refer [service-context]]
[puppetlabs.trapperkeeper.services.scheduler.scheduler-service :refer [scheduler-service]]
[puppetlabs.trapperkeeper.services.webrouting.webrouting-service :refer [webrouting-service]]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer [jetty9-service]]
[puppetlabs.trapperkeeper.testutils.bootstrap :refer [with-app-with-config]]))
(defn on-connect [server ws])
(defn on-error [server ws e])
(defn on-close [server ws status-code reason])
(defn on-text [server ws text])
(defn on-bytes [server ws bytes offset len])
(defprotocol MockServer)
(trapperkeeper/defservice mock-server
MockServer
[[:WebroutingService add-websocket-handler]]
(init [this context]
(let [inventory (atom [])]
(doseq [server [:mock-server-1
:mock-server-2
:mock-server-3]]
(add-websocket-handler this
{:on-connect (fn [ws]
(swap! inventory conj ws)
(on-connect server ws))
:on-error (partial on-error server)
:on-close (partial on-close server)
:on-text (partial on-text server)
:on-bytes (partial on-bytes server)}
{:route-id server
:server-id server}))
(assoc context :inventory inventory)))
(stop [this context]
(doseq [ws @(:inventory context)]
(try
(websockets-client/close! ws)
(catch NullPointerException _)))
(Thread/sleep 200)
(dissoc context :inventory)))
(def mock-server-services
[mock-server webrouting-service jetty9-service])
(defn wait-for-inbound-connection
[svc-context]
(loop [i 0]
(when (empty? @(:inventory svc-context))
(if (> i 50)
(throw (Exception. "Test timed out waiting for inbound connection"))
(do
(Thread/sleep 100)
(recur (inc i)))))))
|
73867f7f958ce04e2bfa08a71454be2cbc48443ae90d0c60aa2fca5fe80e0cb2 | mclumd/Meta-AQUA | unify.lisp | ;;;-*- Mode: Lisp; Package: NONLIN -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
Application : NONLIN
Appl . Version : 1.3
Appl . Date : Oct. 1992
;;;;
;;;; File: UNIFY.LISP
;;;; Contents: Unification routines.
;;;;
Dept . of Computer Science , University of Maryland at College Park
;;;; email:
;;;;
Language : Macintosh Common Lisp 2.0
;;;;
Requirements : package NONLIN
;;;;
;;;; History:
;;;; Date Who Modification
;;;; ---------------------------------------------------------------------------------
(in-package :nonlin)
From Charniak & McDermott ( see pp . ? ? ? for documentation )
(defstruct (pcvar (:print-function print-pcvar)) id)
(defvar *assertions* nil " list of dumb assertions")
(defvar *occurs-check-p* t)
(defvar *retrieval-methods* (make-hash-table))
(defvar *storage-methods* (make-hash-table))
(defun print-pcvar (var stream depth)
(declare (ignore depth))
(format stream "!~s" (pcvar-id var))
)
(set-macro-character #\!
#'(lambda (stream char)
(declare (ignore char))
(make-pcvar :id (read stream t nil t)))
t)
(defun unify (pat1 pat2)
(unify-1 pat1 pat2 nil))
(defun unify-1 (pat1 pat2 sub)
(cond ((pcvar-p pat1)
(var-unify pat1 pat2 sub))
((pcvar-p pat2)
(var-unify pat2 pat1 sub))
((atom pat1)
(cond ((eql pat1 pat2) (list sub))
(t nil)))
((atom pat2) nil)
(t (for (sub :in (unify-1 (car pat1) (car pat2) sub))
:splice
(unify-1 (cdr pat1) (cdr pat2) sub)))))
(defun var-unify (pcvar pat sub)
(cond ((or (eql pcvar pat)
(and (pcvar-p pat)
(eql (pcvar-id pcvar)
(pcvar-id pat))))
(list sub))
(t (let ((binding (pcvar-binding pcvar sub)))
(cond (binding
(unify-1 (binding-value binding)
pat sub))
((and *occurs-check-p*
(occurs-in-p pcvar pat sub))
nil)
(t
(list (extend-binding pcvar pat sub))
))))))
(defun occurs-in-p (pcvar pat sub)
(cond ((pcvar-p pat)
(or (eq (pcvar-id pcvar)(pcvar-id pat))
(let ((binding (pcvar-binding pat sub)))
(and binding
(occurs-in-p pcvar
(binding-value binding) sub)))))
((atom pat) nil)
(t (or (occurs-in-p pcvar (car pat) sub)
(occurs-in-p pcvar (cdr pat) sub))))) ;
(defun pcvar-binding (pcvar alist)
(assoc (pcvar-id pcvar) alist))
(defun extend-binding (pcvar pat alist)
(cons (list (pcvar-id pcvar) pat)
alist))
(defun binding-value (binding) (cadr binding))
from pp 463
;;;this wont be used unless we are doing backward chaining or
;;;doing "and" type retrievals (for (on ?x ?y)&(on ?y ?z)&(on ?z ?w) type)
(defun replace-variables (pat sub)
(cond ((pcvar-p pat) (pcvar-value pat sub))
((atom pat) pat)
(t (cons (replace-variables (car pat) sub)
(replace-variables (cdr pat) sub)))))
(defun pcvar-value (pat sub)
(let ((binding (pcvar-binding pat sub)))
(cond ((null binding) pat)
(t (let ((value (binding-value binding)))
(cond ((eql value pat) pat)
(t (safe-replace-variables value sub)
)))))))
;the retrieval section
(defun safe-replace-variables (pat sub)
(let* ((old-renames (rename-list pat))
(new-pat (replace-variables pat sub))
(new-renames (rename-list new-pat)))
(rename-variables new-pat
(for (pair :in new-renames)
:when (not (assoc (car pair) old-renames))
:save pair))))
(defun store-pattern (pat &rest keys)
(let ((safe-pat (uniquify-variables pat))
(method (and (consp pat)
(storage-method
(pattern-head pat)))))
(cond (method (apply method safe-pat keys))
((not
(there-exists
(assertion :in (eval `(dumb-fetch ',safe-pat ,@keys)))
(variants-p safe-pat assertion)))
(eval `(dumb-index ',safe-pat ,@keys))))
safe-pat))
(defmacro store-pat (pat &rest keys)
;;this is so that the place is not evaluated
`(apply #'store-pattern ,pat ',keys))
(defun variants-p (pat1 pat2)
(let ((alist '()))
(labels ((variant-ids-p (id1 id2)
(let ((entry1 (assoc id1 alist))
(entry2 (rassoc id2 alist)))
(if (and (null entry1)
(null entry2))
(push (cons id1 id2) alist))
(eq entry1 entry2)))
(test (pat1 pat2)
(or (and (pcvar-p pat1)
(pcvar-p pat2)
(variant-ids-p
(pcvar-id pat1)
(pcvar-id pat2)))
(eql pat1 pat2)
(and (consp pat1)
(consp pat2)
(test (car pat1) (car pat2))
(test (cdr pat1) (cdr pat2))
))))
(test pat1 pat2))))
(defun retrieve (pat &rest keyword-pairs )
(let ((method (and (consp pat)
(retrieval-method (pattern-head pat)))))
(if method
(eval `(apply ',method ',pat ',keyword-pairs))
(nconc (apply #'from-assertions pat keyword-pairs)
nil
;;(from-backward-chaining pat)
;;we don't use the back-ward chaining for now
))))
;;;this slightly complex from-assertions takes care of retrieval from
;;;specified data list (keyword :from-data-list), the key function used to
;;;get pattern from data list (:key-function)
;;;make sure that the key-function is given as a function name, without
;;;"function" special form, if you want :with-replacement to work
;;;if :with-pat is set, then the result is a list of items of the form
( < list of data>.<list of substitutions > ) . thus , ( car item ) gives the
data list and ( cadr item ) gives the binding list
(defun from-assertions (pat &key with-pat with-replacement from-data-list key-function)
(let ((from-data-list (or from-data-list
(dumb-fetch pat))))
(for (data :in from-data-list)
:splice (let* ((assertion (if key-function
(funcall key-function data)
data))
(result (unify assertion pat)))
;;; we unify the assertion with pat rather than other way round
;;; so that we get right binding list....
(if result
(if with-pat
(progn
(if with-replacement
(progn
(if key-function
(eval `(setf (,key-function ',data)
(safe-replace-variables
',assertion (car ',result))))
(setf data (safe-replace-variables
assertion (car result))))))
(list (list (list data) (car result))))
result))
))))
these two will go away and will be replaced by the gost and tome retrieval functions
(defmacro dumb-index (pat &key (place '*assertions*) )
`(progn (push ,pat ,place)
,pat))
(defmacro dumb-fetch (pat &key (place '*assertions*))
(declare (ignore pat))
`,place)
from pp 206
(defun uniquify-variables (pat)
(let ((new-names (rename-list pat nil)))
(if (null new-names)
pat
(rename-variables pat new-names))))
(defun rename-list (pat &optional new-names)
(cond ((pcvar-p pat)
(let ((id (pcvar-id pat)))
(cond ((assoc id new-names) new-names)
(t (cons (list id (make-pcvar :id
(copy-symbol id)))
new-names)))))
((consp pat)
(rename-list (cdr pat)
(rename-list (car pat) new-names)))
(t new-names)))
(defun rename-variables (pat new-names)
(cond ((pcvar-p pat)
(let ((entry
(assoc (pcvar-id pat) new-names)))
(if entry (cadr entry) pat)))
((atom pat)
(let ((entry (assoc pat new-names)))
(if entry (pcvar-id (cadr entry)) pat)))
(t
(cons (rename-variables (car pat) new-names)
(rename-variables (cdr pat) new-names)))))
storage methods can be implemented using code in pp 215
;;;right now, i will use a dumb function...
(defmacro define-retrieval-method (head args . body)
`(progn
(setf (gethash ',head *retrieval-methods*)
#'(lambda ,args ,@body))
',head))
(defun retrieval-method (key)
(gethash key *retrieval-methods*))
(defmacro define-storage-method (head args . body)
`(progn
(setf (gethash ',head *storage-methods*)
#'(lambda ,args ,@body))
',head))
(defun storage-method (key)
(gethash key *storage-methods*))
(defun pattern-head (pat)
(car pat))
(defun pattern-args (pat)
(cdr pat))
;;;the storage and retrieval methods for and
(define-storage-method and (pat &rest keys)
(for (assertion :in (pattern-args pat))
:do (apply #'store-pattern assertion keys)))
(define-retrieval-method and (pat &rest keyword-pairs)
(let ((results (apply #'conjunct-retrieve
(pattern-args pat) nil keyword-pairs)))
(if (getf keyword-pairs :with-pat)
(for (result :in results)
:save (list (progn (push 'and result) result)))
;;this way, the data is always single..
results ; else
)))
(defun partial-p (result)
(eq (car result) '*partial*)
)
(defun partial-mapping (result)
;;if the result is partial, then the mapping will be in the
third position
(if (partial-p result)
(third result)
result
))
(define-retrieval-method pand (pat &rest keyword-pairs)
;;this will never be called with any keywords other than
;;from-data-list
(let ((results (apply #'pconjunct-retrieve
(pattern-args pat) nil keyword-pairs))
filtered-results best
sresults)
(for (result :in results)
:when (not (partial-p result))
:do (push result filtered-results))
(cond ( filtered-results)
;;ie, if there are non-partial results,
;;pand is equivalent to and you
;;just return them
;;else
(t ;;all the results are partial matches..
(setq sresults (sort results #'> :key #'second))
(setq best (second (first sresults)))
;;best is the minimum number of predicates not
;;matched
(for (sresult :in sresults)
:when (eql (second sresult) best)
:save sresult
)) ;;the best sresults will be returned..
)))
(defun pconjunct-retrieve (conjuncts sub &rest keyword-pairs)
;;supposed to return the best match when it fails...
;;doesn't care about with-pat keyword...
(cond ((null conjuncts) (list sub))
(t (let ((subs (apply #'retrieve
(safe-replace-variables
(car conjuncts)
sub)
keyword-pairs)))
(cond ((null subs)
`((*partial* ,(- 0 (length conjuncts))
;;so many conjuncts are not working..
,sub)))
(t (for (next-sub :in subs)
:splice (apply #'pconjunct-retrieve
(cdr conjuncts)
(append next-sub sub)
keyword-pairs)))
))))
)
(defun conjunct-retrieve (conjuncts sub &rest keyword-pairs)
(cond ((null conjuncts) (list sub))
(t (for (next-sub :in
(apply #'retrieve
(safe-replace-variables
(car conjuncts)
(if (getf keyword-pairs :with-pat)
;;if the retrieval is being done with patterns,
;;the result given by find-assertions will be
;;in the form ( (data . sub)), so sub is
(cadr sub)
sub))
keyword-pairs))
:splice (apply #'conjunct-retrieve
(cdr conjuncts)
(if (getf keyword-pairs :with-pat)
(list (append (car next-sub) (car sub))
(append (cadr next-sub) (cadr sub)))
(append next-sub sub))
keyword-pairs)))))
;;;for not
(define-retrieval-method not (pat &rest keyword-pairs)
(or (apply #'from-assertions pat keyword-pairs)
(if (apply #'retrieve (car (pattern-args pat)) keyword-pairs )
nil
(list nil))))
;;;there is no separate storage method for not...
;;;though we can say that to store (not (on a b)) we just remove anything that
;;;unifies with (on a b)????
;;; my function for schema reading;;;;
(defun pcvar-subst (id subpcvar glist)
substitute all occurances of a pcvar with " i d " by
;; at all levels of the list glist
(for (x :in glist)
:save (cond ((consp x)
(pcvar-subst id subpcvar x))
((and (pcvar-p x)
(eql (pcvar-id x) id))
subpcvar)
(t x))))
;;;convert-pat takes a possibly negated pattern and returns its
ground form and sign ( multiple values ) called by gost and tome
(defun convert-pat (pattern)
(let (gpat sign)
(cond ((eql (first pattern) 'not)
(setf gpat (cadr pattern))
(setf sign :minus))
(t (setf gpat pattern)
(setf sign :plus)))
(values gpat sign)))
(defun sign (pat)
(multiple-value-bind (pattern sgn) (convert-pat pat)
(declare (ignore pattern))
(return-from sign sgn)))
(defun negate-pat (pat)
(if (eql (car pat) 'not)
(cadr pat)
;;else
(list 'not pat)
))
;;;this function checks if a given pattern is ground (no variables)
;;;won't work for conjunctive patterns
(defun ground-pat-p (pattern)
(not (some #'pcvar-p pattern)))
;;; macros for taking care of retrieval results-they correctly find the
;;; binding and data from the retrieval result.
(defun retrieval-result-binding (result)
(if (eql (length result) 2)
which means there is data along with binding ( ( data ) ( bindlist ) )
(cadr result)
;; else
result))
(defun retrieval-result-data (result)
(if (eql (length result) 2)
(if (eql (length (car result)) 1)
only one data matches
(caar result)
;; else, for conjunctive-retrieval??
;; with the change in retrieval-method of 'and
;; the else part is no longer required
;; (car result)
)
result))
; (error "~s does not contain any retrieval data" result)))
(defun remove-binding (pat sub)
(cond ((atom pat) (var-value pat sub))
(t (cons (remove-binding (car pat) sub)
(remove-binding (cdr pat) sub)))))
(defun value-binding (value alist)
(assoc value alist))
(defun var-value (pat sub)
(let ((binding (value-binding pat sub)))
(cond ((null binding) pat)
(t (make-pcvar :id (cadr binding))))))
| null | https://raw.githubusercontent.com/mclumd/Meta-AQUA/e4d4f83330fd07d1354aec245a49bde9e246c618/Nonlin/unify.lisp | lisp | -*- Mode: Lisp; Package: NONLIN -*-
File: UNIFY.LISP
Contents: Unification routines.
email:
History:
Date Who Modification
---------------------------------------------------------------------------------
this wont be used unless we are doing backward chaining or
doing "and" type retrievals (for (on ?x ?y)&(on ?y ?z)&(on ?z ?w) type)
the retrieval section
this is so that the place is not evaluated
(from-backward-chaining pat)
we don't use the back-ward chaining for now
this slightly complex from-assertions takes care of retrieval from
specified data list (keyword :from-data-list), the key function used to
get pattern from data list (:key-function)
make sure that the key-function is given as a function name, without
"function" special form, if you want :with-replacement to work
if :with-pat is set, then the result is a list of items of the form
we unify the assertion with pat rather than other way round
so that we get right binding list....
right now, i will use a dumb function...
the storage and retrieval methods for and
this way, the data is always single..
else
if the result is partial, then the mapping will be in the
this will never be called with any keywords other than
from-data-list
ie, if there are non-partial results,
pand is equivalent to and you
just return them
else
all the results are partial matches..
best is the minimum number of predicates not
matched
the best sresults will be returned..
supposed to return the best match when it fails...
doesn't care about with-pat keyword...
so many conjuncts are not working..
if the retrieval is being done with patterns,
the result given by find-assertions will be
in the form ( (data . sub)), so sub is
for not
there is no separate storage method for not...
though we can say that to store (not (on a b)) we just remove anything that
unifies with (on a b)????
my function for schema reading;;;;
at all levels of the list glist
convert-pat takes a possibly negated pattern and returns its
else
this function checks if a given pattern is ground (no variables)
won't work for conjunctive patterns
macros for taking care of retrieval results-they correctly find the
binding and data from the retrieval result.
else
else, for conjunctive-retrieval??
with the change in retrieval-method of 'and
the else part is no longer required
(car result)
(error "~s does not contain any retrieval data" result)))
| Application : NONLIN
Appl . Version : 1.3
Appl . Date : Oct. 1992
Dept . of Computer Science , University of Maryland at College Park
Language : Macintosh Common Lisp 2.0
Requirements : package NONLIN
(in-package :nonlin)
From Charniak & McDermott ( see pp . ? ? ? for documentation )
(defstruct (pcvar (:print-function print-pcvar)) id)
(defvar *assertions* nil " list of dumb assertions")
(defvar *occurs-check-p* t)
(defvar *retrieval-methods* (make-hash-table))
(defvar *storage-methods* (make-hash-table))
(defun print-pcvar (var stream depth)
(declare (ignore depth))
(format stream "!~s" (pcvar-id var))
)
(set-macro-character #\!
#'(lambda (stream char)
(declare (ignore char))
(make-pcvar :id (read stream t nil t)))
t)
(defun unify (pat1 pat2)
(unify-1 pat1 pat2 nil))
(defun unify-1 (pat1 pat2 sub)
(cond ((pcvar-p pat1)
(var-unify pat1 pat2 sub))
((pcvar-p pat2)
(var-unify pat2 pat1 sub))
((atom pat1)
(cond ((eql pat1 pat2) (list sub))
(t nil)))
((atom pat2) nil)
(t (for (sub :in (unify-1 (car pat1) (car pat2) sub))
:splice
(unify-1 (cdr pat1) (cdr pat2) sub)))))
(defun var-unify (pcvar pat sub)
(cond ((or (eql pcvar pat)
(and (pcvar-p pat)
(eql (pcvar-id pcvar)
(pcvar-id pat))))
(list sub))
(t (let ((binding (pcvar-binding pcvar sub)))
(cond (binding
(unify-1 (binding-value binding)
pat sub))
((and *occurs-check-p*
(occurs-in-p pcvar pat sub))
nil)
(t
(list (extend-binding pcvar pat sub))
))))))
(defun occurs-in-p (pcvar pat sub)
(cond ((pcvar-p pat)
(or (eq (pcvar-id pcvar)(pcvar-id pat))
(let ((binding (pcvar-binding pat sub)))
(and binding
(occurs-in-p pcvar
(binding-value binding) sub)))))
((atom pat) nil)
(t (or (occurs-in-p pcvar (car pat) sub)
(defun pcvar-binding (pcvar alist)
(assoc (pcvar-id pcvar) alist))
(defun extend-binding (pcvar pat alist)
(cons (list (pcvar-id pcvar) pat)
alist))
(defun binding-value (binding) (cadr binding))
from pp 463
(defun replace-variables (pat sub)
(cond ((pcvar-p pat) (pcvar-value pat sub))
((atom pat) pat)
(t (cons (replace-variables (car pat) sub)
(replace-variables (cdr pat) sub)))))
(defun pcvar-value (pat sub)
(let ((binding (pcvar-binding pat sub)))
(cond ((null binding) pat)
(t (let ((value (binding-value binding)))
(cond ((eql value pat) pat)
(t (safe-replace-variables value sub)
)))))))
(defun safe-replace-variables (pat sub)
(let* ((old-renames (rename-list pat))
(new-pat (replace-variables pat sub))
(new-renames (rename-list new-pat)))
(rename-variables new-pat
(for (pair :in new-renames)
:when (not (assoc (car pair) old-renames))
:save pair))))
(defun store-pattern (pat &rest keys)
(let ((safe-pat (uniquify-variables pat))
(method (and (consp pat)
(storage-method
(pattern-head pat)))))
(cond (method (apply method safe-pat keys))
((not
(there-exists
(assertion :in (eval `(dumb-fetch ',safe-pat ,@keys)))
(variants-p safe-pat assertion)))
(eval `(dumb-index ',safe-pat ,@keys))))
safe-pat))
(defmacro store-pat (pat &rest keys)
`(apply #'store-pattern ,pat ',keys))
(defun variants-p (pat1 pat2)
(let ((alist '()))
(labels ((variant-ids-p (id1 id2)
(let ((entry1 (assoc id1 alist))
(entry2 (rassoc id2 alist)))
(if (and (null entry1)
(null entry2))
(push (cons id1 id2) alist))
(eq entry1 entry2)))
(test (pat1 pat2)
(or (and (pcvar-p pat1)
(pcvar-p pat2)
(variant-ids-p
(pcvar-id pat1)
(pcvar-id pat2)))
(eql pat1 pat2)
(and (consp pat1)
(consp pat2)
(test (car pat1) (car pat2))
(test (cdr pat1) (cdr pat2))
))))
(test pat1 pat2))))
(defun retrieve (pat &rest keyword-pairs )
(let ((method (and (consp pat)
(retrieval-method (pattern-head pat)))))
(if method
(eval `(apply ',method ',pat ',keyword-pairs))
(nconc (apply #'from-assertions pat keyword-pairs)
nil
))))
( < list of data>.<list of substitutions > ) . thus , ( car item ) gives the
data list and ( cadr item ) gives the binding list
(defun from-assertions (pat &key with-pat with-replacement from-data-list key-function)
(let ((from-data-list (or from-data-list
(dumb-fetch pat))))
(for (data :in from-data-list)
:splice (let* ((assertion (if key-function
(funcall key-function data)
data))
(result (unify assertion pat)))
(if result
(if with-pat
(progn
(if with-replacement
(progn
(if key-function
(eval `(setf (,key-function ',data)
(safe-replace-variables
',assertion (car ',result))))
(setf data (safe-replace-variables
assertion (car result))))))
(list (list (list data) (car result))))
result))
))))
these two will go away and will be replaced by the gost and tome retrieval functions
(defmacro dumb-index (pat &key (place '*assertions*) )
`(progn (push ,pat ,place)
,pat))
(defmacro dumb-fetch (pat &key (place '*assertions*))
(declare (ignore pat))
`,place)
from pp 206
(defun uniquify-variables (pat)
(let ((new-names (rename-list pat nil)))
(if (null new-names)
pat
(rename-variables pat new-names))))
(defun rename-list (pat &optional new-names)
(cond ((pcvar-p pat)
(let ((id (pcvar-id pat)))
(cond ((assoc id new-names) new-names)
(t (cons (list id (make-pcvar :id
(copy-symbol id)))
new-names)))))
((consp pat)
(rename-list (cdr pat)
(rename-list (car pat) new-names)))
(t new-names)))
(defun rename-variables (pat new-names)
(cond ((pcvar-p pat)
(let ((entry
(assoc (pcvar-id pat) new-names)))
(if entry (cadr entry) pat)))
((atom pat)
(let ((entry (assoc pat new-names)))
(if entry (pcvar-id (cadr entry)) pat)))
(t
(cons (rename-variables (car pat) new-names)
(rename-variables (cdr pat) new-names)))))
storage methods can be implemented using code in pp 215
(defmacro define-retrieval-method (head args . body)
`(progn
(setf (gethash ',head *retrieval-methods*)
#'(lambda ,args ,@body))
',head))
(defun retrieval-method (key)
(gethash key *retrieval-methods*))
(defmacro define-storage-method (head args . body)
`(progn
(setf (gethash ',head *storage-methods*)
#'(lambda ,args ,@body))
',head))
(defun storage-method (key)
(gethash key *storage-methods*))
(defun pattern-head (pat)
(car pat))
(defun pattern-args (pat)
(cdr pat))
(define-storage-method and (pat &rest keys)
(for (assertion :in (pattern-args pat))
:do (apply #'store-pattern assertion keys)))
(define-retrieval-method and (pat &rest keyword-pairs)
(let ((results (apply #'conjunct-retrieve
(pattern-args pat) nil keyword-pairs)))
(if (getf keyword-pairs :with-pat)
(for (result :in results)
:save (list (progn (push 'and result) result)))
)))
(defun partial-p (result)
(eq (car result) '*partial*)
)
(defun partial-mapping (result)
third position
(if (partial-p result)
(third result)
result
))
(define-retrieval-method pand (pat &rest keyword-pairs)
(let ((results (apply #'pconjunct-retrieve
(pattern-args pat) nil keyword-pairs))
filtered-results best
sresults)
(for (result :in results)
:when (not (partial-p result))
:do (push result filtered-results))
(cond ( filtered-results)
(setq sresults (sort results #'> :key #'second))
(setq best (second (first sresults)))
(for (sresult :in sresults)
:when (eql (second sresult) best)
:save sresult
)))
(defun pconjunct-retrieve (conjuncts sub &rest keyword-pairs)
(cond ((null conjuncts) (list sub))
(t (let ((subs (apply #'retrieve
(safe-replace-variables
(car conjuncts)
sub)
keyword-pairs)))
(cond ((null subs)
`((*partial* ,(- 0 (length conjuncts))
,sub)))
(t (for (next-sub :in subs)
:splice (apply #'pconjunct-retrieve
(cdr conjuncts)
(append next-sub sub)
keyword-pairs)))
))))
)
(defun conjunct-retrieve (conjuncts sub &rest keyword-pairs)
(cond ((null conjuncts) (list sub))
(t (for (next-sub :in
(apply #'retrieve
(safe-replace-variables
(car conjuncts)
(if (getf keyword-pairs :with-pat)
(cadr sub)
sub))
keyword-pairs))
:splice (apply #'conjunct-retrieve
(cdr conjuncts)
(if (getf keyword-pairs :with-pat)
(list (append (car next-sub) (car sub))
(append (cadr next-sub) (cadr sub)))
(append next-sub sub))
keyword-pairs)))))
(define-retrieval-method not (pat &rest keyword-pairs)
(or (apply #'from-assertions pat keyword-pairs)
(if (apply #'retrieve (car (pattern-args pat)) keyword-pairs )
nil
(list nil))))
(defun pcvar-subst (id subpcvar glist)
substitute all occurances of a pcvar with " i d " by
(for (x :in glist)
:save (cond ((consp x)
(pcvar-subst id subpcvar x))
((and (pcvar-p x)
(eql (pcvar-id x) id))
subpcvar)
(t x))))
ground form and sign ( multiple values ) called by gost and tome
(defun convert-pat (pattern)
(let (gpat sign)
(cond ((eql (first pattern) 'not)
(setf gpat (cadr pattern))
(setf sign :minus))
(t (setf gpat pattern)
(setf sign :plus)))
(values gpat sign)))
(defun sign (pat)
(multiple-value-bind (pattern sgn) (convert-pat pat)
(declare (ignore pattern))
(return-from sign sgn)))
(defun negate-pat (pat)
(if (eql (car pat) 'not)
(cadr pat)
(list 'not pat)
))
(defun ground-pat-p (pattern)
(not (some #'pcvar-p pattern)))
(defun retrieval-result-binding (result)
(if (eql (length result) 2)
which means there is data along with binding ( ( data ) ( bindlist ) )
(cadr result)
result))
(defun retrieval-result-data (result)
(if (eql (length result) 2)
(if (eql (length (car result)) 1)
only one data matches
(caar result)
)
result))
(defun remove-binding (pat sub)
(cond ((atom pat) (var-value pat sub))
(t (cons (remove-binding (car pat) sub)
(remove-binding (cdr pat) sub)))))
(defun value-binding (value alist)
(assoc value alist))
(defun var-value (pat sub)
(let ((binding (value-binding pat sub)))
(cond ((null binding) pat)
(t (make-pcvar :id (cadr binding))))))
|
3030b1e3175eaec0aa450c57aa1436fcd9aa21b9ba8befd6d37c1d8f35ec1611 | dongcarl/guix | kerberos.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2012 , 2013 < >
Copyright © 2014 , 2015 , 2016 < >
Copyright © 2016 , 2017 < >
Copyright © 2016 < >
Copyright © 2012 , 2013 < >
Copyright © 2012 , 2017 < >
Copyright © 2017 , 2019 < >
Copyright © 2018 < >
Copyright © 2017 < >
Copyright © 2019 < >
Copyright © 2020 Jan ( janneke ) Nieuwenhuizen < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages kerberos)
#:use-module (gnu packages)
#:use-module (gnu packages autotools)
#:use-module (gnu packages bison)
#:use-module (gnu packages dbm)
#:use-module (gnu packages perl)
#:use-module (gnu packages gettext)
#:use-module (gnu packages gnupg)
#:use-module (gnu packages libidn)
#:use-module (gnu packages hurd)
#:use-module (gnu packages linux)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages compression)
#:use-module (gnu packages readline)
#:use-module (gnu packages sqlite)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages tls)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix build-system gnu))
(define-public mit-krb5
(package
(name "mit-krb5")
(version "1.18")
(source (origin
(method url-fetch)
(uri (list
(string-append "/"
(version-major+minor version)
"/krb5-" version ".tar.gz")
(string-append "/"
(version-major+minor version)
"/krb5-" version ".tar.gz")))
(patches (search-patches "mit-krb5-qualify-short-hostnames.patch"
"mit-krb5-hurd.patch"))
(sha256
(base32
"121c5xsy3x0i4wdkrpw62yhvji6virbh6n30ypazkp0isws3k4bk"))))
(build-system gnu-build-system)
(native-inputs
`(("bison" ,bison)
("perl" ,perl)))
(arguments
XXX : On 32 - bit systems , ' kdb5_util ' hangs on an fcntl / F_SETLKW call
;; while running the tests in 'src/tests'. Also disable tests when
;; cross-compiling.
#:tests? ,(and (not (%current-target-system))
(string=? (%current-system) "x86_64-linux"))
,@(if (%current-target-system)
'(#:configure-flags
(list "--localstatedir=/var"
"krb5_cv_attr_constructor_destructor=yes"
"ac_cv_func_regcomp=yes"
"ac_cv_printf_positional=yes"
"ac_cv_file__etc_environment=yes"
"ac_cv_file__etc_TIMEZONE=no")
#:make-flags
(list "CFLAGS+=-DDESTRUCTOR_ATTR_WORKS=1"))
'(#:configure-flags
(list "--localstatedir=/var")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'enter-source-directory
(lambda _
(chdir "src")
#t))
(add-before 'check 'pre-check
(lambda* (#:key inputs native-inputs #:allow-other-keys)
(let ((perl (assoc-ref (or native-inputs inputs) "perl")))
(substitute* "plugins/kdb/db2/libdb2/test/run.test"
(("/bin/cat") (string-append perl "/bin/perl"))
(("D/bin/sh") (string-append "D" (which "sh")))
(("bindir=/bin/.") (string-append "bindir=" perl "/bin"))))
;; avoid service names since /etc/services is unavailable
(substitute* "tests/resolve/Makefile"
(("-p telnet") "-p 23"))
#t)))))
(synopsis "MIT Kerberos 5")
(description
"Massachusetts Institute of Technology implementation of Kerberos.
Kerberos is a network authentication protocol designed to provide strong
authentication for client/server applications by using secret-key
cryptography.")
(license (license:non-copyleft "file"
"See NOTICE in the distribution."))
(home-page "/")
(properties '((cpe-name . "kerberos")))))
(define-public shishi
(package
(name "shishi")
(version "1.0.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(patches (search-patches "shishi-fix-libgcrypt-detection.patch"))
(sha256
(base32
"032qf72cpjdfffq1yq54gz3ahgqf2ijca4vl31sfabmjzq9q370d"))))
(build-system gnu-build-system)
(arguments
'(;; This is required since we patch some of the build scripts.
Remove first two items for the next Shishi release after 1.0.2 or
;; when removing 'shishi-fix-libgcrypt-detection.patch'.
#:configure-flags
'("ac_cv_libgcrypt=yes" "--disable-static"
"--with-key-dir=/etc/shishi" "--with-db-dir=/var/shishi")
#:phases
(modify-phases %standard-phases
(add-after 'configure 'disable-automatic-key-generation
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "Makefile"
(("^install-data-hook:")
"install-data-hook:\nx:\n"))
#t)))))
(native-inputs `(("pkg-config" ,pkg-config)))
(inputs
`(("gnutls" ,gnutls)
("libidn" ,libidn)
("linux-pam" ,linux-pam-1.2)
("zlib" ,zlib)
("libgcrypt" ,libgcrypt)
("libtasn1" ,libtasn1)))
(home-page "/")
(synopsis "Implementation of the Kerberos 5 network security system")
(description
"GNU Shishi is a free implementation of the Kerberos 5 network security
system. It is used to allow non-secure network nodes to communicate in a
secure manner through client-server mutual authentication via tickets.
After installation, the system administrator should generate keys using
@code{shisa -a /etc/shishi/shishi.keys}.")
(license license:gpl3+)))
(define-public heimdal
(package
(name "heimdal")
(version "7.7.0")
(source (origin
(method url-fetch)
(uri (string-append
"/"
"heimdal-" version "/" "heimdal-" version ".tar.gz"))
(sha256
(base32
"06vx3cb01s4lv3lpv0qzbbj97cln1np1wjphkkmmbk1lsqa36bgh"))
(modules '((guix build utils)))
(snippet
'(begin
(substitute* "configure"
(("User=.*$") "User=Guix\n")
(("Host=.*$") "Host=GNU")
(("Date=.*$") "Date=2019\n"))
#t))))
(build-system gnu-build-system)
(arguments
'(#:configure-flags (list
Avoid 7 MiB of .a files .
"--disable-static"
;; Do not build libedit.
(string-append
"--with-readline-lib="
(assoc-ref %build-inputs "readline") "/lib")
(string-append
"--with-readline-include="
(assoc-ref %build-inputs "readline") "/include")
;; Do not build sqlite.
(string-append
"--with-sqlite3="
(assoc-ref %build-inputs "sqlite")))
#:phases (modify-phases %standard-phases
(add-before 'configure 'pre-configure
(lambda _
(substitute* '("appl/afsutil/pagsh.c"
"tools/Makefile.in")
(("/bin/sh") (which "sh")))
#t))
(add-before 'check 'pre-check
(lambda _
;; For 'getxxyyy-test'.
(setenv "USER" (passwd:name (getpwuid (getuid))))
Skip ' db ' and ' ' tests for now .
FIXME : figure out why ' ' tests fail .
(with-output-to-file "tests/db/have-db.in"
(lambda ()
(format #t "#!~a~%exit 1~%" (which "sh"))))
#t)))
;; Tests fail when run in parallel.
#:parallel-tests? #f))
for ' compile_et '
("texinfo" ,texinfo)
("unzip" ,unzip))) ;for tests
(inputs `(("readline" ,readline)
("bdb" ,bdb)
("e2fsprogs" ,e2fsprogs) ;for libcom_err
("sqlite" ,sqlite)))
(home-page "/")
(synopsis "Kerberos 5 network authentication")
(description
"Heimdal is an implementation of Kerberos 5 network authentication
service.")
(license license:bsd-3)))
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/kerberos.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
while running the tests in 'src/tests'. Also disable tests when
cross-compiling.
avoid service names since /etc/services is unavailable
This is required since we patch some of the build scripts.
when removing 'shishi-fix-libgcrypt-detection.patch'.
Do not build libedit.
Do not build sqlite.
For 'getxxyyy-test'.
Tests fail when run in parallel.
for tests
for libcom_err | Copyright © 2012 , 2013 < >
Copyright © 2014 , 2015 , 2016 < >
Copyright © 2016 , 2017 < >
Copyright © 2016 < >
Copyright © 2012 , 2013 < >
Copyright © 2012 , 2017 < >
Copyright © 2017 , 2019 < >
Copyright © 2018 < >
Copyright © 2017 < >
Copyright © 2019 < >
Copyright © 2020 Jan ( janneke ) Nieuwenhuizen < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages kerberos)
#:use-module (gnu packages)
#:use-module (gnu packages autotools)
#:use-module (gnu packages bison)
#:use-module (gnu packages dbm)
#:use-module (gnu packages perl)
#:use-module (gnu packages gettext)
#:use-module (gnu packages gnupg)
#:use-module (gnu packages libidn)
#:use-module (gnu packages hurd)
#:use-module (gnu packages linux)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages compression)
#:use-module (gnu packages readline)
#:use-module (gnu packages sqlite)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages tls)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix utils)
#:use-module (guix build-system gnu))
(define-public mit-krb5
(package
(name "mit-krb5")
(version "1.18")
(source (origin
(method url-fetch)
(uri (list
(string-append "/"
(version-major+minor version)
"/krb5-" version ".tar.gz")
(string-append "/"
(version-major+minor version)
"/krb5-" version ".tar.gz")))
(patches (search-patches "mit-krb5-qualify-short-hostnames.patch"
"mit-krb5-hurd.patch"))
(sha256
(base32
"121c5xsy3x0i4wdkrpw62yhvji6virbh6n30ypazkp0isws3k4bk"))))
(build-system gnu-build-system)
(native-inputs
`(("bison" ,bison)
("perl" ,perl)))
(arguments
XXX : On 32 - bit systems , ' kdb5_util ' hangs on an fcntl / F_SETLKW call
#:tests? ,(and (not (%current-target-system))
(string=? (%current-system) "x86_64-linux"))
,@(if (%current-target-system)
'(#:configure-flags
(list "--localstatedir=/var"
"krb5_cv_attr_constructor_destructor=yes"
"ac_cv_func_regcomp=yes"
"ac_cv_printf_positional=yes"
"ac_cv_file__etc_environment=yes"
"ac_cv_file__etc_TIMEZONE=no")
#:make-flags
(list "CFLAGS+=-DDESTRUCTOR_ATTR_WORKS=1"))
'(#:configure-flags
(list "--localstatedir=/var")))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'enter-source-directory
(lambda _
(chdir "src")
#t))
(add-before 'check 'pre-check
(lambda* (#:key inputs native-inputs #:allow-other-keys)
(let ((perl (assoc-ref (or native-inputs inputs) "perl")))
(substitute* "plugins/kdb/db2/libdb2/test/run.test"
(("/bin/cat") (string-append perl "/bin/perl"))
(("D/bin/sh") (string-append "D" (which "sh")))
(("bindir=/bin/.") (string-append "bindir=" perl "/bin"))))
(substitute* "tests/resolve/Makefile"
(("-p telnet") "-p 23"))
#t)))))
(synopsis "MIT Kerberos 5")
(description
"Massachusetts Institute of Technology implementation of Kerberos.
Kerberos is a network authentication protocol designed to provide strong
authentication for client/server applications by using secret-key
cryptography.")
(license (license:non-copyleft "file"
"See NOTICE in the distribution."))
(home-page "/")
(properties '((cpe-name . "kerberos")))))
(define-public shishi
(package
(name "shishi")
(version "1.0.2")
(source
(origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(patches (search-patches "shishi-fix-libgcrypt-detection.patch"))
(sha256
(base32
"032qf72cpjdfffq1yq54gz3ahgqf2ijca4vl31sfabmjzq9q370d"))))
(build-system gnu-build-system)
(arguments
Remove first two items for the next Shishi release after 1.0.2 or
#:configure-flags
'("ac_cv_libgcrypt=yes" "--disable-static"
"--with-key-dir=/etc/shishi" "--with-db-dir=/var/shishi")
#:phases
(modify-phases %standard-phases
(add-after 'configure 'disable-automatic-key-generation
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "Makefile"
(("^install-data-hook:")
"install-data-hook:\nx:\n"))
#t)))))
(native-inputs `(("pkg-config" ,pkg-config)))
(inputs
`(("gnutls" ,gnutls)
("libidn" ,libidn)
("linux-pam" ,linux-pam-1.2)
("zlib" ,zlib)
("libgcrypt" ,libgcrypt)
("libtasn1" ,libtasn1)))
(home-page "/")
(synopsis "Implementation of the Kerberos 5 network security system")
(description
"GNU Shishi is a free implementation of the Kerberos 5 network security
system. It is used to allow non-secure network nodes to communicate in a
secure manner through client-server mutual authentication via tickets.
After installation, the system administrator should generate keys using
@code{shisa -a /etc/shishi/shishi.keys}.")
(license license:gpl3+)))
(define-public heimdal
(package
(name "heimdal")
(version "7.7.0")
(source (origin
(method url-fetch)
(uri (string-append
"/"
"heimdal-" version "/" "heimdal-" version ".tar.gz"))
(sha256
(base32
"06vx3cb01s4lv3lpv0qzbbj97cln1np1wjphkkmmbk1lsqa36bgh"))
(modules '((guix build utils)))
(snippet
'(begin
(substitute* "configure"
(("User=.*$") "User=Guix\n")
(("Host=.*$") "Host=GNU")
(("Date=.*$") "Date=2019\n"))
#t))))
(build-system gnu-build-system)
(arguments
'(#:configure-flags (list
Avoid 7 MiB of .a files .
"--disable-static"
(string-append
"--with-readline-lib="
(assoc-ref %build-inputs "readline") "/lib")
(string-append
"--with-readline-include="
(assoc-ref %build-inputs "readline") "/include")
(string-append
"--with-sqlite3="
(assoc-ref %build-inputs "sqlite")))
#:phases (modify-phases %standard-phases
(add-before 'configure 'pre-configure
(lambda _
(substitute* '("appl/afsutil/pagsh.c"
"tools/Makefile.in")
(("/bin/sh") (which "sh")))
#t))
(add-before 'check 'pre-check
(lambda _
(setenv "USER" (passwd:name (getpwuid (getuid))))
Skip ' db ' and ' ' tests for now .
FIXME : figure out why ' ' tests fail .
(with-output-to-file "tests/db/have-db.in"
(lambda ()
(format #t "#!~a~%exit 1~%" (which "sh"))))
#t)))
#:parallel-tests? #f))
for ' compile_et '
("texinfo" ,texinfo)
(inputs `(("readline" ,readline)
("bdb" ,bdb)
("sqlite" ,sqlite)))
(home-page "/")
(synopsis "Kerberos 5 network authentication")
(description
"Heimdal is an implementation of Kerberos 5 network authentication
service.")
(license license:bsd-3)))
|
131eb319623f014c0a7a33b563f68920f05e9aaf6301abc9f0330c0c1c5db13f | facebook/flow | flow.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(***********************************************************************)
(* flow shell is just a simple command-dispatching main *)
(***********************************************************************)
module FlowShell : sig
val main : unit -> unit
end = struct
(* normal commands *)
let commands =
[
AstCommand.command;
AutocompleteCommand.command;
AutofixCommand.command;
CheckCommands.CheckCommand.command;
CheckCommands.FocusCheckCommand.command;
CheckContentsCommand.command;
CodemodCommand.command;
ConfigCommand.command;
CoverageCommand.command;
BatchCoverageCommand.command;
CycleCommand.command;
GraphCommand.command;
DumpTypesCommand.command;
FindModuleCommand.command;
FixCommand.command;
ForceRecheckCommand.command;
GetDefCommand.command;
GetImportsCommand.command;
GleanCommand.command;
InitCommand.command;
LspCommand.command;
LsCommand.command;
SaveStateCommand.command;
ServerCommand.command;
StartCommand.command;
StopCommand.command;
TypeAtPosCommand.command;
VersionCommand.command;
]
@ Extra_commands.extra_commands ()
(* status commands, which need a list of other commands *)
module StatusCommand = StatusCommands.Status (struct
let commands = commands
end)
let commands = StatusCommand.command :: commands
module DefaultCommand = StatusCommands.Default (struct
let commands = commands
end)
let commands = DefaultCommand.command :: commands
module ShellCommand = ShellCompleteCommand.Command (struct
let commands = commands
end)
let commands = ShellCommand.command :: commands
let main () =
let default_command = DefaultCommand.command in
let argv = Array.to_list Sys.argv in
let (command, argv) =
match argv with
| [] -> failwith "Expected command"
| [_cmd] -> (default_command, [])
| _cmd :: next :: rest ->
let subcmd = String.lowercase_ascii next in
(try
let command = List.find (fun command -> CommandSpec.name command = subcmd) commands in
(command, rest)
with
| Not_found -> (default_command, next :: rest))
in
let command_string = CommandSpec.name command in
FlowEventLogger.set_command (Some command_string);
let init_id = Random_id.short_string () in
FlowEventLogger.init_flow_command ~init_id;
CommandUtils.run_command command argv
end
let _ =
A SIGPIPE signal happens when writing to a closed pipe ( e.g. C - c , or piping to ` head ` which
exits after it prints enough lines ) . By default , SIGPIPE kills the program because this is a
sane behavior for most commands ; it makes them stop processing input if they ca n't write it
anywhere .
We do n't like being killed uncleanly like that . By ignoring , the write ( ) syscall that
normally would cause a SIGPIPE instead throws an EPIPE exception . We handle exceptions and
exit via Exit.exit instead .
exits after it prints enough lines). By default, SIGPIPE kills the program because this is a
sane behavior for most commands; it makes them stop processing input if they can't write it
anywhere.
We don't like being killed uncleanly like that. By ignoring SIGPIPE, the write() syscall that
normally would cause a SIGPIPE instead throws an EPIPE exception. We handle exceptions and
exit via Exit.exit instead. *)
let () = Sys_utils.set_signal Sys.sigpipe Sys.Signal_ignore in
let () = Exception.record_backtrace true in
let () = Random.self_init () in
let () = if Utils_js.in_flow_test then LoggingUtils.disable_logging () in
try
Daemon.check_entry_point ();
(* this call might not return *)
FlowShell.main ()
with
| SharedMem.Out_of_shared_memory as e ->
let e = Exception.wrap e in
let bt = Exception.get_backtrace_string e in
let msg =
Printf.sprintf
"Out of shared memory%s"
( if bt = "" then
bt
else
":\n" ^ bt
)
in
Exit.(exit ~msg Out_of_shared_memory)
| e ->
let e = Exception.wrap e in
let msg = Printf.sprintf "Unhandled exception: %s" (Exception.to_string e) in
Exit.(exit ~msg Unknown_error)
(* If we haven't exited yet, let's exit now for logging's sake *)
let _ = Exit.(exit No_error)
| null | https://raw.githubusercontent.com/facebook/flow/6f944d973c81cdc8df8433b3a2f861b1f14c302e/src/flow.ml | ocaml | *********************************************************************
flow shell is just a simple command-dispatching main
*********************************************************************
normal commands
status commands, which need a list of other commands
this call might not return
If we haven't exited yet, let's exit now for logging's sake |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module FlowShell : sig
val main : unit -> unit
end = struct
let commands =
[
AstCommand.command;
AutocompleteCommand.command;
AutofixCommand.command;
CheckCommands.CheckCommand.command;
CheckCommands.FocusCheckCommand.command;
CheckContentsCommand.command;
CodemodCommand.command;
ConfigCommand.command;
CoverageCommand.command;
BatchCoverageCommand.command;
CycleCommand.command;
GraphCommand.command;
DumpTypesCommand.command;
FindModuleCommand.command;
FixCommand.command;
ForceRecheckCommand.command;
GetDefCommand.command;
GetImportsCommand.command;
GleanCommand.command;
InitCommand.command;
LspCommand.command;
LsCommand.command;
SaveStateCommand.command;
ServerCommand.command;
StartCommand.command;
StopCommand.command;
TypeAtPosCommand.command;
VersionCommand.command;
]
@ Extra_commands.extra_commands ()
module StatusCommand = StatusCommands.Status (struct
let commands = commands
end)
let commands = StatusCommand.command :: commands
module DefaultCommand = StatusCommands.Default (struct
let commands = commands
end)
let commands = DefaultCommand.command :: commands
module ShellCommand = ShellCompleteCommand.Command (struct
let commands = commands
end)
let commands = ShellCommand.command :: commands
let main () =
let default_command = DefaultCommand.command in
let argv = Array.to_list Sys.argv in
let (command, argv) =
match argv with
| [] -> failwith "Expected command"
| [_cmd] -> (default_command, [])
| _cmd :: next :: rest ->
let subcmd = String.lowercase_ascii next in
(try
let command = List.find (fun command -> CommandSpec.name command = subcmd) commands in
(command, rest)
with
| Not_found -> (default_command, next :: rest))
in
let command_string = CommandSpec.name command in
FlowEventLogger.set_command (Some command_string);
let init_id = Random_id.short_string () in
FlowEventLogger.init_flow_command ~init_id;
CommandUtils.run_command command argv
end
let _ =
A SIGPIPE signal happens when writing to a closed pipe ( e.g. C - c , or piping to ` head ` which
exits after it prints enough lines ) . By default , SIGPIPE kills the program because this is a
sane behavior for most commands ; it makes them stop processing input if they ca n't write it
anywhere .
We do n't like being killed uncleanly like that . By ignoring , the write ( ) syscall that
normally would cause a SIGPIPE instead throws an EPIPE exception . We handle exceptions and
exit via Exit.exit instead .
exits after it prints enough lines). By default, SIGPIPE kills the program because this is a
sane behavior for most commands; it makes them stop processing input if they can't write it
anywhere.
We don't like being killed uncleanly like that. By ignoring SIGPIPE, the write() syscall that
normally would cause a SIGPIPE instead throws an EPIPE exception. We handle exceptions and
exit via Exit.exit instead. *)
let () = Sys_utils.set_signal Sys.sigpipe Sys.Signal_ignore in
let () = Exception.record_backtrace true in
let () = Random.self_init () in
let () = if Utils_js.in_flow_test then LoggingUtils.disable_logging () in
try
Daemon.check_entry_point ();
FlowShell.main ()
with
| SharedMem.Out_of_shared_memory as e ->
let e = Exception.wrap e in
let bt = Exception.get_backtrace_string e in
let msg =
Printf.sprintf
"Out of shared memory%s"
( if bt = "" then
bt
else
":\n" ^ bt
)
in
Exit.(exit ~msg Out_of_shared_memory)
| e ->
let e = Exception.wrap e in
let msg = Printf.sprintf "Unhandled exception: %s" (Exception.to_string e) in
Exit.(exit ~msg Unknown_error)
let _ = Exit.(exit No_error)
|
9ca9b207327ead8dc820c02bffb630028f8f56a8a96d5c7cd9b8fef2816a7c49 | glondu/belenios | mail_formatter.mli | (**************************************************************************)
(* BELENIOS *)
(* *)
Copyright © 2012 - 2022
(* *)
(* This program is free software: you can redistribute it and/or modify *)
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation , either version 3 of the
(* License, or (at your option) any later version, with the additional *)
exemption that compiling , linking , and/or using OpenSSL is allowed .
(* *)
(* This program is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *)
(* Affero General Public License for more details. *)
(* *)
You should have received a copy of the GNU Affero General Public
(* License along with this program. If not, see *)
(* </>. *)
(**************************************************************************)
type t
val create : unit -> t
val add_newline : t -> unit
val add_string : t -> string -> unit
val add_sentence : t -> string -> unit
val contents : t -> string
| null | https://raw.githubusercontent.com/glondu/belenios/5306402c15c6a76438b13b8b9da0f45d02a0563d/src/web/common/mail_formatter.mli | ocaml | ************************************************************************
BELENIOS
This program is free software: you can redistribute it and/or modify
License, or (at your option) any later version, with the additional
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
License along with this program. If not, see
</>.
************************************************************************ | Copyright © 2012 - 2022
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation , either version 3 of the
exemption that compiling , linking , and/or using OpenSSL is allowed .
You should have received a copy of the GNU Affero General Public
type t
val create : unit -> t
val add_newline : t -> unit
val add_string : t -> string -> unit
val add_sentence : t -> string -> unit
val contents : t -> string
|
6635f80bad1a750a5a5c1760d2464230684bfdc3ff53a3a064d8c13f34ae3ffc | namin/lambdajam | factorial-cps.scm | (let ()
(define factorial-cps
(lambda (n k)
(begin
(show n)
(if (= n 0) (k 1)
(factorial-cps (- n 1) (lambda (v)
(k (* n v))))))))
(define factorial
(lambda (n)
(factorial-cps n (lambda (v) v))))
(show (factorial 5)))
| null | https://raw.githubusercontent.com/namin/lambdajam/58824eeccc15b11f09a02db5a3e3660fbdfe9c3d/factorial-cps.scm | scheme | (let ()
(define factorial-cps
(lambda (n k)
(begin
(show n)
(if (= n 0) (k 1)
(factorial-cps (- n 1) (lambda (v)
(k (* n v))))))))
(define factorial
(lambda (n)
(factorial-cps n (lambda (v) v))))
(show (factorial 5)))
| |
c63bc4d73e46d3843c885dfa03a770264a8f204a8bb38dde2ef01a144da2b6ca | ocaml/ocaml | injectivity.ml | (* TEST
* expect
*)
(* Syntax *)
type ! 'a t = private 'a ref
type +! 'a t = private 'a
type -!'a t = private 'a -> unit
type + !'a t = private 'a
type - ! 'a t = private 'a -> unit
type !+ 'a t = private 'a
type !-'a t = private 'a -> unit
type ! +'a t = private 'a
type ! -'a t = private 'a -> unit
[%%expect{|
type 'a t = private 'a ref
type +'a t = private 'a
type -'a t = private 'a -> unit
type +'a t = private 'a
type -'a t = private 'a -> unit
type +'a t = private 'a
type -'a t = private 'a -> unit
type +'a t = private 'a
type -'a t = private 'a -> unit
|}]
(* Expect doesn't support syntax errors
type -+ 'a t
[%%expect]
type -!! 'a t
[%%expect]
*)
Define an injective abstract type , and use it in a GADT
and a constrained type
and a constrained type *)
module M : sig type +!'a t end = struct type 'a t = 'a list end
[%%expect{|
module M : sig type +!'a t end
|}]
type _ t = M : 'a -> 'a M.t t (* OK *)
type 'a u = 'b constraint 'a = 'b M.t
[%%expect{|
type _ t = M : 'a -> 'a M.t t
type 'a u = 'b constraint 'a = 'b M.t
|}]
(* Without the injectivity annotation, the cannot be defined *)
module N : sig type +'a t end = struct type 'a t = 'a list end
[%%expect{|
module N : sig type +'a t end
|}]
type _ t = N : 'a -> 'a N.t t (* KO *)
[%%expect{|
Line 1, characters 0-29:
1 | type _ t = N : 'a -> 'a N.t t (* KO *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
N : 'a -> 'a N.t t
the type variable 'a cannot be deduced from the type parameters.
|}]
type 'a u = 'b constraint 'a = 'b N.t
[%%expect{|
Line 1, characters 0-37:
1 | type 'a u = 'b constraint 'a = 'b N.t
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type 'a u = 'b constraint 'a = 'b N.t
the type variable 'b cannot be deduced from the type parameters.
|}]
(* Of course, the internal type should be injective in this parameter *)
module M : sig type +!'a t end = struct type 'a t = int end (* KO *)
[%%expect{|
Line 1, characters 33-59:
1 | module M : sig type +!'a t end = struct type 'a t = int end (* KO *)
^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
sig type 'a t = int end
is not included in
sig type +!'a t end
Type declarations do not match:
type 'a t = int
is not included in
type +!'a t
Their variances do not agree.
|}]
(* Annotations in type abbreviations allow to check injectivity *)
type !'a t = 'a list
type !'a u = int
[%%expect{|
type 'a t = 'a list
Line 2, characters 0-16:
2 | type !'a u = int
^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
type !'a t = private 'a list
type !'a t = private int
[%%expect{|
type 'a t = private 'a list
Line 2, characters 0-24:
2 | type !'a t = private int
^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
(* Can also use to add injectivity in private row types *)
module M : sig type !'a t = private < m : int ; .. > end =
struct type 'a t = < m : int ; n : 'a > end
type 'a u = M : 'a -> 'a M.t u
[%%expect{|
module M : sig type !'a t = private < m : int; .. > end
type 'a u = M : 'a -> 'a M.t u
|}]
module M : sig type 'a t = private < m : int ; .. > end =
struct type 'a t = < m : int ; n : 'a > end
type 'a u = M : 'a -> 'a M.t u
[%%expect{|
module M : sig type 'a t = private < m : int; .. > end
Line 3, characters 0-30:
3 | type 'a u = M : 'a -> 'a M.t u
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
M : 'a -> 'a M.t u
the type variable 'a cannot be deduced from the type parameters.
|}]
module M : sig type !'a t = private < m : int ; .. > end =
struct type 'a t = < m : int > end
[%%expect{|
Line 2, characters 2-36:
2 | struct type 'a t = < m : int > end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
sig type 'a t = < m : int > end
is not included in
sig type !'a t = private < m : int; .. > end
Type declarations do not match:
type 'a t = < m : int >
is not included in
type !'a t
Their variances do not agree.
|}]
Injectivity annotations are inferred correctly for constrained parameters
type 'a t = 'b constraint 'a = <b:'b>
type !'b u = <b:'b> t
[%%expect{|
type 'a t = 'b constraint 'a = < b : 'b >
type 'b u = < b : 'b > t
|}]
(* Ignore injectivity for nominal types *)
type !_ t = X
[%%expect{|
type _ t = X
|}]
(* Beware of constrained parameters *)
type (_,_) eq = Refl : ('a,'a) eq
type !'a t = private 'b constraint 'a = < b : 'b > (* OK *)
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
type 'a t = private 'b constraint 'a = < b : 'b >
|}]
type !'a t = private 'b constraint 'a = < b : 'b; c : 'c > (* KO *)
module M : sig type !'a t constraint 'a = < b : 'b; c : 'c > end =
struct type nonrec 'a t = 'a t end
let inj_t : type a b. (<b:_; c:a> M.t, <b:_; c:b> M.t) eq -> (a, b) eq =
fun Refl -> Refl
[%%expect{|
Line 1, characters 0-58:
1 | type !'a t = private 'b constraint 'a = < b : 'b; c : 'c > (* KO *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
(* One cannot assume that abstract types are not injective *)
module F(X : sig type 'a t end) = struct
type 'a u = unit constraint 'a = 'b X.t
type _ x = G : 'a -> 'a u x
end
module M = F(struct type 'a t = 'a end)
let M.G (x : bool) = M.G 3
[%%expect{|
Line 3, characters 2-29:
3 | type _ x = G : 'a -> 'a u x
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
G : 'a X.t -> 'a X.t u x
the type variable 'a cannot be deduced from the type parameters.
|}]
(* Try to be clever *)
type 'a t = unit
type !'a u = int constraint 'a = 'b t
[%%expect{|
type 'a t = unit
type 'a u = int constraint 'a = 'b t
|}]
module F(X : sig type 'a t end) = struct
type !'a u = 'b constraint 'a = <b : 'b> constraint 'b = _ X.t
end
[%%expect{|
module F :
functor (X : sig type 'a t end) ->
sig type 'a u = 'b X.t constraint 'a = < b : 'b X.t > end
|}]
(* But not too clever *)
module F(X : sig type 'a t end) = struct
type !'a u = 'b X.t constraint 'a = <b : 'b X.t>
end
[%%expect{|
Line 2, characters 2-50:
2 | type !'a u = 'b X.t constraint 'a = <b : 'b X.t>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
module F(X : sig type 'a t end) = struct
type !'a u = 'b constraint 'a = <b : _ X.t as 'b>
end
[%%expect{|
module F :
functor (X : sig type 'a t end) ->
sig type 'a u = 'b X.t constraint 'a = < b : 'b X.t > end
|}, Principal{|
Line 2, characters 2-51:
2 | type !'a u = 'b constraint 'a = <b : _ X.t as 'b>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
Motivating examples with GADTs
type (_,_) eq = Refl : ('a,'a) eq
module Vec : sig
type +!'a t
val make : int -> (int -> 'a) -> 'a t
val get : 'a t -> int -> 'a
end = struct
type 'a t = Vec of Obj.t array
let make n f = Vec (Obj.magic Array.init n f)
let get (Vec v) n = Obj.obj (Array.get v n)
end
type _ ty =
| Int : int ty
| Fun : 'a ty * 'b ty -> ('a -> 'b) ty
| Vec : 'a ty -> 'a Vec.t ty
type dyn = Dyn : 'a ty * 'a -> dyn
let rec eq_ty : type a b. a ty -> b ty -> (a,b) eq option =
fun t1 t2 -> match t1, t2 with
| Int, Int -> Some Refl
| Fun (t11, t12), Fun (t21, t22) ->
begin match eq_ty t11 t21, eq_ty t12 t22 with
| Some Refl, Some Refl -> Some Refl
| _ -> None
end
| Vec t1, Vec t2 ->
begin match eq_ty t1 t2 with
| Some Refl -> Some Refl
| None -> None
end
| _ -> None
let undyn : type a. a ty -> dyn -> a option =
fun t1 (Dyn (t2, v)) ->
match eq_ty t1 t2 with
| Some Refl -> Some v
| None -> None
let v = Vec.make 3 (fun n -> Vec.make n (fun m -> (m*n)))
let int_vec_vec = Vec (Vec Int)
let d = Dyn (int_vec_vec, v)
let Some v' = undyn int_vec_vec d
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
module Vec :
sig
type +!'a t
val make : int -> (int -> 'a) -> 'a t
val get : 'a t -> int -> 'a
end
type _ ty =
Int : int ty
| Fun : 'a ty * 'b ty -> ('a -> 'b) ty
| Vec : 'a ty -> 'a Vec.t ty
type dyn = Dyn : 'a ty * 'a -> dyn
val eq_ty : 'a ty -> 'b ty -> ('a, 'b) eq option = <fun>
val undyn : 'a ty -> dyn -> 'a option = <fun>
val v : int Vec.t Vec.t = <abstr>
val int_vec_vec : int Vec.t Vec.t ty = Vec (Vec Int)
val d : dyn = Dyn (Vec (Vec Int), <poly>)
Line 47, characters 4-11:
47 | let Some v' = undyn int_vec_vec d
^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
None
val v' : int Vec.t Vec.t = <abstr>
|}]
(* Break it (using magic) *)
module Vec : sig
type +!'a t
val eqt : ('a t, 'b t) eq
end = struct
type 'a t = 'a
let eqt = Obj.magic Refl (* Never do that! *)
end
type _ ty =
| Int : int ty
| Vec : 'a ty -> 'a Vec.t ty
let coe : type a b. (a,b) eq -> a ty -> b ty =
fun Refl x -> x
let eq_int_any : type a. unit -> (int, a) eq = fun () ->
let vec_ty : a Vec.t ty = coe Vec.eqt (Vec Int) in
let Vec Int = vec_ty in Refl
[%%expect{|
module Vec : sig type +!'a t val eqt : ('a t, 'b t) eq end
type _ ty = Int : int ty | Vec : 'a ty -> 'a Vec.t ty
val coe : ('a, 'b) eq -> 'a ty -> 'b ty = <fun>
Line 17, characters 2-30:
17 | let Vec Int = vec_ty in Refl
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Vec (Vec Int)
val eq_int_any : unit -> (int, 'a) eq = <fun>
|}]
(* Not directly related: injectivity and constraints *)
type 'a t = 'b constraint 'a = <b : 'b>
class type ['a] ct = object method m : 'b constraint 'a = < b : 'b > end
[%%expect{|
type 'a t = 'b constraint 'a = < b : 'b >
class type ['a] ct = object constraint 'a = < b : 'b > method m : 'b end
|}]
type _ u = M : 'a -> 'a t u (* OK *)
[%%expect{|
type _ u = M : < b : 'a > -> < b : 'a > t u
|}]
type _ v = M : 'a -> 'a ct v (* OK *)
[%%expect{|
type _ v = M : < b : 'a > -> < b : 'a > ct v
|}]
type 'a t = 'b constraint 'a = <b : 'b; c : 'c>
type _ u = M : 'a -> 'a t u (* KO *)
[%%expect{|
type 'a t = 'b constraint 'a = < b : 'b; c : 'c >
Line 2, characters 0-27:
2 | type _ u = M : 'a -> 'a t u (* KO *)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
M : < b : 'a; c : 'b > -> < b : 'a; c : 'b > t u
the type variable 'b cannot be deduced from the type parameters.
|}]
# 9721 by
First , some standard bits and pieces for equality & injectivity :
type (_,_) eql = Refl : ('a, 'a) eql
module Uninj(X: sig type !'a t end) :
sig val uninj : ('a X.t, 'b X.t) eql -> ('a, 'b) eql end =
struct let uninj : type a b. (a X.t, b X.t) eql -> (a, b) eql = fun Refl -> Refl end
let coerce : type a b. (a, b) eql -> a -> b = fun Refl x -> x;;
[%%expect{|
type (_, _) eql = Refl : ('a, 'a) eql
module Uninj :
functor (X : sig type !'a t end) ->
sig val uninj : ('a X.t, 'b X.t) eql -> ('a, 'b) eql end
val coerce : ('a, 'b) eql -> 'a -> 'b = <fun>
|}]
Now the questionable part , defining two " injective " type definitions in
a pair of mutually - recursive modules . These definitions are correctly
rejected if given as a pair of mutually - recursive types , but wrongly
accepted when defined as follows :
a pair of mutually-recursive modules. These definitions are correctly
rejected if given as a pair of mutually-recursive types, but wrongly
accepted when defined as follows:
*)
module rec R : sig type !'a t = [ `A of 'a S.t] end = R
and S : sig type !'a t = 'a R.t end = S ;;
[%%expect{|
Line 1, characters 19-47:
1 | module rec R : sig type !'a t = [ `A of 'a S.t] end = R
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is invariant.
|}]
(* The parameter of R.t is never used, so we can build an equality witness
for any instantiation: *)
let x_eq_y : (int R.t, string R.t) eql = Refl
let boom = let module U = Uninj(R) in print_endline (coerce (U.uninj x_eq_y) 0)
;;
[%%expect{|
Line 1, characters 18-21:
1 | let x_eq_y : (int R.t, string R.t) eql = Refl
^^^
Error: Unbound module R
|}]
# 10028 by
module rec A : sig
type _ t = Foo : 'a -> 'a A.s t
type 'a s = T of 'a
end =
A
;;
[%%expect{|
module rec A : sig type _ t = Foo : 'a -> 'a A.s t type 'a s = T of 'a end
|}]
| null | https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-misc/injectivity.ml | ocaml | TEST
* expect
Syntax
Expect doesn't support syntax errors
type -+ 'a t
[%%expect]
type -!! 'a t
[%%expect]
OK
Without the injectivity annotation, the cannot be defined
KO
KO
Of course, the internal type should be injective in this parameter
KO
KO
Annotations in type abbreviations allow to check injectivity
Can also use to add injectivity in private row types
Ignore injectivity for nominal types
Beware of constrained parameters
OK
KO
KO
One cannot assume that abstract types are not injective
Try to be clever
But not too clever
Break it (using magic)
Never do that!
Not directly related: injectivity and constraints
OK
OK
KO
KO
The parameter of R.t is never used, so we can build an equality witness
for any instantiation: |
type ! 'a t = private 'a ref
type +! 'a t = private 'a
type -!'a t = private 'a -> unit
type + !'a t = private 'a
type - ! 'a t = private 'a -> unit
type !+ 'a t = private 'a
type !-'a t = private 'a -> unit
type ! +'a t = private 'a
type ! -'a t = private 'a -> unit
[%%expect{|
type 'a t = private 'a ref
type +'a t = private 'a
type -'a t = private 'a -> unit
type +'a t = private 'a
type -'a t = private 'a -> unit
type +'a t = private 'a
type -'a t = private 'a -> unit
type +'a t = private 'a
type -'a t = private 'a -> unit
|}]
Define an injective abstract type , and use it in a GADT
and a constrained type
and a constrained type *)
module M : sig type +!'a t end = struct type 'a t = 'a list end
[%%expect{|
module M : sig type +!'a t end
|}]
type 'a u = 'b constraint 'a = 'b M.t
[%%expect{|
type _ t = M : 'a -> 'a M.t t
type 'a u = 'b constraint 'a = 'b M.t
|}]
module N : sig type +'a t end = struct type 'a t = 'a list end
[%%expect{|
module N : sig type +'a t end
|}]
[%%expect{|
Line 1, characters 0-29:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
N : 'a -> 'a N.t t
the type variable 'a cannot be deduced from the type parameters.
|}]
type 'a u = 'b constraint 'a = 'b N.t
[%%expect{|
Line 1, characters 0-37:
1 | type 'a u = 'b constraint 'a = 'b N.t
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition
type 'a u = 'b constraint 'a = 'b N.t
the type variable 'b cannot be deduced from the type parameters.
|}]
[%%expect{|
Line 1, characters 33-59:
^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
sig type 'a t = int end
is not included in
sig type +!'a t end
Type declarations do not match:
type 'a t = int
is not included in
type +!'a t
Their variances do not agree.
|}]
type !'a t = 'a list
type !'a u = int
[%%expect{|
type 'a t = 'a list
Line 2, characters 0-16:
2 | type !'a u = int
^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
type !'a t = private 'a list
type !'a t = private int
[%%expect{|
type 'a t = private 'a list
Line 2, characters 0-24:
2 | type !'a t = private int
^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
module M : sig type !'a t = private < m : int ; .. > end =
struct type 'a t = < m : int ; n : 'a > end
type 'a u = M : 'a -> 'a M.t u
[%%expect{|
module M : sig type !'a t = private < m : int; .. > end
type 'a u = M : 'a -> 'a M.t u
|}]
module M : sig type 'a t = private < m : int ; .. > end =
struct type 'a t = < m : int ; n : 'a > end
type 'a u = M : 'a -> 'a M.t u
[%%expect{|
module M : sig type 'a t = private < m : int; .. > end
Line 3, characters 0-30:
3 | type 'a u = M : 'a -> 'a M.t u
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
M : 'a -> 'a M.t u
the type variable 'a cannot be deduced from the type parameters.
|}]
module M : sig type !'a t = private < m : int ; .. > end =
struct type 'a t = < m : int > end
[%%expect{|
Line 2, characters 2-36:
2 | struct type 'a t = < m : int > end
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: Signature mismatch:
Modules do not match:
sig type 'a t = < m : int > end
is not included in
sig type !'a t = private < m : int; .. > end
Type declarations do not match:
type 'a t = < m : int >
is not included in
type !'a t
Their variances do not agree.
|}]
Injectivity annotations are inferred correctly for constrained parameters
type 'a t = 'b constraint 'a = <b:'b>
type !'b u = <b:'b> t
[%%expect{|
type 'a t = 'b constraint 'a = < b : 'b >
type 'b u = < b : 'b > t
|}]
type !_ t = X
[%%expect{|
type _ t = X
|}]
type (_,_) eq = Refl : ('a,'a) eq
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
type 'a t = private 'b constraint 'a = < b : 'b >
|}]
module M : sig type !'a t constraint 'a = < b : 'b; c : 'c > end =
struct type nonrec 'a t = 'a t end
let inj_t : type a b. (<b:_; c:a> M.t, <b:_; c:b> M.t) eq -> (a, b) eq =
fun Refl -> Refl
[%%expect{|
Line 1, characters 0-58:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
module F(X : sig type 'a t end) = struct
type 'a u = unit constraint 'a = 'b X.t
type _ x = G : 'a -> 'a u x
end
module M = F(struct type 'a t = 'a end)
let M.G (x : bool) = M.G 3
[%%expect{|
Line 3, characters 2-29:
3 | type _ x = G : 'a -> 'a u x
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
G : 'a X.t -> 'a X.t u x
the type variable 'a cannot be deduced from the type parameters.
|}]
type 'a t = unit
type !'a u = int constraint 'a = 'b t
[%%expect{|
type 'a t = unit
type 'a u = int constraint 'a = 'b t
|}]
module F(X : sig type 'a t end) = struct
type !'a u = 'b constraint 'a = <b : 'b> constraint 'b = _ X.t
end
[%%expect{|
module F :
functor (X : sig type 'a t end) ->
sig type 'a u = 'b X.t constraint 'a = < b : 'b X.t > end
|}]
module F(X : sig type 'a t end) = struct
type !'a u = 'b X.t constraint 'a = <b : 'b X.t>
end
[%%expect{|
Line 2, characters 2-50:
2 | type !'a u = 'b X.t constraint 'a = <b : 'b X.t>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
module F(X : sig type 'a t end) = struct
type !'a u = 'b constraint 'a = <b : _ X.t as 'b>
end
[%%expect{|
module F :
functor (X : sig type 'a t end) ->
sig type 'a u = 'b X.t constraint 'a = < b : 'b X.t > end
|}, Principal{|
Line 2, characters 2-51:
2 | type !'a u = 'b constraint 'a = <b : _ X.t as 'b>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is unrestricted.
|}]
Motivating examples with GADTs
type (_,_) eq = Refl : ('a,'a) eq
module Vec : sig
type +!'a t
val make : int -> (int -> 'a) -> 'a t
val get : 'a t -> int -> 'a
end = struct
type 'a t = Vec of Obj.t array
let make n f = Vec (Obj.magic Array.init n f)
let get (Vec v) n = Obj.obj (Array.get v n)
end
type _ ty =
| Int : int ty
| Fun : 'a ty * 'b ty -> ('a -> 'b) ty
| Vec : 'a ty -> 'a Vec.t ty
type dyn = Dyn : 'a ty * 'a -> dyn
let rec eq_ty : type a b. a ty -> b ty -> (a,b) eq option =
fun t1 t2 -> match t1, t2 with
| Int, Int -> Some Refl
| Fun (t11, t12), Fun (t21, t22) ->
begin match eq_ty t11 t21, eq_ty t12 t22 with
| Some Refl, Some Refl -> Some Refl
| _ -> None
end
| Vec t1, Vec t2 ->
begin match eq_ty t1 t2 with
| Some Refl -> Some Refl
| None -> None
end
| _ -> None
let undyn : type a. a ty -> dyn -> a option =
fun t1 (Dyn (t2, v)) ->
match eq_ty t1 t2 with
| Some Refl -> Some v
| None -> None
let v = Vec.make 3 (fun n -> Vec.make n (fun m -> (m*n)))
let int_vec_vec = Vec (Vec Int)
let d = Dyn (int_vec_vec, v)
let Some v' = undyn int_vec_vec d
[%%expect{|
type (_, _) eq = Refl : ('a, 'a) eq
module Vec :
sig
type +!'a t
val make : int -> (int -> 'a) -> 'a t
val get : 'a t -> int -> 'a
end
type _ ty =
Int : int ty
| Fun : 'a ty * 'b ty -> ('a -> 'b) ty
| Vec : 'a ty -> 'a Vec.t ty
type dyn = Dyn : 'a ty * 'a -> dyn
val eq_ty : 'a ty -> 'b ty -> ('a, 'b) eq option = <fun>
val undyn : 'a ty -> dyn -> 'a option = <fun>
val v : int Vec.t Vec.t = <abstr>
val int_vec_vec : int Vec.t Vec.t ty = Vec (Vec Int)
val d : dyn = Dyn (Vec (Vec Int), <poly>)
Line 47, characters 4-11:
47 | let Some v' = undyn int_vec_vec d
^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
None
val v' : int Vec.t Vec.t = <abstr>
|}]
module Vec : sig
type +!'a t
val eqt : ('a t, 'b t) eq
end = struct
type 'a t = 'a
end
type _ ty =
| Int : int ty
| Vec : 'a ty -> 'a Vec.t ty
let coe : type a b. (a,b) eq -> a ty -> b ty =
fun Refl x -> x
let eq_int_any : type a. unit -> (int, a) eq = fun () ->
let vec_ty : a Vec.t ty = coe Vec.eqt (Vec Int) in
let Vec Int = vec_ty in Refl
[%%expect{|
module Vec : sig type +!'a t val eqt : ('a t, 'b t) eq end
type _ ty = Int : int ty | Vec : 'a ty -> 'a Vec.t ty
val coe : ('a, 'b) eq -> 'a ty -> 'b ty = <fun>
Line 17, characters 2-30:
17 | let Vec Int = vec_ty in Refl
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Warning 8 [partial-match]: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
Vec (Vec Int)
val eq_int_any : unit -> (int, 'a) eq = <fun>
|}]
type 'a t = 'b constraint 'a = <b : 'b>
class type ['a] ct = object method m : 'b constraint 'a = < b : 'b > end
[%%expect{|
type 'a t = 'b constraint 'a = < b : 'b >
class type ['a] ct = object constraint 'a = < b : 'b > method m : 'b end
|}]
[%%expect{|
type _ u = M : < b : 'a > -> < b : 'a > t u
|}]
[%%expect{|
type _ v = M : < b : 'a > -> < b : 'a > ct v
|}]
type 'a t = 'b constraint 'a = <b : 'b; c : 'c>
[%%expect{|
type 'a t = 'b constraint 'a = < b : 'b; c : 'c >
Line 2, characters 0-27:
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the GADT constructor
M : < b : 'a; c : 'b > -> < b : 'a; c : 'b > t u
the type variable 'b cannot be deduced from the type parameters.
|}]
# 9721 by
First , some standard bits and pieces for equality & injectivity :
type (_,_) eql = Refl : ('a, 'a) eql
module Uninj(X: sig type !'a t end) :
sig val uninj : ('a X.t, 'b X.t) eql -> ('a, 'b) eql end =
struct let uninj : type a b. (a X.t, b X.t) eql -> (a, b) eql = fun Refl -> Refl end
let coerce : type a b. (a, b) eql -> a -> b = fun Refl x -> x;;
[%%expect{|
type (_, _) eql = Refl : ('a, 'a) eql
module Uninj :
functor (X : sig type !'a t end) ->
sig val uninj : ('a X.t, 'b X.t) eql -> ('a, 'b) eql end
val coerce : ('a, 'b) eql -> 'a -> 'b = <fun>
|}]
Now the questionable part , defining two " injective " type definitions in
a pair of mutually - recursive modules . These definitions are correctly
rejected if given as a pair of mutually - recursive types , but wrongly
accepted when defined as follows :
a pair of mutually-recursive modules. These definitions are correctly
rejected if given as a pair of mutually-recursive types, but wrongly
accepted when defined as follows:
*)
module rec R : sig type !'a t = [ `A of 'a S.t] end = R
and S : sig type !'a t = 'a R.t end = S ;;
[%%expect{|
Line 1, characters 19-47:
1 | module rec R : sig type !'a t = [ `A of 'a S.t] end = R
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In this definition, expected parameter variances are not satisfied.
The 1st type parameter was expected to be injective invariant,
but it is invariant.
|}]
let x_eq_y : (int R.t, string R.t) eql = Refl
let boom = let module U = Uninj(R) in print_endline (coerce (U.uninj x_eq_y) 0)
;;
[%%expect{|
Line 1, characters 18-21:
1 | let x_eq_y : (int R.t, string R.t) eql = Refl
^^^
Error: Unbound module R
|}]
# 10028 by
module rec A : sig
type _ t = Foo : 'a -> 'a A.s t
type 'a s = T of 'a
end =
A
;;
[%%expect{|
module rec A : sig type _ t = Foo : 'a -> 'a A.s t type 'a s = T of 'a end
|}]
|
d4be38105c35c9f86988d162daaefa6fd1df39f968fcabd5ffe215966f070cab | luc-tielen/eclair-lang | Diagnostics.hs | # LANGUAGE RecordWildCards #
module Eclair.LSP.Diagnostics
( errorToDiagnostics
) where
import Language.LSP.Types hiding (Range(..), Location(..), ParseError, Position, line)
import qualified Language.LSP.Types as LSP
import Language.LSP.Server (getLspEnv)
import Eclair.Error
import Eclair.LSP.Monad
import Data.Maybe (fromJust)
errorToDiagnostics :: Uri -> EclairError -> HandlerM [Diagnostic]
errorToDiagnostics uri err = do
file <- fileFromUri uri
fileContent <- readUri (filePathToUri file)
env <- lift getLspEnv
let readSourceFile = map (map fromJust) $ lspReadFromVFS env
issues <- liftIO $ errorToIssues readSourceFile err
let source = errorSource err
pure $ map (toDiagnostic source file fileContent) issues
where
toDiagnostic source file fileContent issue =
mkDiagnostic (renderIssueMessage file fileContent issue) (issueRange issue) source
issueRange issue =
Just (locationToLspRange $ issueLocation issue)
data Source
= Parser
| Typesystem
| SemanticAnalysis
sourceToText :: Source -> Text
sourceToText = \case
Parser -> "Eclair.Parser"
Typesystem -> "Eclair.Typesystem"
SemanticAnalysis -> "Eclair.SemanticAnalysis"
errorSource :: EclairError -> Source
errorSource = \case
ParseErr {} -> Parser
TypeErr {} -> Typesystem
SemanticErr {} -> SemanticAnalysis
mkDiagnostic :: Text -> Maybe LSP.Range -> Source -> Diagnostic
mkDiagnostic message location source =
let _range = fromMaybe nullRange location
_severity = Just DsError
_source = Just $ sourceToText source
_code = Nothing
_tags = Nothing
_message = message
_relatedInformation = Nothing
in Diagnostic {..}
nullRange :: LSP.Range
nullRange =
LSP.Range (LSP.Position 0 0) (LSP.Position 0 0)
Helper conversion function . Eclair has a separate type so it does not need
to rely on the LSP library .
locationToLspRange :: Location -> LSP.Range
locationToLspRange loc =
LSP.Range (LSP.Position (fromIntegral $ posLine start) (fromIntegral $ posColumn start))
(LSP.Position (fromIntegral $ posLine end) (fromIntegral $ posColumn end))
where
start = locationStart loc
end = locationEnd loc
| null | https://raw.githubusercontent.com/luc-tielen/eclair-lang/f96fa7ac720e60bd6c6e460feff6707a1e95e0a0/src/lsp/Eclair/LSP/Diagnostics.hs | haskell | # LANGUAGE RecordWildCards #
module Eclair.LSP.Diagnostics
( errorToDiagnostics
) where
import Language.LSP.Types hiding (Range(..), Location(..), ParseError, Position, line)
import qualified Language.LSP.Types as LSP
import Language.LSP.Server (getLspEnv)
import Eclair.Error
import Eclair.LSP.Monad
import Data.Maybe (fromJust)
errorToDiagnostics :: Uri -> EclairError -> HandlerM [Diagnostic]
errorToDiagnostics uri err = do
file <- fileFromUri uri
fileContent <- readUri (filePathToUri file)
env <- lift getLspEnv
let readSourceFile = map (map fromJust) $ lspReadFromVFS env
issues <- liftIO $ errorToIssues readSourceFile err
let source = errorSource err
pure $ map (toDiagnostic source file fileContent) issues
where
toDiagnostic source file fileContent issue =
mkDiagnostic (renderIssueMessage file fileContent issue) (issueRange issue) source
issueRange issue =
Just (locationToLspRange $ issueLocation issue)
data Source
= Parser
| Typesystem
| SemanticAnalysis
sourceToText :: Source -> Text
sourceToText = \case
Parser -> "Eclair.Parser"
Typesystem -> "Eclair.Typesystem"
SemanticAnalysis -> "Eclair.SemanticAnalysis"
errorSource :: EclairError -> Source
errorSource = \case
ParseErr {} -> Parser
TypeErr {} -> Typesystem
SemanticErr {} -> SemanticAnalysis
mkDiagnostic :: Text -> Maybe LSP.Range -> Source -> Diagnostic
mkDiagnostic message location source =
let _range = fromMaybe nullRange location
_severity = Just DsError
_source = Just $ sourceToText source
_code = Nothing
_tags = Nothing
_message = message
_relatedInformation = Nothing
in Diagnostic {..}
nullRange :: LSP.Range
nullRange =
LSP.Range (LSP.Position 0 0) (LSP.Position 0 0)
Helper conversion function . Eclair has a separate type so it does not need
to rely on the LSP library .
locationToLspRange :: Location -> LSP.Range
locationToLspRange loc =
LSP.Range (LSP.Position (fromIntegral $ posLine start) (fromIntegral $ posColumn start))
(LSP.Position (fromIntegral $ posLine end) (fromIntegral $ posColumn end))
where
start = locationStart loc
end = locationEnd loc
| |
089be3f2ce5c0d6bfb1e02afe57e3f94c5c4f9567a3b2582b459cfe1296060c6 | Oblosys/proxima | Main.hs | module Main where
import Proxima.Proxima
import Settings
import Evaluator
import Reducer
import PresentationAG
import ProxParser
import ScannerSheetHS
import Evaluation.DocTypes
import DocTypes_Generated
import Evaluation.EnrTypes
import Presentation.PresTypes
import Layout.LayTypes
import Arrangement.ArrTypes
import Common.CommonTypes
when typing during compilation GHCI replaces the first command line char by ' g '
main = proxima Settings.settings
PresentationAG.presentationSheet
ProxParser.recognizeEnrichedDoc
ScannerSheetHS.scanner
-- sheet parameters (evaluation and reduction sheets are passed implicitly through
-- instances of Evaluation/ReductionSheet classes)
--
(DocumentLevel HoleDocument NoPathD Clip_Nothing)
(EnrichedDocLevel HoleEnrichedDoc NoPathD HoleDocument)
-- Note: this file does not need to be changed when instantiating an editor.
| null | https://raw.githubusercontent.com/Oblosys/proxima/f154dff2ccb8afe00eeb325d9d06f5e2a5ee7589/dazzle-editor/src/Main.hs | haskell | sheet parameters (evaluation and reduction sheets are passed implicitly through
instances of Evaluation/ReductionSheet classes)
Note: this file does not need to be changed when instantiating an editor. | module Main where
import Proxima.Proxima
import Settings
import Evaluator
import Reducer
import PresentationAG
import ProxParser
import ScannerSheetHS
import Evaluation.DocTypes
import DocTypes_Generated
import Evaluation.EnrTypes
import Presentation.PresTypes
import Layout.LayTypes
import Arrangement.ArrTypes
import Common.CommonTypes
when typing during compilation GHCI replaces the first command line char by ' g '
main = proxima Settings.settings
PresentationAG.presentationSheet
ProxParser.recognizeEnrichedDoc
ScannerSheetHS.scanner
(DocumentLevel HoleDocument NoPathD Clip_Nothing)
(EnrichedDocLevel HoleEnrichedDoc NoPathD HoleDocument)
|
dca9bb33b491984d5e7d6ad93003f6427fc1dbe310f84f4dcee1eab90e6e5253 | metosin/mallitaulut | embedded_postgres.clj | (ns mallitaulut.embedded-postgres
"Mostly snarfed from specql:
MIT License
Copyright (c) 2017 Tatu Tarvainen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."
(:require [next.jdbc :as jdbc]
[clojure.string :as str])
(:import [com.opentable.db.postgres.embedded PreparedDbProvider DatabasePreparer]))
(def ^:dynamic *db* nil)
(defn- run-statements [db resource split]
(doseq [statement (remove str/blank?
(str/split (slurp resource) split))]
(println "SQL: " statement)
(jdbc/execute! db [statement])))
(defn- create-test-database [db]
(run-statements db "test/database.sql" #";"))
(defn- provider []
(PreparedDbProvider/forPreparer
(reify DatabasePreparer
(prepare [_ ds]
(create-test-database ds)))))
(defonce db-provider (provider))
(defn reset-db [] (alter-var-root #'db-provider (fn [_] (provider))))
(defn datasource [] (.createDataSource db-provider))
(defn with-db [fn]
(binding [*db* (datasource)]
(fn)))
| null | https://raw.githubusercontent.com/metosin/mallitaulut/ce6e5d01903b6f8ab840eddb6906285788688554/test/mallitaulut/embedded_postgres.clj | clojure | (ns mallitaulut.embedded-postgres
"Mostly snarfed from specql:
MIT License
Copyright (c) 2017 Tatu Tarvainen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."
(:require [next.jdbc :as jdbc]
[clojure.string :as str])
(:import [com.opentable.db.postgres.embedded PreparedDbProvider DatabasePreparer]))
(def ^:dynamic *db* nil)
(defn- run-statements [db resource split]
(doseq [statement (remove str/blank?
(str/split (slurp resource) split))]
(println "SQL: " statement)
(jdbc/execute! db [statement])))
(defn- create-test-database [db]
(run-statements db "test/database.sql" #";"))
(defn- provider []
(PreparedDbProvider/forPreparer
(reify DatabasePreparer
(prepare [_ ds]
(create-test-database ds)))))
(defonce db-provider (provider))
(defn reset-db [] (alter-var-root #'db-provider (fn [_] (provider))))
(defn datasource [] (.createDataSource db-provider))
(defn with-db [fn]
(binding [*db* (datasource)]
(fn)))
| |
3c39a1ad76a7c795929f2d01b1347bf4fe16a610ffb3c3c205c5596613a3ee4b | facebook/duckling | Corpus.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.AmountOfMoney.NB.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.AmountOfMoney.Types
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale NB Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (simple Dollar 10)
[ "$10"
, "10$"
, "ti dollar"
]
, examples (simple Cent 10)
[ "ti øre"
]
, examples (simple Dollar 10000)
[ "$10.000"
, "10K$"
, "$10k"
]
, examples (simple USD 1.23)
[ "USD1,23"
]
, examples (simple NOK 10)
[ "10kroner"
, "10kr"
, "ti kroner"
, "10 NOK"
, "ti norske kroner"
]
, examples (simple SEK 10)
[ "10kronor"
, "10 svenske kroner"
, "10 svenske kr"
, "10 svenske kronor"
, "ti kronor"
]
, examples (simple DKK 10)
[ "10 danske kroner"
, "ti danske kroner"
, "ti danske kr"
]
, examples (simple AUD 10)
[ "10 australske dollar"
, "10 australske dollars"
]
, examples (simple CAD 10)
[ "10 kanadiske dollar"
, "10 kanadiske dollars"
, "10 canadiske dollar"
, "10 canadiske dollars"
]
, examples (simple CHF 10)
[ "10 sveitsiske franc"
, "10 sveitsiske francs"
]
, examples (simple CNY 10)
[ "10 yuan"
, "10 kinesiske yuan"
, "10 kinesisk yuan"
, "10 renminbi"
, "10 kinesiske renminbi"
, "10 kinesisk renminbi"
]
, examples (simple CZK 10)
[ "10 koruna"
, "10 tsjekkiske koruna"
]
, examples (simple INR 10)
[ "10 rupi"
, "10 rupier"
, "10 rupee"
, "10 rupees"
, "10 indisk rupi"
, "10 indiske rupi"
, "10 indiske rupee"
, "10 indiske rupees"
, "10 indiske rupier"
, "10 indisk rupier"
, "ti rupi"
, "ti rupier"
, "ti indisk rupi"
, "ti indiske rupi"
, "ti indiske rupee"
, "ti indiske rupees"
, "ti indiske rupier"
, "ti indisk rupier"
]
, examples (simple JPY 10)
[ "10 japanske yen"
, "10 yen"
, "ti japanske yen"
, "ti yen"
]
, examples (simple PKR 10)
[ "10 pakistansk rupi"
, "10 pakistanske rupi"
, "10 pakistanske rupee"
, "10 pakistanske rupees"
, "10 pakistanske rupier"
, "10 pakistansk rupier"
, "ti pakistansk rupi"
, "ti pakistanske rupi"
, "ti pakistanske rupee"
, "ti pakistanske rupees"
, "ti pakistanske rupier"
, "ti pakistansk rupier"
]
, examples (simple PLN 10)
[ "10 zloty"
, "10 sloty"
, "10 polske zloty"
, "10 polske sloty"
, "ti zloty"
, "ti sloty"
, "ti polske zloty"
, "ti polske sloty"
]
, examples (simple SGD 10)
[ "10 singapore dollar"
, "10 singapore dollars"
, "10 singaporske dollar"
, "10 singaporske dollars"
, "ti singapore dollar"
, "ti singapore dollars"
, "ti singaporske dollar"
, "ti singaporske dollars"
]
, examples (simple THB 10)
[ "10 bhat"
, "10 thai baht"
, "10 thai bhat"
, "10 thailand baht"
, "10 thailand bhat"
, "10 thailandske baht"
, "10 thailandske bhat"
, "ti baht"
, "ti bhat"
, "ti thai baht"
, "ti thai bhat"
, "ti thailand baht"
, "ti thailand bhat"
, "ti thailandske baht"
, "ti thailandske bhat"
]
, examples (simple ZAR 10)
[ "10 rand"
, "10 sørafrikanske rand"
, "10 sør-afrikanske rand"
, "10 rand"
, "10 sørafrikanske rand"
, "10 sør-afrikanske rand"
, "ti rand"
, "ti sørafrikanske rand"
, "ti sør-afrikanske rand"
]
, examples (simple NOK 2.23)
[ "2 kroner og 23 øre"
, "to kroner 23 øre"
, "to kroner og 23 øre"
, "to kr 23"
]
, examples (simple SEK 2.23)
[ "2 kronor og 23 öre"
, "to kronor 23 öre"
, "to svenske kronor 23 öre"
, "to svenske kroner 23 öre"
, "to svenske kroner 23 øre"
, "to kronor og 23 öre"
, "to svenske kronor og 23 öre"
, "to svenske kroner og 23 öre"
, "to svenske kroner og 23 øre"
, "to svensk kroner og 23 øre"
]
, examples (simple DKK 2.23)
[ "2 danske kroner og 23 øre"
, "to danske kroner 23 øre"
, "to danske kroner og 23 øre"
, "to danske kr 23"
, "to dansk kr 23"
]
, examples (simple USD 2.23)
[ "2 amerikanske dollar og 23 cent"
, "2 amerikanske dollars og 23 cent"
, "2 amerikanske dollar og 23 cents"
, "2 amerikanske dollars og 23 cents"
, "to amerikanske dollar 23 cent"
, "to amerikanske dollars 23 cent"
, "to amerikanske dollar 23 cents"
, "to amerikanske dollars 23 cents"
, "to amerikanske dollar og 23 cent"
, "to amerikanske dollars og 23 cent"
, "to amerikanske dollar og 23 cents"
, "to amerikanske dollars og 23 cents"
, "to amerikanske dollar 23"
, "to amerikanske dollars 23"
]
, examples (simple AUD 2.23)
[ "2 australske dollar og 23 cent"
, "2 australske dollars og 23 cent"
, "2 australske dollar og 23 cents"
, "2 australske dollars og 23 cents"
, "to australske dollar 23 cent"
, "to australske dollars 23 cent"
, "to australske dollar 23 cents"
, "to australske dollars 23 cents"
, "to australske dollar og 23 cent"
, "to australske dollars og 23 cent"
, "to australske dollar og 23 cents"
, "to australske dollars og 23 cents"
, "to australske dollar 23"
, "to australske dollars 23"
]
, examples (simple CAD 2.23)
[ "2 kanadiske dollar og 23 cent"
, "2 kanadiske dollars og 23 cent"
, "2 canadiske dollar og 23 cent"
, "2 canadiske dollars og 23 cent"
, "2 kanadiske dollar og 23 cents"
, "2 kanadiske dollars og 23 cents"
, "2 canadiske dollar og 23 cents"
, "2 canadiske dollars og 23 cents"
, "to kanadiske dollar 23 cent"
, "to kanadiske dollars 23 cent"
, "to canadiske dollar 23 cent"
, "to canadiske dollars 23 cent"
, "to kanadiske dollar 23 cents"
, "to kanadiske dollars 23 cents"
, "to canadiske dollar 23 cents"
, "to canadiske dollars 23 cents"
, "to kanadiske dollar og 23 cent"
, "to kanadiske dollars og 23 cent"
, "to canadiske dollar og 23 cent"
, "to canadiske dollars og 23 cent"
, "to kanadiske dollar og 23 cents"
, "to kanadiske dollars og 23 cents"
, "to canadiske dollar og 23 cents"
, "to canadiske dollars og 23 cents"
, "to kanadiske dollar 23"
, "to kanadiske dollars 23"
, "to canadiske dollar 23"
, "to canadiske dollars 23"
]
, examples (simple CHF 2.23)
[ "2 sveitsiske franc og 23 rappen"
, "2 sveitsiske francs og 23 rappen"
, "2 sveitsiske franc og 23 rp"
, "2 sveitsiske francs og 23 rp"
, "2 sveitsiske franc og 23 centime"
, "2 sveitsiske francs og 23 centime"
, "2 sveitsiske franc og 23 c"
, "2 sveitsiske francs og 23 c"
, "2 sveitsiske franc og 23 centesimo"
, "2 sveitsiske francs og 23 centesimo"
, "2 sveitsiske franc og 23 ct"
, "2 sveitsiske francs og 23 ct"
, "2 sveitsiske franc og 23 rap"
, "2 sveitsiske francs og 23 rap"
, "to sveitsiske franc 23 rappen"
, "to sveitsiske francs 23 rappen"
, "to sveitsiske franc 23 rp"
, "to sveitsiske francs 23 rp"
, "to sveitsiske franc 23 centime"
, "to sveitsiske francs 23 centime"
, "to sveitsiske franc 23 c"
, "to sveitsiske francs 23 c"
, "to sveitsiske franc 23 centesimo"
, "to sveitsiske francs 23 centesimo"
, "to sveitsiske franc 23 ct"
, "to sveitsiske francs 23 ct"
, "to sveitsiske franc 23 rap"
, "to sveitsiske francs 23 rap"
, "to sveitsiske franc og 23 rappen"
, "to sveitsiske francs og 23 rappen"
, "to sveitsiske franc og 23 rp"
, "to sveitsiske francs og 23 rp"
, "to sveitsiske franc og 23 centime"
, "to sveitsiske francs og 23 centime"
, "to sveitsiske franc og 23 c"
, "to sveitsiske francs og 23 c"
, "to sveitsiske franc og 23 centesimo"
, "to sveitsiske francs og 23 centesimo"
, "to sveitsiske franc og 23 ct"
, "to sveitsiske francs og 23 ct"
, "to sveitsiske franc og 23 rap"
, "to sveitsiske francs og 23 rap"
, "to sveitsiske franc 23"
, "to sveitsiske francs 23"
]
, examples (simple CNY 2.23)
[ "2 yuan og 23 fen"
, "2 kinesiske yuan og 23 fen"
, "2 renminbi og 23 fen"
, "2 kinesiske renminbi og 23 fen"
, "to yuan 23 fen"
, "to kinesiske yuan 23 fen"
, "to renminbi 23 fen"
, "to kinesiske renminbi 23 fen"
, "to yuan og 23 fen"
, "to kinesiske yuan og 23 fen"
, "to renminbi og 23 fen"
, "to kinesiske renminbi og 23 fen"
, "to yuan 23"
, "to kinesiske yuan 23"
, "to renminbi 23"
, "to kinesiske renminbi 23"
]
, examples (simple CZK 2.23)
[ "2 koruna og 23 haleru"
, "2 tsjekkiske koruna og 23 haleru"
, "to koruna 23 haleru"
, "to tsjekkiske koruna 23 haleru"
, "to koruna og 23 haleru"
, "to tsjekkiske koruna og 23 haleru"
, "to koruna 23"
, "to tsjekkiske koruna 23"
]
, examples (simple HKD 2.23)
[ "2 hong kong dollar og 23 cent"
, "2 hong kong dollar og 23 cents"
, "2 hong kong dollars og 23 cent"
, "2 hong kong dollars og 23 cents"
, "2 hong kong dollar og 23 cents"
, "2 hong kong dollars og 23 cents"
, "to hong kong dollar 23 cent"
, "to hong kong dollars 23 cent"
, "to hong kong dollar 23 cents"
, "to hong kong dollars 23 cents"
, "to hong kong dollar og 23 cent"
, "to hong kong dollars og 23 cent"
, "to hong kong dollar og 23 cents"
, "to hong kong dollars og 23 cents"
, "to hong kong dollar 23"
, "to hong kong dollars 23"
]
, examples (simple INR 2.23)
[ "2 indiske rupi og 23 paise"
, "2 indiske rupier og 23 paise"
, "to indiske rupi 23 paise"
, "to indiske rupier 23 paise"
, "to indiske rupier 23 paise"
, "to indiske rupi og 23 paise"
, "to indiske rupier og 23 paise"
, "to indiske rupi 23"
, "to indiske rupier 23"
]
, examples (simple NZD 2.23)
[ "2 new zealand dollar og 23 cent"
, "2 new zealand dollars og 23 cent"
, "2 new zealand dollars og 23 cents"
, "2 new zealandske dollar og 23 cent"
, "2 new zealandske dollars og 23 cent"
, "2 new zealandske dollars og 23 cents"
, "2 new zealand dollar og 23 cents"
, "2 new zealand dollars og 23 cents"
, "2 nz dollar og 23 cents"
, "2 nz dollars og 23 cents"
, "to new zealand dollar 23 cent"
, "to new zealand dollars 23 cent"
, "to new zealand dollars 23 cents"
, "to new zealandske dollar 23 cent"
, "to new zealandske dollars 23 cent"
, "to new zealandske dollars 23 cents"
, "to new zealand dollar 23 cents"
, "to new zealand dollars 23 cents"
, "to new zealand dollars 23 cent"
, "to new zealand dollar og 23 cent"
, "to new zealand dollars og 23 cent"
, "to new zealandske dollar og 23 cent"
, "to new zealandske dollars og 23 cent"
, "to new zealandske dollars og 23 cents"
, "to new zealand dollar og 23 cents"
, "to new zealand dollars og 23 cent"
, "to new zealand dollars og 23 cents"
, "to new zealand dollar 23"
, "to new zealand dollars 23"
, "to new zealandske dollar 23"
, "to new zealandske dollars 23"
, "to nz dollar 23"
, "to nz dollars 23"
]
, examples (simple PLN 2.23)
[ "2 zloty og 23 groszy"
, "2 sloty og 23 groszy"
, "2 polske zloty og 23 groszy"
, "2 polske sloty og 23 groszy"
, "to zloty 23 groszy"
, "to sloty 23 groszy"
, "to polske zloty 23 groszy"
, "to polske sloty 23 groszy"
, "to zloty og 23 groszy"
, "to sloty og 23 groszy"
, "to polske zloty og 23 groszy"
, "to polske sloty og 23 groszy"
, "to zloty 23"
, "to sloty 23"
, "to polske zloty 23"
, "to polske sloty 23"
]
, examples (simple SGD 2.23)
[ "2 singapore dollar og 23 cent"
, "2 singapore dollars og 23 cent"
, "2 singaporske dollar og 23 cent"
, "2 singaporske dollars og 23 cent"
, "2 singapore dollar og 23 cents"
, "2 singapore dollars og 23 cents"
, "to singapore dollar 23 cent"
, "to singapore dollars 23 cent"
, "to singaporske dollar 23 cent"
, "to singaporske dollars 23 cent"
, "to singapore dollar 23 cents"
, "to singapore dollars 23 cents"
, "to singapore dollar og 23 cent"
, "to singapore dollars og 23 cent"
, "to singaporske dollar og 23 cent"
, "to singaporske dollars og 23 cent"
, "to singapore dollar og 23 cents"
, "to singapore dollars og 23 cents"
, "to singapore dollar 23"
, "to singapore dollars 23"
, "to singaporske dollar 23"
, "to singaporske dollars 23"
]
, examples (simple ZAR 2.23)
[ "2 rand og 23 cent"
, "2 sørafrikanske rand og 23 cent"
, "2 sørafrikanske rand og 23 cents"
, "2 sør-afrikanske rand og 23 cent"
, "2 sør-afrikanske rand og 23 cents"
, "to rand 23 cent"
, "to sørafrikanske rand 23 cent"
, "to sørafrikanske rand 23 cents"
, "to sør-afrikanske rand 23 cent"
, "to sør-afrikanske rand 23 cents"
, "to rand og 23 cent"
, "to sørafrikanske rand og 23 cent"
, "to sørafrikanske rand og 23 cents"
, "to sør-afrikanske rand og 23 cent"
, "to sør-afrikanske rand og 23 cents"
, "to rand 23"
, "to sørafrikanske rand 23"
, "to sør-afrikanske rand 23"
]
, examples (simple THB 2.23)
[ "2 baht og 23 satang"
, "2 bhat og 23 satang"
, "2 thai baht og 23 satang"
, "2 thai bhat og 23 satang"
, "2 thailandske baht og 23 satang"
, "2 thailandske bhat og 23 satang"
, "to baht 23 satang"
, "to bhat 23 satang"
, "to thai baht 23 satang"
, "to thai bhat 23 satang"
, "to thailandske baht 23 satang"
, "to thailandske bhat 23 satang"
, "to baht og 23 satang"
, "to bhat og 23 satang"
, "to thai baht og 23 satang"
, "to thai bhat og 23 satang"
, "to thailandske baht og 23 satang"
, "to thailandske bhat og 23 satang"
, "to baht 23"
, "to bhat 23"
, "to thai baht 23"
, "to thai bhat 23"
, "to thailandske baht 23"
, "to thailandske bhat 23"
]
, examples (simple Cent 10)
[ "ti cent"
, "ti cents"
, "ti pence"
, "ti penny"
, "ti pennies"
, "10 cent"
, "10 cents"
, "10 cents"
, "10 pence"
, "10 penny"
, "10 øre"
, "10 ører"
, "10 öre"
, "10 örer"
, "10 p"
, "10 c"
, "10 fen"
, "10 haleru"
, "10 groszy"
, "10 paise"
, "10 paisa"
, "10 centesimo"
, "10 centesimi"
, "10 centime"
, "10 centimes"
, "10 ct"
, "10 rap"
, "10 rappen"
, "10 rappens"
, "10 rp"
, "10 satang"
]
, examples (simple EUR 20)
[ "20€"
, "20 euro"
, "20 Euro"
, "20 Euros"
, "EUR 20"
]
, examples (simple EUR 29.99)
[ "EUR29,99"
]
, examples (simple INR 20)
[ "Rs. 20"
, "Rs 20"
, "20 Rupees"
, "20Rs"
, "Rs20"
, "INR20"
]
, examples (simple INR 20.43)
[ "20 Rupees 43"
, "tjue rupees 43"
, "tjue rupees 43¢"
]
, examples (simple Pound 9)
[ "£9"
, "ni pund"
]
, examples (simple GBP 3.01)
[ "GBP3,01"
, "GBP 3,01"
]
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/AmountOfMoney/NB/Corpus.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.AmountOfMoney.NB.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.AmountOfMoney.Types
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale NB Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (simple Dollar 10)
[ "$10"
, "10$"
, "ti dollar"
]
, examples (simple Cent 10)
[ "ti øre"
]
, examples (simple Dollar 10000)
[ "$10.000"
, "10K$"
, "$10k"
]
, examples (simple USD 1.23)
[ "USD1,23"
]
, examples (simple NOK 10)
[ "10kroner"
, "10kr"
, "ti kroner"
, "10 NOK"
, "ti norske kroner"
]
, examples (simple SEK 10)
[ "10kronor"
, "10 svenske kroner"
, "10 svenske kr"
, "10 svenske kronor"
, "ti kronor"
]
, examples (simple DKK 10)
[ "10 danske kroner"
, "ti danske kroner"
, "ti danske kr"
]
, examples (simple AUD 10)
[ "10 australske dollar"
, "10 australske dollars"
]
, examples (simple CAD 10)
[ "10 kanadiske dollar"
, "10 kanadiske dollars"
, "10 canadiske dollar"
, "10 canadiske dollars"
]
, examples (simple CHF 10)
[ "10 sveitsiske franc"
, "10 sveitsiske francs"
]
, examples (simple CNY 10)
[ "10 yuan"
, "10 kinesiske yuan"
, "10 kinesisk yuan"
, "10 renminbi"
, "10 kinesiske renminbi"
, "10 kinesisk renminbi"
]
, examples (simple CZK 10)
[ "10 koruna"
, "10 tsjekkiske koruna"
]
, examples (simple INR 10)
[ "10 rupi"
, "10 rupier"
, "10 rupee"
, "10 rupees"
, "10 indisk rupi"
, "10 indiske rupi"
, "10 indiske rupee"
, "10 indiske rupees"
, "10 indiske rupier"
, "10 indisk rupier"
, "ti rupi"
, "ti rupier"
, "ti indisk rupi"
, "ti indiske rupi"
, "ti indiske rupee"
, "ti indiske rupees"
, "ti indiske rupier"
, "ti indisk rupier"
]
, examples (simple JPY 10)
[ "10 japanske yen"
, "10 yen"
, "ti japanske yen"
, "ti yen"
]
, examples (simple PKR 10)
[ "10 pakistansk rupi"
, "10 pakistanske rupi"
, "10 pakistanske rupee"
, "10 pakistanske rupees"
, "10 pakistanske rupier"
, "10 pakistansk rupier"
, "ti pakistansk rupi"
, "ti pakistanske rupi"
, "ti pakistanske rupee"
, "ti pakistanske rupees"
, "ti pakistanske rupier"
, "ti pakistansk rupier"
]
, examples (simple PLN 10)
[ "10 zloty"
, "10 sloty"
, "10 polske zloty"
, "10 polske sloty"
, "ti zloty"
, "ti sloty"
, "ti polske zloty"
, "ti polske sloty"
]
, examples (simple SGD 10)
[ "10 singapore dollar"
, "10 singapore dollars"
, "10 singaporske dollar"
, "10 singaporske dollars"
, "ti singapore dollar"
, "ti singapore dollars"
, "ti singaporske dollar"
, "ti singaporske dollars"
]
, examples (simple THB 10)
[ "10 bhat"
, "10 thai baht"
, "10 thai bhat"
, "10 thailand baht"
, "10 thailand bhat"
, "10 thailandske baht"
, "10 thailandske bhat"
, "ti baht"
, "ti bhat"
, "ti thai baht"
, "ti thai bhat"
, "ti thailand baht"
, "ti thailand bhat"
, "ti thailandske baht"
, "ti thailandske bhat"
]
, examples (simple ZAR 10)
[ "10 rand"
, "10 sørafrikanske rand"
, "10 sør-afrikanske rand"
, "10 rand"
, "10 sørafrikanske rand"
, "10 sør-afrikanske rand"
, "ti rand"
, "ti sørafrikanske rand"
, "ti sør-afrikanske rand"
]
, examples (simple NOK 2.23)
[ "2 kroner og 23 øre"
, "to kroner 23 øre"
, "to kroner og 23 øre"
, "to kr 23"
]
, examples (simple SEK 2.23)
[ "2 kronor og 23 öre"
, "to kronor 23 öre"
, "to svenske kronor 23 öre"
, "to svenske kroner 23 öre"
, "to svenske kroner 23 øre"
, "to kronor og 23 öre"
, "to svenske kronor og 23 öre"
, "to svenske kroner og 23 öre"
, "to svenske kroner og 23 øre"
, "to svensk kroner og 23 øre"
]
, examples (simple DKK 2.23)
[ "2 danske kroner og 23 øre"
, "to danske kroner 23 øre"
, "to danske kroner og 23 øre"
, "to danske kr 23"
, "to dansk kr 23"
]
, examples (simple USD 2.23)
[ "2 amerikanske dollar og 23 cent"
, "2 amerikanske dollars og 23 cent"
, "2 amerikanske dollar og 23 cents"
, "2 amerikanske dollars og 23 cents"
, "to amerikanske dollar 23 cent"
, "to amerikanske dollars 23 cent"
, "to amerikanske dollar 23 cents"
, "to amerikanske dollars 23 cents"
, "to amerikanske dollar og 23 cent"
, "to amerikanske dollars og 23 cent"
, "to amerikanske dollar og 23 cents"
, "to amerikanske dollars og 23 cents"
, "to amerikanske dollar 23"
, "to amerikanske dollars 23"
]
, examples (simple AUD 2.23)
[ "2 australske dollar og 23 cent"
, "2 australske dollars og 23 cent"
, "2 australske dollar og 23 cents"
, "2 australske dollars og 23 cents"
, "to australske dollar 23 cent"
, "to australske dollars 23 cent"
, "to australske dollar 23 cents"
, "to australske dollars 23 cents"
, "to australske dollar og 23 cent"
, "to australske dollars og 23 cent"
, "to australske dollar og 23 cents"
, "to australske dollars og 23 cents"
, "to australske dollar 23"
, "to australske dollars 23"
]
, examples (simple CAD 2.23)
[ "2 kanadiske dollar og 23 cent"
, "2 kanadiske dollars og 23 cent"
, "2 canadiske dollar og 23 cent"
, "2 canadiske dollars og 23 cent"
, "2 kanadiske dollar og 23 cents"
, "2 kanadiske dollars og 23 cents"
, "2 canadiske dollar og 23 cents"
, "2 canadiske dollars og 23 cents"
, "to kanadiske dollar 23 cent"
, "to kanadiske dollars 23 cent"
, "to canadiske dollar 23 cent"
, "to canadiske dollars 23 cent"
, "to kanadiske dollar 23 cents"
, "to kanadiske dollars 23 cents"
, "to canadiske dollar 23 cents"
, "to canadiske dollars 23 cents"
, "to kanadiske dollar og 23 cent"
, "to kanadiske dollars og 23 cent"
, "to canadiske dollar og 23 cent"
, "to canadiske dollars og 23 cent"
, "to kanadiske dollar og 23 cents"
, "to kanadiske dollars og 23 cents"
, "to canadiske dollar og 23 cents"
, "to canadiske dollars og 23 cents"
, "to kanadiske dollar 23"
, "to kanadiske dollars 23"
, "to canadiske dollar 23"
, "to canadiske dollars 23"
]
, examples (simple CHF 2.23)
[ "2 sveitsiske franc og 23 rappen"
, "2 sveitsiske francs og 23 rappen"
, "2 sveitsiske franc og 23 rp"
, "2 sveitsiske francs og 23 rp"
, "2 sveitsiske franc og 23 centime"
, "2 sveitsiske francs og 23 centime"
, "2 sveitsiske franc og 23 c"
, "2 sveitsiske francs og 23 c"
, "2 sveitsiske franc og 23 centesimo"
, "2 sveitsiske francs og 23 centesimo"
, "2 sveitsiske franc og 23 ct"
, "2 sveitsiske francs og 23 ct"
, "2 sveitsiske franc og 23 rap"
, "2 sveitsiske francs og 23 rap"
, "to sveitsiske franc 23 rappen"
, "to sveitsiske francs 23 rappen"
, "to sveitsiske franc 23 rp"
, "to sveitsiske francs 23 rp"
, "to sveitsiske franc 23 centime"
, "to sveitsiske francs 23 centime"
, "to sveitsiske franc 23 c"
, "to sveitsiske francs 23 c"
, "to sveitsiske franc 23 centesimo"
, "to sveitsiske francs 23 centesimo"
, "to sveitsiske franc 23 ct"
, "to sveitsiske francs 23 ct"
, "to sveitsiske franc 23 rap"
, "to sveitsiske francs 23 rap"
, "to sveitsiske franc og 23 rappen"
, "to sveitsiske francs og 23 rappen"
, "to sveitsiske franc og 23 rp"
, "to sveitsiske francs og 23 rp"
, "to sveitsiske franc og 23 centime"
, "to sveitsiske francs og 23 centime"
, "to sveitsiske franc og 23 c"
, "to sveitsiske francs og 23 c"
, "to sveitsiske franc og 23 centesimo"
, "to sveitsiske francs og 23 centesimo"
, "to sveitsiske franc og 23 ct"
, "to sveitsiske francs og 23 ct"
, "to sveitsiske franc og 23 rap"
, "to sveitsiske francs og 23 rap"
, "to sveitsiske franc 23"
, "to sveitsiske francs 23"
]
, examples (simple CNY 2.23)
[ "2 yuan og 23 fen"
, "2 kinesiske yuan og 23 fen"
, "2 renminbi og 23 fen"
, "2 kinesiske renminbi og 23 fen"
, "to yuan 23 fen"
, "to kinesiske yuan 23 fen"
, "to renminbi 23 fen"
, "to kinesiske renminbi 23 fen"
, "to yuan og 23 fen"
, "to kinesiske yuan og 23 fen"
, "to renminbi og 23 fen"
, "to kinesiske renminbi og 23 fen"
, "to yuan 23"
, "to kinesiske yuan 23"
, "to renminbi 23"
, "to kinesiske renminbi 23"
]
, examples (simple CZK 2.23)
[ "2 koruna og 23 haleru"
, "2 tsjekkiske koruna og 23 haleru"
, "to koruna 23 haleru"
, "to tsjekkiske koruna 23 haleru"
, "to koruna og 23 haleru"
, "to tsjekkiske koruna og 23 haleru"
, "to koruna 23"
, "to tsjekkiske koruna 23"
]
, examples (simple HKD 2.23)
[ "2 hong kong dollar og 23 cent"
, "2 hong kong dollar og 23 cents"
, "2 hong kong dollars og 23 cent"
, "2 hong kong dollars og 23 cents"
, "2 hong kong dollar og 23 cents"
, "2 hong kong dollars og 23 cents"
, "to hong kong dollar 23 cent"
, "to hong kong dollars 23 cent"
, "to hong kong dollar 23 cents"
, "to hong kong dollars 23 cents"
, "to hong kong dollar og 23 cent"
, "to hong kong dollars og 23 cent"
, "to hong kong dollar og 23 cents"
, "to hong kong dollars og 23 cents"
, "to hong kong dollar 23"
, "to hong kong dollars 23"
]
, examples (simple INR 2.23)
[ "2 indiske rupi og 23 paise"
, "2 indiske rupier og 23 paise"
, "to indiske rupi 23 paise"
, "to indiske rupier 23 paise"
, "to indiske rupier 23 paise"
, "to indiske rupi og 23 paise"
, "to indiske rupier og 23 paise"
, "to indiske rupi 23"
, "to indiske rupier 23"
]
, examples (simple NZD 2.23)
[ "2 new zealand dollar og 23 cent"
, "2 new zealand dollars og 23 cent"
, "2 new zealand dollars og 23 cents"
, "2 new zealandske dollar og 23 cent"
, "2 new zealandske dollars og 23 cent"
, "2 new zealandske dollars og 23 cents"
, "2 new zealand dollar og 23 cents"
, "2 new zealand dollars og 23 cents"
, "2 nz dollar og 23 cents"
, "2 nz dollars og 23 cents"
, "to new zealand dollar 23 cent"
, "to new zealand dollars 23 cent"
, "to new zealand dollars 23 cents"
, "to new zealandske dollar 23 cent"
, "to new zealandske dollars 23 cent"
, "to new zealandske dollars 23 cents"
, "to new zealand dollar 23 cents"
, "to new zealand dollars 23 cents"
, "to new zealand dollars 23 cent"
, "to new zealand dollar og 23 cent"
, "to new zealand dollars og 23 cent"
, "to new zealandske dollar og 23 cent"
, "to new zealandske dollars og 23 cent"
, "to new zealandske dollars og 23 cents"
, "to new zealand dollar og 23 cents"
, "to new zealand dollars og 23 cent"
, "to new zealand dollars og 23 cents"
, "to new zealand dollar 23"
, "to new zealand dollars 23"
, "to new zealandske dollar 23"
, "to new zealandske dollars 23"
, "to nz dollar 23"
, "to nz dollars 23"
]
, examples (simple PLN 2.23)
[ "2 zloty og 23 groszy"
, "2 sloty og 23 groszy"
, "2 polske zloty og 23 groszy"
, "2 polske sloty og 23 groszy"
, "to zloty 23 groszy"
, "to sloty 23 groszy"
, "to polske zloty 23 groszy"
, "to polske sloty 23 groszy"
, "to zloty og 23 groszy"
, "to sloty og 23 groszy"
, "to polske zloty og 23 groszy"
, "to polske sloty og 23 groszy"
, "to zloty 23"
, "to sloty 23"
, "to polske zloty 23"
, "to polske sloty 23"
]
, examples (simple SGD 2.23)
[ "2 singapore dollar og 23 cent"
, "2 singapore dollars og 23 cent"
, "2 singaporske dollar og 23 cent"
, "2 singaporske dollars og 23 cent"
, "2 singapore dollar og 23 cents"
, "2 singapore dollars og 23 cents"
, "to singapore dollar 23 cent"
, "to singapore dollars 23 cent"
, "to singaporske dollar 23 cent"
, "to singaporske dollars 23 cent"
, "to singapore dollar 23 cents"
, "to singapore dollars 23 cents"
, "to singapore dollar og 23 cent"
, "to singapore dollars og 23 cent"
, "to singaporske dollar og 23 cent"
, "to singaporske dollars og 23 cent"
, "to singapore dollar og 23 cents"
, "to singapore dollars og 23 cents"
, "to singapore dollar 23"
, "to singapore dollars 23"
, "to singaporske dollar 23"
, "to singaporske dollars 23"
]
, examples (simple ZAR 2.23)
[ "2 rand og 23 cent"
, "2 sørafrikanske rand og 23 cent"
, "2 sørafrikanske rand og 23 cents"
, "2 sør-afrikanske rand og 23 cent"
, "2 sør-afrikanske rand og 23 cents"
, "to rand 23 cent"
, "to sørafrikanske rand 23 cent"
, "to sørafrikanske rand 23 cents"
, "to sør-afrikanske rand 23 cent"
, "to sør-afrikanske rand 23 cents"
, "to rand og 23 cent"
, "to sørafrikanske rand og 23 cent"
, "to sørafrikanske rand og 23 cents"
, "to sør-afrikanske rand og 23 cent"
, "to sør-afrikanske rand og 23 cents"
, "to rand 23"
, "to sørafrikanske rand 23"
, "to sør-afrikanske rand 23"
]
, examples (simple THB 2.23)
[ "2 baht og 23 satang"
, "2 bhat og 23 satang"
, "2 thai baht og 23 satang"
, "2 thai bhat og 23 satang"
, "2 thailandske baht og 23 satang"
, "2 thailandske bhat og 23 satang"
, "to baht 23 satang"
, "to bhat 23 satang"
, "to thai baht 23 satang"
, "to thai bhat 23 satang"
, "to thailandske baht 23 satang"
, "to thailandske bhat 23 satang"
, "to baht og 23 satang"
, "to bhat og 23 satang"
, "to thai baht og 23 satang"
, "to thai bhat og 23 satang"
, "to thailandske baht og 23 satang"
, "to thailandske bhat og 23 satang"
, "to baht 23"
, "to bhat 23"
, "to thai baht 23"
, "to thai bhat 23"
, "to thailandske baht 23"
, "to thailandske bhat 23"
]
, examples (simple Cent 10)
[ "ti cent"
, "ti cents"
, "ti pence"
, "ti penny"
, "ti pennies"
, "10 cent"
, "10 cents"
, "10 cents"
, "10 pence"
, "10 penny"
, "10 øre"
, "10 ører"
, "10 öre"
, "10 örer"
, "10 p"
, "10 c"
, "10 fen"
, "10 haleru"
, "10 groszy"
, "10 paise"
, "10 paisa"
, "10 centesimo"
, "10 centesimi"
, "10 centime"
, "10 centimes"
, "10 ct"
, "10 rap"
, "10 rappen"
, "10 rappens"
, "10 rp"
, "10 satang"
]
, examples (simple EUR 20)
[ "20€"
, "20 euro"
, "20 Euro"
, "20 Euros"
, "EUR 20"
]
, examples (simple EUR 29.99)
[ "EUR29,99"
]
, examples (simple INR 20)
[ "Rs. 20"
, "Rs 20"
, "20 Rupees"
, "20Rs"
, "Rs20"
, "INR20"
]
, examples (simple INR 20.43)
[ "20 Rupees 43"
, "tjue rupees 43"
, "tjue rupees 43¢"
]
, examples (simple Pound 9)
[ "£9"
, "ni pund"
]
, examples (simple GBP 3.01)
[ "GBP3,01"
, "GBP 3,01"
]
]
|
b45d28c7ee02eb1e374b08efbb13fa4804452f0038b93c46c2bb6a463c8ecc9e | PacktWorkshops/The-Clojure-Workshop | elo.clj | (ns packt-clj.tennis.elo
(:require
[clojure.java.jdbc :as jdbc]
[packt-clj.tennis.query :as query]))
(def ^:private k-factor 32)
(defn- match-probability [player-1-rating player-2-rating]
(/ 1
(+ 1 (Math/pow 10 (/ (- player-2-rating player-1-rating) 1000)))))
(defn- recalculate-rating [previous-rating expected-outcome real-outcome]
(+ previous-rating (* k-factor (- real-outcome expected-outcome))))
(defn- expected-outcomes
[winner-rating loser-rating]
(let [winner-expected-outcome (match-probability winner-rating loser-rating)]
[winner-expected-outcome (- 1 winner-expected-outcome)]))
(defn- calculate-new-ratings [current-player-ratings {:keys [winner_id loser_id]}]
(let [winner-rating (get current-player-ratings winner_id 1000)
loser-rating (get current-player-ratings loser_id 1000)
[winner-expected-outcome loser-expected-outcome] (expected-outcomes winner-rating loser-rating)]
[{:player_id winner_id
:rating (recalculate-rating winner-rating winner-expected-outcome 1)}
{:player_id loser_id
:rating (recalculate-rating loser-rating loser-expected-outcome 0)}]))
(defn calculate-all
[db]
(->> (query/all-tennis-matches db)
(reduce
(fn [{:keys [current-player-ratings] :as acc} match]
(let [[{winner-id :player_id :as new-winner-rating} {loser-id :player_id :as new-loser-rating}] (calculate-new-ratings current-player-ratings match)]
(-> acc
(update :elo-ratings into [new-winner-rating
new-loser-rating])
(assoc-in [:current-player-ratings winner-id] (:rating new-winner-rating))
(assoc-in [:current-player-ratings loser-id] (:rating new-loser-rating)))))
{:elo-ratings []
:current-player-ratings {}})
:elo-ratings))
(defn persist-all
[db]
(let [elo-ratings (calculate-all db)]
(jdbc/insert-multi! db :elo elo-ratings)))
| null | https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter13/Activity13.01/src/packt_clj/tennis/elo.clj | clojure | (ns packt-clj.tennis.elo
(:require
[clojure.java.jdbc :as jdbc]
[packt-clj.tennis.query :as query]))
(def ^:private k-factor 32)
(defn- match-probability [player-1-rating player-2-rating]
(/ 1
(+ 1 (Math/pow 10 (/ (- player-2-rating player-1-rating) 1000)))))
(defn- recalculate-rating [previous-rating expected-outcome real-outcome]
(+ previous-rating (* k-factor (- real-outcome expected-outcome))))
(defn- expected-outcomes
[winner-rating loser-rating]
(let [winner-expected-outcome (match-probability winner-rating loser-rating)]
[winner-expected-outcome (- 1 winner-expected-outcome)]))
(defn- calculate-new-ratings [current-player-ratings {:keys [winner_id loser_id]}]
(let [winner-rating (get current-player-ratings winner_id 1000)
loser-rating (get current-player-ratings loser_id 1000)
[winner-expected-outcome loser-expected-outcome] (expected-outcomes winner-rating loser-rating)]
[{:player_id winner_id
:rating (recalculate-rating winner-rating winner-expected-outcome 1)}
{:player_id loser_id
:rating (recalculate-rating loser-rating loser-expected-outcome 0)}]))
(defn calculate-all
[db]
(->> (query/all-tennis-matches db)
(reduce
(fn [{:keys [current-player-ratings] :as acc} match]
(let [[{winner-id :player_id :as new-winner-rating} {loser-id :player_id :as new-loser-rating}] (calculate-new-ratings current-player-ratings match)]
(-> acc
(update :elo-ratings into [new-winner-rating
new-loser-rating])
(assoc-in [:current-player-ratings winner-id] (:rating new-winner-rating))
(assoc-in [:current-player-ratings loser-id] (:rating new-loser-rating)))))
{:elo-ratings []
:current-player-ratings {}})
:elo-ratings))
(defn persist-all
[db]
(let [elo-ratings (calculate-all db)]
(jdbc/insert-multi! db :elo elo-ratings)))
| |
d52d0e4467cfbbac883685b1c96143fd6cd55183cd686bd9ff6e7248c77538e4 | kototama/picobit | library-arduino.scm | ; File: "library.scm"
(define-macro (cond . a)
(if (null? a) '(if #f #f)
(cond ((eq? (caar a) 'else) `(begin . ,(cdar a)))
((and (not (null? (cdar a))) (eq? (cadar a) '=>))
(let ((x (gensym)))
`(let ((,x ,(caar a)))
(if ,x (,(caddar a) ,x) (cond . ,(cdr a))))))
(else `(if ,(caar a) (begin . ,(cdar a)) (cond . ,(cdr a)))))))
(define-macro (case a . cs)
(let ((x (gensym)))
`(let ((,x ,a))
(cond . ,(map (lambda (c)
(if (eq? (car c) 'else) c
`((memq ,x ',(car c)) . ,(cdr c))))
cs)))))
(define LOW 0)
(define HIGH 1)
(define number?
(lambda (x)
(#%number? x)))
(define +
(lambda (x . rest)
(if (#%pair? rest)
(#%+-aux x rest)
x)))
(define #%+-aux
(lambda (x rest)
(if (#%pair? rest)
(#%+-aux (#%+ x (#%car rest)) (#%cdr rest))
x)))
(define neg
(lambda (x)
(- 0 x)))
(define -
(lambda (x . rest)
(if (#%pair? rest)
(#%--aux x rest)
(neg x))))
(define #%--aux
(lambda (x rest)
(if (#%pair? rest)
(#%--aux (#%- x (#%car rest)) (#%cdr rest))
x)))
(define *
(lambda (x . rest)
(if (#%pair? rest)
(#%*-aux x rest)
x)))
(define #%*-aux
(lambda (x rest)
(if (#%pair? rest)
(#%*-aux (#%mul x (#%car rest)) (#%cdr rest))
x)))
(define #%mul
(lambda (x y)
(let* ((x-neg? (< x 0))
(y-neg? (< y 0))
(x (if x-neg? (neg x) x))
(y (if y-neg? (neg y) y)))
(let ((prod (#%mul-non-neg x y)))
(cond ((and x-neg? y-neg?)
prod)
((or x-neg? y-neg?)
(neg prod))
(else
prod))))))
(define / quotient)
TODO similar to # % mul , abstract ?
(lambda (x y)
(let* ((x-neg? (< x 0))
(y-neg? (< y 0))
(x (if x-neg? (neg x) x))
(y (if y-neg? (neg y) y)))
(let ((quot (#%quotient x y)))
(cond ((and x-neg? y-neg?)
quot)
((or x-neg? y-neg?)
(neg quot))
(else
quot))))))
(define remainder
(lambda (x y)
(#%remainder x y)))
(define =
(lambda (x y)
(#%= x y)))
(define <
(lambda (x y)
(#%< x y)))
(define <=
(lambda (x y)
(or (< x y) (= x y))))
(define >
(lambda (x y)
(#%> x y)))
(define >=
(lambda (x y)
(or (> x y) (= x y))))
(define pair?
(lambda (x)
(#%pair? x)))
(define cons
(lambda (x y)
(#%cons x y)))
(define car
(lambda (x)
(#%car x)))
(define cdr
(lambda (x)
(#%cdr x)))
(define set-car!
(lambda (x y)
(#%set-car! x y)))
(define set-cdr!
(lambda (x y)
(#%set-cdr! x y)))
(define null?
(lambda (x)
(#%null? x)))
(define eq?
(lambda (x y)
(#%eq? x y)))
(define not
(lambda (x)
(#%not x)))
(define list
(lambda lst lst))
(define length
(lambda (lst)
(#%length-aux lst 0)))
(define #%length-aux
(lambda (lst n)
(if (#%pair? lst)
(#%length-aux (cdr lst) (#%+ n 1))
n)))
(define append
(lambda (lst1 lst2)
(if (#%pair? lst1)
(#%cons (#%car lst1) (append (#%cdr lst1) lst2))
lst2)))
(define reverse
(lambda (lst)
(reverse-aux lst '())))
(define reverse-aux
(lambda (lst rev)
(if (#%pair? lst)
(reverse-aux (#%cdr lst) (#%cons (#%car lst) rev))
rev)))
(define list-ref
(lambda (lst i)
(if (#%= i 0)
(#%car lst)
(list-ref (#%cdr lst) (#%- i 1)))))
(define list-set!
(lambda (lst i x)
(if (#%= i 0)
(#%set-car! lst x)
(list-set! (#%cdr lst) (#%- i 1) x))))
(define max
(lambda (x y)
(if (#%> x y) x y)))
(define min
(lambda (x y)
(if (#%< x y) x y)))
(define abs
(lambda (x)
(if (#%< x 0) (neg x) x)))
(define modulo
(lambda (x y)
(#%remainder x y)))
(define #%box (lambda (a) (#%cons a '())))
(define #%unbox (lambda (a) (#%car a)))
(define #%box-set! (lambda (a b) (#%set-car! a b)))
(define symbol?
(lambda (x)
(#%symbol? x)))
(define string?
(lambda (x)
(#%string? x)))
(define string
(lambda chars
(#%list->string chars)))
(define string->list
(lambda (str)
(#%string->list str)))
(define list->string
(lambda (chars)
(#%list->string chars)))
(define string-length
(lambda (str)
(length (#%string->list str))))
(define string-append
(lambda (str1 str2)
(#%list->string (append (#%string->list str1) (#%string->list str2)))))
(define substring
(lambda (str start end)
(#%list->string
(#%substring-aux2
(#%substring-aux1 (#%string->list str) start)
(#%- end start)))))
(define #%substring-aux1
(lambda (lst n)
(if (>= n 1)
(#%substring-aux1 (#%cdr lst) (#%- n 1))
lst)))
(define #%substring-aux2
(lambda (lst n)
(if (>= n 1)
(#%cons (#%car lst) (#%substring-aux2 (#%cdr lst) (#%- n 1)))
'())))
(define boolean?
(lambda (x)
(#%boolean? x)))
(define map
(lambda (f lst)
(if (#%pair? lst)
(#%cons (f (#%car lst))
(map f (#%cdr lst)))
'())))
(define for-each
(lambda (f lst)
(if (#%pair? lst)
(begin
(f (#%car lst))
(for-each f (#%cdr lst)))
#f)))
(define call/cc
(lambda (receiver)
(let ((k (#%get-cont)))
(receiver
(lambda (r)
(#%return-to-cont k r))))))
(define root-k #f)
(define readyq #f)
(define start-first-process
(lambda (thunk)
(set! root-k (#%get-cont))
(set! readyq (#%cons #f #f))
(#%set-cdr! readyq readyq)
(thunk)))
(define spawn
(lambda (thunk)
(let* ((k (#%get-cont))
(next (#%cons k (#%cdr readyq))))
(#%set-cdr! readyq next)
(#%graft-to-cont root-k thunk))))
(define exit
(lambda ()
(let ((next (#%cdr readyq)))
(if (#%eq? next readyq)
(#%halt)
(begin
(#%set-cdr! readyq (#%cdr next))
(#%return-to-cont (#%car next) #f))))))
(define yield
(lambda ()
(let ((k (#%get-cont)))
(#%set-car! readyq k)
(set! readyq (#%cdr readyq))
(let ((next-k (#%car readyq)))
(#%set-car! readyq #f)
(#%return-to-cont next-k #f)))))
(define clock
(lambda ()
(#%clock)))
(define beep
(lambda (freq-div duration)
(#%beep freq-div duration)))
(define light
(lambda (sensor)
(#%adc sensor)))
(define adc
(lambda (sensor)
(#%adc sensor)))
(define sernum
(lambda ()
(#%sernum)))
(define putchar
(lambda (c)
(#%putchar c 3)))
(define getchar
(lambda ()
(or (#%getchar-wait 0 3)
(getchar))))
(define getchar-wait
(lambda (duration)
(#%getchar-wait duration 3)))
(define sleep
(lambda (duration)
(#%sleep-aux (#%+ (#%clock) duration))))
(define #%sleep-aux
(lambda (wake-up)
(if (#%< (#%clock) wake-up)
(#%sleep-aux wake-up)
#f)))
(define pin-mode
(lambda (pin mode)
(#%pin-mode pin mode)))
(define digital-write
(lambda (pin value)
(#%digital-write pin value)))
(define led2-color
(lambda (state)
(if (#%eq? state 'red)
(#%led2-color 1)
(#%led2-color 0))))
(define display
(lambda (x)
(if (#%string? x)
(for-each putchar (#%string->list x))
(write x))))
(define write
(lambda (x)
(cond ((#%string? x)
(begin (#%putchar #\" 3)
(display x)
(#%putchar #\" 3)))
((#%number? x)
(display (number->string x)))
((#%pair? x)
(begin (#%putchar #\( 3)
(write (#%car x))
(#%write-list (#%cdr x))))
((#%symbol? x)
(display "#<symbol>"))
((#%boolean? x)
(display (if x "#t" "#f")))
(else
(display "#<object>")))))
TODO have vectors and co ?
(define #%write-list
(lambda (lst)
(cond ((#%null? lst)
(#%putchar #\) 3))
((#%pair? lst)
(begin (#%putchar #\space 3)
(write (#%car lst))
(#%write-list (#%cdr lst))))
(else
(begin (display " . ")
(write lst)
(#%putchar #\) 3))))))
(define number->string
(lambda (n)
(#%list->string
(if (#%< n 0)
(#%cons #\- (#%number->string-aux (neg n) '()))
(#%number->string-aux n '())))))
(define #%number->string-aux
(lambda (n lst)
(let ((rest (#%cons (#%+ #\0 (remainder n 10)) lst)))
(if (#%< n 10)
rest
(#%number->string-aux (quotient n 10) rest)))))
(define pp
(lambda (x)
(write x)
(#%putchar #\newline 3)))
(define caar
(lambda (p)
(#%car (#%car p))))
(define cadr
(lambda (p)
(#%car (#%cdr p))))
(define cdar
(lambda (p)
(#%cdr (#%car p))))
(define cddr
(lambda (p)
(#%cdr (#%cdr p))))
(define caaar
(lambda (p)
(#%car (#%car (#%car p)))))
(define caadr
(lambda (p)
(#%car (#%car (#%cdr p)))))
(define cadar
(lambda (p)
(#%car (#%cdr (#%car p)))))
(define caddr
(lambda (p)
(#%car (#%cdr (#%cdr p)))))
(define cdaar
(lambda (p)
(#%cdr (#%car (#%car p)))))
(define cdadr
(lambda (p)
(#%cdr (#%car (#%cdr p)))))
(define cddar
(lambda (p)
(#%cdr (#%cdr (#%car p)))))
(define cdddr
(lambda (p)
(#%cdr (#%cdr (#%cdr p)))))
(define equal?
(lambda (x y)
(cond ((#%eq? x y)
#t)
((and (#%pair? x) (#%pair? y))
(and (equal? (#%car x) (#%car y))
(equal? (#%cdr x) (#%cdr y))))
((and (#%u8vector? x) (#%u8vector? y))
(u8vector-equal? x y))
(else
#f))))
(define u8vector-equal?
(lambda (x y)
(let ((lx (#%u8vector-length x)))
(if (#%= lx (#%u8vector-length y))
(u8vector-equal?-loop x y (- lx 1))
#f))))
(define u8vector-equal?-loop
(lambda (x y l)
(if (#%= l 0)
#t
(and (#%= (#%u8vector-ref x l) (#%u8vector-ref y l))
(u8vector-equal?-loop x y (#%- l 1))))))
(define assoc
(lambda (t l)
(cond ((#%null? l)
#f)
((equal? t (caar l))
(#%car l))
(else
(assoc t (#%cdr l))))))
(define memq
(lambda (t l)
(cond ((#%null? l)
#f)
((#%eq? (#%car l) t)
l)
(else
(memq t (#%cdr l))))))
(define vector list)
(define vector-ref list-ref)
(define vector-set! list-set!)
(define bitwise-ior (lambda (x y) (#%ior x y)))
(define bitwise-xor (lambda (x y) (#%xor x y)))
TODO add bitwise - and ? bitwise - not ?
(define current-time (lambda () (#%clock)))
(define time->seconds (lambda (t) (quotient t 100)))
(define u8vector
(lambda x
(list->u8vector x)))
(define list->u8vector
(lambda (x)
(let* ((n (length x))
(v (#%make-u8vector n)))
(list->u8vector-loop v 0 x)
v)))
(define list->u8vector-loop
(lambda (v n x)
(#%u8vector-set! v n (#%car x))
(if (#%not (#%null? (#%cdr x)))
(list->u8vector-loop v (#%+ n 1) (#%cdr x)))))
(define u8vector-length (lambda (x) (#%u8vector-length x)))
(define u8vector-ref (lambda (x y) (#%u8vector-ref x y)))
(define u8vector-set! (lambda (x y z) (#%u8vector-set! x y z)))
(define make-u8vector
(lambda (n x)
(make-u8vector-loop (#%make-u8vector n) (- n 1) x)))
(define make-u8vector-loop
(lambda (v n x)
(if (>= n 0)
(begin (u8vector-set! v n x)
(make-u8vector-loop v (- n 1) x))
v)))
(define u8vector-copy!
(lambda (source source-start target target-start n)
(if (> n 0)
(begin (u8vector-set! target target-start
(u8vector-ref source source-start))
(u8vector-copy! source (+ source-start 1)
target (+ target-start 1)
(- n 1))))))
(define network-init (lambda () (#%network-init)))
(define network-cleanup (lambda () (#%network-cleanup)))
(define receive-packet-to-u8vector
(lambda (x)
(#%receive-packet-to-u8vector x)))
(define send-packet-from-u8vector
(lambda (x y)
(#%send-packet-from-u8vector x y)))
| null | https://raw.githubusercontent.com/kototama/picobit/8bdfc092266803bc6b1151177a7e668c9b050bea/library-arduino.scm | scheme | File: "library.scm" |
(define-macro (cond . a)
(if (null? a) '(if #f #f)
(cond ((eq? (caar a) 'else) `(begin . ,(cdar a)))
((and (not (null? (cdar a))) (eq? (cadar a) '=>))
(let ((x (gensym)))
`(let ((,x ,(caar a)))
(if ,x (,(caddar a) ,x) (cond . ,(cdr a))))))
(else `(if ,(caar a) (begin . ,(cdar a)) (cond . ,(cdr a)))))))
(define-macro (case a . cs)
(let ((x (gensym)))
`(let ((,x ,a))
(cond . ,(map (lambda (c)
(if (eq? (car c) 'else) c
`((memq ,x ',(car c)) . ,(cdr c))))
cs)))))
(define LOW 0)
(define HIGH 1)
(define number?
(lambda (x)
(#%number? x)))
(define +
(lambda (x . rest)
(if (#%pair? rest)
(#%+-aux x rest)
x)))
(define #%+-aux
(lambda (x rest)
(if (#%pair? rest)
(#%+-aux (#%+ x (#%car rest)) (#%cdr rest))
x)))
(define neg
(lambda (x)
(- 0 x)))
(define -
(lambda (x . rest)
(if (#%pair? rest)
(#%--aux x rest)
(neg x))))
(define #%--aux
(lambda (x rest)
(if (#%pair? rest)
(#%--aux (#%- x (#%car rest)) (#%cdr rest))
x)))
(define *
(lambda (x . rest)
(if (#%pair? rest)
(#%*-aux x rest)
x)))
(define #%*-aux
(lambda (x rest)
(if (#%pair? rest)
(#%*-aux (#%mul x (#%car rest)) (#%cdr rest))
x)))
(define #%mul
(lambda (x y)
(let* ((x-neg? (< x 0))
(y-neg? (< y 0))
(x (if x-neg? (neg x) x))
(y (if y-neg? (neg y) y)))
(let ((prod (#%mul-non-neg x y)))
(cond ((and x-neg? y-neg?)
prod)
((or x-neg? y-neg?)
(neg prod))
(else
prod))))))
(define / quotient)
TODO similar to # % mul , abstract ?
(lambda (x y)
(let* ((x-neg? (< x 0))
(y-neg? (< y 0))
(x (if x-neg? (neg x) x))
(y (if y-neg? (neg y) y)))
(let ((quot (#%quotient x y)))
(cond ((and x-neg? y-neg?)
quot)
((or x-neg? y-neg?)
(neg quot))
(else
quot))))))
(define remainder
(lambda (x y)
(#%remainder x y)))
(define =
(lambda (x y)
(#%= x y)))
(define <
(lambda (x y)
(#%< x y)))
(define <=
(lambda (x y)
(or (< x y) (= x y))))
(define >
(lambda (x y)
(#%> x y)))
(define >=
(lambda (x y)
(or (> x y) (= x y))))
(define pair?
(lambda (x)
(#%pair? x)))
(define cons
(lambda (x y)
(#%cons x y)))
(define car
(lambda (x)
(#%car x)))
(define cdr
(lambda (x)
(#%cdr x)))
(define set-car!
(lambda (x y)
(#%set-car! x y)))
(define set-cdr!
(lambda (x y)
(#%set-cdr! x y)))
(define null?
(lambda (x)
(#%null? x)))
(define eq?
(lambda (x y)
(#%eq? x y)))
(define not
(lambda (x)
(#%not x)))
(define list
(lambda lst lst))
(define length
(lambda (lst)
(#%length-aux lst 0)))
(define #%length-aux
(lambda (lst n)
(if (#%pair? lst)
(#%length-aux (cdr lst) (#%+ n 1))
n)))
(define append
(lambda (lst1 lst2)
(if (#%pair? lst1)
(#%cons (#%car lst1) (append (#%cdr lst1) lst2))
lst2)))
(define reverse
(lambda (lst)
(reverse-aux lst '())))
(define reverse-aux
(lambda (lst rev)
(if (#%pair? lst)
(reverse-aux (#%cdr lst) (#%cons (#%car lst) rev))
rev)))
(define list-ref
(lambda (lst i)
(if (#%= i 0)
(#%car lst)
(list-ref (#%cdr lst) (#%- i 1)))))
(define list-set!
(lambda (lst i x)
(if (#%= i 0)
(#%set-car! lst x)
(list-set! (#%cdr lst) (#%- i 1) x))))
(define max
(lambda (x y)
(if (#%> x y) x y)))
(define min
(lambda (x y)
(if (#%< x y) x y)))
(define abs
(lambda (x)
(if (#%< x 0) (neg x) x)))
(define modulo
(lambda (x y)
(#%remainder x y)))
(define #%box (lambda (a) (#%cons a '())))
(define #%unbox (lambda (a) (#%car a)))
(define #%box-set! (lambda (a b) (#%set-car! a b)))
(define symbol?
(lambda (x)
(#%symbol? x)))
(define string?
(lambda (x)
(#%string? x)))
(define string
(lambda chars
(#%list->string chars)))
(define string->list
(lambda (str)
(#%string->list str)))
(define list->string
(lambda (chars)
(#%list->string chars)))
(define string-length
(lambda (str)
(length (#%string->list str))))
(define string-append
(lambda (str1 str2)
(#%list->string (append (#%string->list str1) (#%string->list str2)))))
(define substring
(lambda (str start end)
(#%list->string
(#%substring-aux2
(#%substring-aux1 (#%string->list str) start)
(#%- end start)))))
(define #%substring-aux1
(lambda (lst n)
(if (>= n 1)
(#%substring-aux1 (#%cdr lst) (#%- n 1))
lst)))
(define #%substring-aux2
(lambda (lst n)
(if (>= n 1)
(#%cons (#%car lst) (#%substring-aux2 (#%cdr lst) (#%- n 1)))
'())))
(define boolean?
(lambda (x)
(#%boolean? x)))
(define map
(lambda (f lst)
(if (#%pair? lst)
(#%cons (f (#%car lst))
(map f (#%cdr lst)))
'())))
(define for-each
(lambda (f lst)
(if (#%pair? lst)
(begin
(f (#%car lst))
(for-each f (#%cdr lst)))
#f)))
(define call/cc
(lambda (receiver)
(let ((k (#%get-cont)))
(receiver
(lambda (r)
(#%return-to-cont k r))))))
(define root-k #f)
(define readyq #f)
(define start-first-process
(lambda (thunk)
(set! root-k (#%get-cont))
(set! readyq (#%cons #f #f))
(#%set-cdr! readyq readyq)
(thunk)))
(define spawn
(lambda (thunk)
(let* ((k (#%get-cont))
(next (#%cons k (#%cdr readyq))))
(#%set-cdr! readyq next)
(#%graft-to-cont root-k thunk))))
(define exit
(lambda ()
(let ((next (#%cdr readyq)))
(if (#%eq? next readyq)
(#%halt)
(begin
(#%set-cdr! readyq (#%cdr next))
(#%return-to-cont (#%car next) #f))))))
(define yield
(lambda ()
(let ((k (#%get-cont)))
(#%set-car! readyq k)
(set! readyq (#%cdr readyq))
(let ((next-k (#%car readyq)))
(#%set-car! readyq #f)
(#%return-to-cont next-k #f)))))
(define clock
(lambda ()
(#%clock)))
(define beep
(lambda (freq-div duration)
(#%beep freq-div duration)))
(define light
(lambda (sensor)
(#%adc sensor)))
(define adc
(lambda (sensor)
(#%adc sensor)))
(define sernum
(lambda ()
(#%sernum)))
(define putchar
(lambda (c)
(#%putchar c 3)))
(define getchar
(lambda ()
(or (#%getchar-wait 0 3)
(getchar))))
(define getchar-wait
(lambda (duration)
(#%getchar-wait duration 3)))
(define sleep
(lambda (duration)
(#%sleep-aux (#%+ (#%clock) duration))))
(define #%sleep-aux
(lambda (wake-up)
(if (#%< (#%clock) wake-up)
(#%sleep-aux wake-up)
#f)))
(define pin-mode
(lambda (pin mode)
(#%pin-mode pin mode)))
(define digital-write
(lambda (pin value)
(#%digital-write pin value)))
(define led2-color
(lambda (state)
(if (#%eq? state 'red)
(#%led2-color 1)
(#%led2-color 0))))
(define display
(lambda (x)
(if (#%string? x)
(for-each putchar (#%string->list x))
(write x))))
(define write
(lambda (x)
(cond ((#%string? x)
(begin (#%putchar #\" 3)
(display x)
(#%putchar #\" 3)))
((#%number? x)
(display (number->string x)))
((#%pair? x)
(begin (#%putchar #\( 3)
(write (#%car x))
(#%write-list (#%cdr x))))
((#%symbol? x)
(display "#<symbol>"))
((#%boolean? x)
(display (if x "#t" "#f")))
(else
(display "#<object>")))))
TODO have vectors and co ?
(define #%write-list
(lambda (lst)
(cond ((#%null? lst)
(#%putchar #\) 3))
((#%pair? lst)
(begin (#%putchar #\space 3)
(write (#%car lst))
(#%write-list (#%cdr lst))))
(else
(begin (display " . ")
(write lst)
(#%putchar #\) 3))))))
(define number->string
(lambda (n)
(#%list->string
(if (#%< n 0)
(#%cons #\- (#%number->string-aux (neg n) '()))
(#%number->string-aux n '())))))
(define #%number->string-aux
(lambda (n lst)
(let ((rest (#%cons (#%+ #\0 (remainder n 10)) lst)))
(if (#%< n 10)
rest
(#%number->string-aux (quotient n 10) rest)))))
(define pp
(lambda (x)
(write x)
(#%putchar #\newline 3)))
(define caar
(lambda (p)
(#%car (#%car p))))
(define cadr
(lambda (p)
(#%car (#%cdr p))))
(define cdar
(lambda (p)
(#%cdr (#%car p))))
(define cddr
(lambda (p)
(#%cdr (#%cdr p))))
(define caaar
(lambda (p)
(#%car (#%car (#%car p)))))
(define caadr
(lambda (p)
(#%car (#%car (#%cdr p)))))
(define cadar
(lambda (p)
(#%car (#%cdr (#%car p)))))
(define caddr
(lambda (p)
(#%car (#%cdr (#%cdr p)))))
(define cdaar
(lambda (p)
(#%cdr (#%car (#%car p)))))
(define cdadr
(lambda (p)
(#%cdr (#%car (#%cdr p)))))
(define cddar
(lambda (p)
(#%cdr (#%cdr (#%car p)))))
(define cdddr
(lambda (p)
(#%cdr (#%cdr (#%cdr p)))))
(define equal?
(lambda (x y)
(cond ((#%eq? x y)
#t)
((and (#%pair? x) (#%pair? y))
(and (equal? (#%car x) (#%car y))
(equal? (#%cdr x) (#%cdr y))))
((and (#%u8vector? x) (#%u8vector? y))
(u8vector-equal? x y))
(else
#f))))
(define u8vector-equal?
(lambda (x y)
(let ((lx (#%u8vector-length x)))
(if (#%= lx (#%u8vector-length y))
(u8vector-equal?-loop x y (- lx 1))
#f))))
(define u8vector-equal?-loop
(lambda (x y l)
(if (#%= l 0)
#t
(and (#%= (#%u8vector-ref x l) (#%u8vector-ref y l))
(u8vector-equal?-loop x y (#%- l 1))))))
(define assoc
(lambda (t l)
(cond ((#%null? l)
#f)
((equal? t (caar l))
(#%car l))
(else
(assoc t (#%cdr l))))))
(define memq
(lambda (t l)
(cond ((#%null? l)
#f)
((#%eq? (#%car l) t)
l)
(else
(memq t (#%cdr l))))))
(define vector list)
(define vector-ref list-ref)
(define vector-set! list-set!)
(define bitwise-ior (lambda (x y) (#%ior x y)))
(define bitwise-xor (lambda (x y) (#%xor x y)))
TODO add bitwise - and ? bitwise - not ?
(define current-time (lambda () (#%clock)))
(define time->seconds (lambda (t) (quotient t 100)))
(define u8vector
(lambda x
(list->u8vector x)))
(define list->u8vector
(lambda (x)
(let* ((n (length x))
(v (#%make-u8vector n)))
(list->u8vector-loop v 0 x)
v)))
(define list->u8vector-loop
(lambda (v n x)
(#%u8vector-set! v n (#%car x))
(if (#%not (#%null? (#%cdr x)))
(list->u8vector-loop v (#%+ n 1) (#%cdr x)))))
(define u8vector-length (lambda (x) (#%u8vector-length x)))
(define u8vector-ref (lambda (x y) (#%u8vector-ref x y)))
(define u8vector-set! (lambda (x y z) (#%u8vector-set! x y z)))
(define make-u8vector
(lambda (n x)
(make-u8vector-loop (#%make-u8vector n) (- n 1) x)))
(define make-u8vector-loop
(lambda (v n x)
(if (>= n 0)
(begin (u8vector-set! v n x)
(make-u8vector-loop v (- n 1) x))
v)))
(define u8vector-copy!
(lambda (source source-start target target-start n)
(if (> n 0)
(begin (u8vector-set! target target-start
(u8vector-ref source source-start))
(u8vector-copy! source (+ source-start 1)
target (+ target-start 1)
(- n 1))))))
(define network-init (lambda () (#%network-init)))
(define network-cleanup (lambda () (#%network-cleanup)))
(define receive-packet-to-u8vector
(lambda (x)
(#%receive-packet-to-u8vector x)))
(define send-packet-from-u8vector
(lambda (x y)
(#%send-packet-from-u8vector x y)))
|
1c1f17a8308378f9ea287dd20183dc2b1f7de1fcc41c6b04cd02b274843d4e04 | tek/polysemy-hasql | PrimDecoder.hs | module Polysemy.Hasql.Table.PrimDecoder where
import qualified Chronos as Chronos
import Data.Scientific (Scientific)
import Data.Time (
Day,
DiffTime,
LocalTime (LocalTime),
TimeOfDay (TimeOfDay),
TimeZone,
UTCTime,
toModifiedJulianDay,
)
import Data.UUID (UUID)
import Hasql.Decoders (
Value,
bool,
bytea,
char,
custom,
date,
float4,
float8,
int2,
int4,
int8,
interval,
numeric,
text,
time,
timestamp,
timestamptz,
timetz,
uuid,
)
import Path (Abs, Dir, File, Path, Rel, parseAbsDir, parseAbsFile, parseRelDir, parseRelFile)
import Prelude hiding (Enum, bool)
class PrimDecoder a where
primDecoder :: Value a
instance PrimDecoder Bool where
primDecoder =
bool
instance PrimDecoder Int16 where
primDecoder =
int2
instance PrimDecoder Int32 where
primDecoder =
int4
instance PrimDecoder Int64 where
primDecoder =
int8
instance PrimDecoder Int where
primDecoder =
fromIntegral <$> int8
instance PrimDecoder Float where
primDecoder =
float4
instance PrimDecoder Double where
primDecoder =
float8
instance PrimDecoder Scientific where
primDecoder =
numeric
instance PrimDecoder Char where
primDecoder =
char
instance PrimDecoder Text where
primDecoder =
text
instance PrimDecoder ByteString where
primDecoder =
bytea
instance PrimDecoder Day where
primDecoder =
date
instance PrimDecoder LocalTime where
primDecoder =
timestamp
instance PrimDecoder UTCTime where
primDecoder =
timestamptz
instance PrimDecoder TimeOfDay where
primDecoder =
time
instance PrimDecoder (TimeOfDay, TimeZone) where
primDecoder =
timetz
instance PrimDecoder DiffTime where
primDecoder =
interval
instance PrimDecoder UUID where
primDecoder =
uuid
decodePath ::
Show e =>
(String -> Either e (Path b t)) ->
Bool ->
ByteString ->
Either Text (Path b t)
decodePath parse _ =
first show . parse . decodeUtf8
instance PrimDecoder (Path Abs File) where
primDecoder =
custom (decodePath parseAbsFile)
instance PrimDecoder (Path Abs Dir) where
primDecoder =
custom (decodePath parseAbsDir)
instance PrimDecoder (Path Rel File) where
primDecoder =
custom (decodePath parseRelFile)
instance PrimDecoder (Path Rel Dir) where
primDecoder =
custom (decodePath parseRelDir)
dayToChronos :: Day -> Chronos.Date
dayToChronos =
Chronos.dayToDate . Chronos.Day . fromIntegral . toModifiedJulianDay
instance PrimDecoder Chronos.Date where
primDecoder =
dayToChronos <$> date
instance PrimDecoder Chronos.Time where
primDecoder =
Chronos.Time <$> int8
chronosToTimeOfDay :: TimeOfDay -> Chronos.TimeOfDay
chronosToTimeOfDay (TimeOfDay h m ns) =
Chronos.TimeOfDay h m (round (ns * 1000000000))
localTimeToDatetime :: LocalTime -> Chronos.Datetime
localTimeToDatetime (LocalTime d t) =
Chronos.Datetime (dayToChronos d) (chronosToTimeOfDay t)
instance PrimDecoder Chronos.Datetime where
primDecoder =
localTimeToDatetime <$> primDecoder
| null | https://raw.githubusercontent.com/tek/polysemy-hasql/443ccf348bb8af0ec0543981d58af8aa26fc4c10/packages/hasql/lib/Polysemy/Hasql/Table/PrimDecoder.hs | haskell | module Polysemy.Hasql.Table.PrimDecoder where
import qualified Chronos as Chronos
import Data.Scientific (Scientific)
import Data.Time (
Day,
DiffTime,
LocalTime (LocalTime),
TimeOfDay (TimeOfDay),
TimeZone,
UTCTime,
toModifiedJulianDay,
)
import Data.UUID (UUID)
import Hasql.Decoders (
Value,
bool,
bytea,
char,
custom,
date,
float4,
float8,
int2,
int4,
int8,
interval,
numeric,
text,
time,
timestamp,
timestamptz,
timetz,
uuid,
)
import Path (Abs, Dir, File, Path, Rel, parseAbsDir, parseAbsFile, parseRelDir, parseRelFile)
import Prelude hiding (Enum, bool)
class PrimDecoder a where
primDecoder :: Value a
instance PrimDecoder Bool where
primDecoder =
bool
instance PrimDecoder Int16 where
primDecoder =
int2
instance PrimDecoder Int32 where
primDecoder =
int4
instance PrimDecoder Int64 where
primDecoder =
int8
instance PrimDecoder Int where
primDecoder =
fromIntegral <$> int8
instance PrimDecoder Float where
primDecoder =
float4
instance PrimDecoder Double where
primDecoder =
float8
instance PrimDecoder Scientific where
primDecoder =
numeric
instance PrimDecoder Char where
primDecoder =
char
instance PrimDecoder Text where
primDecoder =
text
instance PrimDecoder ByteString where
primDecoder =
bytea
instance PrimDecoder Day where
primDecoder =
date
instance PrimDecoder LocalTime where
primDecoder =
timestamp
instance PrimDecoder UTCTime where
primDecoder =
timestamptz
instance PrimDecoder TimeOfDay where
primDecoder =
time
instance PrimDecoder (TimeOfDay, TimeZone) where
primDecoder =
timetz
instance PrimDecoder DiffTime where
primDecoder =
interval
instance PrimDecoder UUID where
primDecoder =
uuid
decodePath ::
Show e =>
(String -> Either e (Path b t)) ->
Bool ->
ByteString ->
Either Text (Path b t)
decodePath parse _ =
first show . parse . decodeUtf8
instance PrimDecoder (Path Abs File) where
primDecoder =
custom (decodePath parseAbsFile)
instance PrimDecoder (Path Abs Dir) where
primDecoder =
custom (decodePath parseAbsDir)
instance PrimDecoder (Path Rel File) where
primDecoder =
custom (decodePath parseRelFile)
instance PrimDecoder (Path Rel Dir) where
primDecoder =
custom (decodePath parseRelDir)
dayToChronos :: Day -> Chronos.Date
dayToChronos =
Chronos.dayToDate . Chronos.Day . fromIntegral . toModifiedJulianDay
instance PrimDecoder Chronos.Date where
primDecoder =
dayToChronos <$> date
instance PrimDecoder Chronos.Time where
primDecoder =
Chronos.Time <$> int8
chronosToTimeOfDay :: TimeOfDay -> Chronos.TimeOfDay
chronosToTimeOfDay (TimeOfDay h m ns) =
Chronos.TimeOfDay h m (round (ns * 1000000000))
localTimeToDatetime :: LocalTime -> Chronos.Datetime
localTimeToDatetime (LocalTime d t) =
Chronos.Datetime (dayToChronos d) (chronosToTimeOfDay t)
instance PrimDecoder Chronos.Datetime where
primDecoder =
localTimeToDatetime <$> primDecoder
| |
8d5da87f59638b728d46aa5625a0621df5123605ab294703f887cf4d08fa94bb | xapi-project/xen-api | xenops_client.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
open Xenops_interface
open Xcp_client
module Client = Xenops_interface.XenopsAPI (Idl.Exn.GenClient (struct
let rpc call =
if !use_switch then
json_switch_rpc !queue_name call
else
xml_http_rpc ~srcstr:"xapi" ~dststr:"xenops" default_uri call
end))
let query dbg url =
let module Remote = Xenops_interface.XenopsAPI (Idl.Exn.GenClient (struct
let rpc = xml_http_rpc ~srcstr:"xenops" ~dststr:"dst_xenops" (fun () -> url)
end)) in
Remote.query dbg ()
let event_wait dbg ?from p =
let finished = ref false in
let event_id = ref from in
while not !finished do
let _, deltas, next_id = Client.UPDATES.get dbg !event_id (Some 30) in
event_id := Some next_id ;
List.iter (fun d -> if p d then finished := true) deltas
done
let task_ended dbg id =
match (Client.TASK.stat dbg id).Task.state with
| Task.Completed _ | Task.Failed _ ->
true
| Task.Pending _ ->
false
let success_task dbg id =
let t = Client.TASK.stat dbg id in
Client.TASK.destroy dbg id ;
match t.Task.state with
| Task.Completed _ ->
t
| Task.Failed x -> (
match Rpcmarshal.unmarshal Errors.error.Rpc.Types.ty x with
| Ok x ->
raise (Xenops_interface.Xenopsd_error x)
| Error _ ->
raise
(Xenops_interface.Xenopsd_error
(Errors.Internal_error (Jsonrpc.to_string x))
)
)
| Task.Pending _ ->
failwith "task pending"
let wait_for_task dbg id =
let finished = function
| Dynamic.Task id' ->
id = id' && task_ended dbg id
| _ ->
false
in
let from = Client.UPDATES.last_id dbg in
if not (task_ended dbg id) then event_wait dbg ~from finished ;
id
let ignore_task (_ : Task.t) = ()
| null | https://raw.githubusercontent.com/xapi-project/xen-api/1e1165f330c30ee6cb8e8f325af9fdd07474ca24/ocaml/xapi-idl/xen/xenops_client.ml | ocaml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* 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 .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* 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.
*)
open Xenops_interface
open Xcp_client
module Client = Xenops_interface.XenopsAPI (Idl.Exn.GenClient (struct
let rpc call =
if !use_switch then
json_switch_rpc !queue_name call
else
xml_http_rpc ~srcstr:"xapi" ~dststr:"xenops" default_uri call
end))
let query dbg url =
let module Remote = Xenops_interface.XenopsAPI (Idl.Exn.GenClient (struct
let rpc = xml_http_rpc ~srcstr:"xenops" ~dststr:"dst_xenops" (fun () -> url)
end)) in
Remote.query dbg ()
let event_wait dbg ?from p =
let finished = ref false in
let event_id = ref from in
while not !finished do
let _, deltas, next_id = Client.UPDATES.get dbg !event_id (Some 30) in
event_id := Some next_id ;
List.iter (fun d -> if p d then finished := true) deltas
done
let task_ended dbg id =
match (Client.TASK.stat dbg id).Task.state with
| Task.Completed _ | Task.Failed _ ->
true
| Task.Pending _ ->
false
let success_task dbg id =
let t = Client.TASK.stat dbg id in
Client.TASK.destroy dbg id ;
match t.Task.state with
| Task.Completed _ ->
t
| Task.Failed x -> (
match Rpcmarshal.unmarshal Errors.error.Rpc.Types.ty x with
| Ok x ->
raise (Xenops_interface.Xenopsd_error x)
| Error _ ->
raise
(Xenops_interface.Xenopsd_error
(Errors.Internal_error (Jsonrpc.to_string x))
)
)
| Task.Pending _ ->
failwith "task pending"
let wait_for_task dbg id =
let finished = function
| Dynamic.Task id' ->
id = id' && task_ended dbg id
| _ ->
false
in
let from = Client.UPDATES.last_id dbg in
if not (task_ended dbg id) then event_wait dbg ~from finished ;
id
let ignore_task (_ : Task.t) = ()
| |
f9bac29557713bd85bb8e324b99d08d60f4852d2de86be98a94f932a83aa01ff | c-cube/ocaml-containers | CCCache.mli | (* This file is free software, part of containers. See file "license" for more details. *)
* Caches Utils
Particularly useful for memoization . See { ! with_cache } and { ! with_cache_rec }
for more details .
@since 0.6
Particularly useful for memoization. See {!with_cache} and {!with_cache_rec}
for more details.
@since 0.6 *)
type 'a equal = 'a -> 'a -> bool
type 'a hash = 'a -> int
* { 2 Value interface }
Typical use case : one wants to memoize a function [ f : ' a - > ' b ] . Code sample :
{ [
let f x =
print_endline " call f " ;
x + 1 ; ;
let f ' = with_cache ( lru 256 ) f ; ;
f ' 0 ; ; ( * prints
Typical use case: one wants to memoize a function [f : 'a -> 'b]. Code sample:
{[
let f x =
print_endline "call f";
x + 1;;
let f' = with_cache (lru 256) f;;
f' 0;; (* prints *)
f' 1;; (* prints *)
f' 0;; (* doesn't print, returns cached value *)
]}
@since 0.6 *)
type ('a, 'b) t
val clear : (_, _) t -> unit
(** Clear the content of the cache. *)
type ('a, 'b) callback = in_cache:bool -> 'a -> 'b -> unit
* Type of the callback that is called once a cached value is found
or not .
Should never raise .
@param in_cache is [ true ] if the value was in cache , [ false ]
if the value was just produced .
@since 1.3
or not.
Should never raise.
@param in_cache is [true] if the value was in cache, [false]
if the value was just produced.
@since 1.3 *)
val with_cache : ?cb:('a, 'b) callback -> ('a, 'b) t -> ('a -> 'b) -> 'a -> 'b
(** [with_cache c f] behaves like [f], but caches calls to [f] in the
cache [c]. It always returns the same value as
[f x], if [f x] returns, or raise the same exception.
However, [f] may not be called if [x] is in the cache.
@param cb called after the value is generated or retrieved. *)
val with_cache_rec :
?cb:('a, 'b) callback -> ('a, 'b) t -> (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
* [ with_cache_rec c f ] is a function that first , applies [ f ] to
some [ f ' = fix f ] , such that recursive calls to [ f ' ] are cached in [ c ] .
It is similar to { ! with_cache } but with a function that takes as
first argument its own recursive version .
Example ( memoized Fibonacci function ):
{ [
let fib = with_cache_rec ( lru 256 )
( fun fib ' n - > match n with
| 1 | 2 - > 1
| _ - > fib ' ( n-1 ) + fib ' ( n-2 )
) ; ;
fib 70 ; ;
] }
@param cb called after the value is generated or retrieved .
some [f' = fix f], such that recursive calls to [f'] are cached in [c].
It is similar to {!with_cache} but with a function that takes as
first argument its own recursive version.
Example (memoized Fibonacci function):
{[
let fib = with_cache_rec (lru 256)
(fun fib' n -> match n with
| 1 | 2 -> 1
| _ -> fib' (n-1) + fib' (n-2)
);;
fib 70;;
]}
@param cb called after the value is generated or retrieved.
*)
val size : (_, _) t -> int
(** Size of the cache (number of entries). At most linear in the number
of entries. *)
val iter : ('a, 'b) t -> ('a -> 'b -> unit) -> unit
(** Iterate on cached values. Should yield [size cache] pairs. *)
val add : ('a, 'b) t -> 'a -> 'b -> bool
* Manually add a cached value . Return [ true ] if the value has successfully
been added , and [ false ] if the value was already bound .
@since 1.5
been added, and [false] if the value was already bound.
@since 1.5 *)
val dummy : ('a, 'b) t
(** Dummy cache, never stores any value. *)
val linear : eq:'a equal -> int -> ('a, 'b) t
(** Linear cache with the given size. It stores key/value pairs in
an array and does linear search at every call, so it should only be used
with small size.
@param eq optional equality predicate for keys. *)
val replacing : eq:'a equal -> ?hash:'a hash -> int -> ('a, 'b) t
(** Replacing cache of the given size. Equality and hash functions can be
parametrized. It's a hash table that handles collisions by replacing
the old value with the new (so a cache entry is evicted when another
entry with the same hash (modulo size) is added).
Never grows wider than the given size. *)
val lru : eq:'a equal -> ?hash:'a hash -> int -> ('a, 'b) t
* LRU cache of the given size ( " Least Recently Used " : keys that have not been
used recently are deleted first ) . Never grows wider than the given size .
used recently are deleted first). Never grows wider than the given size. *)
val unbounded : eq:'a equal -> ?hash:'a hash -> int -> ('a, 'b) t
(** Unbounded cache, backed by a Hash table. Will grow forever
unless {!clear} is called manually. *)
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/src/data/CCCache.mli | ocaml | This file is free software, part of containers. See file "license" for more details.
prints
prints
doesn't print, returns cached value
* Clear the content of the cache.
* [with_cache c f] behaves like [f], but caches calls to [f] in the
cache [c]. It always returns the same value as
[f x], if [f x] returns, or raise the same exception.
However, [f] may not be called if [x] is in the cache.
@param cb called after the value is generated or retrieved.
* Size of the cache (number of entries). At most linear in the number
of entries.
* Iterate on cached values. Should yield [size cache] pairs.
* Dummy cache, never stores any value.
* Linear cache with the given size. It stores key/value pairs in
an array and does linear search at every call, so it should only be used
with small size.
@param eq optional equality predicate for keys.
* Replacing cache of the given size. Equality and hash functions can be
parametrized. It's a hash table that handles collisions by replacing
the old value with the new (so a cache entry is evicted when another
entry with the same hash (modulo size) is added).
Never grows wider than the given size.
* Unbounded cache, backed by a Hash table. Will grow forever
unless {!clear} is called manually. |
* Caches Utils
Particularly useful for memoization . See { ! with_cache } and { ! with_cache_rec }
for more details .
@since 0.6
Particularly useful for memoization. See {!with_cache} and {!with_cache_rec}
for more details.
@since 0.6 *)
type 'a equal = 'a -> 'a -> bool
type 'a hash = 'a -> int
* { 2 Value interface }
Typical use case : one wants to memoize a function [ f : ' a - > ' b ] . Code sample :
{ [
let f x =
print_endline " call f " ;
x + 1 ; ;
let f ' = with_cache ( lru 256 ) f ; ;
f ' 0 ; ; ( * prints
Typical use case: one wants to memoize a function [f : 'a -> 'b]. Code sample:
{[
let f x =
print_endline "call f";
x + 1;;
let f' = with_cache (lru 256) f;;
]}
@since 0.6 *)
type ('a, 'b) t
val clear : (_, _) t -> unit
type ('a, 'b) callback = in_cache:bool -> 'a -> 'b -> unit
* Type of the callback that is called once a cached value is found
or not .
Should never raise .
@param in_cache is [ true ] if the value was in cache , [ false ]
if the value was just produced .
@since 1.3
or not.
Should never raise.
@param in_cache is [true] if the value was in cache, [false]
if the value was just produced.
@since 1.3 *)
val with_cache : ?cb:('a, 'b) callback -> ('a, 'b) t -> ('a -> 'b) -> 'a -> 'b
val with_cache_rec :
?cb:('a, 'b) callback -> ('a, 'b) t -> (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
* [ with_cache_rec c f ] is a function that first , applies [ f ] to
some [ f ' = fix f ] , such that recursive calls to [ f ' ] are cached in [ c ] .
It is similar to { ! with_cache } but with a function that takes as
first argument its own recursive version .
Example ( memoized Fibonacci function ):
{ [
let fib = with_cache_rec ( lru 256 )
( fun fib ' n - > match n with
| 1 | 2 - > 1
| _ - > fib ' ( n-1 ) + fib ' ( n-2 )
) ; ;
fib 70 ; ;
] }
@param cb called after the value is generated or retrieved .
some [f' = fix f], such that recursive calls to [f'] are cached in [c].
It is similar to {!with_cache} but with a function that takes as
first argument its own recursive version.
Example (memoized Fibonacci function):
{[
let fib = with_cache_rec (lru 256)
(fun fib' n -> match n with
| 1 | 2 -> 1
| _ -> fib' (n-1) + fib' (n-2)
);;
fib 70;;
]}
@param cb called after the value is generated or retrieved.
*)
val size : (_, _) t -> int
val iter : ('a, 'b) t -> ('a -> 'b -> unit) -> unit
val add : ('a, 'b) t -> 'a -> 'b -> bool
* Manually add a cached value . Return [ true ] if the value has successfully
been added , and [ false ] if the value was already bound .
@since 1.5
been added, and [false] if the value was already bound.
@since 1.5 *)
val dummy : ('a, 'b) t
val linear : eq:'a equal -> int -> ('a, 'b) t
val replacing : eq:'a equal -> ?hash:'a hash -> int -> ('a, 'b) t
val lru : eq:'a equal -> ?hash:'a hash -> int -> ('a, 'b) t
* LRU cache of the given size ( " Least Recently Used " : keys that have not been
used recently are deleted first ) . Never grows wider than the given size .
used recently are deleted first). Never grows wider than the given size. *)
val unbounded : eq:'a equal -> ?hash:'a hash -> int -> ('a, 'b) t
|
1e58688fbca3ad1f93176e1eb66a13eb51a4c7bd71a3098be557ea80b2816220 | b-ryan/farmhand | registry_test.clj | (ns farmhand.registry-test
(:require [clojure.test :refer :all]
[farmhand.jobs :as jobs]
[farmhand.queue :as q]
[farmhand.redis :refer [with-transaction]]
[farmhand.registry :as registry]
[farmhand.utils :refer [now-millis]]
[farmhand.test-utils :as tu]))
(defn work-fn [])
(def job1 {:job-id "foo" :fn-path "abc/def" :fn-var nil})
(def job2 {:job-id "bar" :fn-path "abc/def" :fn-var nil})
(def job3 {:job-id "baz" :fn-path "abc/def" :fn-var nil})
(defmacro save
[context job expiration]
`(with-redefs [registry/expiration (constantly ~expiration)]
(jobs/save ~context ~job)
(registry/add ~context (:job-id ~job) q/completed-registry)))
(defn save-jobs-fixture
[f]
(with-transaction [context tu/context]
(save context job1 1234)
(save context job2 3456)
(save context job3 5678))
(f))
(use-fixtures :each tu/redis-test-fixture save-jobs-fixture)
(deftest sorts-items-by-oldest-first
(is (= (registry/page tu/context q/completed-registry {})
{:items [{:expiration 1234 :job job1}
{:expiration 3456 :job job2}
{:expiration 5678 :job job3}]
:prev-page nil
:next-page nil})))
(deftest sorts-items-by-newest-first
(is (= (registry/page tu/context q/completed-registry {:newest-first? true})
{:items [{:expiration 5678 :job job3}
{:expiration 3456 :job job2}
{:expiration 1234 :job job1}]
:prev-page nil
:next-page nil})))
(deftest pages-are-handled
(is (= (registry/page tu/context q/completed-registry {:page 1 :size 1})
{:items [{:expiration 3456 :job job2}]
:prev-page 0
:next-page 2})))
(deftest cleanup-removes-older-jobs
(with-redefs [now-millis (constantly 4000)]
(registry/cleanup tu/context))
(is (= (registry/page tu/context q/completed-registry {})
{:items [{:expiration 5678 :job job3}]
:prev-page nil
:next-page nil}))
(is (nil? (jobs/fetch tu/context (:job-id job1))))
(is (nil? (jobs/fetch tu/context (:job-id job2))))
(is (= (jobs/fetch tu/context (:job-id job3)) job3)))
| null | https://raw.githubusercontent.com/b-ryan/farmhand/b5c79124c710b69cce9d4a436228f9ae7e2cbb99/test/farmhand/registry_test.clj | clojure | (ns farmhand.registry-test
(:require [clojure.test :refer :all]
[farmhand.jobs :as jobs]
[farmhand.queue :as q]
[farmhand.redis :refer [with-transaction]]
[farmhand.registry :as registry]
[farmhand.utils :refer [now-millis]]
[farmhand.test-utils :as tu]))
(defn work-fn [])
(def job1 {:job-id "foo" :fn-path "abc/def" :fn-var nil})
(def job2 {:job-id "bar" :fn-path "abc/def" :fn-var nil})
(def job3 {:job-id "baz" :fn-path "abc/def" :fn-var nil})
(defmacro save
[context job expiration]
`(with-redefs [registry/expiration (constantly ~expiration)]
(jobs/save ~context ~job)
(registry/add ~context (:job-id ~job) q/completed-registry)))
(defn save-jobs-fixture
[f]
(with-transaction [context tu/context]
(save context job1 1234)
(save context job2 3456)
(save context job3 5678))
(f))
(use-fixtures :each tu/redis-test-fixture save-jobs-fixture)
(deftest sorts-items-by-oldest-first
(is (= (registry/page tu/context q/completed-registry {})
{:items [{:expiration 1234 :job job1}
{:expiration 3456 :job job2}
{:expiration 5678 :job job3}]
:prev-page nil
:next-page nil})))
(deftest sorts-items-by-newest-first
(is (= (registry/page tu/context q/completed-registry {:newest-first? true})
{:items [{:expiration 5678 :job job3}
{:expiration 3456 :job job2}
{:expiration 1234 :job job1}]
:prev-page nil
:next-page nil})))
(deftest pages-are-handled
(is (= (registry/page tu/context q/completed-registry {:page 1 :size 1})
{:items [{:expiration 3456 :job job2}]
:prev-page 0
:next-page 2})))
(deftest cleanup-removes-older-jobs
(with-redefs [now-millis (constantly 4000)]
(registry/cleanup tu/context))
(is (= (registry/page tu/context q/completed-registry {})
{:items [{:expiration 5678 :job job3}]
:prev-page nil
:next-page nil}))
(is (nil? (jobs/fetch tu/context (:job-id job1))))
(is (nil? (jobs/fetch tu/context (:job-id job2))))
(is (= (jobs/fetch tu/context (:job-id job3)) job3)))
| |
ae0df71df610ca513dc88fbe6f545f73d1f09f52a5977c4a82616f6bc907a020 | Atidot/snippets | WebBlog.hs | #! /usr/bin/env nix-shell
pure -i runhaskell -p " pkgs.haskellPackages.ghcWithPackages ( ps : with ps ; [ aeson text lucid shakespeare clay ] ) "
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE FlexibleContexts #
import "text" Data.Text (Text)
import "text" Data.Text.Lazy (toStrict)
import qualified "text" Data.Text.IO as T (putStrLn)
import "lucid" Lucid
import "shakespeare" Text.Julius
main :: IO ()
main = do
T.putStrLn . toStrict $ renderText blog
blog :: Html ()
blog = html_ $ do
blogHead
body_ $ do
intro
part1
part2
conclusion
blogHead :: Html ()
blogHead = head_ $ do
title_ "The Title"
meta_ [charset_ "utf-8"]
meta_ [ name_ "viewport"
,content_ "width=device-width, initial-scale=1"
]
script' ""
link' ""
script' ""
intro :: Html ()
intro = do
h1_ "Intorduction"
p_ $ do
"lorem ipsum"
"lorem ipsum"
"lorem ipsum"
"lorem ipsum"
part1 :: Html ()
part1 = do
h2_ "Part 1"
p_ $ do
"lorem ipsum"
"lorem ipsum"
"lorem ipsum"
newline
newline
"lorem ipsum"
ul_ $ do
li_ $ "A" --> ""
li_ $ "B" --> ""
li_ $ "C" --> ""
part2 :: Html ()
part2 = do
h2_ "Part 2"
p_ $ do
"lorem ipsum"
"lorem ipsum"
"lorem ipsum" >> b_ "lorem ipsum" >> "lorem ipsum"
newline
"lorem ipsum" >> b_ "lorem ipsum" >> "lorem ipsum"
ul_ $ do
li_ $ "X" --> ""
li_ $ "Y" --> ""
li_ $ "Z" --> ""
div_ [id_ "chart"] ""
barChart
where
conclusion :: Html ()
conclusion = do
h2_ $ "Conslusion"
p_ $ do
"lorem ipsum"
"lorem ipsum"
newline
"lorem ipsum"
newline
barChart :: Html ()
barChart = do
scriptJs [js|
var chart = c3.generate({
bindto: "#chart",
grid: {
x: {
show: true
},
y: {
show: true
}
},
axis: {
y : {
tick: {
format: d3.format("$,")
}
}
},
data: {
type: "bar",
x: "x",
json: {
x: [2010, 2011, 2012, 2013, 2014, 2015],
A: [30, 20, 50, 40, 60, 50],
B: [200, 130, 90, 240, 130, 220],
C: [300, 200, 160, 400, 250, 250]
}
}
});
|]
-- helpers
text --> uri = a_ [href_ uri] text
script' uri = script_ [src_ uri] ("" :: Text)
scriptJs js = script_ [] $ renderJs js
link' uri = link_ [ rel_ "stylesheet", href_ uri ]
newline :: Html ()
newline = br_ []
renderJs = renderJavascriptUrl (\_ _ -> undefined)
| null | https://raw.githubusercontent.com/Atidot/snippets/55fa5fbff396817e16c039dc16d859338e411ac1/Haskell/WebBlog.hs | haskell | # LANGUAGE PackageImports #
# LANGUAGE OverloadedStrings #
> ""
> ""
> ""
> ""
> ""
> ""
helpers
> uri = a_ [href_ uri] text | #! /usr/bin/env nix-shell
pure -i runhaskell -p " pkgs.haskellPackages.ghcWithPackages ( ps : with ps ; [ aeson text lucid shakespeare clay ] ) "
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE FlexibleContexts #
import "text" Data.Text (Text)
import "text" Data.Text.Lazy (toStrict)
import qualified "text" Data.Text.IO as T (putStrLn)
import "lucid" Lucid
import "shakespeare" Text.Julius
main :: IO ()
main = do
T.putStrLn . toStrict $ renderText blog
blog :: Html ()
blog = html_ $ do
blogHead
body_ $ do
intro
part1
part2
conclusion
blogHead :: Html ()
blogHead = head_ $ do
title_ "The Title"
meta_ [charset_ "utf-8"]
meta_ [ name_ "viewport"
,content_ "width=device-width, initial-scale=1"
]
script' ""
link' ""
script' ""
intro :: Html ()
intro = do
h1_ "Intorduction"
p_ $ do
"lorem ipsum"
"lorem ipsum"
"lorem ipsum"
"lorem ipsum"
part1 :: Html ()
part1 = do
h2_ "Part 1"
p_ $ do
"lorem ipsum"
"lorem ipsum"
"lorem ipsum"
newline
newline
"lorem ipsum"
ul_ $ do
part2 :: Html ()
part2 = do
h2_ "Part 2"
p_ $ do
"lorem ipsum"
"lorem ipsum"
"lorem ipsum" >> b_ "lorem ipsum" >> "lorem ipsum"
newline
"lorem ipsum" >> b_ "lorem ipsum" >> "lorem ipsum"
ul_ $ do
div_ [id_ "chart"] ""
barChart
where
conclusion :: Html ()
conclusion = do
h2_ $ "Conslusion"
p_ $ do
"lorem ipsum"
"lorem ipsum"
newline
"lorem ipsum"
newline
barChart :: Html ()
barChart = do
scriptJs [js|
var chart = c3.generate({
bindto: "#chart",
grid: {
x: {
show: true
},
y: {
show: true
}
},
axis: {
y : {
tick: {
format: d3.format("$,")
}
}
},
data: {
type: "bar",
x: "x",
json: {
x: [2010, 2011, 2012, 2013, 2014, 2015],
A: [30, 20, 50, 40, 60, 50],
B: [200, 130, 90, 240, 130, 220],
C: [300, 200, 160, 400, 250, 250]
}
}
});
|]
script' uri = script_ [src_ uri] ("" :: Text)
scriptJs js = script_ [] $ renderJs js
link' uri = link_ [ rel_ "stylesheet", href_ uri ]
newline :: Html ()
newline = br_ []
renderJs = renderJavascriptUrl (\_ _ -> undefined)
|
51f34e2f9df57613032fea0dab56e1b2db0933833e36da179b4683c3cd4862d2 | ollef/sixten | Options.hs | module Command.Check.Options where
import Protolude
data Options = Options
{ inputFiles :: [FilePath]
, logPrefixes :: [Text]
, logFile :: Maybe FilePath
, watch :: !Bool
} deriving (Show)
| null | https://raw.githubusercontent.com/ollef/sixten/60d46eee20abd62599badea85774a9365c81af45/src/Command/Check/Options.hs | haskell | module Command.Check.Options where
import Protolude
data Options = Options
{ inputFiles :: [FilePath]
, logPrefixes :: [Text]
, logFile :: Maybe FilePath
, watch :: !Bool
} deriving (Show)
| |
ca46edfea0d80d5877852e4c8e0c25d2b1ceb3b40a0cd6ad9ce6845b21eb344c | macourtney/Dark-Exchange | notify.clj | (ns darkexchange.model.actions.notify
(:require [clojure.contrib.logging :as logging]
[darkexchange.model.actions.action-keys :as action-keys]
[darkexchange.model.peer :as peer-model]))
(def action-key action-keys/notify-action-key)
(defn action [request-map]
(peer-model/update-destination (:destination (:data request-map)))
{ :data "ok" }) | null | https://raw.githubusercontent.com/macourtney/Dark-Exchange/1654d05cda0c81585da7b8e64f9ea3e2944b27f1/src/darkexchange/model/actions/notify.clj | clojure | (ns darkexchange.model.actions.notify
(:require [clojure.contrib.logging :as logging]
[darkexchange.model.actions.action-keys :as action-keys]
[darkexchange.model.peer :as peer-model]))
(def action-key action-keys/notify-action-key)
(defn action [request-map]
(peer-model/update-destination (:destination (:data request-map)))
{ :data "ok" }) | |
0ffd06c3d68ebadc1216c661c9ef6d3acf651e595e4427dd113ecc99d22ee1fe | clojure-interop/java-jdk | core.clj | (ns javax.xml.stream.util.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[javax.xml.stream.util.EventReaderDelegate])
(require '[javax.xml.stream.util.StreamReaderDelegate])
(require '[javax.xml.stream.util.XMLEventAllocator])
(require '[javax.xml.stream.util.XMLEventConsumer])
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.xml/src/javax/xml/stream/util/core.clj | clojure | (ns javax.xml.stream.util.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[javax.xml.stream.util.EventReaderDelegate])
(require '[javax.xml.stream.util.StreamReaderDelegate])
(require '[javax.xml.stream.util.XMLEventAllocator])
(require '[javax.xml.stream.util.XMLEventConsumer])
| |
852484047e6f543f05cc2d996934d2b96f3a6bfb29f54adf9fda040b7bd5de66 | serokell/github-app | Auth.hs | This Source Code Form is subject to the terms of the Mozilla Public
- License , v. 2.0 . If a copy of the MPL was not distributed with this
- file , You can obtain one at /.
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at /.
-}
{-# LANGUAGE CPP #-}
# LANGUAGE DataKinds #
module GitHub.App.Auth
( AppAuth (..)
, InstallationAuth
, mkInstallationAuth
, obtainAccessToken
) where
import Prelude hiding (exp)
import Control.Concurrent (MVar, newMVar, putMVar, readMVar, takeMVar)
import Control.Exception.Safe (bracketOnError, catch)
import Control.Monad.Except (ExceptT, MonadError (throwError), runExceptT)
import Control.Monad.Trans (lift)
import Crypto.PubKey.RSA (PrivateKey)
import Data.Aeson (FromJSON (..), withObject, (.:))
import qualified Data.ByteString.Lazy as LBS
import Data.Functor (($>))
import Data.Maybe (fromMaybe)
import Data.Semigroup ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Time (NominalDiffTime, UTCTime, diffUTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import GitHub.Auth (Auth (OAuth))
import GitHub.Data.Apps (App)
import GitHub.Data.Definitions (Error (HTTPError))
import GitHub.Data.Id (Id, untagId)
import GitHub.Data.Installations (Installation)
import GitHub.Data.Request (StatusMap)
import GitHub.Request (parseResponse)
import Network.HTTP.Client as HTTP
import qualified Network.HTTP.Client.Internal as HTTP
import qualified Network.HTTP.Types as HTTP
import Web.JWT (JWTClaimsSet (exp, iat, iss), Signer (RSAPrivateKey), encodeSigned, numericDate,
stringOrURI)
| JWT expiration time . Maximum accepted by GitHub is 10 minutes
jwtExpTime :: NominalDiffTime
jwtExpTime = 600
| Installation access token expiration time . It is fixed by GitHub and is equal to 1 hour
instKeyExpTime :: NominalDiffTime
instKeyExpTime = 3600
-- | When to renew the installation access token
--
-- We renew the access token when it is valid for less than 'bufferTime'
-- just to be on the safe side.
bufferTime :: NominalDiffTime
bufferTime = instKeyExpTime * 0.25
baseUrl :: Text
baseUrl = ""
-- | Credentials of a GitHub App
data AppAuth = AppAuth
{ aaAppId :: !(Id App)
, aaPrivateKey :: !PrivateKey
}
| Cached GitHub installation access token
data InstallationToken = InstallationToken
{ itToken :: !Auth
, itExpirationTime :: !UTCTime
} deriving (Show)
instance FromJSON InstallationToken where
parseJSON = withObject "Installation access token" $ \o ->
InstallationToken
<$> (OAuth . encodeUtf8 <$> o .: "token")
<*> o .: "expires_at"
-- | Credentials required for an App to authenticate as an installation
data InstallationAuth = InstallationAuth
{ iaClaimsSet :: !JWTClaimsSet -- ^ Prefilled claims set
, iaAppPrivateKey :: !PrivateKey -- ^ Private key to sign token requests
, iaInstallationId :: !Text -- ^ Installation id
, iaToken :: !(MVar (Maybe InstallationToken)) -- ^ Installation Auth token
}
| Smart constructor for ' InstallationAuth '
mkInstallationAuth
:: AppAuth
-> Id Installation
-> IO InstallationAuth
mkInstallationAuth AppAuth{aaAppId, aaPrivateKey} instId = do
varToken <- newMVar Nothing
let issuer = fromMaybe (error "impossible") . stringOrURI . T.pack . show . untagId $ aaAppId
claimsSet = mempty { iss = Just issuer }
pure $ InstallationAuth claimsSet aaPrivateKey (T.pack . show . untagId $ instId) varToken
-- | Create a request which, when executed, will obtain a new access token
createAccessTokenR :: InstallationAuth -> IO HTTP.Request
createAccessTokenR InstallationAuth{..} = do
currentTime <- utcTimeToPOSIXSeconds <$> getCurrentTime
let expiryTime = currentTime + jwtExpTime
claims = iaClaimsSet
{ iat = Just $ toJsonTime currentTime
, exp = Just $ toJsonTime expiryTime
}
jwt = encodeSigned (RSAPrivateKey iaAppPrivateKey) claims
req <- HTTP.parseRequest . T.unpack $ url
pure req
{ HTTP.requestHeaders =
[ ("Authorization", "Bearer " <> encodeUtf8 jwt)
, ("Accept", "application/vnd.github.machine-man-preview+json")
, ("User-Agent", "github-app/Haskell")
]
, HTTP.checkResponse = successOrMissing Nothing
, HTTP.method = "POST"
}
where
toJsonTime = fromMaybe (error "impossible") . numericDate
url = baseUrl <> "/installations/" <> iaInstallationId <> "/access_tokens"
-- | Get a valid access token
--
Tries to use the cached one . If it is invalid , requests a new one
-- and caches it for future use.
obtainAccessToken
:: Manager
-> InstallationAuth
-> IO (Either Error Auth)
obtainAccessToken mgr ia@InstallationAuth{..} = readMVar iaToken >>= \case
Nothing -> renew
Just InstallationToken{itToken, itExpirationTime} -> do
currentTime <- getCurrentTime
if itExpirationTime `diffUTCTime` currentTime < bufferTime
then renew
else pure $ Right itToken
where
renew :: IO (Either Error Auth)
renew = bracketOnError (takeMVar iaToken) (putMVar iaToken) $ \_ -> do
req <- createAccessTokenR ia
result <- runExceptT $ httpLbs' req >>= parseResponse
case result of
Right newToken -> putMVar iaToken (Just newToken) $> Right (itToken newToken)
Left err -> putMVar iaToken Nothing $> Left err
httpLbs' :: HTTP.Request -> ExceptT Error IO (Response LBS.ByteString)
httpLbs' req' = lift (httpLbs req' mgr) `catch` onHttpException
---------------------------------------
-- Copy-pasted from the github package
---------------------------------------
#if MIN_VERSION_http_client(0,5,0)
successOrMissing :: Maybe (StatusMap a) -> HTTP.Request -> HTTP.Response HTTP.BodyReader -> IO ()
successOrMissing sm _req res
| check = pure ()
| otherwise = do
chunk <- HTTP.brReadSome (HTTP.responseBody res) 1024
let res' = fmap (const ()) res
HTTP.throwHttp $ HTTP.StatusCodeException res' (LBS.toStrict chunk)
where
HTTP.Status sci _ = HTTP.responseStatus res
#else
successOrMissing :: Maybe (StatusMap a) -> Status -> ResponseHeaders -> HTTP.CookieJar -> Maybe E.SomeException
successOrMissing sm s@(Status sci _) hs cookiejar
| check = Nothing
| otherwise = Just $ E.toException $ StatusCodeException s hs cookiejar
where
#endif
check = case sm of
Nothing -> 200 <= sci && sci < 300
Just sm' -> sci `elem` map fst sm'
onHttpException :: MonadError Error m => HttpException -> m a
onHttpException = throwError . HTTPError
| null | https://raw.githubusercontent.com/serokell/github-app/1ac32618ed039dccb0ec9c44a8160e582928bd44/src/GitHub/App/Auth.hs | haskell | # LANGUAGE CPP #
| When to renew the installation access token
We renew the access token when it is valid for less than 'bufferTime'
just to be on the safe side.
| Credentials of a GitHub App
| Credentials required for an App to authenticate as an installation
^ Prefilled claims set
^ Private key to sign token requests
^ Installation id
^ Installation Auth token
| Create a request which, when executed, will obtain a new access token
| Get a valid access token
and caches it for future use.
-------------------------------------
Copy-pasted from the github package
------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
- License , v. 2.0 . If a copy of the MPL was not distributed with this
- file , You can obtain one at /.
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at /.
-}
# LANGUAGE DataKinds #
module GitHub.App.Auth
( AppAuth (..)
, InstallationAuth
, mkInstallationAuth
, obtainAccessToken
) where
import Prelude hiding (exp)
import Control.Concurrent (MVar, newMVar, putMVar, readMVar, takeMVar)
import Control.Exception.Safe (bracketOnError, catch)
import Control.Monad.Except (ExceptT, MonadError (throwError), runExceptT)
import Control.Monad.Trans (lift)
import Crypto.PubKey.RSA (PrivateKey)
import Data.Aeson (FromJSON (..), withObject, (.:))
import qualified Data.ByteString.Lazy as LBS
import Data.Functor (($>))
import Data.Maybe (fromMaybe)
import Data.Semigroup ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Time (NominalDiffTime, UTCTime, diffUTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import GitHub.Auth (Auth (OAuth))
import GitHub.Data.Apps (App)
import GitHub.Data.Definitions (Error (HTTPError))
import GitHub.Data.Id (Id, untagId)
import GitHub.Data.Installations (Installation)
import GitHub.Data.Request (StatusMap)
import GitHub.Request (parseResponse)
import Network.HTTP.Client as HTTP
import qualified Network.HTTP.Client.Internal as HTTP
import qualified Network.HTTP.Types as HTTP
import Web.JWT (JWTClaimsSet (exp, iat, iss), Signer (RSAPrivateKey), encodeSigned, numericDate,
stringOrURI)
| JWT expiration time . Maximum accepted by GitHub is 10 minutes
jwtExpTime :: NominalDiffTime
jwtExpTime = 600
| Installation access token expiration time . It is fixed by GitHub and is equal to 1 hour
instKeyExpTime :: NominalDiffTime
instKeyExpTime = 3600
bufferTime :: NominalDiffTime
bufferTime = instKeyExpTime * 0.25
baseUrl :: Text
baseUrl = ""
data AppAuth = AppAuth
{ aaAppId :: !(Id App)
, aaPrivateKey :: !PrivateKey
}
| Cached GitHub installation access token
data InstallationToken = InstallationToken
{ itToken :: !Auth
, itExpirationTime :: !UTCTime
} deriving (Show)
instance FromJSON InstallationToken where
parseJSON = withObject "Installation access token" $ \o ->
InstallationToken
<$> (OAuth . encodeUtf8 <$> o .: "token")
<*> o .: "expires_at"
data InstallationAuth = InstallationAuth
}
| Smart constructor for ' InstallationAuth '
mkInstallationAuth
:: AppAuth
-> Id Installation
-> IO InstallationAuth
mkInstallationAuth AppAuth{aaAppId, aaPrivateKey} instId = do
varToken <- newMVar Nothing
let issuer = fromMaybe (error "impossible") . stringOrURI . T.pack . show . untagId $ aaAppId
claimsSet = mempty { iss = Just issuer }
pure $ InstallationAuth claimsSet aaPrivateKey (T.pack . show . untagId $ instId) varToken
createAccessTokenR :: InstallationAuth -> IO HTTP.Request
createAccessTokenR InstallationAuth{..} = do
currentTime <- utcTimeToPOSIXSeconds <$> getCurrentTime
let expiryTime = currentTime + jwtExpTime
claims = iaClaimsSet
{ iat = Just $ toJsonTime currentTime
, exp = Just $ toJsonTime expiryTime
}
jwt = encodeSigned (RSAPrivateKey iaAppPrivateKey) claims
req <- HTTP.parseRequest . T.unpack $ url
pure req
{ HTTP.requestHeaders =
[ ("Authorization", "Bearer " <> encodeUtf8 jwt)
, ("Accept", "application/vnd.github.machine-man-preview+json")
, ("User-Agent", "github-app/Haskell")
]
, HTTP.checkResponse = successOrMissing Nothing
, HTTP.method = "POST"
}
where
toJsonTime = fromMaybe (error "impossible") . numericDate
url = baseUrl <> "/installations/" <> iaInstallationId <> "/access_tokens"
Tries to use the cached one . If it is invalid , requests a new one
obtainAccessToken
:: Manager
-> InstallationAuth
-> IO (Either Error Auth)
obtainAccessToken mgr ia@InstallationAuth{..} = readMVar iaToken >>= \case
Nothing -> renew
Just InstallationToken{itToken, itExpirationTime} -> do
currentTime <- getCurrentTime
if itExpirationTime `diffUTCTime` currentTime < bufferTime
then renew
else pure $ Right itToken
where
renew :: IO (Either Error Auth)
renew = bracketOnError (takeMVar iaToken) (putMVar iaToken) $ \_ -> do
req <- createAccessTokenR ia
result <- runExceptT $ httpLbs' req >>= parseResponse
case result of
Right newToken -> putMVar iaToken (Just newToken) $> Right (itToken newToken)
Left err -> putMVar iaToken Nothing $> Left err
httpLbs' :: HTTP.Request -> ExceptT Error IO (Response LBS.ByteString)
httpLbs' req' = lift (httpLbs req' mgr) `catch` onHttpException
#if MIN_VERSION_http_client(0,5,0)
successOrMissing :: Maybe (StatusMap a) -> HTTP.Request -> HTTP.Response HTTP.BodyReader -> IO ()
successOrMissing sm _req res
| check = pure ()
| otherwise = do
chunk <- HTTP.brReadSome (HTTP.responseBody res) 1024
let res' = fmap (const ()) res
HTTP.throwHttp $ HTTP.StatusCodeException res' (LBS.toStrict chunk)
where
HTTP.Status sci _ = HTTP.responseStatus res
#else
successOrMissing :: Maybe (StatusMap a) -> Status -> ResponseHeaders -> HTTP.CookieJar -> Maybe E.SomeException
successOrMissing sm s@(Status sci _) hs cookiejar
| check = Nothing
| otherwise = Just $ E.toException $ StatusCodeException s hs cookiejar
where
#endif
check = case sm of
Nothing -> 200 <= sci && sci < 300
Just sm' -> sci `elem` map fst sm'
onHttpException :: MonadError Error m => HttpException -> m a
onHttpException = throwError . HTTPError
|
4809de2bdac2268f0cd659607ba436fcd6e5ced4446367126f488cadd21b853c | madvas/emojillionaire | styles.cljs | (ns emojillionaire.styles)
(def main-grid {:margin-top 20})
(def paper-base {:padding 20
:margin-top 10
:margin-bottom 10})
(def jackpot-paper (merge paper-base
{:text-align :center}))
(def jackpot-text {:font-size "3em"
:line-height "1.4em"})
(def welcome-text {:margin-bottom 10
:margin-top 10})
(def emoji-select-form-wrap {:height 250
:overflow :scroll})
(def selectable-emoji {:padding-top 5
:padding-bottom 5
:border-radius 10
:cursor :pointer})
(def selected-emoji-preview {:margin-bottom 30
:margin-top 10})
(def add-selected-emoji-btn {:margin-bottom 10})
(defn vertical-margin [x]
{:margin-top x
:margin-bottom x})
(def clickable {:cursor :pointer})
(def table-narrow-col {:width 40})
(def text-center {:text-align :center})
(def text-right {:text-align :right})
(def text-left {:text-align :left})
(def grey-text {:color "#9e9e9e"})
(def table-summary (merge text-right
{:line-height "1.4em"}))
(def bet-btns-wrap (merge text-right {:margin-top 30}))
(def full-width {:width "100%"})
(def congrats-title {:text-align :center
:font-weight 300
:font-size "3em"
:line-height "1.1em"
:padding-top 20
:padding-bottom 20})
(def winning-amount {:font-size "1.8em"
:font-weight 300
:line-height "2em"
:margin-bottom 30})
(def table-emoji {:width 25})
(def multi-emoji-row-col {:white-space :normal
:padding-top 5
:padding-bottom 5})
(def ellipsis {:text-overflow :ellipsis
:overflow :auto})
(def main-logo {:margin-left 10
:height 47
})
(def eth-logo {:margin-top -1
:margin-right 10
:height 50})
(def network-title {:color "#FFF"
:margin-top "-8px"}) | null | https://raw.githubusercontent.com/madvas/emojillionaire/ee47e874db0c88b91985b6f9e72221f12d3010ff/src/cljs/emojillionaire/styles.cljs | clojure | (ns emojillionaire.styles)
(def main-grid {:margin-top 20})
(def paper-base {:padding 20
:margin-top 10
:margin-bottom 10})
(def jackpot-paper (merge paper-base
{:text-align :center}))
(def jackpot-text {:font-size "3em"
:line-height "1.4em"})
(def welcome-text {:margin-bottom 10
:margin-top 10})
(def emoji-select-form-wrap {:height 250
:overflow :scroll})
(def selectable-emoji {:padding-top 5
:padding-bottom 5
:border-radius 10
:cursor :pointer})
(def selected-emoji-preview {:margin-bottom 30
:margin-top 10})
(def add-selected-emoji-btn {:margin-bottom 10})
(defn vertical-margin [x]
{:margin-top x
:margin-bottom x})
(def clickable {:cursor :pointer})
(def table-narrow-col {:width 40})
(def text-center {:text-align :center})
(def text-right {:text-align :right})
(def text-left {:text-align :left})
(def grey-text {:color "#9e9e9e"})
(def table-summary (merge text-right
{:line-height "1.4em"}))
(def bet-btns-wrap (merge text-right {:margin-top 30}))
(def full-width {:width "100%"})
(def congrats-title {:text-align :center
:font-weight 300
:font-size "3em"
:line-height "1.1em"
:padding-top 20
:padding-bottom 20})
(def winning-amount {:font-size "1.8em"
:font-weight 300
:line-height "2em"
:margin-bottom 30})
(def table-emoji {:width 25})
(def multi-emoji-row-col {:white-space :normal
:padding-top 5
:padding-bottom 5})
(def ellipsis {:text-overflow :ellipsis
:overflow :auto})
(def main-logo {:margin-left 10
:height 47
})
(def eth-logo {:margin-top -1
:margin-right 10
:height 50})
(def network-title {:color "#FFF"
:margin-top "-8px"}) | |
f8f07844c52860fb2e8171a3acb82dd237c654f2102385364d5e5e8dbdd6c51e | lem-project/lem | nim-mode.lisp | (defpackage :lem-nim-mode
(:use :cl :lem :lem.language-mode :lem.language-mode-tools)
(:export :*nim-mode-hook*
:nim-mode)
#+sbcl
(:lock t))
(in-package :lem-nim-mode)
(defun tokens (boundary strings)
(let ((alternation
`(:alternation ,@(sort (copy-list strings)
#'> :key #'length))))
(if boundary
`(:sequence ,boundary ,alternation ,boundary)
alternation)))
;; numerical literals
cf .
(let* ((digit "[0-9]")
(octdigit "[0-7]")
(hexdigit "[0-9A-Fa-f]")
(bindigit "[0-1]")
(hexlit (format nil "0(x|X)~a(_?~a)*"
hexdigit hexdigit))
(declit (format nil "~a(_?~a)*" digit digit))
(octlit (format nil "0(o|c|C)~a(_?~a)*"
octdigit octdigit))
(binlit (format nil "0(b|b)~a(_?~a)*"
bindigit bindigit)))
(defun integer-literals ()
(let* ((intlit (format nil "(~@{~a~^|~})"
hexlit declit octlit binlit))
(intsuffix "'?(i|I)(8|16|32|64)"))
(format nil "\\b~a(~a)?\\b" intlit intsuffix)))
(defun float-literals ()
(let* ((exponent (format nil "(e|E)[+-]?~a(_?~a)*"
digit digit))
(floatlit (format nil
"~a(_?~a)*((\\.(_?~a)*(~a)?)|~a)"
digit digit digit exponent exponent))
(floatsuffix "((f|F)(32)?|((f|F)64)|d|D)")
(floatsuffixlit
(format nil
"(~a'~a)|((~a|~a|~a|~a)'?~a)"
hexlit floatsuffix
floatlit declit octlit
binlit floatsuffix)))
(format nil "\\b(~a|~a)\\b" floatlit
floatsuffixlit))))
cf .
;; Section: Identifiers & Keywords
(defparameter keywords
'( "addr" "and" "as" "asm"
"bind" "block" "break"
"case" "cast" "concept" "const" "continue" "converter"
"defer" "discard" "distinct" "div" "do"
"elif" "else" "end" "enum"
"except" "export"
"finally" "for" "from" "func"
"if" "import" "in" "include" "interface"
"is" "isnot" "iterator"
"let" "macro" "method" "mixin" "mod"
"nil" "not" "notin"
"object" "of" "or" "out"
"proc" "ptr" "raise" "ref" "return"
"shl" "shr" "static"
"template" "try" "tuple" "type"
"using" "var" "when" "while" "xor" "yield"
"result" "echo" "writeLine"))
(defparameter nimtypes
'( "int" "int8" "int16" "int32" "int64"
"uint" "uint8" "uint16" "uint32" "uint64"
"float" "float32" "float64"
"bool" "char" "string" "pointer" "typedesc"
"void" "auto" "any" "sink" "lent"
"untyped" "typed" "typedesc"
"range" "array" "openArray"
"varargs" "seq" "set" "byte"
;; c interop types
"cchar" "cschar" "cshort" "cint" "clong"
"clonglong" "cfloat" "cdouble"
"cstring" "clongdouble" "cstringArray"))
cf .
(defun make-tmlanguage-nim ()
(let* ((patterns (make-tm-patterns
(make-tm-region "#" "$" :name
'syntax-comment-attribute)
;; keywords: -lang.org/docs/manual.html
(make-tm-match (tokens :word-boundary keywords)
:name 'syntax-keyword-attribute)
(make-tm-match (tokens :word-boundary nimtypes )
:name 'syntax-type-attribute)
;; operators: -lang.org/docs/manual.html
(make-tm-match (tokens nil
'( "=" "+" "-" "*" "/"
"<" ">@" "$" "~" "&"
"%" "|!" "?" "^" "." ":"))
:name 'syntax-keyword-attribute)
(make-tm-match (tokens :word-boundary
'("false" "true" "nil"))
:name 'syntax-constant-attribute)
(make-tm-string-region "\"")
(make-tm-string-region "\"\"\"")
(make-tm-match (integer-literals)
:name 'syntax-constant-attribute)
(make-tm-match (float-literals)
:name 'syntax-constant-attribute)
(make-tm-region `(:sequence "#[") `(:sequence "]#")
:name 'syntax-comment-attribute))))
(make-tmlanguage :patterns patterns)))
(defvar *nim-syntax-table*
(let ((table (make-syntax-table
:space-chars '(#\space #\newline)
:paren-pairs '((#\( . #\))
(#\{ . #\})
(#\[ . #\]))
:string-quote-chars '(#\" #\')
:block-string-pairs '(("\"\"\"" . "\"\"\""))
:line-comment-string "#"))
(tmlanguage (make-tmlanguage-nim)))
(set-syntax-parser table tmlanguage)
table))
three functions below from lem - python - mode ,
;; it seems almost works
(defun nim-calc-indent (point)
(with-point ((point point))
(let ((tab-width (variable-value 'tab-width :default point))
(column (point-column point)))
(+ column (- tab-width (rem column tab-width))))))
(defun beginning-of-defun (point n)
(loop :repeat n :do (search-backward-regexp point "^\\w")))
(defun end-of-defun (point n)
(with-point ((p point))
(loop :repeat n
:do (line-offset p 1)
(unless (search-forward-regexp p "^\\w") (return)))
(line-start p)
(move-point point p)))
(define-major-mode nim-mode language-mode
(:name "nim"
:keymap *nim-mode-keymap*
:syntax-table *nim-syntax-table*
:mode-hook *nim-mode-hook*)
(setf (variable-value 'enable-syntax-highlight) t
(variable-value 'indent-tabs-mode) nil
(variable-value 'tab-width) 2
(variable-value 'calc-indent-function) 'nim-calc-indent
(variable-value 'line-comment) "#"
(variable-value 'beginning-of-defun-function) 'beginning-of-defun
(variable-value 'end-of-defun-function) 'end-of-defun))
(define-file-type ("nim" "nimble") nim-mode)
| null | https://raw.githubusercontent.com/lem-project/lem/26bd2dc10d92a90317d99ac818286371e5da9b14/modes/nim-mode/nim-mode.lisp | lisp | numerical literals
Section: Identifiers & Keywords
c interop types
keywords: -lang.org/docs/manual.html
operators: -lang.org/docs/manual.html
it seems almost works | (defpackage :lem-nim-mode
(:use :cl :lem :lem.language-mode :lem.language-mode-tools)
(:export :*nim-mode-hook*
:nim-mode)
#+sbcl
(:lock t))
(in-package :lem-nim-mode)
(defun tokens (boundary strings)
(let ((alternation
`(:alternation ,@(sort (copy-list strings)
#'> :key #'length))))
(if boundary
`(:sequence ,boundary ,alternation ,boundary)
alternation)))
cf .
(let* ((digit "[0-9]")
(octdigit "[0-7]")
(hexdigit "[0-9A-Fa-f]")
(bindigit "[0-1]")
(hexlit (format nil "0(x|X)~a(_?~a)*"
hexdigit hexdigit))
(declit (format nil "~a(_?~a)*" digit digit))
(octlit (format nil "0(o|c|C)~a(_?~a)*"
octdigit octdigit))
(binlit (format nil "0(b|b)~a(_?~a)*"
bindigit bindigit)))
(defun integer-literals ()
(let* ((intlit (format nil "(~@{~a~^|~})"
hexlit declit octlit binlit))
(intsuffix "'?(i|I)(8|16|32|64)"))
(format nil "\\b~a(~a)?\\b" intlit intsuffix)))
(defun float-literals ()
(let* ((exponent (format nil "(e|E)[+-]?~a(_?~a)*"
digit digit))
(floatlit (format nil
"~a(_?~a)*((\\.(_?~a)*(~a)?)|~a)"
digit digit digit exponent exponent))
(floatsuffix "((f|F)(32)?|((f|F)64)|d|D)")
(floatsuffixlit
(format nil
"(~a'~a)|((~a|~a|~a|~a)'?~a)"
hexlit floatsuffix
floatlit declit octlit
binlit floatsuffix)))
(format nil "\\b(~a|~a)\\b" floatlit
floatsuffixlit))))
cf .
(defparameter keywords
'( "addr" "and" "as" "asm"
"bind" "block" "break"
"case" "cast" "concept" "const" "continue" "converter"
"defer" "discard" "distinct" "div" "do"
"elif" "else" "end" "enum"
"except" "export"
"finally" "for" "from" "func"
"if" "import" "in" "include" "interface"
"is" "isnot" "iterator"
"let" "macro" "method" "mixin" "mod"
"nil" "not" "notin"
"object" "of" "or" "out"
"proc" "ptr" "raise" "ref" "return"
"shl" "shr" "static"
"template" "try" "tuple" "type"
"using" "var" "when" "while" "xor" "yield"
"result" "echo" "writeLine"))
(defparameter nimtypes
'( "int" "int8" "int16" "int32" "int64"
"uint" "uint8" "uint16" "uint32" "uint64"
"float" "float32" "float64"
"bool" "char" "string" "pointer" "typedesc"
"void" "auto" "any" "sink" "lent"
"untyped" "typed" "typedesc"
"range" "array" "openArray"
"varargs" "seq" "set" "byte"
"cchar" "cschar" "cshort" "cint" "clong"
"clonglong" "cfloat" "cdouble"
"cstring" "clongdouble" "cstringArray"))
cf .
(defun make-tmlanguage-nim ()
(let* ((patterns (make-tm-patterns
(make-tm-region "#" "$" :name
'syntax-comment-attribute)
(make-tm-match (tokens :word-boundary keywords)
:name 'syntax-keyword-attribute)
(make-tm-match (tokens :word-boundary nimtypes )
:name 'syntax-type-attribute)
(make-tm-match (tokens nil
'( "=" "+" "-" "*" "/"
"<" ">@" "$" "~" "&"
"%" "|!" "?" "^" "." ":"))
:name 'syntax-keyword-attribute)
(make-tm-match (tokens :word-boundary
'("false" "true" "nil"))
:name 'syntax-constant-attribute)
(make-tm-string-region "\"")
(make-tm-string-region "\"\"\"")
(make-tm-match (integer-literals)
:name 'syntax-constant-attribute)
(make-tm-match (float-literals)
:name 'syntax-constant-attribute)
(make-tm-region `(:sequence "#[") `(:sequence "]#")
:name 'syntax-comment-attribute))))
(make-tmlanguage :patterns patterns)))
(defvar *nim-syntax-table*
(let ((table (make-syntax-table
:space-chars '(#\space #\newline)
:paren-pairs '((#\( . #\))
(#\{ . #\})
(#\[ . #\]))
:string-quote-chars '(#\" #\')
:block-string-pairs '(("\"\"\"" . "\"\"\""))
:line-comment-string "#"))
(tmlanguage (make-tmlanguage-nim)))
(set-syntax-parser table tmlanguage)
table))
three functions below from lem - python - mode ,
(defun nim-calc-indent (point)
(with-point ((point point))
(let ((tab-width (variable-value 'tab-width :default point))
(column (point-column point)))
(+ column (- tab-width (rem column tab-width))))))
(defun beginning-of-defun (point n)
(loop :repeat n :do (search-backward-regexp point "^\\w")))
(defun end-of-defun (point n)
(with-point ((p point))
(loop :repeat n
:do (line-offset p 1)
(unless (search-forward-regexp p "^\\w") (return)))
(line-start p)
(move-point point p)))
(define-major-mode nim-mode language-mode
(:name "nim"
:keymap *nim-mode-keymap*
:syntax-table *nim-syntax-table*
:mode-hook *nim-mode-hook*)
(setf (variable-value 'enable-syntax-highlight) t
(variable-value 'indent-tabs-mode) nil
(variable-value 'tab-width) 2
(variable-value 'calc-indent-function) 'nim-calc-indent
(variable-value 'line-comment) "#"
(variable-value 'beginning-of-defun-function) 'beginning-of-defun
(variable-value 'end-of-defun-function) 'end-of-defun))
(define-file-type ("nim" "nimble") nim-mode)
|
206d5fb4de3fb32274c2119fd6c30b83694e5ce1437713d8454ff73e9d603765 | ocaml-ppx/ppx_tools_versioned | ast_convenience_404.ml | open Migrate_parsetree.Ast_404
(* This file is part of the ppx_tools package. It is released *)
under the terms of the MIT license ( see LICENSE file ) .
Copyright 2013 and LexiFi
open Parsetree
open Asttypes
open Location
open Ast_helper
module Label = struct
type t = Asttypes.arg_label
type desc = Asttypes.arg_label =
Nolabel
| Labelled of string
| Optional of string
let explode x = x
let nolabel = Nolabel
let labelled x = Labelled x
let optional x = Optional x
end
module Constant = struct
type t = Parsetree.constant =
Pconst_integer of string * char option
| Pconst_char of char
| Pconst_string of string * string option
| Pconst_float of string * char option
let of_constant x = x
let to_constant x = x
end
let may_tuple ?loc tup = function
| [] -> None
| [x] -> Some x
| l -> Some (tup ?loc ?attrs:None l)
let lid ?(loc = !default_loc) s = mkloc (Longident.parse s) loc
let constr ?loc ?attrs s args = Exp.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Exp.tuple args)
let nil ?loc ?attrs () = constr ?loc ?attrs "[]" []
let unit ?loc ?attrs () = constr ?loc ?attrs "()" []
let tuple ?loc ?attrs = function
| [] -> unit ?loc ?attrs ()
| [x] -> x
| xs -> Exp.tuple ?loc ?attrs xs
let cons ?loc ?attrs hd tl = constr ?loc ?attrs "::" [hd; tl]
let list ?loc ?attrs l = List.fold_right (cons ?loc ?attrs) l (nil ?loc ?attrs ())
let str ?loc ?attrs s = Exp.constant ?loc ?attrs (Pconst_string (s, None))
let int ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (string_of_int x, None))
let int32 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int32.to_string x, Some 'l'))
let int64 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int64.to_string x, Some 'L'))
let char ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_char x)
let float ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_float (string_of_float x, None))
let record ?loc ?attrs ?over l =
Exp.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.pexp_loc s, e)) l) over
let func ?loc ?attrs l = Exp.function_ ?loc ?attrs (List.map (fun (p, e) -> Exp.case p e) l)
let lam ?loc ?attrs ?(label = Label.nolabel) ?default pat exp = Exp.fun_ ?loc ?attrs label default pat exp
let app ?loc ?attrs f l = if l = [] then f else Exp.apply ?loc ?attrs f (List.map (fun a -> Label.nolabel, a) l)
let evar ?loc ?attrs s = Exp.ident ?loc ?attrs (lid ?loc s)
let let_in ?loc ?attrs ?(recursive = false) b body =
Exp.let_ ?loc ?attrs (if recursive then Recursive else Nonrecursive) b body
let sequence ?loc ?attrs = function
| [] -> unit ?loc ?attrs ()
| hd :: tl -> List.fold_left (fun e1 e2 -> Exp.sequence ?loc ?attrs e1 e2) hd tl
let pvar ?(loc = !default_loc) ?attrs s = Pat.var ~loc ?attrs (mkloc s loc)
let pconstr ?loc ?attrs s args = Pat.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Pat.tuple args)
let precord ?loc ?attrs ?(closed = Open) l =
Pat.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.ppat_loc s, e)) l) closed
let pnil ?loc ?attrs () = pconstr ?loc ?attrs "[]" []
let pcons ?loc ?attrs hd tl = pconstr ?loc ?attrs "::" [hd; tl]
let punit ?loc ?attrs () = pconstr ?loc ?attrs "()" []
let ptuple ?loc ?attrs = function
| [] -> punit ?loc ?attrs ()
| [x] -> x
| xs -> Pat.tuple ?loc ?attrs xs
let plist ?loc ?attrs l = List.fold_right (pcons ?loc ?attrs) l (pnil ?loc ?attrs ())
let pstr ?loc ?attrs s = Pat.constant ?loc ?attrs (Pconst_string (s, None))
let pint ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_integer (string_of_int x, None))
let pchar ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_char x)
let pfloat ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_float (string_of_float x, None))
let tconstr ?loc ?attrs c l = Typ.constr ?loc ?attrs (lid ?loc c) l
let get_str = function
| {pexp_desc=Pexp_constant (Pconst_string (s, _)); _} -> Some s
| _ -> None
let get_str_with_quotation_delimiter = function
| {pexp_desc=Pexp_constant (Pconst_string (s, d)); _} -> Some (s, d)
| _ -> None
let get_lid = function
| {pexp_desc=Pexp_ident{txt=id;_};_} ->
Some (String.concat "." (Longident.flatten id))
| _ -> None
let find_attr s attrs =
try Some (snd (List.find (fun (x, _) -> x.txt = s) attrs))
with Not_found -> None
let expr_of_payload = function
| PStr [{pstr_desc=Pstr_eval(e, _); _}] -> Some e
| _ -> None
let find_attr_expr s attrs =
match find_attr s attrs with
| Some e -> expr_of_payload e
| None -> None
let has_attr s attrs =
find_attr s attrs <> None
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx_tools_versioned/00a0150cdabfa7f0dad2c5e0e6b32230d22295ca/ast_convenience_404.ml | ocaml | This file is part of the ppx_tools package. It is released | open Migrate_parsetree.Ast_404
under the terms of the MIT license ( see LICENSE file ) .
Copyright 2013 and LexiFi
open Parsetree
open Asttypes
open Location
open Ast_helper
module Label = struct
type t = Asttypes.arg_label
type desc = Asttypes.arg_label =
Nolabel
| Labelled of string
| Optional of string
let explode x = x
let nolabel = Nolabel
let labelled x = Labelled x
let optional x = Optional x
end
module Constant = struct
type t = Parsetree.constant =
Pconst_integer of string * char option
| Pconst_char of char
| Pconst_string of string * string option
| Pconst_float of string * char option
let of_constant x = x
let to_constant x = x
end
let may_tuple ?loc tup = function
| [] -> None
| [x] -> Some x
| l -> Some (tup ?loc ?attrs:None l)
let lid ?(loc = !default_loc) s = mkloc (Longident.parse s) loc
let constr ?loc ?attrs s args = Exp.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Exp.tuple args)
let nil ?loc ?attrs () = constr ?loc ?attrs "[]" []
let unit ?loc ?attrs () = constr ?loc ?attrs "()" []
let tuple ?loc ?attrs = function
| [] -> unit ?loc ?attrs ()
| [x] -> x
| xs -> Exp.tuple ?loc ?attrs xs
let cons ?loc ?attrs hd tl = constr ?loc ?attrs "::" [hd; tl]
let list ?loc ?attrs l = List.fold_right (cons ?loc ?attrs) l (nil ?loc ?attrs ())
let str ?loc ?attrs s = Exp.constant ?loc ?attrs (Pconst_string (s, None))
let int ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (string_of_int x, None))
let int32 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int32.to_string x, Some 'l'))
let int64 ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_integer (Int64.to_string x, Some 'L'))
let char ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_char x)
let float ?loc ?attrs x = Exp.constant ?loc ?attrs (Pconst_float (string_of_float x, None))
let record ?loc ?attrs ?over l =
Exp.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.pexp_loc s, e)) l) over
let func ?loc ?attrs l = Exp.function_ ?loc ?attrs (List.map (fun (p, e) -> Exp.case p e) l)
let lam ?loc ?attrs ?(label = Label.nolabel) ?default pat exp = Exp.fun_ ?loc ?attrs label default pat exp
let app ?loc ?attrs f l = if l = [] then f else Exp.apply ?loc ?attrs f (List.map (fun a -> Label.nolabel, a) l)
let evar ?loc ?attrs s = Exp.ident ?loc ?attrs (lid ?loc s)
let let_in ?loc ?attrs ?(recursive = false) b body =
Exp.let_ ?loc ?attrs (if recursive then Recursive else Nonrecursive) b body
let sequence ?loc ?attrs = function
| [] -> unit ?loc ?attrs ()
| hd :: tl -> List.fold_left (fun e1 e2 -> Exp.sequence ?loc ?attrs e1 e2) hd tl
let pvar ?(loc = !default_loc) ?attrs s = Pat.var ~loc ?attrs (mkloc s loc)
let pconstr ?loc ?attrs s args = Pat.construct ?loc ?attrs (lid ?loc s) (may_tuple ?loc Pat.tuple args)
let precord ?loc ?attrs ?(closed = Open) l =
Pat.record ?loc ?attrs (List.map (fun (s, e) -> (lid ~loc:e.ppat_loc s, e)) l) closed
let pnil ?loc ?attrs () = pconstr ?loc ?attrs "[]" []
let pcons ?loc ?attrs hd tl = pconstr ?loc ?attrs "::" [hd; tl]
let punit ?loc ?attrs () = pconstr ?loc ?attrs "()" []
let ptuple ?loc ?attrs = function
| [] -> punit ?loc ?attrs ()
| [x] -> x
| xs -> Pat.tuple ?loc ?attrs xs
let plist ?loc ?attrs l = List.fold_right (pcons ?loc ?attrs) l (pnil ?loc ?attrs ())
let pstr ?loc ?attrs s = Pat.constant ?loc ?attrs (Pconst_string (s, None))
let pint ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_integer (string_of_int x, None))
let pchar ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_char x)
let pfloat ?loc ?attrs x = Pat.constant ?loc ?attrs (Pconst_float (string_of_float x, None))
let tconstr ?loc ?attrs c l = Typ.constr ?loc ?attrs (lid ?loc c) l
let get_str = function
| {pexp_desc=Pexp_constant (Pconst_string (s, _)); _} -> Some s
| _ -> None
let get_str_with_quotation_delimiter = function
| {pexp_desc=Pexp_constant (Pconst_string (s, d)); _} -> Some (s, d)
| _ -> None
let get_lid = function
| {pexp_desc=Pexp_ident{txt=id;_};_} ->
Some (String.concat "." (Longident.flatten id))
| _ -> None
let find_attr s attrs =
try Some (snd (List.find (fun (x, _) -> x.txt = s) attrs))
with Not_found -> None
let expr_of_payload = function
| PStr [{pstr_desc=Pstr_eval(e, _); _}] -> Some e
| _ -> None
let find_attr_expr s attrs =
match find_attr s attrs with
| Some e -> expr_of_payload e
| None -> None
let has_attr s attrs =
find_attr s attrs <> None
|
ef76975c1676e9b388c99a7dac8d8583da3bf87c321508bd761b3f6b1cb3e352 | kframework/semantic-approaches | Imp_Syntax.hs | This module defines imp data structures to be used in the semantics . We now need to derive to throw away duplicate states when finding nondeterminism - see the semantics .
module Imp_Syntax where
-- Arithmetic Binary Operators (operators for binary arithmetic expressions)
data ABinOp =
Plus |
Divide
deriving (Show, Eq)
-- Arithmentic Expressions
data AExp =
Id String |
AConst Integer |
ABinExp ABinOp AExp AExp
deriving (Show, Eq)
-- Boolean Expressions
data BExp =
BConst Bool |
BAndExp BExp BExp |
BLtEqExp AExp AExp |
BNotExp BExp
deriving (Show, Eq)
-- Statements
data Stmt =
Assignment String AExp |
SeqComp Stmt Stmt |
If BExp Stmt Stmt |
While BExp Stmt |
Block Stmt |
Spawn Stmt | -- NEW
Skip
deriving (Show, Eq)
Program
data Pgm =
Init [String] Stmt
deriving (Show, Eq) | null | https://raw.githubusercontent.com/kframework/semantic-approaches/6f64eac09e005fe4eae7141e3c0e0f5711da0647/haskell/imp/4-imp-threads/1-imp-bigstep/Imp_Syntax.hs | haskell | Arithmetic Binary Operators (operators for binary arithmetic expressions)
Arithmentic Expressions
Boolean Expressions
Statements
NEW | This module defines imp data structures to be used in the semantics . We now need to derive to throw away duplicate states when finding nondeterminism - see the semantics .
module Imp_Syntax where
data ABinOp =
Plus |
Divide
deriving (Show, Eq)
data AExp =
Id String |
AConst Integer |
ABinExp ABinOp AExp AExp
deriving (Show, Eq)
data BExp =
BConst Bool |
BAndExp BExp BExp |
BLtEqExp AExp AExp |
BNotExp BExp
deriving (Show, Eq)
data Stmt =
Assignment String AExp |
SeqComp Stmt Stmt |
If BExp Stmt Stmt |
While BExp Stmt |
Block Stmt |
Skip
deriving (Show, Eq)
Program
data Pgm =
Init [String] Stmt
deriving (Show, Eq) |
9c5f8362632ea87d680d5bc5fb50c3d664745fc921fe9dcaf54977d90708ab0d | NickSeagull/drahko | TopLevel.hs | module Drahko.Generate.TopLevel where
import qualified Drahko.Generate.Block as Block
import Drahko.Generate.Common
import Drahko.Generate.Name
import Drahko.Syntax
import qualified IRTS.Lang as Idris
import qualified Idris.Core.TT as Idris
import Relude
generate :: MonadState UnusedNames m => MonadIO m => (Idris.Name, Idris.LDecl) -> m Statement
generate (_, Idris.LConstructor {}) = pure NoOp
generate (functionName, Idris.LFun _ _ args definition) = do
let funName = toName functionName
let funArgs = toName <$> args
let scope = funName : funArgs
funBlock <- flip runReaderT funArgs $ Block.generate scope Return definition
pure $ Function funName funArgs funBlock
| null | https://raw.githubusercontent.com/NickSeagull/drahko/cd84ee4b25f0d51900c248dfdc225370bfe19728/codegen/src/Drahko/Generate/TopLevel.hs | haskell | module Drahko.Generate.TopLevel where
import qualified Drahko.Generate.Block as Block
import Drahko.Generate.Common
import Drahko.Generate.Name
import Drahko.Syntax
import qualified IRTS.Lang as Idris
import qualified Idris.Core.TT as Idris
import Relude
generate :: MonadState UnusedNames m => MonadIO m => (Idris.Name, Idris.LDecl) -> m Statement
generate (_, Idris.LConstructor {}) = pure NoOp
generate (functionName, Idris.LFun _ _ args definition) = do
let funName = toName functionName
let funArgs = toName <$> args
let scope = funName : funArgs
funBlock <- flip runReaderT funArgs $ Block.generate scope Return definition
pure $ Function funName funArgs funBlock
| |
36c6ce08fb73c08bbc61e8dc3e3871cae9ae87680e2585d0faeeffef2d718126 | CafeOBJ/cafeobj | regularize.lisp | -*- Mode : LISP ; Package : CHAOS ; ; Syntax : Common - lisp -*-
;;;
Copyright ( c ) 2000 - 2015 , . 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 :chaos)
#|==============================================================================
System: Chaos
Module: tools
File: regularize.lisp
==============================================================================|#
#-:chaos-debug
(declaim (optimize (speed 3) (safety 0) #-GCL (debug 0)))
#+:chaos-debug
(declaim (optimize (speed 1) (safety 3) #-GCL (debug 3)))
;;; == DESCRIPTION =============================================================
;;; procedure for regularizing the signature of a module.
;;;
;;; REGULARIZE-SIGNATURE : Module -> Module'
;;; regularize a signature of given module.
;;;
(defun regularize-signature-internal (module)
;;
(unless *regularize-signature*
(return-from regularize-signature-internal nil))
;;
(with-in-module (module)
(let ((*print-indent* (+ *print-indent* 2)))
;; init.
(setf (module-sorts-for-regularity module) nil
(module-methods-for-regularity module) nil
(module-void-methods module) nil)
;;
(multiple-value-bind (empty-sorts
new-sorts
new-methods
redundant-methods
empty-methods)
(examine-regularity module)
;; declare new sorts in module
(dolist (new-sort new-sorts)
(unless (memq new-sort (module-sorts-for-regularity module))
(push new-sort (module-sorts-for-regularity module))
(add-sort-to-module new-sort module)
(declare-subsort-in-module
` ((,new-sort :< ,@(and-sort-components new-sort)))
module)
(unless *chaos-quiet*
(let ((*standard-output* *error-output*))
(print-next)
(princ "-- declaring sort [")
(print-sort-name new-sort module)
(princ " <")
(dolist (s (and-sort-components new-sort))
(princ " ")
(print-sort-name s module))
(princ "], for regularity.")))
))
;; declare new operators.
(dolist (m new-methods)
(let ((name (operator-symbol (car m)))
(ranks (cdr m)))
(dolist (rank ranks)
(multiple-value-bind (op meth)
(declare-operator-in-module name
(car rank)
(cadr rank)
module)
(declare (ignore op))
(unless *chaos-quiet*
(let ((*standard-output* *error-output*))
(print-next)
(princ "-- declaring operator ")
(print-chaos-object meth)
(princ " for regularity.")))
(pushnew meth (module-methods-for-regularity module))
))))
;; set void-methods -- not used now?
(dolist (m empty-methods)
(pushnew m (module-void-methods module) :test #'eq))
;; reports misc infos.
(unless *chaos-quiet*
(when empty-sorts
(let ((*standard-output* *error-output*))
(print-next)
(format t ">> The following sorts are empty:")
(dolist (s empty-sorts)
(print-next)
(print-sort-name s module))))
(when redundant-methods
(let ((*standard-output* *error-output*))
(print-next)
(format t ">> The following operators are detected as redundant,")
(print-next)
(format t " due to the above new operators.")
(dolist (m redundant-methods)
(print-next)
(reg-report-method m module))))
(when empty-methods
(let ((*standard-output* *error-output*))
(print-next)
(format t ">> The following operators have empty arity:")
(dolist (m empty-methods)
(print-next)
(reg-report-method m module))))
)
;;
t))))
;;;
;;; REGULARIZE-SIGNATURE
;;;
(defun regularize-signature (module)
(let ((chaos-quiet *chaos-quiet*)
;; (*chaos-verbose* t)
(*regularize-signature* t)
(*auto-reconstruct* t))
(declare (special *regularize-signature*
*auto-reconstruct*
;; *chaos-verbose*
*chaos-quiet*))
(setq *chaos-quiet* nil)
(regularize-signature-internal module)
(mark-need-parsing-preparation module)
(setq *chaos-quiet* t)
(compile-module module)
(setq *chaos-quiet* chaos-quiet)
))
EOF
| null | https://raw.githubusercontent.com/CafeOBJ/cafeobj/261e3a50407f568272321378df370e5cf7492aaf/chaos/tools/regularize.lisp | lisp | Package : CHAOS ; ; Syntax : Common - lisp -*-
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.
==============================================================================
System: Chaos
Module: tools
File: regularize.lisp
==============================================================================
== DESCRIPTION =============================================================
procedure for regularizing the signature of a module.
REGULARIZE-SIGNATURE : Module -> Module'
regularize a signature of given module.
init.
declare new sorts in module
declare new operators.
set void-methods -- not used now?
reports misc infos.
REGULARIZE-SIGNATURE
(*chaos-verbose* t)
*chaos-verbose* | Copyright ( c ) 2000 - 2015 , . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :chaos)
#-:chaos-debug
(declaim (optimize (speed 3) (safety 0) #-GCL (debug 0)))
#+:chaos-debug
(declaim (optimize (speed 1) (safety 3) #-GCL (debug 3)))
(defun regularize-signature-internal (module)
(unless *regularize-signature*
(return-from regularize-signature-internal nil))
(with-in-module (module)
(let ((*print-indent* (+ *print-indent* 2)))
(setf (module-sorts-for-regularity module) nil
(module-methods-for-regularity module) nil
(module-void-methods module) nil)
(multiple-value-bind (empty-sorts
new-sorts
new-methods
redundant-methods
empty-methods)
(examine-regularity module)
(dolist (new-sort new-sorts)
(unless (memq new-sort (module-sorts-for-regularity module))
(push new-sort (module-sorts-for-regularity module))
(add-sort-to-module new-sort module)
(declare-subsort-in-module
` ((,new-sort :< ,@(and-sort-components new-sort)))
module)
(unless *chaos-quiet*
(let ((*standard-output* *error-output*))
(print-next)
(princ "-- declaring sort [")
(print-sort-name new-sort module)
(princ " <")
(dolist (s (and-sort-components new-sort))
(princ " ")
(print-sort-name s module))
(princ "], for regularity.")))
))
(dolist (m new-methods)
(let ((name (operator-symbol (car m)))
(ranks (cdr m)))
(dolist (rank ranks)
(multiple-value-bind (op meth)
(declare-operator-in-module name
(car rank)
(cadr rank)
module)
(declare (ignore op))
(unless *chaos-quiet*
(let ((*standard-output* *error-output*))
(print-next)
(princ "-- declaring operator ")
(print-chaos-object meth)
(princ " for regularity.")))
(pushnew meth (module-methods-for-regularity module))
))))
(dolist (m empty-methods)
(pushnew m (module-void-methods module) :test #'eq))
(unless *chaos-quiet*
(when empty-sorts
(let ((*standard-output* *error-output*))
(print-next)
(format t ">> The following sorts are empty:")
(dolist (s empty-sorts)
(print-next)
(print-sort-name s module))))
(when redundant-methods
(let ((*standard-output* *error-output*))
(print-next)
(format t ">> The following operators are detected as redundant,")
(print-next)
(format t " due to the above new operators.")
(dolist (m redundant-methods)
(print-next)
(reg-report-method m module))))
(when empty-methods
(let ((*standard-output* *error-output*))
(print-next)
(format t ">> The following operators have empty arity:")
(dolist (m empty-methods)
(print-next)
(reg-report-method m module))))
)
t))))
(defun regularize-signature (module)
(let ((chaos-quiet *chaos-quiet*)
(*regularize-signature* t)
(*auto-reconstruct* t))
(declare (special *regularize-signature*
*auto-reconstruct*
*chaos-quiet*))
(setq *chaos-quiet* nil)
(regularize-signature-internal module)
(mark-need-parsing-preparation module)
(setq *chaos-quiet* t)
(compile-module module)
(setq *chaos-quiet* chaos-quiet)
))
EOF
|
a53a9eb313e5246a3cc61e183a8fbf85053710b939cc6f9c683aaa193ad96265 | labra/Haws | testLDOM.hs | module TestLDOm where
import LDOM
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Node)
import Data.Set (Set)
import qualified Data.Set as Set
import RDF
import Sets
import Typing
test_surrounding_1 = surroundingTriples (uri_s ":a") graph1 @?= surrounding_1
where graph1 = Graph( mktriples [ (":a", ":p", ":c")
, (":c", ":r", ":e")
, (":a", ":q", ":d")
, (":d", ":r", ":f")
])
surrounding_1 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
]
test_surrounding_2 = surroundingTriples (uri_s ":a") graph2 @?= surrounding_2
where graph2 = Graph (mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
])
surrounding_2 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
]
test_same_object = same_object (uri_s ":a") (triple (":c", ":r", ":a")) @?= True
Schemas
test_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_empty_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_closed_empty_succeed_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples []
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_closed_empty_succeed_no_surrounding = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":b", ":p", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_matchArc_1 = matchArc p vo t ctx @?= [emptyTyping]
where
p = u ":p"
vo = valueSet [u ":a1",u ":a2"]
cs = noTriples
t = triple (":x", ":p", ":a1")
rs = noTriples
typing = singleTyping (uri_s ":x") (u "label")
ctx = Context { schema = emptySchema, graph = emptyGraph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = emptyTyping }
s' = s { checked = insert t cs }
test_arc_single = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t]
rs = noTriples
graph = Graph ts
t = triple (":x", ":p", ":a1")
ts = Set.fromList [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_single_two = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_1ok_1bad = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_2ok = head (validate node label ctx) @?= s
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1,t2]
rs = Set.fromList []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_2_2ok = validate node label ctx @?= [s1,s2]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 2 2))])
node = uri_s ":x"
label = u "label"
cs = mkset [t1,t2]
rs = mkset []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s1 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
s2 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_3_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
t3 = triple (":x", ":p", ":a3")
ts = Set.fromList [t1,t2,t3]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_23_1_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 2 3))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_11 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_11_rem = validate node label ctx @?= [s]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_and_12 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
And (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":r", ":c")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_2 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":r", ":c")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_or_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
Closed
(Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_xor_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_xor_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_Rec = validate node shapeA ctx @?= [s]
where
schema = Schema (mkset [(shapeA, (Arc (u ":p") (ValueRef shapeA) (Range 1 1)))])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref1 = validate nodeX shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (ValueRef shapeB) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
nodeX = uri_s ":x"
nodeY = uri_s ":y"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = addType nodeY shapeB $ singleTyping nodeX shapeA
cs = mkset [t1]
rs = noTriples
t1 = triple (":x", ":p", ":y")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref2 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (valueSet [u ":a"]) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
node = uri_s ":x"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1], remaining = noTriples, typing = typ }
test_NegRec = validate node shapeA ctx @?= []
where
schema = Schema ( mkset
[(shapeA, (Not (Arc (u ":p") (ValueRef shapeA) (Range 1 1))))
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t], remaining = noTriples, typing = typ }
main = defaultMain tests
tests = [ testsGraph
, testsArc
, testsSchema
]
testsGraph =
testGroup "Graph" [
testCase "test_same_object" test_same_object
, testCase "surrounding_1" test_surrounding_1
, testCase "surrounding_2" test_surrounding_2
]
testsArc =
testGroup "ValidateArc" [
testCase "matchArc_1" test_matchArc_1
]
testsSchema =
testGroup "Schema" [
testCase "test_empty" test_empty
, testCase "test_closed_empty_fail" test_closed_empty_fail
, testCase "test_closed_empty_succeed_empty" test_closed_empty_succeed_empty
, testCase "test_closed_empty_succeed_no_surroounding" test_closed_empty_succeed_no_surrounding
, testCase "test_arc_single" test_arc_single
, testCase "test_arc_single_two" test_arc_single_two
, testCase "test_arc_12_1ok_1bad" test_arc_12_1ok_1bad
, testCase "test_arc_12_2ok" test_arc_12_2ok
, testCase "test_arc_2_2ok" test_arc_2_2ok
, testCase "test_arc_12_3_fail" test_arc_12_3_fail
, testCase "test_arc_23_1_fail" test_arc_23_1_fail
, testCase "test_arc_11" test_arc_11
, testCase "test_arc_11_rem" test_arc_11_rem
, testCase "test_and12" test_and_12
, testCase "test_or_12_1" test_or_12_1
, testCase "test_or_12_2" test_or_12_2
, testCase "test_closed_or_12_12_fail" test_closed_or_12_12_fail
, testCase "test_xor_12_12_fail" test_xor_12_12_fail
, testCase "test_xor_12_1" test_xor_12_1
, testCase "test_Rec" test_Rec
, testCase "test_Ref1" test_Ref1
, testCase "test_Ref2" test_Ref2
, testCase "test_NegRec" test_NegRec
]
| null | https://raw.githubusercontent.com/labra/Haws/2417adc37522994e2bbb8e9e397481a1f6f4f038/papers/testLDOM.hs | haskell | module TestLDOm where
import LDOM
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Node)
import Data.Set (Set)
import qualified Data.Set as Set
import RDF
import Sets
import Typing
test_surrounding_1 = surroundingTriples (uri_s ":a") graph1 @?= surrounding_1
where graph1 = Graph( mktriples [ (":a", ":p", ":c")
, (":c", ":r", ":e")
, (":a", ":q", ":d")
, (":d", ":r", ":f")
])
surrounding_1 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
]
test_surrounding_2 = surroundingTriples (uri_s ":a") graph2 @?= surrounding_2
where graph2 = Graph (mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
])
surrounding_2 = mktriples [ (":a", ":p", ":c")
, (":a", ":q", ":d")
, (":c", ":r", ":a")
]
test_same_object = same_object (uri_s ":a") (triple (":c", ":r", ":a")) @?= True
Schemas
test_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_empty_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":a", ":b", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_closed_empty_succeed_empty = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples []
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_closed_empty_succeed_no_surrounding = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Closed Empty)])
node = uri_s ":a"
label = u "label"
cs = noTriples
rs = ts
graph = Graph ts
ts = mktriples [(":b", ":p", ":c")]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = noTriples, remaining = noTriples, typing = singleTyping node label }
test_matchArc_1 = matchArc p vo t ctx @?= [emptyTyping]
where
p = u ":p"
vo = valueSet [u ":a1",u ":a2"]
cs = noTriples
t = triple (":x", ":p", ":a1")
rs = noTriples
typing = singleTyping (uri_s ":x") (u "label")
ctx = Context { schema = emptySchema, graph = emptyGraph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = emptyTyping }
s' = s { checked = insert t cs }
test_arc_single = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t]
rs = noTriples
graph = Graph ts
t = triple (":x", ":p", ":a1")
ts = Set.fromList [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_single_two = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_1ok_1bad = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) plus)])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1]
rs = Set.fromList [t2]
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":y")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_2ok = head (validate node label ctx) @?= s
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
cs = Set.fromList [t1,t2]
rs = Set.fromList []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_2_2ok = validate node label ctx @?= [s1,s2]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 2 2))])
node = uri_s ":x"
label = u "label"
cs = mkset [t1,t2]
rs = mkset []
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s1 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
s2 = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_12_3_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 1 2))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":p", ":a2")
t3 = triple (":x", ":p", ":a3")
ts = Set.fromList [t1,t2,t3]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_23_1_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2",u ":a3"]) (Range 2 3))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_arc_11 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
ts = Set.fromList [t1]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_arc_11_rem = validate node label ctx @?= [s]
where
schema = Schema (mkset [(label, Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_and_12 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
And (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = ts
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b2")
ts = Set.fromList [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t1]
rs = mkset [t2]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":r", ":c")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_or_12_2 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
)])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":r", ":c")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_closed_or_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
Closed
(Or (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
test_xor_12_12_fail = validate node label ctx @?= []
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
cs = mkset [t2]
rs = mkset [t1]
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":b1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_xor_12_1 = validate node label ctx @?= [s]
where
schema = Schema (Set.fromList [(label,
(Xor (Arc (u ":p") (valueSet [u ":a1",u ":a2"]) (Range 1 1))
(Arc (u ":q") (valueSet [u ":b1",u ":b2"]) (Range 1 1))
))])
node = uri_s ":x"
label = u "label"
graph = Graph ts
typ = singleTyping node label
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a1")
t2 = triple (":x", ":q", ":c1")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = singleTyping node label }
test_Rec = validate node shapeA ctx @?= [s]
where
schema = Schema (mkset [(shapeA, (Arc (u ":p") (ValueRef shapeA) (Range 1 1)))])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref1 = validate nodeX shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (ValueRef shapeB) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
nodeX = uri_s ":x"
nodeY = uri_s ":y"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = addType nodeY shapeB $ singleTyping nodeX shapeA
cs = mkset [t1]
rs = noTriples
t1 = triple (":x", ":p", ":y")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = cs, remaining = rs, typing = typ }
test_Ref2 = validate node shapeA ctx @?= [s]
where
schema = Schema ( mkset
[(shapeA, (Arc (u ":p") (valueSet [u ":a"]) (Range 1 1)))
,(shapeB, (Arc (u ":q") (valueSet [u ":b"]) (Range 1 1)))
])
node = uri_s ":x"
shapeA = u "shapeA"
shapeB = u "shapeB"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t1,t2]
rs = noTriples
t1 = triple (":x", ":p", ":a")
t2 = triple (":y", ":q", ":b")
ts = mkset [t1,t2]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t1], remaining = noTriples, typing = typ }
test_NegRec = validate node shapeA ctx @?= []
where
schema = Schema ( mkset
[(shapeA, (Not (Arc (u ":p") (ValueRef shapeA) (Range 1 1))))
])
node = uri_s ":x"
shapeA = u "shapeA"
graph = Graph ts
typ = singleTyping node shapeA
cs = mkset [t]
rs = noTriples
t = triple (":x", ":p", ":x")
ts = mkset [t]
ctx = Context { schema = schema, graph = graph, currentTyping = emptyTyping }
s = ValidationState { checked = mkset [t], remaining = noTriples, typing = typ }
main = defaultMain tests
tests = [ testsGraph
, testsArc
, testsSchema
]
testsGraph =
testGroup "Graph" [
testCase "test_same_object" test_same_object
, testCase "surrounding_1" test_surrounding_1
, testCase "surrounding_2" test_surrounding_2
]
testsArc =
testGroup "ValidateArc" [
testCase "matchArc_1" test_matchArc_1
]
testsSchema =
testGroup "Schema" [
testCase "test_empty" test_empty
, testCase "test_closed_empty_fail" test_closed_empty_fail
, testCase "test_closed_empty_succeed_empty" test_closed_empty_succeed_empty
, testCase "test_closed_empty_succeed_no_surroounding" test_closed_empty_succeed_no_surrounding
, testCase "test_arc_single" test_arc_single
, testCase "test_arc_single_two" test_arc_single_two
, testCase "test_arc_12_1ok_1bad" test_arc_12_1ok_1bad
, testCase "test_arc_12_2ok" test_arc_12_2ok
, testCase "test_arc_2_2ok" test_arc_2_2ok
, testCase "test_arc_12_3_fail" test_arc_12_3_fail
, testCase "test_arc_23_1_fail" test_arc_23_1_fail
, testCase "test_arc_11" test_arc_11
, testCase "test_arc_11_rem" test_arc_11_rem
, testCase "test_and12" test_and_12
, testCase "test_or_12_1" test_or_12_1
, testCase "test_or_12_2" test_or_12_2
, testCase "test_closed_or_12_12_fail" test_closed_or_12_12_fail
, testCase "test_xor_12_12_fail" test_xor_12_12_fail
, testCase "test_xor_12_1" test_xor_12_1
, testCase "test_Rec" test_Rec
, testCase "test_Ref1" test_Ref1
, testCase "test_Ref2" test_Ref2
, testCase "test_NegRec" test_NegRec
]
| |
af95f53d6cdac80930ef1abf22d7972ff75c4c495a8b976cc9e5e200b6c59a32 | mcorbin/meuse | mirror.clj | (ns meuse.mirror
"The store for the crates.io mirror."
(:require [meuse.config :as config]
[meuse.crate-file :refer [->CrateStore]]
[meuse.log :as log]
[meuse.store.protocol :as store]
[byte-streams :as bs]
[mount.core :refer [defstate]]
[clj-http.client :as http]))
(defstate mirror-store
:start
(let [crate-config (:crate config/config)]
(->CrateStore crate-config true)))
(def crates-io-base-url "")
(defn download-crate
"Download a crate file."
[crate-name version]
(let [url (str crates-io-base-url "/" crate-name "/" version "/download")]
(-> (http/get url {:as :byte-array})
:body)))
(defn download-and-save
"Download a crate file, save it in the crate mirror store, and return the
file content."
[mirror-store crate-name version]
(log/infof {} "mirror: cache crate %s %s" crate-name version)
(let [crate-file (download-crate crate-name version)]
(store/write-file mirror-store
{:name crate-name
:vers version}
crate-file)
crate-file))
| null | https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/mirror.clj | clojure | (ns meuse.mirror
"The store for the crates.io mirror."
(:require [meuse.config :as config]
[meuse.crate-file :refer [->CrateStore]]
[meuse.log :as log]
[meuse.store.protocol :as store]
[byte-streams :as bs]
[mount.core :refer [defstate]]
[clj-http.client :as http]))
(defstate mirror-store
:start
(let [crate-config (:crate config/config)]
(->CrateStore crate-config true)))
(def crates-io-base-url "")
(defn download-crate
"Download a crate file."
[crate-name version]
(let [url (str crates-io-base-url "/" crate-name "/" version "/download")]
(-> (http/get url {:as :byte-array})
:body)))
(defn download-and-save
"Download a crate file, save it in the crate mirror store, and return the
file content."
[mirror-store crate-name version]
(log/infof {} "mirror: cache crate %s %s" crate-name version)
(let [crate-file (download-crate crate-name version)]
(store/write-file mirror-store
{:name crate-name
:vers version}
crate-file)
crate-file))
| |
7fd3dd5c25af760bb35e8c7ae6b4ab5b46ee7df670395e64ce2b5b626e05f5e0 | OlivierNicole/macros-examples | demo.ml | * © , 2017 - 2018
let () =
begin
assert
(Fmt.sprintf [%fmt "(%d, %d)"] 2 3 = "(2, 3)");
assert
($(Fmt.sprintf2 [%fmt "(%d, %d)"]) 2 3 = "(2, 3)");
assert
($(Fmt.sprintf3 [%fmt "(%d, %d)"]) 2 3 = "(2, 3)");
assert
($(Fmt.sprintf4 [%fmt "(%b, %b)"]) true false = "(true, false)");
(* sscanf *)
assert
(Fmt.sscanf [%fmt "(%d, %d)"] "(2, 3)" (+) = 5);
assert
($(Fmt.sscanf2 [%fmt "(%d, %d)"]) "(2, 3)" (+) = 5);
assert
($(Fmt.sscanf3 [%fmt "(%d, %d)"]) "(2, 3)" (+) = 5);
end
| null | https://raw.githubusercontent.com/OlivierNicole/macros-examples/53a614be8aa91b44cbc9d7982dcebc40e5d22818/printf-scanf/demo.ml | ocaml | sscanf | * © , 2017 - 2018
let () =
begin
assert
(Fmt.sprintf [%fmt "(%d, %d)"] 2 3 = "(2, 3)");
assert
($(Fmt.sprintf2 [%fmt "(%d, %d)"]) 2 3 = "(2, 3)");
assert
($(Fmt.sprintf3 [%fmt "(%d, %d)"]) 2 3 = "(2, 3)");
assert
($(Fmt.sprintf4 [%fmt "(%b, %b)"]) true false = "(true, false)");
assert
(Fmt.sscanf [%fmt "(%d, %d)"] "(2, 3)" (+) = 5);
assert
($(Fmt.sscanf2 [%fmt "(%d, %d)"]) "(2, 3)" (+) = 5);
assert
($(Fmt.sscanf3 [%fmt "(%d, %d)"]) "(2, 3)" (+) = 5);
end
|
43a70700699d9825a95f0c66fd4d84181738b8c380428331b8538826cf65d030 | JPMoresmau/dbIDE | ghci_lib_test.hs | module Main where
import Test.Tasty
import Language.Haskell.Ghci.ParserTest (parserTests)
import Language.Haskell.Ghci.HighLevelTests (highLevelTests)
import Language.Haskell.Ghci.UtilsTest (utilsTests)
main::IO()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests"
[ utilsTests
, parserTests
, highLevelTests
] | null | https://raw.githubusercontent.com/JPMoresmau/dbIDE/dae37edf67fbe55660e7e22c9c5356d0ada47c61/ghci-lib/test/ghci_lib_test.hs | haskell | module Main where
import Test.Tasty
import Language.Haskell.Ghci.ParserTest (parserTests)
import Language.Haskell.Ghci.HighLevelTests (highLevelTests)
import Language.Haskell.Ghci.UtilsTest (utilsTests)
main::IO()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests"
[ utilsTests
, parserTests
, highLevelTests
] | |
92c5df78ef2ec6a4f4b6a8d689a14b0214d0e150a81cfa28c89aebff93a989c0 | damballa/parkour | join_test.clj | (ns parkour.join-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.core.reducers :as r]
[abracad.avro :as avro]
[parkour (conf :as conf) (fs :as fs) (wrapper :as w)
(mapreduce :as mr) (reducers :as pr)]
[parkour.io (dseq :as dseq) (mux :as mux) (avro :as mra)]
[parkour.util :refer [returning]]
[parkour.test-helpers :as th])
(:import [org.apache.hadoop.mapreduce.lib.input FileInputFormat]
[org.apache.hadoop.mapreduce.lib.input TextInputFormat]
[org.apache.hadoop.mapreduce.lib.output FileOutputFormat]
[parkour.hadoop Mux$Mapper]))
(use-fixtures :once th/config-fixture)
(defn mapper
[tag input]
(->> (mr/vals input)
(r/map (fn [line]
(let [[key val] (str/split line #"\s")]
[[(Long/parseLong key) tag] val])))))
(defn partitioner
^long [[key] _ ^long nparts]
(-> key hash (mod nparts)))
(defn reducer
[input]
(->> (mr/keykeyvalgroups input)
(r/mapcat (fn [[[id] keyvals]]
(let [kv-tag (comp second first), kv-val second
vals (pr/group-by+ kv-tag kv-val keyvals)
left (get vals 0), right (get vals 1)]
(for [left left, right right]
[id left right]))))
(mr/sink-as :keys)))
(defn run-join
[leftpath rightpath outpath]
(let [job (mr/job)]
(doto job
(mux/add-subconf
(as-> (mr/job job) job
(doto job
(.setInputFormatClass TextInputFormat)
(FileInputFormat/addInputPath (fs/path leftpath))
(.setMapperClass (mr/mapper! job #'mapper 0)))))
(mux/add-subconf
(as-> (mr/job job) job
(doto job
(.setInputFormatClass TextInputFormat)
(FileInputFormat/addInputPath (fs/path rightpath))
(.setMapperClass (mr/mapper! job #'mapper 1)))))
(.setMapperClass Mux$Mapper)
(mra/set-map-output {:name "key", :type "record"
:abracad.reader "vector"
:fields [{:name "id", :type "long"}
{:name "tag", :type "long"}]}
:string)
(mra/set-grouping {:name "key", :type "record"
:fields [{:name "id", :type "long"}
{:name "tag", :type "long"
:order "ignore"}]})
(.setPartitionerClass (mr/partitioner! job #'partitioner))
(.setReducerClass (mr/reducer! job #'reducer))
(mra/set-output {:name "output", :type "record",
:abracad.reader "vector"
:fields [{:name "id", :type "long"}
{:name "left", :type "string"}
{:name "right", :type "string"}]})
(FileOutputFormat/setOutputPath (fs/path outpath))
(th/config))
(.waitForCompletion job true)))
(deftest test-join
(let [leftpath (io/resource "join-left.txt")
rightpath (io/resource "join-right.txt")
outpath (fs/path "tmp/join-output")]
(with-open [outfs (fs/path-fs outpath)]
(.delete outfs outpath true))
(is (= true (run-join leftpath rightpath outpath)))
(is (= [[0 "foo" "blue"]
[0 "foo" "green"]
[0 "foo" "red"]
[1 "bar" "blue"]
[2 "baz" "green"]
[2 "baz" "red"]]
(->> (mra/dseq [:default] outpath)
(into [])
sort)))))
| null | https://raw.githubusercontent.com/damballa/parkour/2b3c5e1987e18b4c4284dfd4fcdaba267a4d7fbc/test/parkour/join_test.clj | clojure | (ns parkour.join-test
(:require [clojure.test :refer :all]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.core.reducers :as r]
[abracad.avro :as avro]
[parkour (conf :as conf) (fs :as fs) (wrapper :as w)
(mapreduce :as mr) (reducers :as pr)]
[parkour.io (dseq :as dseq) (mux :as mux) (avro :as mra)]
[parkour.util :refer [returning]]
[parkour.test-helpers :as th])
(:import [org.apache.hadoop.mapreduce.lib.input FileInputFormat]
[org.apache.hadoop.mapreduce.lib.input TextInputFormat]
[org.apache.hadoop.mapreduce.lib.output FileOutputFormat]
[parkour.hadoop Mux$Mapper]))
(use-fixtures :once th/config-fixture)
(defn mapper
[tag input]
(->> (mr/vals input)
(r/map (fn [line]
(let [[key val] (str/split line #"\s")]
[[(Long/parseLong key) tag] val])))))
(defn partitioner
^long [[key] _ ^long nparts]
(-> key hash (mod nparts)))
(defn reducer
[input]
(->> (mr/keykeyvalgroups input)
(r/mapcat (fn [[[id] keyvals]]
(let [kv-tag (comp second first), kv-val second
vals (pr/group-by+ kv-tag kv-val keyvals)
left (get vals 0), right (get vals 1)]
(for [left left, right right]
[id left right]))))
(mr/sink-as :keys)))
(defn run-join
[leftpath rightpath outpath]
(let [job (mr/job)]
(doto job
(mux/add-subconf
(as-> (mr/job job) job
(doto job
(.setInputFormatClass TextInputFormat)
(FileInputFormat/addInputPath (fs/path leftpath))
(.setMapperClass (mr/mapper! job #'mapper 0)))))
(mux/add-subconf
(as-> (mr/job job) job
(doto job
(.setInputFormatClass TextInputFormat)
(FileInputFormat/addInputPath (fs/path rightpath))
(.setMapperClass (mr/mapper! job #'mapper 1)))))
(.setMapperClass Mux$Mapper)
(mra/set-map-output {:name "key", :type "record"
:abracad.reader "vector"
:fields [{:name "id", :type "long"}
{:name "tag", :type "long"}]}
:string)
(mra/set-grouping {:name "key", :type "record"
:fields [{:name "id", :type "long"}
{:name "tag", :type "long"
:order "ignore"}]})
(.setPartitionerClass (mr/partitioner! job #'partitioner))
(.setReducerClass (mr/reducer! job #'reducer))
(mra/set-output {:name "output", :type "record",
:abracad.reader "vector"
:fields [{:name "id", :type "long"}
{:name "left", :type "string"}
{:name "right", :type "string"}]})
(FileOutputFormat/setOutputPath (fs/path outpath))
(th/config))
(.waitForCompletion job true)))
(deftest test-join
(let [leftpath (io/resource "join-left.txt")
rightpath (io/resource "join-right.txt")
outpath (fs/path "tmp/join-output")]
(with-open [outfs (fs/path-fs outpath)]
(.delete outfs outpath true))
(is (= true (run-join leftpath rightpath outpath)))
(is (= [[0 "foo" "blue"]
[0 "foo" "green"]
[0 "foo" "red"]
[1 "bar" "blue"]
[2 "baz" "green"]
[2 "baz" "red"]]
(->> (mra/dseq [:default] outpath)
(into [])
sort)))))
| |
b7b12bffa4aefcdc50c33b86f1f318fed385f2d23c3b80c43fab3adac5771918 | emqx/emqx-exhook | emqx_extension_hook_handler.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_extension_hook_handler).
-include("emqx_extension_hook.hrl").
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/logger.hrl").
-logger_header("[ExHook]").
-export([ on_client_connect/2
, on_client_connack/3
, on_client_connected/2
, on_client_disconnected/3
, on_client_authenticate/2
, on_client_check_acl/4
, on_client_subscribe/3
, on_client_unsubscribe/3
]).
%% Session Lifecircle Hooks
-export([ on_session_created/2
, on_session_subscribed/3
, on_session_unsubscribed/3
, on_session_resumed/2
, on_session_discarded/2
, on_session_takeovered/2
, on_session_terminated/3
]).
Utils
-export([ message/1
, validator/1
, assign_to_message/2
, clientinfo/1
, stringfy/1
]).
-import(emqx_extension_hook,
[ cast/2
, call_fold/4
]).
-exhooks([ {'client.connect', {?MODULE, on_client_connect, []}}
, {'client.connack', {?MODULE, on_client_connack, []}}
, {'client.connected', {?MODULE, on_client_connected, []}}
, {'client.disconnected', {?MODULE, on_client_disconnected, []}}
, {'client.authenticate', {?MODULE, on_client_authenticate, []}}
, {'client.check_acl', {?MODULE, on_client_check_acl, []}}
, {'client.subscribe', {?MODULE, on_client_subscribe, []}}
, {'client.unsubscribe', {?MODULE, on_client_unsubscribe, []}}
, {'session.created', {?MODULE, on_session_created, []}}
, {'session.subscribed', {?MODULE, on_session_subscribed, []}}
, {'session.unsubscribed',{?MODULE, on_session_unsubscribed, []}}
, {'session.resumed', {?MODULE, on_session_resumed, []}}
, {'session.discarded', {?MODULE, on_session_discarded, []}}
, {'session.takeovered', {?MODULE, on_session_takeovered, []}}
, {'session.terminated', {?MODULE, on_session_terminated, []}}
]).
%%--------------------------------------------------------------------
%% Clients
%%--------------------------------------------------------------------
on_client_connect(ConnInfo, _Props) ->
cast('client_connect', [conninfo(ConnInfo), props(_Props)]).
on_client_connack(ConnInfo, Rc, _Props) ->
cast('client_connack', [conninfo(ConnInfo), Rc, props(_Props)]).
on_client_connected(ClientInfo, _ConnInfo) ->
cast('client_connected', [clientinfo(ClientInfo)]).
on_client_disconnected(ClientInfo, {shutdown, Reason}, ConnInfo) when is_atom(Reason) ->
on_client_disconnected(ClientInfo, Reason, ConnInfo);
on_client_disconnected(ClientInfo, Reason, _ConnInfo) ->
cast('client_disconnected', [clientinfo(ClientInfo), stringfy(Reason)]).
on_client_authenticate(ClientInfo, AuthResult) ->
AccArg = maps:get(auth_result, AuthResult, undefined) == success,
Name = 'client_authenticate',
case call_fold(Name, [clientinfo(ClientInfo)], AccArg, validator(Name)) of
{stop, Bool} when is_boolean(Bool) ->
Result = case Bool of true -> success; _ -> not_authorized end,
{stop, AuthResult#{auth_result => Result, anonymous => false}};
_ ->
{ok, AuthResult}
end.
on_client_check_acl(ClientInfo, PubSub, Topic, Result) ->
AccArg = Result == allow,
Name = 'client_check_acl',
case call_fold(Name, [clientinfo(ClientInfo), PubSub, Topic], AccArg, validator(Name)) of
{stop, Bool} when is_boolean(Bool) ->
NResult = case Bool of true -> allow; _ -> deny end,
{stop, NResult};
_ -> {ok, Result}
end.
on_client_subscribe(ClientInfo, Props, TopicFilters) ->
cast('client_subscribe', [clientinfo(ClientInfo), props(Props), topicfilters(TopicFilters)]).
on_client_unsubscribe(Clientinfo, Props, TopicFilters) ->
cast('client_unsubscribe', [clientinfo(Clientinfo), props(Props), topicfilters(TopicFilters)]).
%%--------------------------------------------------------------------
%% Session
%%--------------------------------------------------------------------
on_session_created(ClientInfo, _SessInfo) ->
cast('session_created', [clientinfo(ClientInfo)]).
on_session_subscribed(Clientinfo, Topic, SubOpts) ->
cast('session_subscribed', [clientinfo(Clientinfo), Topic, props(SubOpts)]).
on_session_unsubscribed(ClientInfo, Topic, _SubOpts) ->
cast('session_unsubscribed', [clientinfo(ClientInfo), Topic]).
on_session_resumed(ClientInfo, _SessInfo) ->
cast('session_resumed', [clientinfo(ClientInfo)]).
on_session_discarded(ClientInfo, _SessInfo) ->
cast('session_discarded', [clientinfo(ClientInfo)]).
on_session_takeovered(ClientInfo, _SessInfo) ->
cast('session_takeovered', [clientinfo(ClientInfo)]).
on_session_terminated(ClientInfo, Reason, _SessInfo) ->
cast('session_terminated', [clientinfo(ClientInfo), stringfy(Reason)]).
%%--------------------------------------------------------------------
%% Types
props(undefined) -> [];
props(M) when is_map(M) -> maps:to_list(M).
conninfo(_ConnInfo =
#{clientid := ClientId, username := Username, peername := {Peerhost, _},
sockname := {_, SockPort}, proto_name := ProtoName, proto_ver := ProtoVer,
keepalive := Keepalive}) ->
[{node, node()},
{clientid, ClientId},
{username, maybe(Username)},
{peerhost, ntoa(Peerhost)},
{sockport, SockPort},
{proto_name, ProtoName},
{proto_ver, ProtoVer},
{keepalive, Keepalive}].
clientinfo(ClientInfo =
#{clientid := ClientId, username := Username, peerhost := PeerHost,
sockport := SockPort, protocol := Protocol, mountpoint := Mountpoiont}) ->
[{node, node()},
{clientid, ClientId},
{username, maybe(Username)},
{password, maybe(maps:get(password, ClientInfo, undefined))},
{peerhost, ntoa(PeerHost)},
{sockport, SockPort},
{protocol, Protocol},
{mountpoint, maybe(Mountpoiont)},
{is_superuser, maps:get(is_superuser, ClientInfo, false)},
{anonymous, maps:get(anonymous, ClientInfo, true)}].
message(#message{id = Id, qos = Qos, from = From, topic = Topic, payload = Payload, timestamp = Ts}) ->
[{node, node()},
{id, hexstr(Id)},
{qos, Qos},
{from, From},
{topic, Topic},
{payload, Payload},
{timestamp, Ts}].
topicfilters(Tfs = [{_, _}|_]) ->
[{Topic, Qos} || {Topic, #{qos := Qos}} <- Tfs];
topicfilters(Tfs) ->
Tfs.
ntoa({0,0,0,0,0,16#ffff,AB,CD}) ->
list_to_binary(inet_parse:ntoa({AB bsr 8, AB rem 256, CD bsr 8, CD rem 256}));
ntoa(IP) ->
list_to_binary(inet_parse:ntoa(IP)).
maybe(undefined) -> <<"">>;
maybe(B) -> B.
@private
stringfy(Term) when is_binary(Term) ->
Term;
stringfy(Term) when is_atom(Term) ->
atom_to_binary(Term, utf8);
stringfy(Term) when is_tuple(Term) ->
iolist_to_binary(io_lib:format("~p", [Term])).
hexstr(B) ->
iolist_to_binary([io_lib:format("~2.16.0B", [X]) || X <- binary_to_list(B)]).
%%--------------------------------------------------------------------
%% Validator funcs
validator(Name) ->
fun(V) -> validate_acc_arg(Name, V) end.
validate_acc_arg('client_authenticate', V) when is_boolean(V) -> true;
validate_acc_arg('client_check_acl', V) when is_boolean(V) -> true;
validate_acc_arg('message_publish', V) when is_list(V) -> validate_msg(V, true);
validate_acc_arg(_, _) -> false.
validate_msg([], Bool) ->
Bool;
validate_msg(_, false) ->
false;
validate_msg([{topic, T} | More], _) ->
validate_msg(More, is_binary(T));
validate_msg([{payload, P} | More], _) ->
validate_msg(More, is_binary(P));
validate_msg([{qos, Q} | More], _) ->
validate_msg(More, Q =< 2 andalso Q >= 0);
validate_msg([{timestamp, T} | More], _) ->
validate_msg(More, is_integer(T));
validate_msg([_ | More], _) ->
validate_msg(More, true).
%%--------------------------------------------------------------------
%% Misc
assign_to_message([], Message) ->
Message;
assign_to_message([{topic, Topic}|More], Message) ->
assign_to_message(More, Message#message{topic = Topic});
assign_to_message([{qos, Qos}|More], Message) ->
assign_to_message(More, Message#message{qos = Qos});
assign_to_message([{payload, Payload}|More], Message) ->
assign_to_message(More, Message#message{payload = Payload});
assign_to_message([_|More], Message) ->
assign_to_message(More, Message).
| null | https://raw.githubusercontent.com/emqx/emqx-exhook/906ba8c0ac907414b85738c24c7dbef880da844e/src/emqx_extension_hook_handler.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
Session Lifecircle Hooks
--------------------------------------------------------------------
Clients
--------------------------------------------------------------------
--------------------------------------------------------------------
Session
--------------------------------------------------------------------
--------------------------------------------------------------------
Types
--------------------------------------------------------------------
Validator funcs
--------------------------------------------------------------------
Misc | Copyright ( c ) 2020 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_extension_hook_handler).
-include("emqx_extension_hook.hrl").
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/logger.hrl").
-logger_header("[ExHook]").
-export([ on_client_connect/2
, on_client_connack/3
, on_client_connected/2
, on_client_disconnected/3
, on_client_authenticate/2
, on_client_check_acl/4
, on_client_subscribe/3
, on_client_unsubscribe/3
]).
-export([ on_session_created/2
, on_session_subscribed/3
, on_session_unsubscribed/3
, on_session_resumed/2
, on_session_discarded/2
, on_session_takeovered/2
, on_session_terminated/3
]).
Utils
-export([ message/1
, validator/1
, assign_to_message/2
, clientinfo/1
, stringfy/1
]).
-import(emqx_extension_hook,
[ cast/2
, call_fold/4
]).
-exhooks([ {'client.connect', {?MODULE, on_client_connect, []}}
, {'client.connack', {?MODULE, on_client_connack, []}}
, {'client.connected', {?MODULE, on_client_connected, []}}
, {'client.disconnected', {?MODULE, on_client_disconnected, []}}
, {'client.authenticate', {?MODULE, on_client_authenticate, []}}
, {'client.check_acl', {?MODULE, on_client_check_acl, []}}
, {'client.subscribe', {?MODULE, on_client_subscribe, []}}
, {'client.unsubscribe', {?MODULE, on_client_unsubscribe, []}}
, {'session.created', {?MODULE, on_session_created, []}}
, {'session.subscribed', {?MODULE, on_session_subscribed, []}}
, {'session.unsubscribed',{?MODULE, on_session_unsubscribed, []}}
, {'session.resumed', {?MODULE, on_session_resumed, []}}
, {'session.discarded', {?MODULE, on_session_discarded, []}}
, {'session.takeovered', {?MODULE, on_session_takeovered, []}}
, {'session.terminated', {?MODULE, on_session_terminated, []}}
]).
on_client_connect(ConnInfo, _Props) ->
cast('client_connect', [conninfo(ConnInfo), props(_Props)]).
on_client_connack(ConnInfo, Rc, _Props) ->
cast('client_connack', [conninfo(ConnInfo), Rc, props(_Props)]).
on_client_connected(ClientInfo, _ConnInfo) ->
cast('client_connected', [clientinfo(ClientInfo)]).
on_client_disconnected(ClientInfo, {shutdown, Reason}, ConnInfo) when is_atom(Reason) ->
on_client_disconnected(ClientInfo, Reason, ConnInfo);
on_client_disconnected(ClientInfo, Reason, _ConnInfo) ->
cast('client_disconnected', [clientinfo(ClientInfo), stringfy(Reason)]).
on_client_authenticate(ClientInfo, AuthResult) ->
AccArg = maps:get(auth_result, AuthResult, undefined) == success,
Name = 'client_authenticate',
case call_fold(Name, [clientinfo(ClientInfo)], AccArg, validator(Name)) of
{stop, Bool} when is_boolean(Bool) ->
Result = case Bool of true -> success; _ -> not_authorized end,
{stop, AuthResult#{auth_result => Result, anonymous => false}};
_ ->
{ok, AuthResult}
end.
on_client_check_acl(ClientInfo, PubSub, Topic, Result) ->
AccArg = Result == allow,
Name = 'client_check_acl',
case call_fold(Name, [clientinfo(ClientInfo), PubSub, Topic], AccArg, validator(Name)) of
{stop, Bool} when is_boolean(Bool) ->
NResult = case Bool of true -> allow; _ -> deny end,
{stop, NResult};
_ -> {ok, Result}
end.
on_client_subscribe(ClientInfo, Props, TopicFilters) ->
cast('client_subscribe', [clientinfo(ClientInfo), props(Props), topicfilters(TopicFilters)]).
on_client_unsubscribe(Clientinfo, Props, TopicFilters) ->
cast('client_unsubscribe', [clientinfo(Clientinfo), props(Props), topicfilters(TopicFilters)]).
on_session_created(ClientInfo, _SessInfo) ->
cast('session_created', [clientinfo(ClientInfo)]).
on_session_subscribed(Clientinfo, Topic, SubOpts) ->
cast('session_subscribed', [clientinfo(Clientinfo), Topic, props(SubOpts)]).
on_session_unsubscribed(ClientInfo, Topic, _SubOpts) ->
cast('session_unsubscribed', [clientinfo(ClientInfo), Topic]).
on_session_resumed(ClientInfo, _SessInfo) ->
cast('session_resumed', [clientinfo(ClientInfo)]).
on_session_discarded(ClientInfo, _SessInfo) ->
cast('session_discarded', [clientinfo(ClientInfo)]).
on_session_takeovered(ClientInfo, _SessInfo) ->
cast('session_takeovered', [clientinfo(ClientInfo)]).
on_session_terminated(ClientInfo, Reason, _SessInfo) ->
cast('session_terminated', [clientinfo(ClientInfo), stringfy(Reason)]).
props(undefined) -> [];
props(M) when is_map(M) -> maps:to_list(M).
conninfo(_ConnInfo =
#{clientid := ClientId, username := Username, peername := {Peerhost, _},
sockname := {_, SockPort}, proto_name := ProtoName, proto_ver := ProtoVer,
keepalive := Keepalive}) ->
[{node, node()},
{clientid, ClientId},
{username, maybe(Username)},
{peerhost, ntoa(Peerhost)},
{sockport, SockPort},
{proto_name, ProtoName},
{proto_ver, ProtoVer},
{keepalive, Keepalive}].
clientinfo(ClientInfo =
#{clientid := ClientId, username := Username, peerhost := PeerHost,
sockport := SockPort, protocol := Protocol, mountpoint := Mountpoiont}) ->
[{node, node()},
{clientid, ClientId},
{username, maybe(Username)},
{password, maybe(maps:get(password, ClientInfo, undefined))},
{peerhost, ntoa(PeerHost)},
{sockport, SockPort},
{protocol, Protocol},
{mountpoint, maybe(Mountpoiont)},
{is_superuser, maps:get(is_superuser, ClientInfo, false)},
{anonymous, maps:get(anonymous, ClientInfo, true)}].
message(#message{id = Id, qos = Qos, from = From, topic = Topic, payload = Payload, timestamp = Ts}) ->
[{node, node()},
{id, hexstr(Id)},
{qos, Qos},
{from, From},
{topic, Topic},
{payload, Payload},
{timestamp, Ts}].
topicfilters(Tfs = [{_, _}|_]) ->
[{Topic, Qos} || {Topic, #{qos := Qos}} <- Tfs];
topicfilters(Tfs) ->
Tfs.
ntoa({0,0,0,0,0,16#ffff,AB,CD}) ->
list_to_binary(inet_parse:ntoa({AB bsr 8, AB rem 256, CD bsr 8, CD rem 256}));
ntoa(IP) ->
list_to_binary(inet_parse:ntoa(IP)).
maybe(undefined) -> <<"">>;
maybe(B) -> B.
@private
stringfy(Term) when is_binary(Term) ->
Term;
stringfy(Term) when is_atom(Term) ->
atom_to_binary(Term, utf8);
stringfy(Term) when is_tuple(Term) ->
iolist_to_binary(io_lib:format("~p", [Term])).
hexstr(B) ->
iolist_to_binary([io_lib:format("~2.16.0B", [X]) || X <- binary_to_list(B)]).
validator(Name) ->
fun(V) -> validate_acc_arg(Name, V) end.
validate_acc_arg('client_authenticate', V) when is_boolean(V) -> true;
validate_acc_arg('client_check_acl', V) when is_boolean(V) -> true;
validate_acc_arg('message_publish', V) when is_list(V) -> validate_msg(V, true);
validate_acc_arg(_, _) -> false.
validate_msg([], Bool) ->
Bool;
validate_msg(_, false) ->
false;
validate_msg([{topic, T} | More], _) ->
validate_msg(More, is_binary(T));
validate_msg([{payload, P} | More], _) ->
validate_msg(More, is_binary(P));
validate_msg([{qos, Q} | More], _) ->
validate_msg(More, Q =< 2 andalso Q >= 0);
validate_msg([{timestamp, T} | More], _) ->
validate_msg(More, is_integer(T));
validate_msg([_ | More], _) ->
validate_msg(More, true).
assign_to_message([], Message) ->
Message;
assign_to_message([{topic, Topic}|More], Message) ->
assign_to_message(More, Message#message{topic = Topic});
assign_to_message([{qos, Qos}|More], Message) ->
assign_to_message(More, Message#message{qos = Qos});
assign_to_message([{payload, Payload}|More], Message) ->
assign_to_message(More, Message#message{payload = Payload});
assign_to_message([_|More], Message) ->
assign_to_message(More, Message).
|
4ccd9153da61781ae2a1585fb746aec058d419e9a7665fc2f88dd4177e62dec8 | omnyway-labs/amplitude | example.cljs | (ns amplitude.example
(:require
[reagent.core :as r]
[amplitude.rest :as rest]
[amplitude.graphql :as graphql]
[amplitude.auth :as auth]
[amplitude.config :as config]
[amplitude.cache :as cache]
[amplitude.storage :as storage]
[amplitude.log :as log]
["/aws-exports.js" :default awsmobile]))
(defn view []
[:h1 "Amplitude!"])
(defn init-view! []
(r/render [view]
(.getElementById js/document "app")))
(defn init []
(init-view!)
(config/init! awsmobile)
(rest/init!)
(cache/init!)
(log/init!))
| null | https://raw.githubusercontent.com/omnyway-labs/amplitude/4c8468070b70ed49c9293e4fa87e44ce79f3d2aa/example/src/amplitude/example.cljs | clojure | (ns amplitude.example
(:require
[reagent.core :as r]
[amplitude.rest :as rest]
[amplitude.graphql :as graphql]
[amplitude.auth :as auth]
[amplitude.config :as config]
[amplitude.cache :as cache]
[amplitude.storage :as storage]
[amplitude.log :as log]
["/aws-exports.js" :default awsmobile]))
(defn view []
[:h1 "Amplitude!"])
(defn init-view! []
(r/render [view]
(.getElementById js/document "app")))
(defn init []
(init-view!)
(config/init! awsmobile)
(rest/init!)
(cache/init!)
(log/init!))
| |
7b0dfba1f49756b0ac51658202712ad4bb66b28cbeea29ce7b93067d2199dd00 | babashka/neil | test_util.clj | (ns babashka.neil.test-util
(:require [babashka.fs :as fs]
[babashka.neil :as neil-main]
[babashka.process :as process]
[clojure.edn :as edn]
[clojure.string :as str]))
(def test-dir (str (fs/file (fs/temp-dir) "neil")))
(defn reset-test-dir []
(fs/delete-tree test-dir))
(defn test-file [name]
(doto (fs/file test-dir name)
(-> fs/parent (fs/create-dirs))
(fs/delete-on-exit)))
(defn read-deps-edn []
(edn/read-string (slurp (test-file "deps.edn"))))
(defn set-deps-edn! [x]
(spit (test-file "deps.edn") (pr-str x)))
(defn neil [cli-args & {:keys [deps-file dry-run out] :or {out :string}}]
(let [backup-deps-file (str (test-file "deps.edn"))
cli-args' (concat (if (string? cli-args)
(process/tokenize cli-args)
cli-args)
[:deps-file (or deps-file backup-deps-file)]
(when dry-run [:dry-run "true"]))
cli-args' (mapv str cli-args')]
(binding [*command-line-args* cli-args']
(let [s (with-out-str (apply neil-main/-main cli-args'))]
{:out (if (#{:edn} out) (edn/read-string s) (str/trim s))}))))
| null | https://raw.githubusercontent.com/babashka/neil/02f450fc723a0d953c527e7644897c88cf01b658/test/babashka/neil/test_util.clj | clojure | (ns babashka.neil.test-util
(:require [babashka.fs :as fs]
[babashka.neil :as neil-main]
[babashka.process :as process]
[clojure.edn :as edn]
[clojure.string :as str]))
(def test-dir (str (fs/file (fs/temp-dir) "neil")))
(defn reset-test-dir []
(fs/delete-tree test-dir))
(defn test-file [name]
(doto (fs/file test-dir name)
(-> fs/parent (fs/create-dirs))
(fs/delete-on-exit)))
(defn read-deps-edn []
(edn/read-string (slurp (test-file "deps.edn"))))
(defn set-deps-edn! [x]
(spit (test-file "deps.edn") (pr-str x)))
(defn neil [cli-args & {:keys [deps-file dry-run out] :or {out :string}}]
(let [backup-deps-file (str (test-file "deps.edn"))
cli-args' (concat (if (string? cli-args)
(process/tokenize cli-args)
cli-args)
[:deps-file (or deps-file backup-deps-file)]
(when dry-run [:dry-run "true"]))
cli-args' (mapv str cli-args')]
(binding [*command-line-args* cli-args']
(let [s (with-out-str (apply neil-main/-main cli-args'))]
{:out (if (#{:edn} out) (edn/read-string s) (str/trim s))}))))
| |
24a13857c4ba65b702c1a48e039e7498ca670657d5f57223e38d696343dcc920 | ocaml-community/ISO8601.ml | UTILS_TEST.ml | let test a b =
OUnit.(>::)
(string_of_float a)
(fun _ -> OUnit.assert_equal
~cmp:(OUnit.cmp_float ~epsilon:Stdlib.epsilon_float)
~printer:string_of_float
a b)
let suite =
let mkdatetime = Utils.mkdatetime in
let mkdate = Utils.mkdate in
let mktime = Utils.mktime in
OUnit.(>:::) "[UTILS]" [
OUnit.(>:::) "[UTILS mkdatetime]"
[
test 0. (mkdatetime 1970 1 1 0 0 0) ;
test 1. (mkdatetime 1970 1 1 0 0 1) ;
test 60. (mkdatetime 1970 1 1 0 1 0) ;
test 3600. (mkdatetime 1970 1 1 1 0 0) ;
test (31. *. 24. *. 3600.)
(mkdatetime 1970 2 1 0 0 0) ;
test (365. *. 24. *. 3600.) (* not leap year *)
(mkdatetime 1971 1 1 0 0 0) ;
] ;
OUnit.(>:::) "[UTILS mkdate]"
[
test 0. (mkdate 1970 1 1) ;
test (24. *. 3600.) (mkdate 1970 1 2) ;
test (31. *. 24. *. 3600.) (mkdate 1970 2 1) ;
test (365. *. 24. *. 3600.) (mkdate 1971 1 1) ;
test 583804800. (mkdate 1988 7 2) ;
] ;
OUnit.(>:::) "[UTILS mktime]"
[
test 0. (mktime 0. 0. 0.) ;
test 60. (mktime 0. 1. 0.) ;
test 1. (mktime 0. 0. 1.) ;
]
]
| null | https://raw.githubusercontent.com/ocaml-community/ISO8601.ml/4c6820de3098a5e0b00503b899456297706dc0a5/tests/UTILS_TEST.ml | ocaml | not leap year | let test a b =
OUnit.(>::)
(string_of_float a)
(fun _ -> OUnit.assert_equal
~cmp:(OUnit.cmp_float ~epsilon:Stdlib.epsilon_float)
~printer:string_of_float
a b)
let suite =
let mkdatetime = Utils.mkdatetime in
let mkdate = Utils.mkdate in
let mktime = Utils.mktime in
OUnit.(>:::) "[UTILS]" [
OUnit.(>:::) "[UTILS mkdatetime]"
[
test 0. (mkdatetime 1970 1 1 0 0 0) ;
test 1. (mkdatetime 1970 1 1 0 0 1) ;
test 60. (mkdatetime 1970 1 1 0 1 0) ;
test 3600. (mkdatetime 1970 1 1 1 0 0) ;
test (31. *. 24. *. 3600.)
(mkdatetime 1970 2 1 0 0 0) ;
(mkdatetime 1971 1 1 0 0 0) ;
] ;
OUnit.(>:::) "[UTILS mkdate]"
[
test 0. (mkdate 1970 1 1) ;
test (24. *. 3600.) (mkdate 1970 1 2) ;
test (31. *. 24. *. 3600.) (mkdate 1970 2 1) ;
test (365. *. 24. *. 3600.) (mkdate 1971 1 1) ;
test 583804800. (mkdate 1988 7 2) ;
] ;
OUnit.(>:::) "[UTILS mktime]"
[
test 0. (mktime 0. 0. 0.) ;
test 60. (mktime 0. 1. 0.) ;
test 1. (mktime 0. 0. 1.) ;
]
]
|
449a32ef2bbc3c82aedf1e3fd88d635a2989bffa5f6ab3462b43e2f9c474ef3d | fresnel/fresnel | Test.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE TemplateHaskell #
module Iso.Test
( validIso
, invalidIso
, withRoundtrips
, tests
) where
import Fresnel.Getter
import Fresnel.Iso
import Fresnel.Review
import Test.Group
import Test.QuickCheck
validIso :: (Eq a, Show a, Eq s, Show s) => Iso' s a -> s -> a -> Property
validIso o s a = withRoundtrips o $ \ ss aa -> ss s === s .&&. aa a === a
invalidIso :: (Eq a, Show a, Eq s, Show s) => Iso' s a -> s -> a -> Property
invalidIso o s a = withRoundtrips o $ \ ss aa -> ss s =/= s .||. aa a =/= a
withRoundtrips :: Iso' s a -> (((s -> s) -> (a -> a) -> r) -> r)
withRoundtrips o k = withIso o (\ f g -> k (g . f) (f . g))
prop_view_elimination f g x = view (iso (applyFun f) (applyFun g)) x === applyFun f x
prop_review_elimination f g x = review (iso (applyFun f) (applyFun g)) x === applyFun g x
prop_constant_validity c s a = withRoundtrips (constant c) $ \ sasa aa ->
sasa (const a) s === const a s .&&. aa a === a
prop_involuted_validity = validIso (involuted not)
prop_involuted_invalidity = invalidIso (involuted (+ (1 :: Integer)))
pure []
tests :: Entry
tests = $deriveGroup
| null | https://raw.githubusercontent.com/fresnel/fresnel/8f0d267779703049568694834c25f619034ca74d/fresnel/test/Iso/Test.hs | haskell | # LANGUAGE RankNTypes # | # LANGUAGE TemplateHaskell #
module Iso.Test
( validIso
, invalidIso
, withRoundtrips
, tests
) where
import Fresnel.Getter
import Fresnel.Iso
import Fresnel.Review
import Test.Group
import Test.QuickCheck
validIso :: (Eq a, Show a, Eq s, Show s) => Iso' s a -> s -> a -> Property
validIso o s a = withRoundtrips o $ \ ss aa -> ss s === s .&&. aa a === a
invalidIso :: (Eq a, Show a, Eq s, Show s) => Iso' s a -> s -> a -> Property
invalidIso o s a = withRoundtrips o $ \ ss aa -> ss s =/= s .||. aa a =/= a
withRoundtrips :: Iso' s a -> (((s -> s) -> (a -> a) -> r) -> r)
withRoundtrips o k = withIso o (\ f g -> k (g . f) (f . g))
prop_view_elimination f g x = view (iso (applyFun f) (applyFun g)) x === applyFun f x
prop_review_elimination f g x = review (iso (applyFun f) (applyFun g)) x === applyFun g x
prop_constant_validity c s a = withRoundtrips (constant c) $ \ sasa aa ->
sasa (const a) s === const a s .&&. aa a === a
prop_involuted_validity = validIso (involuted not)
prop_involuted_invalidity = invalidIso (involuted (+ (1 :: Integer)))
pure []
tests :: Entry
tests = $deriveGroup
|
d0f532bbc475e8baa9d883d71ecc83d8dac02b0bb65384b01fb16312b9a9c575 | juhp/koji-tool | Time.hs | # LANGUAGE CPP #
module Time (
compactZonedTime,
lookupTime,
lookupTimes,
lookupTimes',
durationOfTask,
formatLocalTime,
renderDuration,
UTCTime)
where
import Data.Time.Clock
import Data.Time.Clock.System
import Data.Time.Format
import Data.Time.LocalTime
import Distribution.Koji.API (Struct, lookupStruct)
readTime' :: Double -> UTCTime
readTime' =
let mkSystemTime t = MkSystemTime t 0
in systemToUTCTime . mkSystemTime . truncate
compactZonedTime :: TimeZone -> UTCTime -> String
compactZonedTime tz =
formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S%Z" . utcToZonedTime tz
lookupTime :: Bool -> Struct -> Maybe UTCTime
lookupTime completion str = do
case lookupStruct (prefix ++ "_ts") str of
Just ts -> return $ readTime' ts
Nothing ->
lookupStruct (prefix ++ "_time") str >>=
parseTimeM False defaultTimeLocale "%Y-%m-%d %H:%M:%S%Q%EZ"
where
prefix = if completion then "completion" else "start"
lookupTimes :: Struct -> Maybe (UTCTime, Maybe UTCTime)
lookupTimes str = do
start <- lookupTime False str
let mend = lookupTime True str
return (start,mend)
lookupTimes' :: Struct -> (UTCTime, UTCTime)
lookupTimes' str =
case lookupTimes str of
Nothing -> error "no start time for task"
Just (start,mend) ->
case mend of
Nothing -> error "no end time for task"
Just end -> (start,end)
durationOfTask :: Struct -> Maybe NominalDiffTime
durationOfTask str = do
(start,mend) <- lookupTimes str
end <- mend
return $ diffUTCTime end start
formatLocalTime :: Bool -> TimeZone -> UTCTime -> String
formatLocalTime start tz t =
formatTime defaultTimeLocale (if start then "Start: %c" else "End: %c") $
utcToZonedTime tz t
renderDuration :: Bool -> NominalDiffTime -> String
#if MIN_VERSION_time(1,9,0)
renderDuration short dur =
let fmtstr
| dur < 60 = "%s" ++ secs
| dur < 3600 = "%m" ++ mins ++ " %S" ++ secs
| otherwise = "%h" ++ hrs ++ " %M" ++ mins
in formatTime defaultTimeLocale fmtstr dur
where
secs = if short then "s" else " sec"
mins = if short then "m" else " min"
hrs = if short then "h" else " hours"
#else
renderDuration short dur =
show dur ++ if short then "" else "ec"
#endif
| null | https://raw.githubusercontent.com/juhp/koji-tool/8f98c3b7a2381ae38e08211da374c5a8d1e5e311/src/Time.hs | haskell | # LANGUAGE CPP #
module Time (
compactZonedTime,
lookupTime,
lookupTimes,
lookupTimes',
durationOfTask,
formatLocalTime,
renderDuration,
UTCTime)
where
import Data.Time.Clock
import Data.Time.Clock.System
import Data.Time.Format
import Data.Time.LocalTime
import Distribution.Koji.API (Struct, lookupStruct)
readTime' :: Double -> UTCTime
readTime' =
let mkSystemTime t = MkSystemTime t 0
in systemToUTCTime . mkSystemTime . truncate
compactZonedTime :: TimeZone -> UTCTime -> String
compactZonedTime tz =
formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S%Z" . utcToZonedTime tz
lookupTime :: Bool -> Struct -> Maybe UTCTime
lookupTime completion str = do
case lookupStruct (prefix ++ "_ts") str of
Just ts -> return $ readTime' ts
Nothing ->
lookupStruct (prefix ++ "_time") str >>=
parseTimeM False defaultTimeLocale "%Y-%m-%d %H:%M:%S%Q%EZ"
where
prefix = if completion then "completion" else "start"
lookupTimes :: Struct -> Maybe (UTCTime, Maybe UTCTime)
lookupTimes str = do
start <- lookupTime False str
let mend = lookupTime True str
return (start,mend)
lookupTimes' :: Struct -> (UTCTime, UTCTime)
lookupTimes' str =
case lookupTimes str of
Nothing -> error "no start time for task"
Just (start,mend) ->
case mend of
Nothing -> error "no end time for task"
Just end -> (start,end)
durationOfTask :: Struct -> Maybe NominalDiffTime
durationOfTask str = do
(start,mend) <- lookupTimes str
end <- mend
return $ diffUTCTime end start
formatLocalTime :: Bool -> TimeZone -> UTCTime -> String
formatLocalTime start tz t =
formatTime defaultTimeLocale (if start then "Start: %c" else "End: %c") $
utcToZonedTime tz t
renderDuration :: Bool -> NominalDiffTime -> String
#if MIN_VERSION_time(1,9,0)
renderDuration short dur =
let fmtstr
| dur < 60 = "%s" ++ secs
| dur < 3600 = "%m" ++ mins ++ " %S" ++ secs
| otherwise = "%h" ++ hrs ++ " %M" ++ mins
in formatTime defaultTimeLocale fmtstr dur
where
secs = if short then "s" else " sec"
mins = if short then "m" else " min"
hrs = if short then "h" else " hours"
#else
renderDuration short dur =
show dur ++ if short then "" else "ec"
#endif
| |
3a325f324809db6417d89b4aec2c4c4659242d373710b2502470961a69149a1e | herd/herdtools7 | config.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2010 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
open Printf
open Code
let verbose = ref 0
let libdir = ref (Filename.concat Version.libdir "herd")
let nprocs = ref 4
let size = ref 6
let one = ref false
let arch = ref (`PPC: Archs.t)
let typ = ref TypBase.default
let hexa = ref false
let tarfile = ref None
let prefix = ref []
let safes = ref []
let relaxs = ref []
let name = ref None
let sufname = ref None
let canonical_only = ref true
let conf = ref None
let mode = ref Default
let mix = ref false
let max_ins = ref 4
let eprocs = ref false
let max_relax = ref 100
let min_relax = ref 1
type 'a cumul = Empty | All | Set of 'a
let cumul = ref All
let poll = ref false
let docheck = ref false
let fmt = ref 3
let no = ref None
let addnum = ref true
let lowercase = ref false
let optcoherence = ref false
let bell = ref None
let scope = ref Scope.No
let variant = ref (fun (_:Variant_gen.t) -> false)
let rejects = ref None
let stdout = ref false
let cycleonly = ref false
let info = ref ([]:MiscParser.info)
let add_info_line line = match LexScan.info line with
| Some kv -> info := !info @ [kv]
| None ->
let msg =
Printf.sprintf "argument '%s' is not in 'key = value' format" line in
raise (Arg.Bad msg)
type do_observers =
| Avoid (* was false *)
| Accept (* was true *)
| Enforce (* is new *)
| Local (* Local observer when possible *)
| Three (* Accept up to three writes, no observers *)
Accept up to four writes , no observers
| Infinity (* Accept all tests, no observers *)
let do_observers = ref Avoid
type obs_type = Straight | Fenced | Loop
let obs_type = ref Straight
let upto = ref true
let optcond = ref true
let overload = ref None
let neg = ref false
let unrollatomic : int option ref = ref None
let same_loc = ref false
type cond = Cycle | Unicond | Observe
let cond = ref Cycle
let hout = ref None
type show = Edges | Annotations | Fences
let show = ref (None:ShowGen.t option)
let debug = ref Debug_gen.none
let moreedges = ref false
let realdep = ref false
let parse_cond tag = match tag with
| "cycle" -> Cycle
| "unicond" -> Unicond
| "observe" -> Observe
| _ -> failwith "Wrong cond, choose cycle, unicond or observe"
let parse_mode s =
match s with
| "default"|"def" -> Default
| "sc" -> Sc
| "thin" -> Thin
| "uni" -> Uni
| "critical" -> Critical
| "free" -> Free
| "ppo" -> Ppo
| "transitive"|"trans" -> Transitive
| "total" -> Total
| "mixed" -> MixedCheck
| _ ->
failwith
(Printf.sprintf
"Wrong mode: choose %s"
(String.concat "," Code.checks))
let parse_do_observers s = match s with
| "avoid"|"false" -> Avoid
| "accept"|"true" -> Accept
| "force" -> Enforce
| "local" -> Local
| "three" -> Three
| "four" -> Four
| "oo"|"infinity" -> Infinity
| _ -> failwith "Wrong observer mode, choose avoid, accept, force, local, three or four"
let parse_obs_type = function
| "straight" -> Straight
| "fenced" -> Fenced
| "loop" -> Loop
| _ -> failwith "Wrong observer style, choose straight, fenced or loop"
let parse_cumul = function
| "false" -> Empty
| "true" -> All
| s -> Set s
(* Helpers *)
let common_specs () =
("-v", Arg.Unit (fun () -> incr verbose)," be verbose")::
("-version", Arg.Unit (fun () -> print_endline Version.version ; exit 0),
" show version number and exit")::
("-set-libdir", Arg.String (fun s -> libdir := s),
" <path> path to libdir")::
Util.parse_tag "-debug"
(fun tag -> match Debug_gen.parse !debug tag with
| None -> false
| Some d -> debug := d ; true)
Debug_gen.tags "specify debugged part"::
Util.parse_tag
"-arch"
(fun tag -> match Archs.parse tag with
| None -> false
| Some a -> arch := a ; true)
Archs.tags "specify architecture"::
("-bell",
Arg.String (fun f -> arch := Archs.lisa ; bell := Some f),
"<name> read bell file <name>, implies -arch LISA")::
Util.parse_tag
"-scopes"
(fun tag -> match Scope.parse tag with
| None -> false
| Some a -> scope := a; true)
Scope.tags "<tag> specifiy scope tree"::
Util.parse_tag
"-type"
(fun tag -> match TypBase.parse tag with
| None -> false
| Some a -> typ := a ; true)
TypBase.tags
(sprintf "specify base type, default %s" (TypBase.pp !typ))::
Util.parse_tags
"-variant"
(fun tag -> match Variant_gen.parse tag with
| None -> false
| Some v0 ->
let open Variant_gen in
let ov =
let ov = !variant in
match v0 with
Special case : Mixed cancels FullMixed
(function
| FullMixed -> false
| v-> ov v)
Special case : cancels FullKVM
(function
| FullKVM -> false
| v-> ov v)
| _ -> ov in
variant := (fun v -> v = v0 || ov v) ;
true)
Variant_gen.tags
(sprintf "specify variant")::
("-hexa", Arg.Unit (fun () -> hexa := true),"hexadecimal output")::
("-o", Arg.String (fun s -> tarfile := Some s),
"<name.tar> output litmus tests in archive <name.tar> (default, output in curent directory)")::
("-c", Arg.Bool (fun b -> canonical_only := b),
sprintf "<b> avoid equivalent cycles (default %b)" !canonical_only)::
("-list",
Arg.Unit (fun () -> show := Some ShowGen.Edges),
"list accepted edge syntax and exit")::
("-show", Arg.String (fun s -> show := Some (ShowGen.parse s)),
"<edges|annotations|fences> list accepted edges, annotations or fences, and exit")::
("-switch", Arg.Set Misc.switch, "switch something")::
("-obs",
Arg.String (fun s -> do_observers := parse_do_observers s),
"<accept|avoid|force|local> enable observers (default avoid)")::
("-obstype",
Arg.String (fun s -> obs_type := parse_obs_type s),
"<fenced|loop|straight> style of observers (default fenced)")::
("-optcond", Arg.Set optcond, " optimize conditions (default)")::
("-nooptcond", Arg.Clear optcond, "do not optimize conditions")::
("-optcoherence", Arg.Set optcoherence, " optimize coherence")::
("-nooptcoherence", Arg.Clear optcoherence, "do not optimize coherence (default)")::
("-info",Arg.String add_info_line,"add metadata to generated test(s)")::
("-moreedges", Arg.Bool (fun b -> moreedges := b),
Printf.sprintf
"consider a very complete set of edges, default %b" !moreedges)::
("-realdep", Arg.Bool (fun b -> realdep := b),
Printf.sprintf
"output \"real\" dependencies, default %b" !moreedges)::
("-overload", Arg.Int (fun n -> overload := Some n),
"<n> stress load unit by <n> useless loads")::
("-unrollatomic",Arg.Int (fun i -> unrollatomic := Some i),
"<n> unroll atomic idioms (default, use loops)")::
("-ua",Arg.Int (fun i -> unrollatomic := Some i),
"<n> shorthand for -unrollatomic <n>")::
("-poll",Arg.Bool (fun b -> poll := b),
"<bool> poll on loaded values, as much as possible")::
("-check",Arg.Bool (fun b -> docheck := b),
"<bool> check loaded values in test code")::
("-neg", Arg.Bool (fun b -> neg := b),
"<bool> negate final condition (default false)")::
("-coherence_decreasing", Arg.Unit (fun () -> ()),
" does nothing, deprecated")::
("-oneloc", Arg.Set same_loc,
"Do not fail on tests with one single location (default false)")::
("-cond",
Arg.String (fun s -> cond := parse_cond s),
"<cycle|unicond|observe> style of final condition, default cycle")::
("-unicond", Arg.Unit (fun () -> cond := Unicond),
"alias for -cond unicond (deprecated)")::
("-oh", Arg.String (fun n -> hout := Some n),
"<fname> save a copy of hints")::
("-addnum", Arg.Bool (fun n -> addnum := n),
sprintf "<bool> complete test name with number when identical (default %b)"
!addnum)::
("-name",Arg.String (fun s -> name := Some s),
"<s> specify base name of tests")::
("-sufname",Arg.String (fun s -> sufname := Some s),
"<s> specify test name suffix")::
("-lowercase", Arg.Bool (fun b -> lowercase := b),
sprintf "<bool> generate lowercase family names (default %b)" !lowercase)::
("-fmt",Arg.Int (fun i -> fmt := i),
sprintf "<i> size of integer added to base name that yield test names (default %i)" !fmt)::
("-no", Arg.String (fun s -> no := Some s),
"<fname> do not generate tests for these cycles")::
("-stdout", Arg.Bool (fun b -> stdout := b),
"output to stdout. If Cycleonly is true, then this is implied to be true. (default false)")::
("-cycleonly", Arg.Bool (fun b -> cycleonly := b),
"output only cycle, i.e. no litmus body (default false)")::
[]
let numeric = ref true
let speclist () =
common_specs () @
("-num", Arg.Bool (fun b -> numeric := b),
sprintf "<bool> use numeric names (default %b)" !numeric)::
("-mode", Arg.String (fun s -> mode := parse_mode s),
sprintf
"<%s> running mode (default %s). Modes thin and uni are experimental."
(String.concat "|" Code.checks)
(Code.pp_check !mode)
)::
("-cumul", Arg.String (fun b -> cumul := parse_cumul b),
"<s> allow non-explicit fence cumulativity for specified fenced (default all)")::
("-conf", Arg.String (fun s -> conf := Some s), "<file> read configuration file")::
("-size", Arg.Int (fun n -> size := n),
sprintf
"<n> set the maximal size of cycles (default %i)"
!size)::
("-exact", Arg.Clear upto, " produce cycle of size exactly <n>")::
("-nprocs", Arg.Int (fun n -> nprocs := n),
sprintf "<n> reject tests with more than <n> threads (default %i)"
!nprocs)::
("-eprocs", Arg.Set eprocs,
"produce tests with exactly <n> threads (default disabled)")::
("-ins", Arg.Int (fun n -> max_ins := n),
sprintf "<n> max number of edges per proc (default %i)" !max_ins)::
("-one", Arg.Unit (fun _ -> one := true),
"<relax-list> specify a sole cycle")::
("-prefix", Arg.String (fun s -> prefix := s :: !prefix),
"<relax-list> specify a prefix for cycles, can be repeated")::
("-relax", Arg.String (fun s -> relaxs := !relaxs @ [s]),
"<relax-list> specify a relax list")::
("-mix", Arg.Bool (fun b -> mix := b),
sprintf
"<bool> mix relaxations when several are given (default %b)" !mix)::
("-maxrelax", Arg.Int (fun n -> mix := true ; max_relax := n),
sprintf "<n> test up to <n> different relaxations together (default %i). Implies -mix true." !max_relax)::
("-minrelax", Arg.Int (fun n -> mix := true ; min_relax := n),
sprintf "<n> test relaxations considering <n> or more different relaxations (default %i). Implies -mix true." !min_relax)::
("-safe", Arg.String (fun s -> safes := !safes @ [s]),
"<relax-list> specify a safe list")::
("-relaxlist", Arg.String (fun s -> relaxs := !relaxs @[s]),
"<relax-list> specify a list of relaxations of interest")::
("-rejectlist", Arg.String (fun s -> rejects := Some s),
"<reject-list> specify a list of relaxation combinations to reject from generation")::
[]
let varatom = ref ([] : string list)
let varatomspec =
("-varatom", Arg.String (fun s -> varatom := !varatom @ [s]),
"<atom specs> specify atom variations")
let prog = if Array.length Sys.argv > 0 then Sys.argv.(0) else "XXX"
let baseprog = sprintf "%s (version %s)" (Filename.basename prog) (Version.version)
let usage_msg = "Usage: " ^ prog ^ " [options]*"
let read_no fname =
try
Misc.input_protect
(fun chan -> MySys.read_list chan (fun s -> Some s))
fname
with _ -> []
let read_bell libfind fname =
let module R =
ReadBell.Make
(struct
let debug_lexer = false
let debug_model = false
let debug_files = false
let verbose = !verbose
let libfind = libfind
let compat = false
let prog = prog
let variant = Misc.delay_parse !variant Variant_gen.parse
end) in
R.read fname
let parse_annots lines = match lines with
| [] -> None
| _ ->
let module P =
Annot.Make
(struct
let debug = !debug.Debug_gen.lexer
end) in
Some (P.parse lines)
Dereference config variables into a config module for
module ToLisa = functor
(O:sig
val debug : Debug_gen.t ref
val verbose : int ref
val prog : string
val bell : string option ref
val varatom : string list ref
val variant : (Variant_gen.t -> bool) ref
end) -> struct
let debug = !O.debug
let verbose = !O.verbose
let libdir = !libdir
let prog = O.prog
let bell = !O.bell
let varatom = !O.varatom
let variant = !O.variant
end
| null | https://raw.githubusercontent.com/herd/herdtools7/319d1c8ec9f7d939e98785dd519a0da54435b606/gen/config.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
was false
was true
is new
Local observer when possible
Accept up to three writes, no observers
Accept all tests, no observers
Helpers | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2010 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
open Printf
open Code
let verbose = ref 0
let libdir = ref (Filename.concat Version.libdir "herd")
let nprocs = ref 4
let size = ref 6
let one = ref false
let arch = ref (`PPC: Archs.t)
let typ = ref TypBase.default
let hexa = ref false
let tarfile = ref None
let prefix = ref []
let safes = ref []
let relaxs = ref []
let name = ref None
let sufname = ref None
let canonical_only = ref true
let conf = ref None
let mode = ref Default
let mix = ref false
let max_ins = ref 4
let eprocs = ref false
let max_relax = ref 100
let min_relax = ref 1
type 'a cumul = Empty | All | Set of 'a
let cumul = ref All
let poll = ref false
let docheck = ref false
let fmt = ref 3
let no = ref None
let addnum = ref true
let lowercase = ref false
let optcoherence = ref false
let bell = ref None
let scope = ref Scope.No
let variant = ref (fun (_:Variant_gen.t) -> false)
let rejects = ref None
let stdout = ref false
let cycleonly = ref false
let info = ref ([]:MiscParser.info)
let add_info_line line = match LexScan.info line with
| Some kv -> info := !info @ [kv]
| None ->
let msg =
Printf.sprintf "argument '%s' is not in 'key = value' format" line in
raise (Arg.Bad msg)
type do_observers =
Accept up to four writes , no observers
let do_observers = ref Avoid
type obs_type = Straight | Fenced | Loop
let obs_type = ref Straight
let upto = ref true
let optcond = ref true
let overload = ref None
let neg = ref false
let unrollatomic : int option ref = ref None
let same_loc = ref false
type cond = Cycle | Unicond | Observe
let cond = ref Cycle
let hout = ref None
type show = Edges | Annotations | Fences
let show = ref (None:ShowGen.t option)
let debug = ref Debug_gen.none
let moreedges = ref false
let realdep = ref false
let parse_cond tag = match tag with
| "cycle" -> Cycle
| "unicond" -> Unicond
| "observe" -> Observe
| _ -> failwith "Wrong cond, choose cycle, unicond or observe"
let parse_mode s =
match s with
| "default"|"def" -> Default
| "sc" -> Sc
| "thin" -> Thin
| "uni" -> Uni
| "critical" -> Critical
| "free" -> Free
| "ppo" -> Ppo
| "transitive"|"trans" -> Transitive
| "total" -> Total
| "mixed" -> MixedCheck
| _ ->
failwith
(Printf.sprintf
"Wrong mode: choose %s"
(String.concat "," Code.checks))
let parse_do_observers s = match s with
| "avoid"|"false" -> Avoid
| "accept"|"true" -> Accept
| "force" -> Enforce
| "local" -> Local
| "three" -> Three
| "four" -> Four
| "oo"|"infinity" -> Infinity
| _ -> failwith "Wrong observer mode, choose avoid, accept, force, local, three or four"
let parse_obs_type = function
| "straight" -> Straight
| "fenced" -> Fenced
| "loop" -> Loop
| _ -> failwith "Wrong observer style, choose straight, fenced or loop"
let parse_cumul = function
| "false" -> Empty
| "true" -> All
| s -> Set s
let common_specs () =
("-v", Arg.Unit (fun () -> incr verbose)," be verbose")::
("-version", Arg.Unit (fun () -> print_endline Version.version ; exit 0),
" show version number and exit")::
("-set-libdir", Arg.String (fun s -> libdir := s),
" <path> path to libdir")::
Util.parse_tag "-debug"
(fun tag -> match Debug_gen.parse !debug tag with
| None -> false
| Some d -> debug := d ; true)
Debug_gen.tags "specify debugged part"::
Util.parse_tag
"-arch"
(fun tag -> match Archs.parse tag with
| None -> false
| Some a -> arch := a ; true)
Archs.tags "specify architecture"::
("-bell",
Arg.String (fun f -> arch := Archs.lisa ; bell := Some f),
"<name> read bell file <name>, implies -arch LISA")::
Util.parse_tag
"-scopes"
(fun tag -> match Scope.parse tag with
| None -> false
| Some a -> scope := a; true)
Scope.tags "<tag> specifiy scope tree"::
Util.parse_tag
"-type"
(fun tag -> match TypBase.parse tag with
| None -> false
| Some a -> typ := a ; true)
TypBase.tags
(sprintf "specify base type, default %s" (TypBase.pp !typ))::
Util.parse_tags
"-variant"
(fun tag -> match Variant_gen.parse tag with
| None -> false
| Some v0 ->
let open Variant_gen in
let ov =
let ov = !variant in
match v0 with
Special case : Mixed cancels FullMixed
(function
| FullMixed -> false
| v-> ov v)
Special case : cancels FullKVM
(function
| FullKVM -> false
| v-> ov v)
| _ -> ov in
variant := (fun v -> v = v0 || ov v) ;
true)
Variant_gen.tags
(sprintf "specify variant")::
("-hexa", Arg.Unit (fun () -> hexa := true),"hexadecimal output")::
("-o", Arg.String (fun s -> tarfile := Some s),
"<name.tar> output litmus tests in archive <name.tar> (default, output in curent directory)")::
("-c", Arg.Bool (fun b -> canonical_only := b),
sprintf "<b> avoid equivalent cycles (default %b)" !canonical_only)::
("-list",
Arg.Unit (fun () -> show := Some ShowGen.Edges),
"list accepted edge syntax and exit")::
("-show", Arg.String (fun s -> show := Some (ShowGen.parse s)),
"<edges|annotations|fences> list accepted edges, annotations or fences, and exit")::
("-switch", Arg.Set Misc.switch, "switch something")::
("-obs",
Arg.String (fun s -> do_observers := parse_do_observers s),
"<accept|avoid|force|local> enable observers (default avoid)")::
("-obstype",
Arg.String (fun s -> obs_type := parse_obs_type s),
"<fenced|loop|straight> style of observers (default fenced)")::
("-optcond", Arg.Set optcond, " optimize conditions (default)")::
("-nooptcond", Arg.Clear optcond, "do not optimize conditions")::
("-optcoherence", Arg.Set optcoherence, " optimize coherence")::
("-nooptcoherence", Arg.Clear optcoherence, "do not optimize coherence (default)")::
("-info",Arg.String add_info_line,"add metadata to generated test(s)")::
("-moreedges", Arg.Bool (fun b -> moreedges := b),
Printf.sprintf
"consider a very complete set of edges, default %b" !moreedges)::
("-realdep", Arg.Bool (fun b -> realdep := b),
Printf.sprintf
"output \"real\" dependencies, default %b" !moreedges)::
("-overload", Arg.Int (fun n -> overload := Some n),
"<n> stress load unit by <n> useless loads")::
("-unrollatomic",Arg.Int (fun i -> unrollatomic := Some i),
"<n> unroll atomic idioms (default, use loops)")::
("-ua",Arg.Int (fun i -> unrollatomic := Some i),
"<n> shorthand for -unrollatomic <n>")::
("-poll",Arg.Bool (fun b -> poll := b),
"<bool> poll on loaded values, as much as possible")::
("-check",Arg.Bool (fun b -> docheck := b),
"<bool> check loaded values in test code")::
("-neg", Arg.Bool (fun b -> neg := b),
"<bool> negate final condition (default false)")::
("-coherence_decreasing", Arg.Unit (fun () -> ()),
" does nothing, deprecated")::
("-oneloc", Arg.Set same_loc,
"Do not fail on tests with one single location (default false)")::
("-cond",
Arg.String (fun s -> cond := parse_cond s),
"<cycle|unicond|observe> style of final condition, default cycle")::
("-unicond", Arg.Unit (fun () -> cond := Unicond),
"alias for -cond unicond (deprecated)")::
("-oh", Arg.String (fun n -> hout := Some n),
"<fname> save a copy of hints")::
("-addnum", Arg.Bool (fun n -> addnum := n),
sprintf "<bool> complete test name with number when identical (default %b)"
!addnum)::
("-name",Arg.String (fun s -> name := Some s),
"<s> specify base name of tests")::
("-sufname",Arg.String (fun s -> sufname := Some s),
"<s> specify test name suffix")::
("-lowercase", Arg.Bool (fun b -> lowercase := b),
sprintf "<bool> generate lowercase family names (default %b)" !lowercase)::
("-fmt",Arg.Int (fun i -> fmt := i),
sprintf "<i> size of integer added to base name that yield test names (default %i)" !fmt)::
("-no", Arg.String (fun s -> no := Some s),
"<fname> do not generate tests for these cycles")::
("-stdout", Arg.Bool (fun b -> stdout := b),
"output to stdout. If Cycleonly is true, then this is implied to be true. (default false)")::
("-cycleonly", Arg.Bool (fun b -> cycleonly := b),
"output only cycle, i.e. no litmus body (default false)")::
[]
let numeric = ref true
let speclist () =
common_specs () @
("-num", Arg.Bool (fun b -> numeric := b),
sprintf "<bool> use numeric names (default %b)" !numeric)::
("-mode", Arg.String (fun s -> mode := parse_mode s),
sprintf
"<%s> running mode (default %s). Modes thin and uni are experimental."
(String.concat "|" Code.checks)
(Code.pp_check !mode)
)::
("-cumul", Arg.String (fun b -> cumul := parse_cumul b),
"<s> allow non-explicit fence cumulativity for specified fenced (default all)")::
("-conf", Arg.String (fun s -> conf := Some s), "<file> read configuration file")::
("-size", Arg.Int (fun n -> size := n),
sprintf
"<n> set the maximal size of cycles (default %i)"
!size)::
("-exact", Arg.Clear upto, " produce cycle of size exactly <n>")::
("-nprocs", Arg.Int (fun n -> nprocs := n),
sprintf "<n> reject tests with more than <n> threads (default %i)"
!nprocs)::
("-eprocs", Arg.Set eprocs,
"produce tests with exactly <n> threads (default disabled)")::
("-ins", Arg.Int (fun n -> max_ins := n),
sprintf "<n> max number of edges per proc (default %i)" !max_ins)::
("-one", Arg.Unit (fun _ -> one := true),
"<relax-list> specify a sole cycle")::
("-prefix", Arg.String (fun s -> prefix := s :: !prefix),
"<relax-list> specify a prefix for cycles, can be repeated")::
("-relax", Arg.String (fun s -> relaxs := !relaxs @ [s]),
"<relax-list> specify a relax list")::
("-mix", Arg.Bool (fun b -> mix := b),
sprintf
"<bool> mix relaxations when several are given (default %b)" !mix)::
("-maxrelax", Arg.Int (fun n -> mix := true ; max_relax := n),
sprintf "<n> test up to <n> different relaxations together (default %i). Implies -mix true." !max_relax)::
("-minrelax", Arg.Int (fun n -> mix := true ; min_relax := n),
sprintf "<n> test relaxations considering <n> or more different relaxations (default %i). Implies -mix true." !min_relax)::
("-safe", Arg.String (fun s -> safes := !safes @ [s]),
"<relax-list> specify a safe list")::
("-relaxlist", Arg.String (fun s -> relaxs := !relaxs @[s]),
"<relax-list> specify a list of relaxations of interest")::
("-rejectlist", Arg.String (fun s -> rejects := Some s),
"<reject-list> specify a list of relaxation combinations to reject from generation")::
[]
let varatom = ref ([] : string list)
let varatomspec =
("-varatom", Arg.String (fun s -> varatom := !varatom @ [s]),
"<atom specs> specify atom variations")
let prog = if Array.length Sys.argv > 0 then Sys.argv.(0) else "XXX"
let baseprog = sprintf "%s (version %s)" (Filename.basename prog) (Version.version)
let usage_msg = "Usage: " ^ prog ^ " [options]*"
let read_no fname =
try
Misc.input_protect
(fun chan -> MySys.read_list chan (fun s -> Some s))
fname
with _ -> []
let read_bell libfind fname =
let module R =
ReadBell.Make
(struct
let debug_lexer = false
let debug_model = false
let debug_files = false
let verbose = !verbose
let libfind = libfind
let compat = false
let prog = prog
let variant = Misc.delay_parse !variant Variant_gen.parse
end) in
R.read fname
let parse_annots lines = match lines with
| [] -> None
| _ ->
let module P =
Annot.Make
(struct
let debug = !debug.Debug_gen.lexer
end) in
Some (P.parse lines)
Dereference config variables into a config module for
module ToLisa = functor
(O:sig
val debug : Debug_gen.t ref
val verbose : int ref
val prog : string
val bell : string option ref
val varatom : string list ref
val variant : (Variant_gen.t -> bool) ref
end) -> struct
let debug = !O.debug
let verbose = !O.verbose
let libdir = !libdir
let prog = O.prog
let bell = !O.bell
let varatom = !O.varatom
let variant = !O.variant
end
|
1be53ae19cb02464b38b7ef354d023025a661dc76a0bd3987338cc04d0b79324 | ih/ikarus.dev | tests-1.9-req.scm |
(add-tests-with-string-output "begin/implicit-begin"
[(begin 12) => "12\n"]
[(begin 13 122) => "122\n"]
[(begin 123 2343 #t) => "#t\n"]
[(let ([t (begin 12 (cons 1 2))]) (begin t t)) => "(1 . 2)\n"]
[(let ([t (begin 13 (cons 1 2))])
(cons 1 t)
t) => "(1 . 2)\n"]
[(let ([t (cons 1 2)])
(if (pair? t)
(begin t)
12)) => "(1 . 2)\n"]
)
(add-tests-with-string-output "set-car! set-cdr!"
[(let ([x (cons 1 2)])
(begin (set-cdr! x ())
x)) => "(1)\n"]
[(let ([x (cons 1 2)])
(set-cdr! x ())
x) => "(1)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! x y)
x) => "(12 14 . 15)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! y x)
y) => "(14 12 . 13)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! y x)
x) => "(12 . 13)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! x y)
y) => "(14 . 15)\n"]
[(let ([x (let ([x (cons 1 2)]) (set-car! x #t) (set-cdr! x #f) x)])
(cons x x)
x) => "(#t . #f)\n"]
[(let ([x (cons 1 2)])
(set-cdr! x x)
(set-car! (cdr x) x)
(cons (eq? x (car x)) (eq? x (cdr x)))) => "(#t . #t)\n"]
[(let ([x #f])
(if (pair? x)
(set-car! x 12)
#f)
x) => "#f\n"]
;;; [(let ([x #f])
;;; (if (pair? #f)
( set - car ! # f 12 )
;;; #f)
;;; x) => "#f\n"]
)
(add-tests-with-string-output "vectors"
[(vector? (make-vector 0)) => "#t\n"]
[(vector-length (make-vector 12)) => "12\n"]
[(vector? (cons 1 2)) => "#f\n"]
[(vector? 1287) => "#f\n"]
[(vector? ()) => "#f\n"]
[(vector? #t) => "#f\n"]
[(vector? #f) => "#f\n"]
[(pair? (make-vector 12)) => "#f\n"]
[(null? (make-vector 12)) => "#f\n"]
[(boolean? (make-vector 12)) => "#f\n"]
[(make-vector 0) => "#()\n"]
[(let ([v (make-vector 2)])
(vector-set! v 0 #t)
(vector-set! v 1 #f)
v) => "#(#t #f)\n"]
[(let ([v (make-vector 2)])
(vector-set! v 0 v)
(vector-set! v 1 v)
(eq? (vector-ref v 0) (vector-ref v 1))) => "#t\n"]
[(let ([v (make-vector 1)] [y (cons 1 2)])
(vector-set! v 0 y)
(cons y (eq? y (vector-ref v 0)))) => "((1 . 2) . #t)\n"]
[(let ([v0 (make-vector 2)])
(let ([v1 (make-vector 2)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(cons v0 v1))) => "(#(100 200) . #(300 400))\n"]
[(let ([v0 (make-vector 3)])
(let ([v1 (make-vector 3)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v0 2 150)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(vector-set! v1 2 350)
(cons v0 v1))) => "(#(100 200 150) . #(300 400 350))\n"]
[(let ([n 2])
(let ([v0 (make-vector n)])
(let ([v1 (make-vector n)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(cons v0 v1)))) => "(#(100 200) . #(300 400))\n"]
[(let ([n 3])
(let ([v0 (make-vector n)])
(let ([v1 (make-vector (vector-length v0))])
(vector-set! v0 (fx- (vector-length v0) 3) 100)
(vector-set! v0 (fx- (vector-length v1) 2) 200)
(vector-set! v0 (fx- (vector-length v0) 1) 150)
(vector-set! v1 (fx- (vector-length v1) 3) 300)
(vector-set! v1 (fx- (vector-length v0) 2) 400)
(vector-set! v1 (fx- (vector-length v1) 1) 350)
(cons v0 v1)))) => "(#(100 200 150) . #(300 400 350))\n"]
[(let ([n 1])
(vector-set! (make-vector n) (fxsub1 n) (fx* n n))
n) => "1\n"]
[(let ([n 1])
(let ([v (make-vector 1)])
(vector-set! v (fxsub1 n) n)
(vector-ref v (fxsub1 n)))) => "1\n"]
[(let ([v0 (make-vector 1)])
(vector-set! v0 0 1)
(let ([v1 (make-vector 1)])
(vector-set! v1 0 13)
(vector-set! (if (vector? v0) v0 v1)
(fxsub1 (vector-length (if (vector? v0) v0 v1)))
(fxadd1 (vector-ref
(if (vector? v0) v0 v1)
(fxsub1 (vector-length (if (vector? v0) v0 v1))))))
(cons v0 v1))) => "(#(2) . #(13))\n"]
)
(add-tests-with-string-output "strings"
[(string? (make-string 0)) => "#t\n"]
[(make-string 0) => "\"\"\n"]
[(let ([s (make-string 1)])
(string-set! s 0 #\a)
(string-ref s 0)) => "#\\a\n"]
[(let ([s (make-string 2)])
(string-set! s 0 #\a)
(string-set! s 1 #\b)
(cons (string-ref s 0) (string-ref s 1))) => "(#\\a . #\\b)\n"]
[(let ([i 0])
(let ([s (make-string 1)])
(string-set! s i #\a)
(string-ref s i))) => "#\\a\n"]
[(let ([i 0] [j 1])
(let ([s (make-string 2)])
(string-set! s i #\a)
(string-set! s j #\b)
(cons (string-ref s i) (string-ref s j)))) => "(#\\a . #\\b)\n"]
[(let ([i 0] [c #\a])
(let ([s (make-string 1)])
(string-set! s i c)
(string-ref s i))) => "#\\a\n"]
[(string-length (make-string 12)) => "12\n"]
[(string? (make-vector 12)) => "#f\n"]
[(string? (cons 1 2)) => "#f\n"]
[(string? 1287) => "#f\n"]
[(string? ()) => "#f\n"]
[(string? #t) => "#f\n"]
[(string? #f) => "#f\n"]
[(pair? (make-string 12)) => "#f\n"]
[(null? (make-string 12)) => "#f\n"]
[(boolean? (make-string 12)) => "#f\n"]
[(vector? (make-string 12)) => "#f\n"]
[(make-string 0) => "\"\"\n"]
[(let ([v (make-string 2)])
(string-set! v 0 #\t)
(string-set! v 1 #\f)
v) => "\"tf\"\n"]
[(let ([v (make-string 2)])
(string-set! v 0 #\x)
(string-set! v 1 #\x)
(char=? (string-ref v 0) (string-ref v 1))) => "#t\n"]
[(let ([v0 (make-string 3)])
(let ([v1 (make-string 3)])
(string-set! v0 0 #\a)
(string-set! v0 1 #\b)
(string-set! v0 2 #\c)
(string-set! v1 0 #\d)
(string-set! v1 1 #\e)
(string-set! v1 2 #\f)
(cons v0 v1))) => "(\"abc\" . \"def\")\n"]
[(let ([n 2])
(let ([v0 (make-string n)])
(let ([v1 (make-string n)])
(string-set! v0 0 #\a)
(string-set! v0 1 #\b)
(string-set! v1 0 #\c)
(string-set! v1 1 #\d)
(cons v0 v1)))) => "(\"ab\" . \"cd\")\n"]
[(let ([n 3])
(let ([v0 (make-string n)])
(let ([v1 (make-string (string-length v0))])
(string-set! v0 (fx- (string-length v0) 3) #\a)
(string-set! v0 (fx- (string-length v1) 2) #\b)
(string-set! v0 (fx- (string-length v0) 1) #\c)
(string-set! v1 (fx- (string-length v1) 3) #\Z)
(string-set! v1 (fx- (string-length v0) 2) #\Y)
(string-set! v1 (fx- (string-length v1) 1) #\X)
(cons v0 v1)))) => "(\"abc\" . \"ZYX\")\n"]
[(let ([n 1])
(string-set! (make-string n) (fxsub1 n) (integer->char 34))
n) => "1\n"]
[(let ([n 1])
(let ([v (make-string 1)])
(string-set! v (fxsub1 n) (integer->char n))
(char->integer (string-ref v (fxsub1 n))))) => "1\n"]
[(let ([v0 (make-string 1)])
(string-set! v0 0 #\a)
(let ([v1 (make-string 1)])
(string-set! v1 0 #\A)
(string-set! (if (string? v0) v0 v1)
(fxsub1 (string-length (if (string? v0) v0 v1)))
(integer->char
(fxadd1
(char->integer
(string-ref
(if (string? v0) v0 v1)
(fxsub1 (string-length (if (string? v0) v0 v1))))))))
(cons v0 v1))) => "(\"b\" . \"A\")\n"]
[(let ([s (make-string 1)])
(string-set! s 0 #\")
s) => "\"\\\"\"\n"]
[(let ([s (make-string 1)])
(string-set! s 0 #\\)
s) => "\"\\\\\"\n"]
)
| null | https://raw.githubusercontent.com/ih/ikarus.dev/8bb0c8e4d1122cf0f9aeb675cb51bc7df178959b/src/old-tests/tests-1.9-req.scm | scheme | [(let ([x #f])
(if (pair? #f)
#f)
x) => "#f\n"] |
(add-tests-with-string-output "begin/implicit-begin"
[(begin 12) => "12\n"]
[(begin 13 122) => "122\n"]
[(begin 123 2343 #t) => "#t\n"]
[(let ([t (begin 12 (cons 1 2))]) (begin t t)) => "(1 . 2)\n"]
[(let ([t (begin 13 (cons 1 2))])
(cons 1 t)
t) => "(1 . 2)\n"]
[(let ([t (cons 1 2)])
(if (pair? t)
(begin t)
12)) => "(1 . 2)\n"]
)
(add-tests-with-string-output "set-car! set-cdr!"
[(let ([x (cons 1 2)])
(begin (set-cdr! x ())
x)) => "(1)\n"]
[(let ([x (cons 1 2)])
(set-cdr! x ())
x) => "(1)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! x y)
x) => "(12 14 . 15)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! y x)
y) => "(14 12 . 13)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! y x)
x) => "(12 . 13)\n"]
[(let ([x (cons 12 13)] [y (cons 14 15)])
(set-cdr! x y)
y) => "(14 . 15)\n"]
[(let ([x (let ([x (cons 1 2)]) (set-car! x #t) (set-cdr! x #f) x)])
(cons x x)
x) => "(#t . #f)\n"]
[(let ([x (cons 1 2)])
(set-cdr! x x)
(set-car! (cdr x) x)
(cons (eq? x (car x)) (eq? x (cdr x)))) => "(#t . #t)\n"]
[(let ([x #f])
(if (pair? x)
(set-car! x 12)
#f)
x) => "#f\n"]
( set - car ! # f 12 )
)
(add-tests-with-string-output "vectors"
[(vector? (make-vector 0)) => "#t\n"]
[(vector-length (make-vector 12)) => "12\n"]
[(vector? (cons 1 2)) => "#f\n"]
[(vector? 1287) => "#f\n"]
[(vector? ()) => "#f\n"]
[(vector? #t) => "#f\n"]
[(vector? #f) => "#f\n"]
[(pair? (make-vector 12)) => "#f\n"]
[(null? (make-vector 12)) => "#f\n"]
[(boolean? (make-vector 12)) => "#f\n"]
[(make-vector 0) => "#()\n"]
[(let ([v (make-vector 2)])
(vector-set! v 0 #t)
(vector-set! v 1 #f)
v) => "#(#t #f)\n"]
[(let ([v (make-vector 2)])
(vector-set! v 0 v)
(vector-set! v 1 v)
(eq? (vector-ref v 0) (vector-ref v 1))) => "#t\n"]
[(let ([v (make-vector 1)] [y (cons 1 2)])
(vector-set! v 0 y)
(cons y (eq? y (vector-ref v 0)))) => "((1 . 2) . #t)\n"]
[(let ([v0 (make-vector 2)])
(let ([v1 (make-vector 2)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(cons v0 v1))) => "(#(100 200) . #(300 400))\n"]
[(let ([v0 (make-vector 3)])
(let ([v1 (make-vector 3)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v0 2 150)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(vector-set! v1 2 350)
(cons v0 v1))) => "(#(100 200 150) . #(300 400 350))\n"]
[(let ([n 2])
(let ([v0 (make-vector n)])
(let ([v1 (make-vector n)])
(vector-set! v0 0 100)
(vector-set! v0 1 200)
(vector-set! v1 0 300)
(vector-set! v1 1 400)
(cons v0 v1)))) => "(#(100 200) . #(300 400))\n"]
[(let ([n 3])
(let ([v0 (make-vector n)])
(let ([v1 (make-vector (vector-length v0))])
(vector-set! v0 (fx- (vector-length v0) 3) 100)
(vector-set! v0 (fx- (vector-length v1) 2) 200)
(vector-set! v0 (fx- (vector-length v0) 1) 150)
(vector-set! v1 (fx- (vector-length v1) 3) 300)
(vector-set! v1 (fx- (vector-length v0) 2) 400)
(vector-set! v1 (fx- (vector-length v1) 1) 350)
(cons v0 v1)))) => "(#(100 200 150) . #(300 400 350))\n"]
[(let ([n 1])
(vector-set! (make-vector n) (fxsub1 n) (fx* n n))
n) => "1\n"]
[(let ([n 1])
(let ([v (make-vector 1)])
(vector-set! v (fxsub1 n) n)
(vector-ref v (fxsub1 n)))) => "1\n"]
[(let ([v0 (make-vector 1)])
(vector-set! v0 0 1)
(let ([v1 (make-vector 1)])
(vector-set! v1 0 13)
(vector-set! (if (vector? v0) v0 v1)
(fxsub1 (vector-length (if (vector? v0) v0 v1)))
(fxadd1 (vector-ref
(if (vector? v0) v0 v1)
(fxsub1 (vector-length (if (vector? v0) v0 v1))))))
(cons v0 v1))) => "(#(2) . #(13))\n"]
)
(add-tests-with-string-output "strings"
[(string? (make-string 0)) => "#t\n"]
[(make-string 0) => "\"\"\n"]
[(let ([s (make-string 1)])
(string-set! s 0 #\a)
(string-ref s 0)) => "#\\a\n"]
[(let ([s (make-string 2)])
(string-set! s 0 #\a)
(string-set! s 1 #\b)
(cons (string-ref s 0) (string-ref s 1))) => "(#\\a . #\\b)\n"]
[(let ([i 0])
(let ([s (make-string 1)])
(string-set! s i #\a)
(string-ref s i))) => "#\\a\n"]
[(let ([i 0] [j 1])
(let ([s (make-string 2)])
(string-set! s i #\a)
(string-set! s j #\b)
(cons (string-ref s i) (string-ref s j)))) => "(#\\a . #\\b)\n"]
[(let ([i 0] [c #\a])
(let ([s (make-string 1)])
(string-set! s i c)
(string-ref s i))) => "#\\a\n"]
[(string-length (make-string 12)) => "12\n"]
[(string? (make-vector 12)) => "#f\n"]
[(string? (cons 1 2)) => "#f\n"]
[(string? 1287) => "#f\n"]
[(string? ()) => "#f\n"]
[(string? #t) => "#f\n"]
[(string? #f) => "#f\n"]
[(pair? (make-string 12)) => "#f\n"]
[(null? (make-string 12)) => "#f\n"]
[(boolean? (make-string 12)) => "#f\n"]
[(vector? (make-string 12)) => "#f\n"]
[(make-string 0) => "\"\"\n"]
[(let ([v (make-string 2)])
(string-set! v 0 #\t)
(string-set! v 1 #\f)
v) => "\"tf\"\n"]
[(let ([v (make-string 2)])
(string-set! v 0 #\x)
(string-set! v 1 #\x)
(char=? (string-ref v 0) (string-ref v 1))) => "#t\n"]
[(let ([v0 (make-string 3)])
(let ([v1 (make-string 3)])
(string-set! v0 0 #\a)
(string-set! v0 1 #\b)
(string-set! v0 2 #\c)
(string-set! v1 0 #\d)
(string-set! v1 1 #\e)
(string-set! v1 2 #\f)
(cons v0 v1))) => "(\"abc\" . \"def\")\n"]
[(let ([n 2])
(let ([v0 (make-string n)])
(let ([v1 (make-string n)])
(string-set! v0 0 #\a)
(string-set! v0 1 #\b)
(string-set! v1 0 #\c)
(string-set! v1 1 #\d)
(cons v0 v1)))) => "(\"ab\" . \"cd\")\n"]
[(let ([n 3])
(let ([v0 (make-string n)])
(let ([v1 (make-string (string-length v0))])
(string-set! v0 (fx- (string-length v0) 3) #\a)
(string-set! v0 (fx- (string-length v1) 2) #\b)
(string-set! v0 (fx- (string-length v0) 1) #\c)
(string-set! v1 (fx- (string-length v1) 3) #\Z)
(string-set! v1 (fx- (string-length v0) 2) #\Y)
(string-set! v1 (fx- (string-length v1) 1) #\X)
(cons v0 v1)))) => "(\"abc\" . \"ZYX\")\n"]
[(let ([n 1])
(string-set! (make-string n) (fxsub1 n) (integer->char 34))
n) => "1\n"]
[(let ([n 1])
(let ([v (make-string 1)])
(string-set! v (fxsub1 n) (integer->char n))
(char->integer (string-ref v (fxsub1 n))))) => "1\n"]
[(let ([v0 (make-string 1)])
(string-set! v0 0 #\a)
(let ([v1 (make-string 1)])
(string-set! v1 0 #\A)
(string-set! (if (string? v0) v0 v1)
(fxsub1 (string-length (if (string? v0) v0 v1)))
(integer->char
(fxadd1
(char->integer
(string-ref
(if (string? v0) v0 v1)
(fxsub1 (string-length (if (string? v0) v0 v1))))))))
(cons v0 v1))) => "(\"b\" . \"A\")\n"]
[(let ([s (make-string 1)])
(string-set! s 0 #\")
s) => "\"\\\"\"\n"]
[(let ([s (make-string 1)])
(string-set! s 0 #\\)
s) => "\"\\\\\"\n"]
)
|
c4e8f281c3e01fe9a72abd880bf5d5412eb14b2791e3f381c3e446ea92dd04d1 | BetterThanTomorrow/joyride | db.cljs | (ns integration-test.db
(:require [cljs.test]))
(def !state (atom {:running nil
:ws-activated? false
:pass 0
:fail 0
:error 0}))
| null | https://raw.githubusercontent.com/BetterThanTomorrow/joyride/760e24ba61e0454f715b15ed29b7ed3d0ca01312/vscode-test-runner/workspace-1/.joyride/src/integration_test/db.cljs | clojure | (ns integration-test.db
(:require [cljs.test]))
(def !state (atom {:running nil
:ws-activated? false
:pass 0
:fail 0
:error 0}))
| |
4f55496beff64864c13c22ea8da736e4ffad79e6fb1ff39e87a73982bd672aa5 | input-output-hk/plutus | Lib.hs | # OPTIONS_GHC -fno - omit - interface - pragmas #
module Plugin.Typeclasses.Lib where
import PlutusTx.Builtins qualified as Builtins
data Animal = Dog | Cat
data Person = Jim | Jane
data Alien = AlienJim | AlienJane
Needs to be in another file because of # 978
class DefaultMethods a where
method1 :: a -> Integer
{-# INLINABLE method2 #-}
method2 :: a -> Integer
method2 a = method1 a `Builtins.addInteger` 1
instance DefaultMethods Integer where
{-# INLINABLE method1 #-}
method1 a = a
instance DefaultMethods Person where
{-# INLINABLE method1 #-}
method1 _ = 1
| null | https://raw.githubusercontent.com/input-output-hk/plutus/1f31e640e8a258185db01fa899da63f9018c0e85/plutus-tx-plugin/test/Plugin/Typeclasses/Lib.hs | haskell | # INLINABLE method2 #
# INLINABLE method1 #
# INLINABLE method1 # | # OPTIONS_GHC -fno - omit - interface - pragmas #
module Plugin.Typeclasses.Lib where
import PlutusTx.Builtins qualified as Builtins
data Animal = Dog | Cat
data Person = Jim | Jane
data Alien = AlienJim | AlienJane
Needs to be in another file because of # 978
class DefaultMethods a where
method1 :: a -> Integer
method2 :: a -> Integer
method2 a = method1 a `Builtins.addInteger` 1
instance DefaultMethods Integer where
method1 a = a
instance DefaultMethods Person where
method1 _ = 1
|
ec7e09389dd1ad2912bec72c0a387dc0d93083ceaef632f96fd29c17d1f8906d | incoherentsoftware/defect-process | Projectile.hs | module Enemy.All.Dog.Projectile
( mkDogProjectile
) where
import Control.Monad.IO.Class (MonadIO)
import Data.Maybe (fromMaybe)
import qualified Data.Set as S
import Attack
import Attack.Hit
import Collision
import Configs
import Configs.All.Enemy
import Configs.All.Enemy.Dog
import Constants
import Enemy as E
import Enemy.All.Dog.AttackDescriptions
import Enemy.All.Dog.Data
import FileCache
import Id
import Msg
import Particle.All.Simple
import Projectile as P
import Util
import Window.Graphics
import World.ZIndex
projHitEffectPath =
PackResourceFilePath "data/enemies/dog-enemy.pack" "attack-projectile-hit.spr" :: PackResourceFilePath
projHitSoundPath = "event:/SFX Events/Enemy/Dog/attack-projectile-hit" :: FilePath
data DogProjectileData = DogProjectileData
{ _attack :: Attack
, _config :: DogEnemyConfig
}
mkDogProjectile :: (ConfigsRead m, MonadIO m) => Enemy DogEnemyData -> m (Some Projectile)
mkDogProjectile enemy =
let
cfg = _dog $ _config (E._data enemy :: DogEnemyData)
Pos2 shootOffsetX shootOffsetY = _shootOffset cfg
dir = E._dir enemy
dirNeg = directionNeg dir
shootOffset = Pos2 (shootOffsetX * dirNeg) shootOffsetY
pos = E._pos enemy `vecAdd` shootOffset
enemyData = E._data enemy
shootProjAtkDesc = _shootProjectile $ _attackDescs enemyData
in do
atk <- mkAttack pos dir shootProjAtkDesc
let
dogProjData = DogProjectileData
{ _attack = atk
, _config = cfg
}
angle = _shootProjectileAngle cfg
aimVec = vecNormalize $ Vec2 (cos angle * dirNeg) (sin angle)
vel = toVel2 $ aimVec `vecMul` _shootProjectileSpeed cfg
hbx = fromMaybe (dummyHitbox pos) (attackHitbox atk)
shootProjAliveSecs = _shootProjectileAliveSecs cfg
msgId <- newId
return . Some $ (mkProjectile dogProjData msgId hbx shootProjAliveSecs)
{ _vel = vel
, _registeredCollisions = S.fromList [ProjRegisteredPlayerCollision]
, _update = updateDogProjectile
, _draw = drawDogProjectile
, _processCollisions = processCollisions
}
updateDogProjectile :: Monad m => ProjectileUpdate DogProjectileData m
updateDogProjectile dogProjectile = return $ dogProjectile
{ _data = dogProjData'
, _hitbox = const $ fromMaybe (dummyHitbox pos) (attackHitbox atk')
, _ttl = ttl
, _vel = vel
}
where
dogProjData = P._data dogProjectile
atk = _attack (dogProjData :: DogProjectileData)
Vel2 velX velY = P._vel dogProjectile
gravity = _shootProjectileGravity $ _config (dogProjData :: DogProjectileData)
vel = Vel2 velX (velY + gravity * timeStep)
atkPos = _pos (atk :: Attack)
pos = atkPos `vecAdd` (toPos2 $ vel `vecMul` timeStep)
dir = _dir (atk :: Attack)
atk' = updateAttack pos dir atk
ttl
| _done atk' = 0.0
| otherwise = _ttl dogProjectile
dogProjData' = dogProjData {_attack = atk'} :: DogProjectileData
processCollisions :: ProjectileProcessCollisions DogProjectileData
processCollisions collisions dogProjectile = case collisions of
[] -> []
(collision:_) -> case collision of
ProjPlayerCollision player -> playerCollision player dogProjectile
_ -> []
playerCollision :: CollisionEntity e => e -> Projectile DogProjectileData -> [Msg ThinkCollisionMsgsPhase]
playerCollision player dogProjectile =
[ mkMsgTo (HurtMsgAttackHit atkHit) playerId
, mkMsg $ ParticleMsgAddM mkHitEffect
, mkMsgTo (ProjectileMsgSetTtl 0.0) dogProjId
, mkMsg $ AudioMsgPlaySound projHitSoundPath pos
]
where
playerId = collisionEntityMsgId player
atk = _attack (P._data dogProjectile :: DogProjectileData)
atkHit = mkAttackHit $ _attack (P._data dogProjectile :: DogProjectileData)
pos = _pos (atk :: Attack)
dir = _dir (atk :: Attack)
mkHitEffect = loadSimpleParticle pos dir enemyAttackProjectileZIndex projHitEffectPath
dogProjId = P._msgId dogProjectile
drawDogProjectile :: (GraphicsReadWrite m, MonadIO m) => ProjectileDraw DogProjectileData m
drawDogProjectile dogProjectile =
let
atk = _attack (P._data dogProjectile :: DogProjectileData)
spr = attackSprite atk
atkPos = _pos (atk :: Attack)
vel = P._vel dogProjectile
dir = _dir (atk :: Attack)
in do
pos <- graphicsLerpPos atkPos vel
drawSprite pos dir enemyAttackProjectileZIndex spr
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/8797aad1d93bff5aadd7226c39a48f45cf76746e/src/Enemy/All/Dog/Projectile.hs | haskell | module Enemy.All.Dog.Projectile
( mkDogProjectile
) where
import Control.Monad.IO.Class (MonadIO)
import Data.Maybe (fromMaybe)
import qualified Data.Set as S
import Attack
import Attack.Hit
import Collision
import Configs
import Configs.All.Enemy
import Configs.All.Enemy.Dog
import Constants
import Enemy as E
import Enemy.All.Dog.AttackDescriptions
import Enemy.All.Dog.Data
import FileCache
import Id
import Msg
import Particle.All.Simple
import Projectile as P
import Util
import Window.Graphics
import World.ZIndex
projHitEffectPath =
PackResourceFilePath "data/enemies/dog-enemy.pack" "attack-projectile-hit.spr" :: PackResourceFilePath
projHitSoundPath = "event:/SFX Events/Enemy/Dog/attack-projectile-hit" :: FilePath
data DogProjectileData = DogProjectileData
{ _attack :: Attack
, _config :: DogEnemyConfig
}
mkDogProjectile :: (ConfigsRead m, MonadIO m) => Enemy DogEnemyData -> m (Some Projectile)
mkDogProjectile enemy =
let
cfg = _dog $ _config (E._data enemy :: DogEnemyData)
Pos2 shootOffsetX shootOffsetY = _shootOffset cfg
dir = E._dir enemy
dirNeg = directionNeg dir
shootOffset = Pos2 (shootOffsetX * dirNeg) shootOffsetY
pos = E._pos enemy `vecAdd` shootOffset
enemyData = E._data enemy
shootProjAtkDesc = _shootProjectile $ _attackDescs enemyData
in do
atk <- mkAttack pos dir shootProjAtkDesc
let
dogProjData = DogProjectileData
{ _attack = atk
, _config = cfg
}
angle = _shootProjectileAngle cfg
aimVec = vecNormalize $ Vec2 (cos angle * dirNeg) (sin angle)
vel = toVel2 $ aimVec `vecMul` _shootProjectileSpeed cfg
hbx = fromMaybe (dummyHitbox pos) (attackHitbox atk)
shootProjAliveSecs = _shootProjectileAliveSecs cfg
msgId <- newId
return . Some $ (mkProjectile dogProjData msgId hbx shootProjAliveSecs)
{ _vel = vel
, _registeredCollisions = S.fromList [ProjRegisteredPlayerCollision]
, _update = updateDogProjectile
, _draw = drawDogProjectile
, _processCollisions = processCollisions
}
updateDogProjectile :: Monad m => ProjectileUpdate DogProjectileData m
updateDogProjectile dogProjectile = return $ dogProjectile
{ _data = dogProjData'
, _hitbox = const $ fromMaybe (dummyHitbox pos) (attackHitbox atk')
, _ttl = ttl
, _vel = vel
}
where
dogProjData = P._data dogProjectile
atk = _attack (dogProjData :: DogProjectileData)
Vel2 velX velY = P._vel dogProjectile
gravity = _shootProjectileGravity $ _config (dogProjData :: DogProjectileData)
vel = Vel2 velX (velY + gravity * timeStep)
atkPos = _pos (atk :: Attack)
pos = atkPos `vecAdd` (toPos2 $ vel `vecMul` timeStep)
dir = _dir (atk :: Attack)
atk' = updateAttack pos dir atk
ttl
| _done atk' = 0.0
| otherwise = _ttl dogProjectile
dogProjData' = dogProjData {_attack = atk'} :: DogProjectileData
processCollisions :: ProjectileProcessCollisions DogProjectileData
processCollisions collisions dogProjectile = case collisions of
[] -> []
(collision:_) -> case collision of
ProjPlayerCollision player -> playerCollision player dogProjectile
_ -> []
playerCollision :: CollisionEntity e => e -> Projectile DogProjectileData -> [Msg ThinkCollisionMsgsPhase]
playerCollision player dogProjectile =
[ mkMsgTo (HurtMsgAttackHit atkHit) playerId
, mkMsg $ ParticleMsgAddM mkHitEffect
, mkMsgTo (ProjectileMsgSetTtl 0.0) dogProjId
, mkMsg $ AudioMsgPlaySound projHitSoundPath pos
]
where
playerId = collisionEntityMsgId player
atk = _attack (P._data dogProjectile :: DogProjectileData)
atkHit = mkAttackHit $ _attack (P._data dogProjectile :: DogProjectileData)
pos = _pos (atk :: Attack)
dir = _dir (atk :: Attack)
mkHitEffect = loadSimpleParticle pos dir enemyAttackProjectileZIndex projHitEffectPath
dogProjId = P._msgId dogProjectile
drawDogProjectile :: (GraphicsReadWrite m, MonadIO m) => ProjectileDraw DogProjectileData m
drawDogProjectile dogProjectile =
let
atk = _attack (P._data dogProjectile :: DogProjectileData)
spr = attackSprite atk
atkPos = _pos (atk :: Attack)
vel = P._vel dogProjectile
dir = _dir (atk :: Attack)
in do
pos <- graphicsLerpPos atkPos vel
drawSprite pos dir enemyAttackProjectileZIndex spr
| |
915be0831cfc378260dfec64ccea220c2c0805360cfa5244bbf3b9d1ddf67c91 | rtoal/ple | mystery.hs | mystery x s =
concat $ replicate (round (sqrt x)) s
| null | https://raw.githubusercontent.com/rtoal/ple/b24cab4de2beca6970833a09d05af6ef96ec3921/haskell/mystery.hs | haskell | mystery x s =
concat $ replicate (round (sqrt x)) s
| |
a792ff8baa81ec4852134a1c008c1f079eeb23168cc90924b3b8ce09ce86856e | srid/Taut | Internal.hs | # LANGUAGE ScopedTypeVariables #
module Common.Slack.Internal where
import Data.Aeson
import Data.Char (isUpper)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Text.Casing (fromHumps, toQuietSnake)
import Text.Read (readMaybe)
| Field label modifier for converting Slack datatypes to json
fieldLabelMod :: Options
fieldLabelMod =
defaultOptions
{ fieldLabelModifier = toQuietSnake . fromHumps . dropWhile (not . isUpper)
}
parseSlackTimestamp :: Monad f => Text -> f UTCTime
parseSlackTimestamp ts' = case readMaybe (T.unpack ts') of
Nothing -> fail $ "Invalid Slack timestamp: " <> T.unpack ts'
Just (ts :: Double) -> do
-- FIXME: Not sure if `round` is problematic here. We want this value to be unique.
pure $ posixSecondsToUTCTime $ fromInteger $ round ts
-- TODO: Check if this converts back to the same value
-- NOTE: it does not; loses the double precision. do we care?
formatSlackTimestamp :: UTCTime -> Text
formatSlackTimestamp t = T.pack (show v)
where
v :: Integer = round $ utcTimeToPOSIXSeconds t
| null | https://raw.githubusercontent.com/srid/Taut/75f10c50a391d6e7301f6a26b2c781f0bf76a5c1/common/src/Common/Slack/Internal.hs | haskell | FIXME: Not sure if `round` is problematic here. We want this value to be unique.
TODO: Check if this converts back to the same value
NOTE: it does not; loses the double precision. do we care? | # LANGUAGE ScopedTypeVariables #
module Common.Slack.Internal where
import Data.Aeson
import Data.Char (isUpper)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock
import Data.Time.Clock.POSIX
import Text.Casing (fromHumps, toQuietSnake)
import Text.Read (readMaybe)
| Field label modifier for converting Slack datatypes to json
fieldLabelMod :: Options
fieldLabelMod =
defaultOptions
{ fieldLabelModifier = toQuietSnake . fromHumps . dropWhile (not . isUpper)
}
parseSlackTimestamp :: Monad f => Text -> f UTCTime
parseSlackTimestamp ts' = case readMaybe (T.unpack ts') of
Nothing -> fail $ "Invalid Slack timestamp: " <> T.unpack ts'
Just (ts :: Double) -> do
pure $ posixSecondsToUTCTime $ fromInteger $ round ts
formatSlackTimestamp :: UTCTime -> Text
formatSlackTimestamp t = T.pack (show v)
where
v :: Integer = round $ utcTimeToPOSIXSeconds t
|
69c6a6094b074b3ffe6c008521db5d990e81c571b31464235859874df08cc277 | malcolmstill/ulubis | wl-output-impl.lisp |
(in-package :ulubis)
(defimplementation wl-output ()
()
())
(def-wl-bind output-bind (client (data :pointer) (version :uint32) (id :uint32))
(let ((output (make-wl-output client 1 id :implementation? nil)))
(wl-output-send-geometry (->resource output) 0 0 1440 900 0 "apple" "apple" 0)))
| null | https://raw.githubusercontent.com/malcolmstill/ulubis/23c89ccd5589930e66025487c31531f49218bb76/wl-output-impl.lisp | lisp |
(in-package :ulubis)
(defimplementation wl-output ()
()
())
(def-wl-bind output-bind (client (data :pointer) (version :uint32) (id :uint32))
(let ((output (make-wl-output client 1 id :implementation? nil)))
(wl-output-send-geometry (->resource output) 0 0 1440 900 0 "apple" "apple" 0)))
| |
ae3751f082cc68b6ae742e5713a834964aeb911c4ccd92176ee803336f111c53 | oklm-wsh/MrMime | input.mli | (** Module Input *)
(** A ringbuffer. *)
type 'a t = 'a RingBuffer.Committed.t
(** A proof to use a [string] internally *)
type st = Internal_buffer.st = St
(** A proof to use a [(char, int8_unsigned_elt, c_layout) Bigarray.Array1.t] *)
type bs = Internal_buffer.bs = Bs
* [ write input buf off len ] writes an internal buffer ( with the same proof
[ ' a ] - see { ! st } or { ! bs } ) starting at [ off ] to [ len ] inside the input .
['a] - see {!st} or {!bs}) starting at [off] to [len] inside the input.
*)
val write : 'a t -> 'a Internal_buffer.t -> int -> int -> unit
* [ write_string input buf off len ] writes a [ string ] starting at [ off ] to
[ len ] inside the input .
[len] inside the input. *)
val write_string : 'a t -> string -> int -> int -> unit
* [ create_bytes size ] returns a fresh input of length [ size ] with the proof { ! .
The sequence is uninitialiazed and contains arbitrary bytes .
The sequence is uninitialiazed and contains arbitrary bytes.
*)
val create_bytes : int -> st t
(** [create_bigstring size] returns a fresh input of length [size] with the
proof {!bs}. The sequence is unintialiazed and contains arbitrary bytes.
*)
val create_bigstring : int -> bs t
(** [size input] returns the length of the given input. *)
val size : 'a t -> int
* [ peek input buf off len ] same as { ! read } but does not advance the read
pointer .
pointer.
*)
val peek : 'a t -> 'a Internal_buffer.t -> int -> int -> unit
* [ read input buf off len ] read the data inside the input and advance the read
pointer .
pointer.
*)
val read : 'a t -> 'a Internal_buffer.t -> int -> int -> unit
(** [read_space input] returns a continuous part of the internal buffer with the
offset and the length of bytes available to read. If {!ravailable}
returns [0], [read_space] returns [None].
The continuous part of the internal buffer is not necessarily a buffer which
contains all bytes available to read (it's a part).
*)
val read_space : 'a t -> ('a Internal_buffer.t * int * int) option
(** [write_space input] returns a continuous part of the internal buffer with
the offset and the length of bytes available to write. If
{!wavailable} returns [0], [write_space] returns [None].
The continuous part of the internal buffer is not necessarily a buffer which
contains all bytes available to write (it's a part).
*)
val write_space : 'a t -> ('a Internal_buffer.t * int * int) option
* [ transmit input f ] same as [ Option.map f ( read_space input ) ] .
val transmit : 'a t -> ('a Internal_buffer.t -> int -> int -> int) -> int
(** [ravailable input] returns available bytes to read. *)
val ravailable : 'a t -> int
(** [wavailable input] returns available bytes to write. *)
val wavailable : 'a t -> int
(** [radvance input n] drops [n] bytes. *)
val radvance : 'a t -> int -> unit
(** [wadvance input n] advances the write pointer. *)
val wadvance : 'a t -> int -> unit
* [ get input ] gets the first character at the read pointer .
val get : 'a t -> char
(** [pp input] prints an human readable representation of [input]. *)
val pp : Format.formatter -> 'a t -> unit
(** [proof input] gets the internal buffer with the proof. *)
val proof : 'a t -> 'a Internal_buffer.t
(** [savailable input] returns available bytes to read or, if the input is
committed, returns available bytes from the commit to the write pointer.
*)
val savailable : 'a t -> int
| null | https://raw.githubusercontent.com/oklm-wsh/MrMime/4d2a9dc75905927a092c0424cff7462e2b26bb96/lib/input.mli | ocaml | * Module Input
* A ringbuffer.
* A proof to use a [string] internally
* A proof to use a [(char, int8_unsigned_elt, c_layout) Bigarray.Array1.t]
* [create_bigstring size] returns a fresh input of length [size] with the
proof {!bs}. The sequence is unintialiazed and contains arbitrary bytes.
* [size input] returns the length of the given input.
* [read_space input] returns a continuous part of the internal buffer with the
offset and the length of bytes available to read. If {!ravailable}
returns [0], [read_space] returns [None].
The continuous part of the internal buffer is not necessarily a buffer which
contains all bytes available to read (it's a part).
* [write_space input] returns a continuous part of the internal buffer with
the offset and the length of bytes available to write. If
{!wavailable} returns [0], [write_space] returns [None].
The continuous part of the internal buffer is not necessarily a buffer which
contains all bytes available to write (it's a part).
* [ravailable input] returns available bytes to read.
* [wavailable input] returns available bytes to write.
* [radvance input n] drops [n] bytes.
* [wadvance input n] advances the write pointer.
* [pp input] prints an human readable representation of [input].
* [proof input] gets the internal buffer with the proof.
* [savailable input] returns available bytes to read or, if the input is
committed, returns available bytes from the commit to the write pointer.
|
type 'a t = 'a RingBuffer.Committed.t
type st = Internal_buffer.st = St
type bs = Internal_buffer.bs = Bs
* [ write input buf off len ] writes an internal buffer ( with the same proof
[ ' a ] - see { ! st } or { ! bs } ) starting at [ off ] to [ len ] inside the input .
['a] - see {!st} or {!bs}) starting at [off] to [len] inside the input.
*)
val write : 'a t -> 'a Internal_buffer.t -> int -> int -> unit
* [ write_string input buf off len ] writes a [ string ] starting at [ off ] to
[ len ] inside the input .
[len] inside the input. *)
val write_string : 'a t -> string -> int -> int -> unit
* [ create_bytes size ] returns a fresh input of length [ size ] with the proof { ! .
The sequence is uninitialiazed and contains arbitrary bytes .
The sequence is uninitialiazed and contains arbitrary bytes.
*)
val create_bytes : int -> st t
val create_bigstring : int -> bs t
val size : 'a t -> int
* [ peek input buf off len ] same as { ! read } but does not advance the read
pointer .
pointer.
*)
val peek : 'a t -> 'a Internal_buffer.t -> int -> int -> unit
* [ read input buf off len ] read the data inside the input and advance the read
pointer .
pointer.
*)
val read : 'a t -> 'a Internal_buffer.t -> int -> int -> unit
val read_space : 'a t -> ('a Internal_buffer.t * int * int) option
val write_space : 'a t -> ('a Internal_buffer.t * int * int) option
* [ transmit input f ] same as [ Option.map f ( read_space input ) ] .
val transmit : 'a t -> ('a Internal_buffer.t -> int -> int -> int) -> int
val ravailable : 'a t -> int
val wavailable : 'a t -> int
val radvance : 'a t -> int -> unit
val wadvance : 'a t -> int -> unit
* [ get input ] gets the first character at the read pointer .
val get : 'a t -> char
val pp : Format.formatter -> 'a t -> unit
val proof : 'a t -> 'a Internal_buffer.t
val savailable : 'a t -> int
|
7d7d0f12aa06dedd79d0522e0cddecbd7bad9c6800d027559eedc6d6ea087488 | LauraVoinea/protocol-reengineering-implementation | agent2_stub.erl | -module(agent2_stub).
-behaviour(gen_statem).
-define(SERVER, ?MODULE).
-export([callback_mode/0,
init/1,
receive_ia_snap/1,
receive_ia_state/1,
send_ai_close/1,
send_ai_coord/1,
send_ai_get/1,
send_ai_set/1,
start_link/0,
state1/3,
state2/3,
state3/3,
state5/3,
stop/0,
terminate/3]).
start_link() -> gen_statem:start_link({local, ?SERVER}, ?MODULE, [], []).
callback_mode() -> [state_functions, state_enter].
%consume n
init([]) -> {ok, state1, {}}.
state1(enter, _OldState, _Data) -> keep_state_and_data;
%consume set
state1(internal, {send_ai_set, Ai_set}, Data) -> {next_state, state2, Data};
%consume get
state1(internal, {send_ai_get, Ai_get}, Data) -> {next_state, state5, Data};
%consume close
state1(internal, {send_ai_close, Ai_close}, Data) -> {stop, normal, Data}.
state2(enter, _OldState, _Data) -> keep_state_and_data;
%consume coord
state2(internal, {send_ai_coord, Ai_coord}, Data) -> {next_state, state3, Data}.
state3(enter, _OldState, _Data) -> keep_state_and_data;
state3(cast, {receive_ia_state, Ia_state}, Data) -> {stop, normal, Data}.
terminate(_Reason, _State, _Data) -> ok.
state5(enter, _OldState, _Data) -> keep_state_and_data;
%consume snap
state5(cast, {receive_ia_snap, Ia_snap}, Data) -> {stop, normal, Data}.
receive_ia_snap(Ia_snap) ->
gen_statem:cast(?SERVER, {receive_ia_snap, Ia_snap}).
receive_ia_state(Ia_state) ->
gen_statem:cast(?SERVER, {receive_ia_state, Ia_state}).
send_ai_close(Ai_close) ->
gen_statem:internal(?SERVER, {send_ai_close, Ai_close}).
send_ai_coord(Ai_coord) ->
gen_statem:internal(?SERVER, {send_ai_coord, Ai_coord}).
send_ai_get(Ai_get) -> gen_statem:internal(?SERVER, {send_ai_get, Ai_get}).
send_ai_set(Ai_set) -> gen_statem:internal(?SERVER, {send_ai_set, Ai_set}).
stop() -> gen_statem:stop(?SERVER). | null | https://raw.githubusercontent.com/LauraVoinea/protocol-reengineering-implementation/c20263e4fb7f88005444638cb23227407d29d698/src/examples/agents/agent2_stub.erl | erlang | consume n
consume set
consume get
consume close
consume coord
consume snap | -module(agent2_stub).
-behaviour(gen_statem).
-define(SERVER, ?MODULE).
-export([callback_mode/0,
init/1,
receive_ia_snap/1,
receive_ia_state/1,
send_ai_close/1,
send_ai_coord/1,
send_ai_get/1,
send_ai_set/1,
start_link/0,
state1/3,
state2/3,
state3/3,
state5/3,
stop/0,
terminate/3]).
start_link() -> gen_statem:start_link({local, ?SERVER}, ?MODULE, [], []).
callback_mode() -> [state_functions, state_enter].
init([]) -> {ok, state1, {}}.
state1(enter, _OldState, _Data) -> keep_state_and_data;
state1(internal, {send_ai_set, Ai_set}, Data) -> {next_state, state2, Data};
state1(internal, {send_ai_get, Ai_get}, Data) -> {next_state, state5, Data};
state1(internal, {send_ai_close, Ai_close}, Data) -> {stop, normal, Data}.
state2(enter, _OldState, _Data) -> keep_state_and_data;
state2(internal, {send_ai_coord, Ai_coord}, Data) -> {next_state, state3, Data}.
state3(enter, _OldState, _Data) -> keep_state_and_data;
state3(cast, {receive_ia_state, Ia_state}, Data) -> {stop, normal, Data}.
terminate(_Reason, _State, _Data) -> ok.
state5(enter, _OldState, _Data) -> keep_state_and_data;
state5(cast, {receive_ia_snap, Ia_snap}, Data) -> {stop, normal, Data}.
receive_ia_snap(Ia_snap) ->
gen_statem:cast(?SERVER, {receive_ia_snap, Ia_snap}).
receive_ia_state(Ia_state) ->
gen_statem:cast(?SERVER, {receive_ia_state, Ia_state}).
send_ai_close(Ai_close) ->
gen_statem:internal(?SERVER, {send_ai_close, Ai_close}).
send_ai_coord(Ai_coord) ->
gen_statem:internal(?SERVER, {send_ai_coord, Ai_coord}).
send_ai_get(Ai_get) -> gen_statem:internal(?SERVER, {send_ai_get, Ai_get}).
send_ai_set(Ai_set) -> gen_statem:internal(?SERVER, {send_ai_set, Ai_set}).
stop() -> gen_statem:stop(?SERVER). |
599cd35d9f070cf5ad9187ba851d3e114f7dc9c16d7cbf57a840a0b8c3dfc50e | hoodunit/grub | grub_list.cljs | (ns grub.view.grub-list
(:require [grub.view.dom :as dom]
[grub.view.grub :as grub-view]
[om.core :as om :include-macros true]
[sablono.core :refer-macros [html]]
[cljs.core.async :as a :refer [<! chan]])
(:require-macros [cljs.core.async.macros :refer [go go-loop]]))
(defn get-grub-ingredient [grub]
(when-not (nil? (:text grub))
(let [text (clojure.string/lower-case (:text grub))
match (re-find #"[a-z]{3}.*$" text)]
match)))
(defn sort-grubs [grubs]
(->> grubs
(vals)
(sort-by (juxt :completed get-grub-ingredient :text))))
(defn add-grub [owner grubs new-grub-text]
(when (not (empty? new-grub-text))
(let [new-grub (grub-view/new-grub new-grub-text)]
(om/set-state! owner :new-grub-text "")
(om/transact! grubs nil #(assoc % (keyword (:id new-grub)) new-grub) :local))))
(defn view [grubs owner]
(reify
om/IInitState
(init-state [_]
{:new-grub-text ""
:remove-grub-ch (chan)})
om/IRenderState
(render-state [this {:keys [new-grub-text remove-grub-ch] :as state}]
(html
[:div
[:h3 "Grub List"]
[:div.input-group.add-grub-input-form
[:span.input-group-btn
[:input.form-control#add-grub-input
{:type "text"
:placeholder "What do you need?"
:value new-grub-text
:on-key-up #(when (dom/enter-pressed? %)
(add-grub owner grubs new-grub-text))
:on-change #(om/set-state! owner :new-grub-text (dom/event-val %))}]]
[:button.btn.btn-primary
{:id "add-grub-btn"
:type "button"
:on-click #(add-grub owner grubs new-grub-text)}
[:span.glyphicon.glyphicon-plus#add-grub-btn]]]
[:ul#grub-list.list-group
(for [grub (sort-grubs grubs)]
(om/build grub-view/view grub {:key :id :opts {:remove-ch remove-grub-ch}}))]
[:button.btn.pull-right
{:id "clear-all-btn"
:class (when (empty? grubs) "hidden")
:type "button"
:on-click #(om/update! grubs nil {} :local)}
"Clear all"]]))
om/IWillMount
(will-mount [_]
(let [add-grubs-ch (om/get-shared owner :add-grubs-ch)
remove-grub-ch (om/get-state owner :remove-grub-ch)]
(go-loop []
(let [grubs-map (<! add-grubs-ch)]
(when-not (nil? grubs-map)
(om/transact! grubs nil #(merge % grubs-map) :local)
(recur))))
(go-loop []
(let [id (<! remove-grub-ch)]
(when-not (nil? id)
(om/transact! grubs nil #(dissoc % (keyword id)) :local)
(recur))))))))
| null | https://raw.githubusercontent.com/hoodunit/grub/6e47218c34a724d1123717997eac5e196a5bba9b/src/cljs/grub/view/grub_list.cljs | clojure | (ns grub.view.grub-list
(:require [grub.view.dom :as dom]
[grub.view.grub :as grub-view]
[om.core :as om :include-macros true]
[sablono.core :refer-macros [html]]
[cljs.core.async :as a :refer [<! chan]])
(:require-macros [cljs.core.async.macros :refer [go go-loop]]))
(defn get-grub-ingredient [grub]
(when-not (nil? (:text grub))
(let [text (clojure.string/lower-case (:text grub))
match (re-find #"[a-z]{3}.*$" text)]
match)))
(defn sort-grubs [grubs]
(->> grubs
(vals)
(sort-by (juxt :completed get-grub-ingredient :text))))
(defn add-grub [owner grubs new-grub-text]
(when (not (empty? new-grub-text))
(let [new-grub (grub-view/new-grub new-grub-text)]
(om/set-state! owner :new-grub-text "")
(om/transact! grubs nil #(assoc % (keyword (:id new-grub)) new-grub) :local))))
(defn view [grubs owner]
(reify
om/IInitState
(init-state [_]
{:new-grub-text ""
:remove-grub-ch (chan)})
om/IRenderState
(render-state [this {:keys [new-grub-text remove-grub-ch] :as state}]
(html
[:div
[:h3 "Grub List"]
[:div.input-group.add-grub-input-form
[:span.input-group-btn
[:input.form-control#add-grub-input
{:type "text"
:placeholder "What do you need?"
:value new-grub-text
:on-key-up #(when (dom/enter-pressed? %)
(add-grub owner grubs new-grub-text))
:on-change #(om/set-state! owner :new-grub-text (dom/event-val %))}]]
[:button.btn.btn-primary
{:id "add-grub-btn"
:type "button"
:on-click #(add-grub owner grubs new-grub-text)}
[:span.glyphicon.glyphicon-plus#add-grub-btn]]]
[:ul#grub-list.list-group
(for [grub (sort-grubs grubs)]
(om/build grub-view/view grub {:key :id :opts {:remove-ch remove-grub-ch}}))]
[:button.btn.pull-right
{:id "clear-all-btn"
:class (when (empty? grubs) "hidden")
:type "button"
:on-click #(om/update! grubs nil {} :local)}
"Clear all"]]))
om/IWillMount
(will-mount [_]
(let [add-grubs-ch (om/get-shared owner :add-grubs-ch)
remove-grub-ch (om/get-state owner :remove-grub-ch)]
(go-loop []
(let [grubs-map (<! add-grubs-ch)]
(when-not (nil? grubs-map)
(om/transact! grubs nil #(merge % grubs-map) :local)
(recur))))
(go-loop []
(let [id (<! remove-grub-ch)]
(when-not (nil? id)
(om/transact! grubs nil #(dissoc % (keyword id)) :local)
(recur))))))))
| |
21d65287f1fc00e98072c0d30d921691986209d4b26f27d1312768150e2f65d6 | EMSL-NMR-EPR/Haskell-MFAPipe-Executable | Statistics.hs | module MFAPipe.Csv.Types.Statistics
( StatisticsRecords(..)
, StatisticsRecord(..)
, encode
, encodeWith
) where
import Data.ByteString.Lazy (ByteString)
import qualified Data.Csv
import Data.Csv (DefaultOrdered(headerOrder), ToField(), ToNamedRecord(toNamedRecord), EncodeOptions)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict
import Data.Text (Text)
import qualified Data.Text
import MFAPipe.Csv.Constants
data StatisticsRecords e = StatisticsRecords e ((e, e), Map Text (e, e)) ((e, e), Map Text (e, e)) (Int, Map Text Int) (Int, Map Text Int) (e, Map Text e) (e, Map Text e) (e, Map Text e)
deriving (Eq, Ord, Read, Show)
data StatisticsRecord e = StatisticsRecord e Text (e, e) (e, e) {-# UNPACK #-} !Int {-# UNPACK #-} !Int e e e
deriving (Eq, Ord, Read, Show)
instance DefaultOrdered (StatisticsRecord e) where
headerOrder _ = Data.Csv.header
[ cExperimentFieldName
, cExperimentMeanFieldName
, cExperimentVarianceFieldName
, cTolerance
, cIndependentMeasurementsCount
, cIndependentFluxesCount
, cDegreesOfFreedomFieldName
, cKolmogorovSmirnovDFieldName
, cKolmogorovSmirnovProbabilityFieldName
, cWeightedSSEFieldName
, cWeightedSSTFieldName
, cWeightedRSquareFieldName
, cWeightedRSquareAdjustedFieldName
, cReducedChiSquare
]
instance (ToField e, Fractional e) => ToNamedRecord (StatisticsRecord e) where
toNamedRecord (StatisticsRecord tol experiment (mean, var) (d, p) degreesOfFreedom measurementsCount sse sst chi2) = Data.Csv.namedRecord
[ Data.Csv.namedField cExperimentFieldName experiment
, Data.Csv.namedField cExperimentMeanFieldName mean
, Data.Csv.namedField cExperimentVarianceFieldName var
, Data.Csv.namedField cTolerance tol
, Data.Csv.namedField cIndependentMeasurementsCount measurementsCount
, Data.Csv.namedField cIndependentFluxesCount fluxVarCount
, Data.Csv.namedField cDegreesOfFreedomFieldName degreesOfFreedom
, Data.Csv.namedField cKolmogorovSmirnovDFieldName d
, Data.Csv.namedField cKolmogorovSmirnovProbabilityFieldName p
, Data.Csv.namedField cWeightedSSEFieldName sse
, Data.Csv.namedField cWeightedSSTFieldName sst
, Data.Csv.namedField cWeightedRSquareFieldName r2
, Data.Csv.namedField cWeightedRSquareAdjustedFieldName adj_r2
, Data.Csv.namedField cReducedChiSquare chi2
]
where
fluxVarCount = measurementsCount - degreesOfFreedom
r2 = 1 - (sse / sst)
-- <#Adjusted_R2>
adj_r2 = r2 - ((1 - r2) * (fromIntegral (fluxVarCount - 1) / fromIntegral degreesOfFreedom))
encode :: (ToField e, Fractional e) => StatisticsRecords e -> ByteString
encode = encodeWith Data.Csv.defaultEncodeOptions
encodeWith :: (ToField e, Fractional e) => EncodeOptions -> StatisticsRecords e -> ByteString
encodeWith opts (StatisticsRecords tol0 (meanVar0, meanVarMap) (p0, pMap) (degreesOfFreedom0, degreesOfFreedomMap) (measurementsCount0, measurementsCountMap) (sse0, sseMap) (sst0, sstMap) (chi20, chi2Map)) = Data.Csv.encodeDefaultOrderedByNameWith opts (x : xs)
where
x = StatisticsRecord tol0 (Data.Text.singleton '*') meanVar0 p0 degreesOfFreedom0 measurementsCount0 sse0 sst0 chi20
xs = map (uncurry (\experiment (meanVar, (p, (degreesOfFreedom, (measurementsCount, (sse, (sst, chi2)))))) -> StatisticsRecord tol0 experiment meanVar p degreesOfFreedom measurementsCount sse sst chi2)) (Data.Map.Strict.toAscList (Data.Map.Strict.intersectionWith (,) meanVarMap (Data.Map.Strict.intersectionWith (,) pMap (Data.Map.Strict.intersectionWith (,) degreesOfFreedomMap (Data.Map.Strict.intersectionWith (,) measurementsCountMap (Data.Map.Strict.intersectionWith (,) sseMap (Data.Map.Strict.intersectionWith (,) sstMap chi2Map)))))))
| null | https://raw.githubusercontent.com/EMSL-NMR-EPR/Haskell-MFAPipe-Executable/8a7fd13202d3b6b7380af52d86e851e995a9b53e/MFAPipe/app/MFAPipe/Csv/Types/Statistics.hs | haskell | # UNPACK #
# UNPACK #
<#Adjusted_R2> | module MFAPipe.Csv.Types.Statistics
( StatisticsRecords(..)
, StatisticsRecord(..)
, encode
, encodeWith
) where
import Data.ByteString.Lazy (ByteString)
import qualified Data.Csv
import Data.Csv (DefaultOrdered(headerOrder), ToField(), ToNamedRecord(toNamedRecord), EncodeOptions)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict
import Data.Text (Text)
import qualified Data.Text
import MFAPipe.Csv.Constants
data StatisticsRecords e = StatisticsRecords e ((e, e), Map Text (e, e)) ((e, e), Map Text (e, e)) (Int, Map Text Int) (Int, Map Text Int) (e, Map Text e) (e, Map Text e) (e, Map Text e)
deriving (Eq, Ord, Read, Show)
deriving (Eq, Ord, Read, Show)
instance DefaultOrdered (StatisticsRecord e) where
headerOrder _ = Data.Csv.header
[ cExperimentFieldName
, cExperimentMeanFieldName
, cExperimentVarianceFieldName
, cTolerance
, cIndependentMeasurementsCount
, cIndependentFluxesCount
, cDegreesOfFreedomFieldName
, cKolmogorovSmirnovDFieldName
, cKolmogorovSmirnovProbabilityFieldName
, cWeightedSSEFieldName
, cWeightedSSTFieldName
, cWeightedRSquareFieldName
, cWeightedRSquareAdjustedFieldName
, cReducedChiSquare
]
instance (ToField e, Fractional e) => ToNamedRecord (StatisticsRecord e) where
toNamedRecord (StatisticsRecord tol experiment (mean, var) (d, p) degreesOfFreedom measurementsCount sse sst chi2) = Data.Csv.namedRecord
[ Data.Csv.namedField cExperimentFieldName experiment
, Data.Csv.namedField cExperimentMeanFieldName mean
, Data.Csv.namedField cExperimentVarianceFieldName var
, Data.Csv.namedField cTolerance tol
, Data.Csv.namedField cIndependentMeasurementsCount measurementsCount
, Data.Csv.namedField cIndependentFluxesCount fluxVarCount
, Data.Csv.namedField cDegreesOfFreedomFieldName degreesOfFreedom
, Data.Csv.namedField cKolmogorovSmirnovDFieldName d
, Data.Csv.namedField cKolmogorovSmirnovProbabilityFieldName p
, Data.Csv.namedField cWeightedSSEFieldName sse
, Data.Csv.namedField cWeightedSSTFieldName sst
, Data.Csv.namedField cWeightedRSquareFieldName r2
, Data.Csv.namedField cWeightedRSquareAdjustedFieldName adj_r2
, Data.Csv.namedField cReducedChiSquare chi2
]
where
fluxVarCount = measurementsCount - degreesOfFreedom
r2 = 1 - (sse / sst)
adj_r2 = r2 - ((1 - r2) * (fromIntegral (fluxVarCount - 1) / fromIntegral degreesOfFreedom))
encode :: (ToField e, Fractional e) => StatisticsRecords e -> ByteString
encode = encodeWith Data.Csv.defaultEncodeOptions
encodeWith :: (ToField e, Fractional e) => EncodeOptions -> StatisticsRecords e -> ByteString
encodeWith opts (StatisticsRecords tol0 (meanVar0, meanVarMap) (p0, pMap) (degreesOfFreedom0, degreesOfFreedomMap) (measurementsCount0, measurementsCountMap) (sse0, sseMap) (sst0, sstMap) (chi20, chi2Map)) = Data.Csv.encodeDefaultOrderedByNameWith opts (x : xs)
where
x = StatisticsRecord tol0 (Data.Text.singleton '*') meanVar0 p0 degreesOfFreedom0 measurementsCount0 sse0 sst0 chi20
xs = map (uncurry (\experiment (meanVar, (p, (degreesOfFreedom, (measurementsCount, (sse, (sst, chi2)))))) -> StatisticsRecord tol0 experiment meanVar p degreesOfFreedom measurementsCount sse sst chi2)) (Data.Map.Strict.toAscList (Data.Map.Strict.intersectionWith (,) meanVarMap (Data.Map.Strict.intersectionWith (,) pMap (Data.Map.Strict.intersectionWith (,) degreesOfFreedomMap (Data.Map.Strict.intersectionWith (,) measurementsCountMap (Data.Map.Strict.intersectionWith (,) sseMap (Data.Map.Strict.intersectionWith (,) sstMap chi2Map)))))))
|
3835e6593517a94904d1aba5a83fc60d3288a157352df5e92576a59e0896f284 | bazqux/bazqux-urweb | YouTube.hs | # LANGUAGE MultiWayIf , ViewPatterns , OverloadedStrings #
-- | YouTube
module Parser.YouTube
( customParsers
) where
import Control.Monad
import Data.Maybe
import Data.List
import Data.Ord
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as B
import qualified Data.Aeson as JSON
import Lib.Json
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as V
import Parser.Types
import Parser.Custom
import Lib.UrTime
import Lib.StringConversion
import Lib.Regex
import Text.HTML.TagSoup hiding (parseTags, renderTags)
import Text.HTML.TagSoup.Fast
import Control.Applicative
import URL
import Config (googleApiKey)
customParsers =
mkCustomParsers ["youtube.com"]
[ ( rt "youtube\\.com/channel/",
changeUrl transformYoutubeChannel, CPJSON handleYoutubeChannel )
, ( rt "youtube\\.com/c/",
noChange, CPTags handleYoutubeCustomUrlChannel )
, ( rt "youtube\\.com/user/",
changeUrl transformYoutubeUser, CPJSON handleYoutubeChannel )
, ( isJust . youtubeUserAndPlaylistV2,
changeUrl transformYoutubeUser, CPJSON handleYoutubeChannel )
, ( isJust . youtubeVideosXmlToChannel,
changeUrl (fromJust . youtubeVideosXmlToChannel), CPJSON handleYoutubeChannel )
, ( isJust . youtubeMostPopularUrl,
changeUrl (fromJust . youtubeMostPopularUrl), CPJSON handleYoutubeMostPopular )
, ( isJust . youtubeSearchUrlAndSubject,
changeUrl (fst . fromJust . youtubeSearchUrlAndSubject), CPJSON handleYoutubeSearch )
, ( isJust . youtubePlaylistId,
youtubePlaylistParser . fromJust . youtubePlaylistId, CPJSON handleYoutubePlaylist )
]
ytBaseUrl = ""
-- +id%2C+snippet%2C+status%2C+
--
contentDetails у playlistItems содержит .
Для получения duration запрос video details
youtubePlaylistParser p _ =
return ( playlistItemsUrl 20 Nothing p
, Just
(T.concat [ytBaseUrl, "/playlists?part=snippet&id="
, p, "&", googleApiKey]
,\ a b -> B.concat ["[", a, ",", b, "]"])
, Nothing)
неприятный момент -- некоторые плейлисты отсортированы от самых ранних
и выдаются именно в таком порядке , т.е . paging использовать
Но uploads отсортированы в обратном порядке
playlistItemsUrl maxResults nextPageToken playlistId =
T.concat [ytBaseUrl, "/playlistItems?part=contentDetails&maxResults="
, showT maxResults
, maybe "" ("&pageToken=" <>) nextPageToken
, "&playlistId=", playlistId, "&", googleApiKey]
youtubePlaylistId u
| [[_,id]] <- regexGet "youtube\\.com/playlist\\?list=([^&=?]+)" u =
Just id
| regexTest "^https?://(www.|gdata.)?youtube.com/(xml/)?feeds/videos.xml" u
, Right qs <- urlQueryStringUtf8Only u
, Just id <- lookup "playlist_id" qs =
Just id
| [[_, _, _, pl]] <-
regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?playlists/([^/?&#]+)" u
= Just pl
| otherwise = Nothing
-- testYoutube = withLogger $ \ l -> logTime l "testYoutube" $ do
-- -- parseUrlT ""
-- parseUrlT " +piano "
-- parseUrlT " "
-- -- parseUrlT ""
-- -- parseUrlT ""
parseUrlT " -index=1&max-results=25&client=ytapi-youtube-user&v=2 "
subscriptions list выдает HTTP 403 subscriptionForbidden
-- --
-- -- parseUrlT "-p_K4bHQ/newsubscriptionvideos"
-- -- parseUrlT "" -- так не находит
handleYoutubeItems guidFormat xs result = do
JSON.Array (V.toList -> is) <- HM.lookup "items" xs
let videoId = withObj $ \ i ->
do cd <-
obj "contentDetails" i -- playlist
<|>
obj "id" i -- search results
str "videoId" cd
<|>
str "id" i -- most popular
vids = mapMaybe videoId is
return $ youtubeVideosBatch guidFormat result vids
youtubeVideosBatch guidFormat result [] = result []
youtubeVideosBatch guidFormat result xs =
PRAdditionalDownload "YouTube video details"
[T.concat
[ ytBaseUrl, "/videos?part=id%2CcontentDetails%2Csnippet&id="
, encodeURIComponentT $ T.intercalate "," ids
, "&maxResults=50&", googleApiKey ]
| ids <- groupByN 50 xs ]
(combineDownloadsBS $ fromMaybe (PRError "Invalid JSON") .
handleYoutubeVideos guidFormat result)
handleYoutubeVideos guidFormat result dat =
fmap (result . take 100 . sortBy (comparing $ Down . fmPublishedTime) . concat) $
forM dat $ \ d -> do
JSON.Object xs <- decodeJson d
is <- arr "items" xs
let mkGuid
| Just f <- guidFormat = \ g -> T.replace "VIDEO_ID" g f
| otherwise = id
feedMsg js = do
-- error $ show js
JSON.Object i <- return js
JSON.Object status < - HM.lookup " status " i
- HM.lookup " privacyStatus " status
guard ( privacyStatus /= " private " )
snippet <- obj "snippet" i
videoId <- str "id" i
title <- str "title" snippet
description <- str "description" snippet
publishedAt <- str "publishedAt" snippet
cd <- obj "contentDetails" i
d <- str "duration" cd
duration <- readIso8601Duration $ T.unpack d
-- statistics <- obj "statistics" i
views < - str " " statistics
likes < - str " likeCount " statistics < | > Just " 0 "
dislikes < - str " dislikeCount " statistics < | > Just " 0 "
return $
defaultFeedMsg
{ fmGuid = mkGuid videoId
, fmAuthor = fromMaybe "" $ str "channelTitle" snippet
, fmPublishedTime = readRfc3339 $ T.unpack publishedAt
, fmBody =
T.concat
[embedYoutube videoId
,videoDuration duration
,htmlfyYoutubeDescription
(addHashTags 1
$ T.append "/" . T.toLower)
description]
, fmSubject = title
, fmLinks =
[(LKLink, T.concat ["="
, videoId])]
++ fromMaybe [] (do
c <- str "channelId" snippet
return [( LKAuthor
, "/" <> c)
, ( LKAuthorPic
, " / " < > T.drop 2 c < > " /1.jpg " )
Не везде такая
-- -mitchell.com/blog/display-youtube-user-avatar-profile-picture-by-username/
])
}
return $ mapMaybe feedMsg is
handleYoutubeMostPopular _ u j = fromMaybe (PRError "Invalid JSON") $ do
JSON.Object xs <- return j
handleYoutubeItems (Just $ youtubeGuidFormat u) xs $
PRFeed u
(defaultFeedMsg
{ fmSubject = "Most Popular"
, fmLinks = [(LKLink, "")] })
handleYoutubeSearch _ u j = fromMaybe (PRError "Invalid JSON") $ do
JSON.Object xs <- return j
(_,(subject,url)) <- youtubeSearchUrlAndSubject u
handleYoutubeItems (Just $ youtubeGuidFormat u) xs $
PRFeed u
(defaultFeedMsg
{ fmSubject = subject
, fmLinks = [(LKLink, url)] })
handleYoutubePlaylist _ u j = fromMaybe (PRError "Invalid JSON") $ do
JSON.Array (V.toList -> [JSON.Object xs, JSON.Object playlist]) <- return j
JSON.Array (V.toList -> (JSON.Object i:_)) <- HM.lookup "items" playlist
JSON.String playlistId <- HM.lookup "id" i
JSON.Object snippet <- HM.lookup "snippet" i
JSON.String title <- HM.lookup "title" snippet
let guidFormat = either (const Nothing) (lookup "bq_guid_format")
$ urlQueryStringUtf8Only u
result =
PRFeed u
(defaultFeedMsg
{ fmSubject = fromMaybe title $ T.stripPrefix "Uploads from " title
, fmLinks =
[(LKLink, "=" <> playlistId) ] })
batch = youtubeVideosBatch guidFormat result . map snd
sortIs = sortBy (comparing $ Down . fst)
loop n xs acc
| n < 2
, Just npt <- str "nextPageToken" xs =
PRAdditionalDownload
("Next page of unsorted playlist (#" <> showT n <> ")")
[playlistItemsUrl 50 (Just npt) playlistId]
(combineDownloadsBS $ \ [d] -> fromMaybe (PRError "Invalid JSON") $ do
JSON.Object xs' <- decodeJson d
is' <- playlistItems xs'
return $ loop (n+1) xs' (is' <> acc))
| otherwise =
batch $ take 20 $ sortIs acc
is <- playlistItems xs
Бывает , что старое видео публикуется не сразу и свежее видео на сайта
-- оказывается далеко не на первом мести внутри плейлиста YouTube.
еще 100 видео ,
сортируем и обрабатываем последние 20 .
return $ if sortIs is == is then batch is else loop 0 xs is
playlistItems xs = do
JSON.Array (V.toList -> is) <- HM.lookup "items" xs
let timeVid = withObj $ \ i -> do
cd <- obj "contentDetails" i
vid <- str "videoId" cd
time <-str "videoPublishedAt" cd
return (readRfc3339 $ T.unpack time, vid)
return $ mapMaybe timeVid is
youtubeChannelUrl u =
T.concat [ytBaseUrl, "/channels?part=id%2C+contentDetails&id="
, u, "&", googleApiKey]
youtubeUserUrl u
| regexTest "^UC[A-Za-z0-9_\\-]{22}$" u = youtubeChannelUrl u
| otherwise =
T.concat [ytBaseUrl, "/channels?part=id%2C+contentDetails&forUsername="
, u, "&", googleApiKey]
transformYoutubeChannel u
| [[_,id]] <- regexGet "youtube\\.com/channel/([^&=?/]+)" u =
youtubeChannelUrl id
| otherwise = u
transformYoutubeUser u
| [[_,id]] <- regexGet "youtube\\.com/user/([^&=?/]+)" u = youtubeUserUrl id
| Just (id,_) <- youtubeUserAndPlaylistV2 u = youtubeUserUrl id
| otherwise = u
TODO : плохо это все с плейлистом -- transform и матчинг
-- в customParsers
youtubeUserAndPlaylistV2 u
| [[_, _, _, user, playlist]] <-
regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?users/([^/?&#]+)/([^/?&#]+)" u
, playlist /= " " -- пока позволяем старым работать
= Just (user, playlist)
| regexTest "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos" u
, Right qs <- urlQueryStringUtf8Only u
, Just user <- lookup "author" qs
= Just (user, "uploads")
| otherwise = Nothing
urlHasV2 u
| Right qs <- urlQueryStringUtf8Only u
, Just v <- lookup "v" qs = v == "2"
| otherwise = False
youtubeVideosXmlToChannel u
| regexTest "^https?://(www.|gdata.)?youtube.com/(xml/)?feeds/videos.xml" u
, Right qs <- urlQueryStringUtf8Only u =
if | Just ch <- lookup "channel_id" qs -> Just (youtubeChannelUrl ch)
| Just us <- lookup "user" qs -> Just (youtubeUserUrl us)
| otherwise -> Nothing
| otherwise = Nothing
-- с поиском , но как ограничить поиск автором я не знаю , так что нафиг
-- ={YOUR_API_KEY}
-- q=query
-- relatedToVideoId=
-- regionCode
order= по умолчанию relevance
-- date
rating -- выводит какую - то фигню
-- viewCount
--
Для related to , но order = date -- видео в разнобой ,
но в RSS - фидах они тоже в разнобой
-- -mlo&type=video&key={YOUR_API_KEY}
-- ={YOUR_API_KEY}
топовые по . На youtube это просто плейлист , и на него можно подписаться
можно к ним привести
youtubeMostPopularUrl u
| r@[[_, _, _, country]] <-
regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)standardfeeds/([A-Z][A-Z])?" u
= Just $ T.concat
[ ytBaseUrl, "/videos?part=id&chart=mostPopular&maxResults=20"
, if | country /= "" ->
"®ionCode=" <> country
| Right (lookup "lang" -> Just lang) <- urlQueryStringUtf8Only u ->
"®ionCode=" <> T.toUpper lang
| otherwise ->
""
, "&", googleApiKey ]
| otherwise = Nothing
youtubeSearchUrlAndSubject u
| [[_,_,_,q]] <- regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos/-/([^?&]+)" u
= r (T.unwords $ map decodeURIComponentT $ T.split (== '/') q) ""
searchSubj searchUrl
| [[_,_,_,vid]] <- regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos/([^/]+)/related" u
= r "" ("&relatedToVideoId=" <> vid)
(const "Related videos")
должно быть Videos related to ' Название видео ' , но что - то лень копаться
(const $
"="
<> vid)
^ такого URL на youtube уже нет
| regexTest "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos" u
, Right qs <- urlQueryStringUtf8Only u
, Just q <- lookup "q" qs
= r q "" searchSubj searchUrl
| regexTest "^https?://(www.)?youtube.com/results" u
, Right qs <- urlQueryStringUtf8Only u
, Just q <- lookup "search_query" qs
= r q filters searchSubj
((<> maybe "" ("&filters="<>) (lookup "filters" qs)) . searchUrl)
| otherwise = Nothing
where r q add subj url = Just (T.concat [ytBaseUrl, "/search?part=id&maxResults=20&order=date&type=video&q=", encodeURIComponentT q, add, "&", googleApiKey], (subj q, url q))
filters
| Right qs <- urlQueryStringUtf8Only u
, Just fs <- lookup "filters" qs
= T.concat $ map (fOpt . T.toLower) $ T.split (== ',') fs
| otherwise = ""
fOpt "short" = "&videoDuration=short"
fOpt "medium" = "&videoDuration=medium"
fOpt "long" = "&videoDuration=long"
fOpt "hd" = "&videoDefinition=hd"
в API вроде пока нет 4k
fOpt "3d" = "&videoDimension=3d"
fOpt "cc" = "&videoCaption=closedCaption"
fOpt "creativecommons" = "&videoLicense=creativeCommon"
fOpt "movie" = "&videoType=movie"
fOpt "show" = "&videoType=episode"
fOpt "live" = "&eventType=live"
fOpt _ = ""
searchSubj q = q <> " - YouTube"
-- searchSubj q = "Videos matching: " <> q
searchUrl q = "=" <> encodeURIComponentT q <> sortByDate
sortByDate = "&search_sort=video_date_uploaded"
handleYoutubeCustomUrlChannel _ _ t = go t
where go [] = PRError "Can’t find Youtube channel"
go (TagOpen "meta" as : ts)
| Just "channelId" <- lookup "itemprop" as
, Just cid <- lookup "content" as =
PRRedirect $ "/" <> cid
go (_ : ts) = go ts
handleYoutubeChannel t u j
| Just (_, p) <- youtubeUserAndPlaylistV2 u =
if p = = " " then
PRError " are no longer supported by Youtube.\nStar this issue -issues/issues/detail?id=3946 "
-- else
handleYoutubeChannel' (Just $ youtubeGuidFormat u)
p t u j
| otherwise =
handleYoutubeChannel'
(fmap (const "yt:video:VIDEO_ID") $ youtubeVideosXmlToChannel u)
"uploads" t u j
стоит собирать все video i d и делать дополнительный запрос по ним
-- DRDependentDownload -- скачивание, которое не redirect-ит при подписке
так можно узнать video duration , а в snippet показываются channelTitle
с пробелами и
-- -api-v3-how-to-get-video-durations
По идее , так же можно и newsubscriptionvideos обработать
Ограничений на youtube , можно параллельно качать
youtubeGuidFormat u =
if urlHasV2 u then
"tag:youtube.com,2008:video:VIDEO_ID"
else if ".com/feeds/base/" `T.isInfixOf` u then
""
else if ".com/feeds/api/" `T.isInfixOf` u then
""
else
""
handleYoutubeChannel' guidFormat playlist _ u j = fromMaybe (PRError "Can’t find Youtube channel") $ do
JSON.Object o <- return j
(JSON.Object i:_) <- arr "items" o
cd <- obj "contentDetails" i
rp <- obj "relatedPlaylists" cd
(do guard (playlist == "newsubscriptionvideos")
ch <- str "id" i
return $ PRAdditionalDownload "YouTube subscriptions list"
[youtubeSubscriptionsListUrl ch Nothing]
(combineDownloadsBS $ handleYoutubeSubscriptionsList guidFormat ch [])
<|>
do u <- str playlist rp
return $ PRRedirect ("=" <> u <>
maybe "" (("&bq_guid_format="<>) . encodeURIComponentT)
guidFormat)
<|>
return (PRError $ T.concat ["Can’t find “", playlist, "” playlist"]))
youtubeSubscriptionsListUrl channelId pageToken =
T.concat [ ytBaseUrl, "/subscriptions?part=snippet&channelId="
, channelId, "&maxResults=50&", googleApiKey
, maybe "" ("&pageToken="<>) pageToken ]
-- Код отсюда
--
handleYoutubeSubscriptionsList guidFormat ch acc dat = fromMaybe (PRError "Invalid user subscriptions JSON") $ do
JSON.Object xs <- decodeJson $ B.concat dat
is <- arr "items" xs
let chans = mapMaybe chan is ++ acc
chan = withObj $ str "channelId" <=< obj "resourceId" <=< obj "snippet"
plUrl cs =
T.concat
[ ytBaseUrl, "/channels?part=contentDetails&id="
, encodeURIComponentT $ T.intercalate "," cs
, "&maxResults=50&", googleApiKey ]
return $ case str "nextPageToken" xs of
Just p ->
PRAdditionalDownload "YouTube subscriptions list (next page)"
[youtubeSubscriptionsListUrl ch (Just p)]
(combineDownloadsBS $
handleYoutubeSubscriptionsList guidFormat ch chans)
Nothing ->
PRAdditionalDownload "YouTube subscriptions playlist IDs"
(map plUrl $ groupByN 50 $ hashSetNub chans)
(combineDownloadsBS $
handleYoutubeSubscriptionsPlaylistsList guidFormat)
handleYoutubeSubscriptionsPlaylistsList guidFormat dat = fromMaybe (PRError "Invalid user subscriptions playlists JSON") $ do
let pls d = do
JSON.Object xs <- decodeJson d
mapMaybe pl `fmap` arr "items" xs
pl = withObj $
str "uploads" <=< obj "relatedPlaylists" <=< obj "contentDetails"
playlists = hashSetNub $ concat $ mapMaybe pls dat
pliUrl p =
T.concat
[ ytBaseUrl
, "/playlistItems?part=contentDetails&maxResults=20&playlistId="
, p, "&", googleApiKey ]
maxResults 5->20 дает общее время 13->19 , что не намного больше ,
зато гораздо меньше вероятность что - либо пропустить ,
а если на 50 , а не 20 , то опять те же 13
return $
PRAdditionalDownload "YouTube playlists"
(map pliUrl playlists)
(CombineDownloads $
handleYoutubeSubscriptionsPlaylistsItems guidFormat)
handleYoutubeSubscriptionsPlaylistsItems guidFormat dat = fromMaybe (PRError "Invalid user subscriptions playlist items JSON") $ do
let vids = either (const $ return []) $ \ d -> do
у каналов без видео бывают плейлисты uploads ,
-- HTTP 404 Not found при попытке их выкачать
JSON.Object xs <- decodeJson d
mapMaybe vid `fmap` arr "items" xs
vid = withObj $ str "videoId" <=< obj "contentDetails"
videos = hashSetNub $ concat $ mapMaybe vids dat
feed = PRFeed "/"
(defaultFeedMsg
{ fmSubject = "New Subscription Videos"
, fmLinks = [(LKLink, "")] })
return $ youtubeVideosBatch guidFormat feed videos
Префикс
-- (www.|gdata.|)youtube.com/feeds/(api/|base/)?
4 вида GUID - ов
GUID yt : video : VIDEO_ID -- videos.xml
GUID tag : youtube.com,2008 : video : VIDEO_ID -- v=2
-- GUID -- без v=2 с base
-- GUID -- без v=2 c api
GUID /<длинная абракадабра ведет на URL >
если с UC , в длину и [ A - Za - z0 - 9_\- ]
-- то это channel
users / USER_NAME / uploads ( )
favorites - playlist , может быть ,
-- playlists/…?
videos/-/Search / Term ? …
videos / VIDEO_ID / related ( не используются /responses|/ratings|/complaints )
-- videos?…q=query
-- videos?…author=USER_NAME
-- standardfeeds/COUNTRY_CODE/TYPE
standardfeeds / TYPE? … lang = COUNTRY_CODE_locase … time = TIME
-- TYPE most_viewed, most_popular, top_rated, recently_featured
TIME today , this_week
-- разницы между most_viewed и API v3 chart=mostPopular
( плейлист самое ) я не нашел
В API v3 дате не задать , ну и ладно
-- -youtube-profile
-- -youtube-profile
уже HTTP 404 , но раньше работало
-- ПОКА РАБОТАЕТ:
--
--
все - таки есть playlist - ы
guid - ы какие - то странные --
--
-- -AUbQ/related?client=ytapi-youtube-watch&v=2
--
-- GUID
-- (http/https, api/base не влияет)
НЕ РАБОТАЕТ
( после device support у некоторых фидов уже появились )
--
--
-- >
-- …
-- …
--
--
-- >
GUID yt : video : VIDEO_ID
НЕ ЗНАЮ АНАЛОГОВ
--
-- ЧЕРЕЗ API
/-/Alasdair/Roberts?v=2&orderby=published&client=ytapi-youtube-rss-redirect&alt=rss
GUID tag : youtube.com,2008 : video : UKY3scPIMd8 ( alt = rss не влияет )
-- /-/bonnie/prince/billy?v=2&alt=rss&client=ytapi-youtube-rss-redirect&orderby=published
тоже , только вот что это ? поиск ? -- да ,
словом них
-- …
-- …
--
-- -youtube-browse&alt=rss&time=today
-- -youtube-browse&alt=rss&time=today&lang=fi
-- -youtube-browse&alt=rss
-- -youtube-rss-redirect&orderby=published&q=connected+home+%7C+smart+home&v=2
-- +education&client=ytapi-youtube-search&v=2
-- GUID
-- даже с alt=rss
-- uploads?orderby=published
-- uploads?orderby=updated
-- ?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile
-- ?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile
? orderby = updated&client = ytapi - youtube - rss - redirect&alt = rss&v=2
много вариантов , надо честно запоминать , что был redirect и обновлять
push
| null | https://raw.githubusercontent.com/bazqux/bazqux-urweb/bf2d5a65b5b286348c131e91b6e57df9e8045c3f/crawler/Parser/YouTube.hs | haskell | | YouTube
+id%2C+snippet%2C+status%2C+
некоторые плейлисты отсортированы от самых ранних
testYoutube = withLogger $ \ l -> logTime l "testYoutube" $ do
-- parseUrlT ""
parseUrlT " +piano "
parseUrlT " "
-- parseUrlT ""
-- parseUrlT ""
--
-- parseUrlT "-p_K4bHQ/newsubscriptionvideos"
-- parseUrlT "" -- так не находит
playlist
search results
most popular
error $ show js
statistics <- obj "statistics" i
-mitchell.com/blog/display-youtube-user-avatar-profile-picture-by-username/
оказывается далеко не на первом мести внутри плейлиста YouTube.
transform и матчинг
в customParsers
пока позволяем старым работать
с поиском , но как ограничить поиск автором я не знаю , так что нафиг
={YOUR_API_KEY}
q=query
relatedToVideoId=
regionCode
date
выводит какую - то фигню
viewCount
видео в разнобой ,
-mlo&type=video&key={YOUR_API_KEY}
={YOUR_API_KEY}
searchSubj q = "Videos matching: " <> q
else
DRDependentDownload -- скачивание, которое не redirect-ит при подписке
-api-v3-how-to-get-video-durations
Код отсюда
HTTP 404 Not found при попытке их выкачать
(www.|gdata.|)youtube.com/feeds/(api/|base/)?
videos.xml
v=2
GUID -- без v=2 с base
GUID -- без v=2 c api
то это channel
playlists/…?
videos?…q=query
videos?…author=USER_NAME
standardfeeds/COUNTRY_CODE/TYPE
TYPE most_viewed, most_popular, top_rated, recently_featured
разницы между most_viewed и API v3 chart=mostPopular
-youtube-profile
-youtube-profile
ПОКА РАБОТАЕТ:
-AUbQ/related?client=ytapi-youtube-watch&v=2
GUID
(http/https, api/base не влияет)
>
…
…
>
ЧЕРЕЗ API
/-/bonnie/prince/billy?v=2&alt=rss&client=ytapi-youtube-rss-redirect&orderby=published
да ,
…
…
-youtube-browse&alt=rss&time=today
-youtube-browse&alt=rss&time=today&lang=fi
-youtube-browse&alt=rss
-youtube-rss-redirect&orderby=published&q=connected+home+%7C+smart+home&v=2
+education&client=ytapi-youtube-search&v=2
GUID
даже с alt=rss
uploads?orderby=published
uploads?orderby=updated
?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile
?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile | # LANGUAGE MultiWayIf , ViewPatterns , OverloadedStrings #
module Parser.YouTube
( customParsers
) where
import Control.Monad
import Data.Maybe
import Data.List
import Data.Ord
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as B
import qualified Data.Aeson as JSON
import Lib.Json
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as V
import Parser.Types
import Parser.Custom
import Lib.UrTime
import Lib.StringConversion
import Lib.Regex
import Text.HTML.TagSoup hiding (parseTags, renderTags)
import Text.HTML.TagSoup.Fast
import Control.Applicative
import URL
import Config (googleApiKey)
customParsers =
mkCustomParsers ["youtube.com"]
[ ( rt "youtube\\.com/channel/",
changeUrl transformYoutubeChannel, CPJSON handleYoutubeChannel )
, ( rt "youtube\\.com/c/",
noChange, CPTags handleYoutubeCustomUrlChannel )
, ( rt "youtube\\.com/user/",
changeUrl transformYoutubeUser, CPJSON handleYoutubeChannel )
, ( isJust . youtubeUserAndPlaylistV2,
changeUrl transformYoutubeUser, CPJSON handleYoutubeChannel )
, ( isJust . youtubeVideosXmlToChannel,
changeUrl (fromJust . youtubeVideosXmlToChannel), CPJSON handleYoutubeChannel )
, ( isJust . youtubeMostPopularUrl,
changeUrl (fromJust . youtubeMostPopularUrl), CPJSON handleYoutubeMostPopular )
, ( isJust . youtubeSearchUrlAndSubject,
changeUrl (fst . fromJust . youtubeSearchUrlAndSubject), CPJSON handleYoutubeSearch )
, ( isJust . youtubePlaylistId,
youtubePlaylistParser . fromJust . youtubePlaylistId, CPJSON handleYoutubePlaylist )
]
ytBaseUrl = ""
contentDetails у playlistItems содержит .
Для получения duration запрос video details
youtubePlaylistParser p _ =
return ( playlistItemsUrl 20 Nothing p
, Just
(T.concat [ytBaseUrl, "/playlists?part=snippet&id="
, p, "&", googleApiKey]
,\ a b -> B.concat ["[", a, ",", b, "]"])
, Nothing)
и выдаются именно в таком порядке , т.е . paging использовать
Но uploads отсортированы в обратном порядке
playlistItemsUrl maxResults nextPageToken playlistId =
T.concat [ytBaseUrl, "/playlistItems?part=contentDetails&maxResults="
, showT maxResults
, maybe "" ("&pageToken=" <>) nextPageToken
, "&playlistId=", playlistId, "&", googleApiKey]
youtubePlaylistId u
| [[_,id]] <- regexGet "youtube\\.com/playlist\\?list=([^&=?]+)" u =
Just id
| regexTest "^https?://(www.|gdata.)?youtube.com/(xml/)?feeds/videos.xml" u
, Right qs <- urlQueryStringUtf8Only u
, Just id <- lookup "playlist_id" qs =
Just id
| [[_, _, _, pl]] <-
regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?playlists/([^/?&#]+)" u
= Just pl
| otherwise = Nothing
parseUrlT " -index=1&max-results=25&client=ytapi-youtube-user&v=2 "
subscriptions list выдает HTTP 403 subscriptionForbidden
handleYoutubeItems guidFormat xs result = do
JSON.Array (V.toList -> is) <- HM.lookup "items" xs
let videoId = withObj $ \ i ->
do cd <-
<|>
str "videoId" cd
<|>
vids = mapMaybe videoId is
return $ youtubeVideosBatch guidFormat result vids
youtubeVideosBatch guidFormat result [] = result []
youtubeVideosBatch guidFormat result xs =
PRAdditionalDownload "YouTube video details"
[T.concat
[ ytBaseUrl, "/videos?part=id%2CcontentDetails%2Csnippet&id="
, encodeURIComponentT $ T.intercalate "," ids
, "&maxResults=50&", googleApiKey ]
| ids <- groupByN 50 xs ]
(combineDownloadsBS $ fromMaybe (PRError "Invalid JSON") .
handleYoutubeVideos guidFormat result)
handleYoutubeVideos guidFormat result dat =
fmap (result . take 100 . sortBy (comparing $ Down . fmPublishedTime) . concat) $
forM dat $ \ d -> do
JSON.Object xs <- decodeJson d
is <- arr "items" xs
let mkGuid
| Just f <- guidFormat = \ g -> T.replace "VIDEO_ID" g f
| otherwise = id
feedMsg js = do
JSON.Object i <- return js
JSON.Object status < - HM.lookup " status " i
- HM.lookup " privacyStatus " status
guard ( privacyStatus /= " private " )
snippet <- obj "snippet" i
videoId <- str "id" i
title <- str "title" snippet
description <- str "description" snippet
publishedAt <- str "publishedAt" snippet
cd <- obj "contentDetails" i
d <- str "duration" cd
duration <- readIso8601Duration $ T.unpack d
views < - str " " statistics
likes < - str " likeCount " statistics < | > Just " 0 "
dislikes < - str " dislikeCount " statistics < | > Just " 0 "
return $
defaultFeedMsg
{ fmGuid = mkGuid videoId
, fmAuthor = fromMaybe "" $ str "channelTitle" snippet
, fmPublishedTime = readRfc3339 $ T.unpack publishedAt
, fmBody =
T.concat
[embedYoutube videoId
,videoDuration duration
,htmlfyYoutubeDescription
(addHashTags 1
$ T.append "/" . T.toLower)
description]
, fmSubject = title
, fmLinks =
[(LKLink, T.concat ["="
, videoId])]
++ fromMaybe [] (do
c <- str "channelId" snippet
return [( LKAuthor
, "/" <> c)
, ( LKAuthorPic
, " / " < > T.drop 2 c < > " /1.jpg " )
Не везде такая
])
}
return $ mapMaybe feedMsg is
handleYoutubeMostPopular _ u j = fromMaybe (PRError "Invalid JSON") $ do
JSON.Object xs <- return j
handleYoutubeItems (Just $ youtubeGuidFormat u) xs $
PRFeed u
(defaultFeedMsg
{ fmSubject = "Most Popular"
, fmLinks = [(LKLink, "")] })
handleYoutubeSearch _ u j = fromMaybe (PRError "Invalid JSON") $ do
JSON.Object xs <- return j
(_,(subject,url)) <- youtubeSearchUrlAndSubject u
handleYoutubeItems (Just $ youtubeGuidFormat u) xs $
PRFeed u
(defaultFeedMsg
{ fmSubject = subject
, fmLinks = [(LKLink, url)] })
handleYoutubePlaylist _ u j = fromMaybe (PRError "Invalid JSON") $ do
JSON.Array (V.toList -> [JSON.Object xs, JSON.Object playlist]) <- return j
JSON.Array (V.toList -> (JSON.Object i:_)) <- HM.lookup "items" playlist
JSON.String playlistId <- HM.lookup "id" i
JSON.Object snippet <- HM.lookup "snippet" i
JSON.String title <- HM.lookup "title" snippet
let guidFormat = either (const Nothing) (lookup "bq_guid_format")
$ urlQueryStringUtf8Only u
result =
PRFeed u
(defaultFeedMsg
{ fmSubject = fromMaybe title $ T.stripPrefix "Uploads from " title
, fmLinks =
[(LKLink, "=" <> playlistId) ] })
batch = youtubeVideosBatch guidFormat result . map snd
sortIs = sortBy (comparing $ Down . fst)
loop n xs acc
| n < 2
, Just npt <- str "nextPageToken" xs =
PRAdditionalDownload
("Next page of unsorted playlist (#" <> showT n <> ")")
[playlistItemsUrl 50 (Just npt) playlistId]
(combineDownloadsBS $ \ [d] -> fromMaybe (PRError "Invalid JSON") $ do
JSON.Object xs' <- decodeJson d
is' <- playlistItems xs'
return $ loop (n+1) xs' (is' <> acc))
| otherwise =
batch $ take 20 $ sortIs acc
is <- playlistItems xs
Бывает , что старое видео публикуется не сразу и свежее видео на сайта
еще 100 видео ,
сортируем и обрабатываем последние 20 .
return $ if sortIs is == is then batch is else loop 0 xs is
playlistItems xs = do
JSON.Array (V.toList -> is) <- HM.lookup "items" xs
let timeVid = withObj $ \ i -> do
cd <- obj "contentDetails" i
vid <- str "videoId" cd
time <-str "videoPublishedAt" cd
return (readRfc3339 $ T.unpack time, vid)
return $ mapMaybe timeVid is
youtubeChannelUrl u =
T.concat [ytBaseUrl, "/channels?part=id%2C+contentDetails&id="
, u, "&", googleApiKey]
youtubeUserUrl u
| regexTest "^UC[A-Za-z0-9_\\-]{22}$" u = youtubeChannelUrl u
| otherwise =
T.concat [ytBaseUrl, "/channels?part=id%2C+contentDetails&forUsername="
, u, "&", googleApiKey]
transformYoutubeChannel u
| [[_,id]] <- regexGet "youtube\\.com/channel/([^&=?/]+)" u =
youtubeChannelUrl id
| otherwise = u
transformYoutubeUser u
| [[_,id]] <- regexGet "youtube\\.com/user/([^&=?/]+)" u = youtubeUserUrl id
| Just (id,_) <- youtubeUserAndPlaylistV2 u = youtubeUserUrl id
| otherwise = u
youtubeUserAndPlaylistV2 u
| [[_, _, _, user, playlist]] <-
regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?users/([^/?&#]+)/([^/?&#]+)" u
= Just (user, playlist)
| regexTest "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos" u
, Right qs <- urlQueryStringUtf8Only u
, Just user <- lookup "author" qs
= Just (user, "uploads")
| otherwise = Nothing
urlHasV2 u
| Right qs <- urlQueryStringUtf8Only u
, Just v <- lookup "v" qs = v == "2"
| otherwise = False
youtubeVideosXmlToChannel u
| regexTest "^https?://(www.|gdata.)?youtube.com/(xml/)?feeds/videos.xml" u
, Right qs <- urlQueryStringUtf8Only u =
if | Just ch <- lookup "channel_id" qs -> Just (youtubeChannelUrl ch)
| Just us <- lookup "user" qs -> Just (youtubeUserUrl us)
| otherwise -> Nothing
| otherwise = Nothing
order= по умолчанию relevance
но в RSS - фидах они тоже в разнобой
топовые по . На youtube это просто плейлист , и на него можно подписаться
можно к ним привести
youtubeMostPopularUrl u
| r@[[_, _, _, country]] <-
regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)standardfeeds/([A-Z][A-Z])?" u
= Just $ T.concat
[ ytBaseUrl, "/videos?part=id&chart=mostPopular&maxResults=20"
, if | country /= "" ->
"®ionCode=" <> country
| Right (lookup "lang" -> Just lang) <- urlQueryStringUtf8Only u ->
"®ionCode=" <> T.toUpper lang
| otherwise ->
""
, "&", googleApiKey ]
| otherwise = Nothing
youtubeSearchUrlAndSubject u
| [[_,_,_,q]] <- regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos/-/([^?&]+)" u
= r (T.unwords $ map decodeURIComponentT $ T.split (== '/') q) ""
searchSubj searchUrl
| [[_,_,_,vid]] <- regexGet "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos/([^/]+)/related" u
= r "" ("&relatedToVideoId=" <> vid)
(const "Related videos")
должно быть Videos related to ' Название видео ' , но что - то лень копаться
(const $
"="
<> vid)
^ такого URL на youtube уже нет
| regexTest "^https?://(www.|gdata.)?youtube.com/feeds/(api/|base/)?videos" u
, Right qs <- urlQueryStringUtf8Only u
, Just q <- lookup "q" qs
= r q "" searchSubj searchUrl
| regexTest "^https?://(www.)?youtube.com/results" u
, Right qs <- urlQueryStringUtf8Only u
, Just q <- lookup "search_query" qs
= r q filters searchSubj
((<> maybe "" ("&filters="<>) (lookup "filters" qs)) . searchUrl)
| otherwise = Nothing
where r q add subj url = Just (T.concat [ytBaseUrl, "/search?part=id&maxResults=20&order=date&type=video&q=", encodeURIComponentT q, add, "&", googleApiKey], (subj q, url q))
filters
| Right qs <- urlQueryStringUtf8Only u
, Just fs <- lookup "filters" qs
= T.concat $ map (fOpt . T.toLower) $ T.split (== ',') fs
| otherwise = ""
fOpt "short" = "&videoDuration=short"
fOpt "medium" = "&videoDuration=medium"
fOpt "long" = "&videoDuration=long"
fOpt "hd" = "&videoDefinition=hd"
в API вроде пока нет 4k
fOpt "3d" = "&videoDimension=3d"
fOpt "cc" = "&videoCaption=closedCaption"
fOpt "creativecommons" = "&videoLicense=creativeCommon"
fOpt "movie" = "&videoType=movie"
fOpt "show" = "&videoType=episode"
fOpt "live" = "&eventType=live"
fOpt _ = ""
searchSubj q = q <> " - YouTube"
searchUrl q = "=" <> encodeURIComponentT q <> sortByDate
sortByDate = "&search_sort=video_date_uploaded"
handleYoutubeCustomUrlChannel _ _ t = go t
where go [] = PRError "Can’t find Youtube channel"
go (TagOpen "meta" as : ts)
| Just "channelId" <- lookup "itemprop" as
, Just cid <- lookup "content" as =
PRRedirect $ "/" <> cid
go (_ : ts) = go ts
handleYoutubeChannel t u j
| Just (_, p) <- youtubeUserAndPlaylistV2 u =
if p = = " " then
PRError " are no longer supported by Youtube.\nStar this issue -issues/issues/detail?id=3946 "
handleYoutubeChannel' (Just $ youtubeGuidFormat u)
p t u j
| otherwise =
handleYoutubeChannel'
(fmap (const "yt:video:VIDEO_ID") $ youtubeVideosXmlToChannel u)
"uploads" t u j
стоит собирать все video i d и делать дополнительный запрос по ним
так можно узнать video duration , а в snippet показываются channelTitle
с пробелами и
По идее , так же можно и newsubscriptionvideos обработать
Ограничений на youtube , можно параллельно качать
youtubeGuidFormat u =
if urlHasV2 u then
"tag:youtube.com,2008:video:VIDEO_ID"
else if ".com/feeds/base/" `T.isInfixOf` u then
""
else if ".com/feeds/api/" `T.isInfixOf` u then
""
else
""
handleYoutubeChannel' guidFormat playlist _ u j = fromMaybe (PRError "Can’t find Youtube channel") $ do
JSON.Object o <- return j
(JSON.Object i:_) <- arr "items" o
cd <- obj "contentDetails" i
rp <- obj "relatedPlaylists" cd
(do guard (playlist == "newsubscriptionvideos")
ch <- str "id" i
return $ PRAdditionalDownload "YouTube subscriptions list"
[youtubeSubscriptionsListUrl ch Nothing]
(combineDownloadsBS $ handleYoutubeSubscriptionsList guidFormat ch [])
<|>
do u <- str playlist rp
return $ PRRedirect ("=" <> u <>
maybe "" (("&bq_guid_format="<>) . encodeURIComponentT)
guidFormat)
<|>
return (PRError $ T.concat ["Can’t find “", playlist, "” playlist"]))
youtubeSubscriptionsListUrl channelId pageToken =
T.concat [ ytBaseUrl, "/subscriptions?part=snippet&channelId="
, channelId, "&maxResults=50&", googleApiKey
, maybe "" ("&pageToken="<>) pageToken ]
handleYoutubeSubscriptionsList guidFormat ch acc dat = fromMaybe (PRError "Invalid user subscriptions JSON") $ do
JSON.Object xs <- decodeJson $ B.concat dat
is <- arr "items" xs
let chans = mapMaybe chan is ++ acc
chan = withObj $ str "channelId" <=< obj "resourceId" <=< obj "snippet"
plUrl cs =
T.concat
[ ytBaseUrl, "/channels?part=contentDetails&id="
, encodeURIComponentT $ T.intercalate "," cs
, "&maxResults=50&", googleApiKey ]
return $ case str "nextPageToken" xs of
Just p ->
PRAdditionalDownload "YouTube subscriptions list (next page)"
[youtubeSubscriptionsListUrl ch (Just p)]
(combineDownloadsBS $
handleYoutubeSubscriptionsList guidFormat ch chans)
Nothing ->
PRAdditionalDownload "YouTube subscriptions playlist IDs"
(map plUrl $ groupByN 50 $ hashSetNub chans)
(combineDownloadsBS $
handleYoutubeSubscriptionsPlaylistsList guidFormat)
handleYoutubeSubscriptionsPlaylistsList guidFormat dat = fromMaybe (PRError "Invalid user subscriptions playlists JSON") $ do
let pls d = do
JSON.Object xs <- decodeJson d
mapMaybe pl `fmap` arr "items" xs
pl = withObj $
str "uploads" <=< obj "relatedPlaylists" <=< obj "contentDetails"
playlists = hashSetNub $ concat $ mapMaybe pls dat
pliUrl p =
T.concat
[ ytBaseUrl
, "/playlistItems?part=contentDetails&maxResults=20&playlistId="
, p, "&", googleApiKey ]
maxResults 5->20 дает общее время 13->19 , что не намного больше ,
зато гораздо меньше вероятность что - либо пропустить ,
а если на 50 , а не 20 , то опять те же 13
return $
PRAdditionalDownload "YouTube playlists"
(map pliUrl playlists)
(CombineDownloads $
handleYoutubeSubscriptionsPlaylistsItems guidFormat)
handleYoutubeSubscriptionsPlaylistsItems guidFormat dat = fromMaybe (PRError "Invalid user subscriptions playlist items JSON") $ do
let vids = either (const $ return []) $ \ d -> do
у каналов без видео бывают плейлисты uploads ,
JSON.Object xs <- decodeJson d
mapMaybe vid `fmap` arr "items" xs
vid = withObj $ str "videoId" <=< obj "contentDetails"
videos = hashSetNub $ concat $ mapMaybe vids dat
feed = PRFeed "/"
(defaultFeedMsg
{ fmSubject = "New Subscription Videos"
, fmLinks = [(LKLink, "")] })
return $ youtubeVideosBatch guidFormat feed videos
Префикс
4 вида GUID - ов
GUID /<длинная абракадабра ведет на URL >
если с UC , в длину и [ A - Za - z0 - 9_\- ]
users / USER_NAME / uploads ( )
favorites - playlist , может быть ,
videos/-/Search / Term ? …
videos / VIDEO_ID / related ( не используются /responses|/ratings|/complaints )
standardfeeds / TYPE? … lang = COUNTRY_CODE_locase … time = TIME
TIME today , this_week
( плейлист самое ) я не нашел
В API v3 дате не задать , ну и ладно
уже HTTP 404 , но раньше работало
все - таки есть playlist - ы
НЕ РАБОТАЕТ
( после device support у некоторых фидов уже появились )
GUID yt : video : VIDEO_ID
НЕ ЗНАЮ АНАЛОГОВ
/-/Alasdair/Roberts?v=2&orderby=published&client=ytapi-youtube-rss-redirect&alt=rss
GUID tag : youtube.com,2008 : video : UKY3scPIMd8 ( alt = rss не влияет )
словом них
? orderby = updated&client = ytapi - youtube - rss - redirect&alt = rss&v=2
много вариантов , надо честно запоминать , что был redirect и обновлять
push
|
ecc393b926371987f442ed23ecaf34d7a2abbe2962e070f6b8be857838f46f9c | samoht/camloo | main.scm | ;; Le module
(module
__caml_main
(library camloo-runtime)
(import
__caml_config
__caml_misc
__caml_modules
__caml_compiler
__caml_dump
__caml_version)
(export
(anonymous_150@main x1)
(c2b_254@main x1)
(set_stdlib_160@main x1)
(add_include_184@main x1)
(open_set_165@main x1)
(show_version_33@main x1)
(show_types_flag_89@main x1)
(debug_option_218@main x1)
(mklib_option_180@main x1)
(main_109@main x1)))
L'initialisation du module
(init_camloo!)
;; Les variables globales
;; Les expressions globales
(begin
(define (anonymous_150@main x1)
(if ((check_suffix_88@filename x1) ".ml")
(let ((x2 ((chop_suffix_96@filename x1) ".ml")))
(2-234-compile_implementation_215@compiler
(basename_226@filename x2)
x2))
(if ((check_suffix_88@filename x1) ".mli")
(let ((x2 ((chop_suffix_96@filename x1) ".mli")))
(2-44-compile_interface_171@compiler
(basename_226@filename x2)
x2))
(caml-raise
(caml-make-static-extensible-1
'Bad_1@arg
((^_54@string "don't know what to do with ") x1))))))
(begin
(define (c2b_254@main x1)
(if ((check_suffix_88@filename x1) ".ml")
(let ((x2 ((chop_suffix_96@filename x1) ".ml")))
(2-63-dump_syntax_implementation_69@dump
(basename_226@filename x2)
x2))
(if ((check_suffix_88@filename x1) ".mli")
(let ((x2 ((chop_suffix_96@filename x1) ".mli")))
(2-199-dump_interface_92@dump
(basename_226@filename x2)
x2))
(caml-raise
(caml-make-static-extensible-1
'Bad_1@arg
((^_54@string "don't know what to do with ") x1))))))
(begin
(define (set_stdlib_160@main x1)
(begin
(cell-set! path_library_222@config x1)
(cell-set!
load_path_99@misc
(cons (cell-ref path_library_222@config) '()))))
(begin
(define (add_include_184@main x1)
(cell-set!
load_path_99@misc
(cons x1 (cell-ref load_path_99@misc))))
(begin
(define (open_set_165@main x1)
(with-handler
(lambda (x2)
(labels
((staticfail1001 () (caml-raise x2)))
(case (caml-extensible-constr-tag x2)
((Not_found_4@exc)
(caml-raise
(caml-make-static-extensible-1
'Bad_1@arg
((^_54@string "unknown module set ") x1))))
(else (staticfail1001)))))
(unwind-protect
(begin
(push-exception-handler)
(cell-set!
default_used_modules_33@modules
((assoc_252@list x1)
default_used_interfaces_171@config)))
(pop-exception-handler))))
(begin
(define (show_version_33@main x1)
(begin
(prerr_string_235@io banner_209@version)
(prerr_endline_232@io "")))
(begin
(define (show_types_flag_89@main x1)
(cell-set! verbose_226@compiler #t))
(begin
(define (debug_option_218@main x1)
(cell-set! write_extended_zi_52@compiler #t))
(define (mklib_option_180@main x1)
(cell-set! mklib_84@dump #t))
))))))))
(define (main_109@main x1)
(with-handler
(lambda (x2)
(labels
((staticfail1003 () (caml-raise x2)))
(case (caml-extensible-constr-tag x2)
((Toplevel_2@misc) (exit_246@io 2))
((Break_2@sys) (exit_246@io 3))
((Zinc_1@misc)
(begin
(prerr_string_235@io "# Internal error: ")
(begin
(prerr_endline_232@io
(caml-constr-get-field x2 0))
(exit_246@io 4))))
(else (staticfail1003)))))
(unwind-protect
(begin
(push-exception-handler)
(begin
(sys_catch_break #t)
(begin
(cell-set!
default_used_modules_33@modules
((assoc_252@list "cautious")
default_used_interfaces_171@config))
(begin
(cell-set!
load_path_99@misc
(cons (cell-ref path_library_222@config) '()))
(((parse_vect_143@arg x1)
(cons (caml-make-regular-2
#f
"-stdlib"
(caml-make-regular-1 #f set_stdlib_160@main))
(cons (caml-make-regular-2
#f
"-I"
(caml-make-regular-1 #f add_include_184@main))
(cons (caml-make-regular-2
#f
"-include"
(caml-make-regular-1
#f
add_include_184@main))
(cons (caml-make-regular-2
#f
"-O"
(caml-make-regular-1
#f
open_set_165@main))
(cons (caml-make-regular-2
#f
"-open"
(caml-make-regular-1
#f
open_set_165@main))
(cons (caml-make-regular-2
#f
"-v"
(caml-make-regular-1
#unspecified
show_version_33@main))
(cons (caml-make-regular-2
#f
"-version"
(caml-make-regular-1
#unspecified
show_version_33@main))
(cons (caml-make-regular-2
#f
"-i"
(caml-make-regular-1
#unspecified
show_types_flag_89@main))
(cons (caml-make-regular-2
#f
"-g"
(caml-make-regular-1
#unspecified
debug_option_218@main))
(cons (caml-make-regular-2
#f
"-debug"
(caml-make-regular-1
#unspecified
debug_option_218@main))
(cons (caml-make-regular-2
#f
"-dump"
(caml-make-regular-1
#f
c2b_254@main))
(cons (caml-make-regular-2
#f
"-mklib"
(caml-make-regular-1
#unspecified
mklib_option_180@main))
(cons (caml-make-regular-2
#f
"-"
(caml-make-regular-1
#f
anonymous_150@main))
'()))))))))))))))
anonymous_150@main)))))
(pop-exception-handler))))
| null | https://raw.githubusercontent.com/samoht/camloo/29a578a152fa23a3125a2a5b23e325b6d45d3abd/src/camloo/Llib.bootstrap/main.scm | scheme | Le module
Les variables globales
Les expressions globales | (module
__caml_main
(library camloo-runtime)
(import
__caml_config
__caml_misc
__caml_modules
__caml_compiler
__caml_dump
__caml_version)
(export
(anonymous_150@main x1)
(c2b_254@main x1)
(set_stdlib_160@main x1)
(add_include_184@main x1)
(open_set_165@main x1)
(show_version_33@main x1)
(show_types_flag_89@main x1)
(debug_option_218@main x1)
(mklib_option_180@main x1)
(main_109@main x1)))
L'initialisation du module
(init_camloo!)
(begin
(define (anonymous_150@main x1)
(if ((check_suffix_88@filename x1) ".ml")
(let ((x2 ((chop_suffix_96@filename x1) ".ml")))
(2-234-compile_implementation_215@compiler
(basename_226@filename x2)
x2))
(if ((check_suffix_88@filename x1) ".mli")
(let ((x2 ((chop_suffix_96@filename x1) ".mli")))
(2-44-compile_interface_171@compiler
(basename_226@filename x2)
x2))
(caml-raise
(caml-make-static-extensible-1
'Bad_1@arg
((^_54@string "don't know what to do with ") x1))))))
(begin
(define (c2b_254@main x1)
(if ((check_suffix_88@filename x1) ".ml")
(let ((x2 ((chop_suffix_96@filename x1) ".ml")))
(2-63-dump_syntax_implementation_69@dump
(basename_226@filename x2)
x2))
(if ((check_suffix_88@filename x1) ".mli")
(let ((x2 ((chop_suffix_96@filename x1) ".mli")))
(2-199-dump_interface_92@dump
(basename_226@filename x2)
x2))
(caml-raise
(caml-make-static-extensible-1
'Bad_1@arg
((^_54@string "don't know what to do with ") x1))))))
(begin
(define (set_stdlib_160@main x1)
(begin
(cell-set! path_library_222@config x1)
(cell-set!
load_path_99@misc
(cons (cell-ref path_library_222@config) '()))))
(begin
(define (add_include_184@main x1)
(cell-set!
load_path_99@misc
(cons x1 (cell-ref load_path_99@misc))))
(begin
(define (open_set_165@main x1)
(with-handler
(lambda (x2)
(labels
((staticfail1001 () (caml-raise x2)))
(case (caml-extensible-constr-tag x2)
((Not_found_4@exc)
(caml-raise
(caml-make-static-extensible-1
'Bad_1@arg
((^_54@string "unknown module set ") x1))))
(else (staticfail1001)))))
(unwind-protect
(begin
(push-exception-handler)
(cell-set!
default_used_modules_33@modules
((assoc_252@list x1)
default_used_interfaces_171@config)))
(pop-exception-handler))))
(begin
(define (show_version_33@main x1)
(begin
(prerr_string_235@io banner_209@version)
(prerr_endline_232@io "")))
(begin
(define (show_types_flag_89@main x1)
(cell-set! verbose_226@compiler #t))
(begin
(define (debug_option_218@main x1)
(cell-set! write_extended_zi_52@compiler #t))
(define (mklib_option_180@main x1)
(cell-set! mklib_84@dump #t))
))))))))
(define (main_109@main x1)
(with-handler
(lambda (x2)
(labels
((staticfail1003 () (caml-raise x2)))
(case (caml-extensible-constr-tag x2)
((Toplevel_2@misc) (exit_246@io 2))
((Break_2@sys) (exit_246@io 3))
((Zinc_1@misc)
(begin
(prerr_string_235@io "# Internal error: ")
(begin
(prerr_endline_232@io
(caml-constr-get-field x2 0))
(exit_246@io 4))))
(else (staticfail1003)))))
(unwind-protect
(begin
(push-exception-handler)
(begin
(sys_catch_break #t)
(begin
(cell-set!
default_used_modules_33@modules
((assoc_252@list "cautious")
default_used_interfaces_171@config))
(begin
(cell-set!
load_path_99@misc
(cons (cell-ref path_library_222@config) '()))
(((parse_vect_143@arg x1)
(cons (caml-make-regular-2
#f
"-stdlib"
(caml-make-regular-1 #f set_stdlib_160@main))
(cons (caml-make-regular-2
#f
"-I"
(caml-make-regular-1 #f add_include_184@main))
(cons (caml-make-regular-2
#f
"-include"
(caml-make-regular-1
#f
add_include_184@main))
(cons (caml-make-regular-2
#f
"-O"
(caml-make-regular-1
#f
open_set_165@main))
(cons (caml-make-regular-2
#f
"-open"
(caml-make-regular-1
#f
open_set_165@main))
(cons (caml-make-regular-2
#f
"-v"
(caml-make-regular-1
#unspecified
show_version_33@main))
(cons (caml-make-regular-2
#f
"-version"
(caml-make-regular-1
#unspecified
show_version_33@main))
(cons (caml-make-regular-2
#f
"-i"
(caml-make-regular-1
#unspecified
show_types_flag_89@main))
(cons (caml-make-regular-2
#f
"-g"
(caml-make-regular-1
#unspecified
debug_option_218@main))
(cons (caml-make-regular-2
#f
"-debug"
(caml-make-regular-1
#unspecified
debug_option_218@main))
(cons (caml-make-regular-2
#f
"-dump"
(caml-make-regular-1
#f
c2b_254@main))
(cons (caml-make-regular-2
#f
"-mklib"
(caml-make-regular-1
#unspecified
mklib_option_180@main))
(cons (caml-make-regular-2
#f
"-"
(caml-make-regular-1
#f
anonymous_150@main))
'()))))))))))))))
anonymous_150@main)))))
(pop-exception-handler))))
|
debada3c74b3993a2de65359f8cd34597684de1447ac75556035f69276fc68b3 | tonyrog/graph | graph_file.erl | @author < >
( C ) 2019 ,
%%% @doc
%%% Some file functions
%%% @end
Created : 24 Feb 2019 by < >
-module(graph_file).
-export([load/1, load_fd/1, load_fd/2]).
%%
%% Load graph in
%% connection matrix format
%%
%%
load(Filename) ->
case file:open(Filename, [read]) of
{ok, Fd} ->
try load_fd(Fd) of
G -> G
after
file:close(Fd)
end;
Error ->
Error
end.
load_fd(Fd) ->
case read_sym_row(Fd) of
eof -> {error, eof};
[] -> {error, missing_size_row};
[N|_Vs] -> load_fd(Fd, N)
end.
load_fd(Fd, N) when is_integer(N), N > 0 ->
try load_lines(Fd, N, N, []) of
M ->
{ok, graph:from_connection_matrix(M)}
catch
error:_ -> {error, badarg}
end.
load_lines(_Fd, 0, _N, Acc) ->
lists:reverse(Acc);
load_lines(Fd, I, N, Acc) ->
Ts = read_bin_row(Fd),
case length(Ts) of
N -> load_lines(Fd, I-1, N, [Ts|Acc])
end.
read_sym_row(Fd) ->
case file:read_line(Fd) of
{ok, Line} ->
transform_sym_row(string:tokens(Line," \t\r\n"));
eof -> eof;
{error,_} -> []
end.
transform_sym_row([H|T]) ->
[ try list_to_integer(H)
catch error:_ -> list_to_atom(H)
end | transform_sym_row(T)];
transform_sym_row([]) ->
[].
read_bin_row(Fd) ->
case file:read_line(Fd) of
{ok, Line} ->
transform_bin_row(string:tokens(Line," \t\r\n"));
eof -> [];
{error,_} -> []
end.
%%
" 1010 " - > [ 1,0,1,0 ]
" 1 0 1 0 " - > [ 1,0,1,0 ]
%%
transform_bin_row([[$0|Rs]|T]) -> [0|transform_bin_row([Rs|T])];
transform_bin_row([[$1|Rs]|T]) -> [1|transform_bin_row([Rs|T])];
transform_bin_row([[]|T]) -> transform_bin_row(T);
transform_bin_row([]) -> [].
| null | https://raw.githubusercontent.com/tonyrog/graph/c930de5707f5e66499b29646b05f4570163ce7c5/src/graph_file.erl | erlang | @doc
Some file functions
@end
Load graph in
connection matrix format
| @author < >
( C ) 2019 ,
Created : 24 Feb 2019 by < >
-module(graph_file).
-export([load/1, load_fd/1, load_fd/2]).
load(Filename) ->
case file:open(Filename, [read]) of
{ok, Fd} ->
try load_fd(Fd) of
G -> G
after
file:close(Fd)
end;
Error ->
Error
end.
load_fd(Fd) ->
case read_sym_row(Fd) of
eof -> {error, eof};
[] -> {error, missing_size_row};
[N|_Vs] -> load_fd(Fd, N)
end.
load_fd(Fd, N) when is_integer(N), N > 0 ->
try load_lines(Fd, N, N, []) of
M ->
{ok, graph:from_connection_matrix(M)}
catch
error:_ -> {error, badarg}
end.
load_lines(_Fd, 0, _N, Acc) ->
lists:reverse(Acc);
load_lines(Fd, I, N, Acc) ->
Ts = read_bin_row(Fd),
case length(Ts) of
N -> load_lines(Fd, I-1, N, [Ts|Acc])
end.
read_sym_row(Fd) ->
case file:read_line(Fd) of
{ok, Line} ->
transform_sym_row(string:tokens(Line," \t\r\n"));
eof -> eof;
{error,_} -> []
end.
transform_sym_row([H|T]) ->
[ try list_to_integer(H)
catch error:_ -> list_to_atom(H)
end | transform_sym_row(T)];
transform_sym_row([]) ->
[].
read_bin_row(Fd) ->
case file:read_line(Fd) of
{ok, Line} ->
transform_bin_row(string:tokens(Line," \t\r\n"));
eof -> [];
{error,_} -> []
end.
" 1010 " - > [ 1,0,1,0 ]
" 1 0 1 0 " - > [ 1,0,1,0 ]
transform_bin_row([[$0|Rs]|T]) -> [0|transform_bin_row([Rs|T])];
transform_bin_row([[$1|Rs]|T]) -> [1|transform_bin_row([Rs|T])];
transform_bin_row([[]|T]) -> transform_bin_row(T);
transform_bin_row([]) -> [].
|
13bd9f8b3d95901d656cdb8f59eba7908d6743fe43948f203c4b2753c47a73ea | PLTools/GT | stateful.ml |
* Generic transformers : plugins .
* Copyright ( C ) 2016 - 2022
* aka Kakadu
* St. Petersburg State University , JetBrains Research
* Generic transformers: plugins.
* Copyright (C) 2016-2022
* Dmitrii Kosarev aka Kakadu
* St.Petersburg State University, JetBrains Research
*)
(** {i Stateful} plugin: functors + inherited value
to make decisions about how to map values.
Behave the same as {!Eval} trait but can may return modified state.
Inherited attributes' type (both default and for type parameters) is ['env].
Synthetized attributes' type (both default and for type parameters) is ['env * _ t].
For type declaration [type ('a,'b,...) typ = ...] it will create transformation
function with type
[('env -> 'a -> 'env * 'a2) ->
('env -> 'b -> 'env * 'b2) -> ... ->
'env -> ('a,'b,...) typ -> 'env * ('a2, 'b2, ...) typ ]
*)
open Ppxlib
open Stdppx
open Printf
open GTCommon
open HelpersBase
let trait_name = "stateful"
module Make (AstHelpers : GTHELPERS_sig.S) = struct
module G = Gmap.Make (AstHelpers)
module P = Plugin.Make (AstHelpers)
let trait_name = trait_name
open AstHelpers
class g initial_args tdecls =
object (self : 'self)
TODO : maybe do not inherit from gmap a.k.a . functor
inherit G.g initial_args tdecls as super
inherit P.with_inherited_attr initial_args tdecls
method trait_name = trait_name
method! inh_of_main ~loc _tdecl = Typ.var ~loc "env"
method! syn_of_param ~loc s =
Typ.tuple ~loc [ Typ.var ~loc "env"; Typ.var ~loc @@ Gmap.param_name_mangler s ]
method inh_of_param ~loc tdecl _name = Typ.var ~loc "env"
method! syn_of_main ~loc ?in_class tdecl =
let in_class =
match in_class with
| None -> false
| Some b -> b
in
Typ.tuple
~loc
[ self#inh_of_main ~loc tdecl; super#syn_of_main ~loc ~in_class tdecl ]
method plugin_class_params ~loc typs ~typname =
super#plugin_class_params ~loc typs ~typname @ [ Typ.var ~loc "env" ]
method on_tuple_constr ~loc ~is_self_rec ~mutual_decls ~inhe tdecl constr_info ts =
let c =
match constr_info with
| Some (`Normal s) -> Exp.construct ~loc (lident s)
| Some (`Poly s) -> Exp.variant ~loc s
| None ->
assert (List.length ts >= 2);
Exp.tuple ~loc
in
match ts with
| [] -> Exp.tuple ~loc [ inhe; c [] ]
| ts ->
let res_var_name = sprintf "%s_rez" in
let ys = List.mapi ~f:(fun n x -> n, x) ts in
List.fold_right
ys
~init:
(Exp.tuple
~loc
[ Exp.sprintf ~loc "env%d" (List.length ys)
; c @@ List.map ts ~f:(fun (n, t) -> Exp.ident ~loc @@ res_var_name n)
])
~f:(fun (i, (name, typ)) acc ->
Exp.let_one
~loc
(Pat.tuple
~loc
[ Pat.sprintf ~loc "env%d" (i + 1)
; Pat.sprintf ~loc "%s" @@ res_var_name name
])
(self#app_transformation_expr
~loc
(self#do_typ_gen ~loc ~is_self_rec ~mutual_decls tdecl typ)
(if i = 0 then inhe else Exp.sprintf ~loc "env%d" i)
(Exp.ident ~loc name))
acc)
method! on_record_declaration ~loc ~is_self_rec ~mutual_decls tdecl labs =
(* TODO: *)
failwith "not implemented"
end
let create = (new g :> P.plugin_constructor)
end
let register () = Expander.register_plugin trait_name (module Make : Plugin_intf.MAKE)
let () = register ()
| null | https://raw.githubusercontent.com/PLTools/GT/62d1a424a3336f2317ba67e447a9ff09d179b583/plugins/stateful.ml | ocaml | * {i Stateful} plugin: functors + inherited value
to make decisions about how to map values.
Behave the same as {!Eval} trait but can may return modified state.
Inherited attributes' type (both default and for type parameters) is ['env].
Synthetized attributes' type (both default and for type parameters) is ['env * _ t].
For type declaration [type ('a,'b,...) typ = ...] it will create transformation
function with type
[('env -> 'a -> 'env * 'a2) ->
('env -> 'b -> 'env * 'b2) -> ... ->
'env -> ('a,'b,...) typ -> 'env * ('a2, 'b2, ...) typ ]
TODO: |
* Generic transformers : plugins .
* Copyright ( C ) 2016 - 2022
* aka Kakadu
* St. Petersburg State University , JetBrains Research
* Generic transformers: plugins.
* Copyright (C) 2016-2022
* Dmitrii Kosarev aka Kakadu
* St.Petersburg State University, JetBrains Research
*)
open Ppxlib
open Stdppx
open Printf
open GTCommon
open HelpersBase
let trait_name = "stateful"
module Make (AstHelpers : GTHELPERS_sig.S) = struct
module G = Gmap.Make (AstHelpers)
module P = Plugin.Make (AstHelpers)
let trait_name = trait_name
open AstHelpers
class g initial_args tdecls =
object (self : 'self)
TODO : maybe do not inherit from gmap a.k.a . functor
inherit G.g initial_args tdecls as super
inherit P.with_inherited_attr initial_args tdecls
method trait_name = trait_name
method! inh_of_main ~loc _tdecl = Typ.var ~loc "env"
method! syn_of_param ~loc s =
Typ.tuple ~loc [ Typ.var ~loc "env"; Typ.var ~loc @@ Gmap.param_name_mangler s ]
method inh_of_param ~loc tdecl _name = Typ.var ~loc "env"
method! syn_of_main ~loc ?in_class tdecl =
let in_class =
match in_class with
| None -> false
| Some b -> b
in
Typ.tuple
~loc
[ self#inh_of_main ~loc tdecl; super#syn_of_main ~loc ~in_class tdecl ]
method plugin_class_params ~loc typs ~typname =
super#plugin_class_params ~loc typs ~typname @ [ Typ.var ~loc "env" ]
method on_tuple_constr ~loc ~is_self_rec ~mutual_decls ~inhe tdecl constr_info ts =
let c =
match constr_info with
| Some (`Normal s) -> Exp.construct ~loc (lident s)
| Some (`Poly s) -> Exp.variant ~loc s
| None ->
assert (List.length ts >= 2);
Exp.tuple ~loc
in
match ts with
| [] -> Exp.tuple ~loc [ inhe; c [] ]
| ts ->
let res_var_name = sprintf "%s_rez" in
let ys = List.mapi ~f:(fun n x -> n, x) ts in
List.fold_right
ys
~init:
(Exp.tuple
~loc
[ Exp.sprintf ~loc "env%d" (List.length ys)
; c @@ List.map ts ~f:(fun (n, t) -> Exp.ident ~loc @@ res_var_name n)
])
~f:(fun (i, (name, typ)) acc ->
Exp.let_one
~loc
(Pat.tuple
~loc
[ Pat.sprintf ~loc "env%d" (i + 1)
; Pat.sprintf ~loc "%s" @@ res_var_name name
])
(self#app_transformation_expr
~loc
(self#do_typ_gen ~loc ~is_self_rec ~mutual_decls tdecl typ)
(if i = 0 then inhe else Exp.sprintf ~loc "env%d" i)
(Exp.ident ~loc name))
acc)
method! on_record_declaration ~loc ~is_self_rec ~mutual_decls tdecl labs =
failwith "not implemented"
end
let create = (new g :> P.plugin_constructor)
end
let register () = Expander.register_plugin trait_name (module Make : Plugin_intf.MAKE)
let () = register ()
|
43f6868772ca8b34579e19533460f63064a7293040b52767dae82bf693429654 | lasp-lang/lasp_pg | lasp_pg_app.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2016 . 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.
%%
%% -------------------------------------------------------------------
-module(lasp_pg_app).
-behaviour(application).
-include("lasp_pg.hrl").
-export([start/2, stop/1]).
%% @doc Initialize the application.
start(_StartType, _StartArgs) ->
case lasp_pg_sup:start_link() of
{ok, Pid} ->
{ok, Pid};
Other ->
{error, Other}
end.
%% @doc Stop the application.
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/lasp-lang/lasp_pg/2879b983613e7546eaf183dbf71efeed6f11cde8/src/lasp_pg_app.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.
-------------------------------------------------------------------
@doc Initialize the application.
@doc Stop the application. | Copyright ( c ) 2016 . 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
-module(lasp_pg_app).
-behaviour(application).
-include("lasp_pg.hrl").
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
case lasp_pg_sup:start_link() of
{ok, Pid} ->
{ok, Pid};
Other ->
{error, Other}
end.
stop(_State) ->
ok.
|
df82059db0bdf98d8d1746cb6e6b67434d119f0bb761851304ec0908300309fe | triffon/fp-2022-23 | 12-to-edges.rkt | #lang racket
ще използваме тази функция в други файлове
(provide to-edges)
(define (to-edges graph)
(define (construct-edges from to)
(map (lambda (x) (cons from x)) to))
(apply
append
(map
(lambda (lst) (construct-edges (car lst) (cdr lst)))
graph))) | null | https://raw.githubusercontent.com/triffon/fp-2022-23/c6f5ed7264fcd8988cf29f2d04fda64faa8c8562/exercises/inf2/08/12-to-edges.rkt | racket | #lang racket
ще използваме тази функция в други файлове
(provide to-edges)
(define (to-edges graph)
(define (construct-edges from to)
(map (lambda (x) (cons from x)) to))
(apply
append
(map
(lambda (lst) (construct-edges (car lst) (cdr lst)))
graph))) | |
8cb3a7cd00f1ff4ff5d9484a0f9c7983ae3f5ccafd5473871570c0cb4668ab67 | jwiegley/notes | main.hs | wontWork :: Prelude.FilePath -> IO ()
wontWork path = do
ls <- lines <$> readFile path
let Just idx = findIndex (" Import " `isInfixOf`) ls
writeFile path
$ unlines
$ take (idx + 2) ls
++ ["#import \"WS-Header.h\""]
++ drop (idx + 2) ls
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/6083978/main.hs | haskell | wontWork :: Prelude.FilePath -> IO ()
wontWork path = do
ls <- lines <$> readFile path
let Just idx = findIndex (" Import " `isInfixOf`) ls
writeFile path
$ unlines
$ take (idx + 2) ls
++ ["#import \"WS-Header.h\""]
++ drop (idx + 2) ls
| |
f430b176493a29bf690b1455205d194e6b1c647cdd4c11ff04664fca192eaa48 | na4zagin3/satyrographos | command_build__doc_with_libraries.ml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(lang "0.0.3")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf" ())
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
; (file "doc/grcnum.md" "README.md")
))
(opam "satysfi-grcnum.opam")
(dependencies (fonts-theano)))
(doc
(name "example-doc")
(build
((satysfi "doc-example.saty" "-o" "doc-example-ja.pdf")
(make "build-doc")))
(dependencies (grcnum fonts-theano)))
|}
let satysfi_grcnum_opam =
"satysfi-grcnum.opam", TestLib.opam_file_for_test
~name:"satysfi-grcnum"
~version:"0.1"
()
let fontHash =
{|{
"grcnum:grcnum-font":<"Single":{"src-dist":"grcnum/grcnum-font.ttf"}>
}|}
let makefile =
{|
PHONY: build-doc
build-doc:
@echo "Target: build-doc"
|}
let files =
[
satysfi_grcnum_opam;
"Satyristes", satyristes;
"README.md", "@@README.md@@";
"fonts.satysfi-hash", fontHash;
"grcnum.satyh", "@@grcnum.satyh@@";
"font.ttf", "@@font.ttf@@";
"doc-grcnum.saty", "@@doc-grcnum.saty@@";
"doc-example.saty", "@@doc-example.saty@@";
"Makefile", makefile;
]
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> prepare_files pkg_dir files
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "fonts.satysfi-hash") (echo fontHash)
>> stdout_to (FilePath.concat pkg_dir "grcnum.satyh") (echo "@@grcnum.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "font.ttf") (echo "@@font.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "doc-grcnum.saty") (echo "@@doc-grcnum.saty@@")
>> stdout_to (FilePath.concat pkg_dir "doc-example.saty") (echo "@@doc-example.saty@@")
>> stdout_to (FilePath.concat pkg_dir "Makefile") (echo makefile)
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let log_file = exec_log_file_path temp_dir in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
let bin = FilePath.concat temp_dir "bin" in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>> PrepareBin.prepare_bin bin log_file
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = false in
let main env ~dest_dir:_ ~temp_dir ~outf =
let names = Some ["example-doc"] in
let dest_dir = FilePath.concat dest_dir " dest " in
Satyrographos_command.Build.build_command
~outf
~verbose
~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes")
~build_dir:(FilePath.concat temp_dir "pkg/_build" |> Core.Option.some)
~env
~names
in
eval (test_install env main)
| null | https://raw.githubusercontent.com/na4zagin3/satyrographos/d2943bac9659d20746720ab36ebe11ae59203d32/test/testcases/command_build__doc_with_libraries.ml | ocaml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(lang "0.0.3")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf" ())
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
; (file "doc/grcnum.md" "README.md")
))
(opam "satysfi-grcnum.opam")
(dependencies (fonts-theano)))
(doc
(name "example-doc")
(build
((satysfi "doc-example.saty" "-o" "doc-example-ja.pdf")
(make "build-doc")))
(dependencies (grcnum fonts-theano)))
|}
let satysfi_grcnum_opam =
"satysfi-grcnum.opam", TestLib.opam_file_for_test
~name:"satysfi-grcnum"
~version:"0.1"
()
let fontHash =
{|{
"grcnum:grcnum-font":<"Single":{"src-dist":"grcnum/grcnum-font.ttf"}>
}|}
let makefile =
{|
PHONY: build-doc
build-doc:
@echo "Target: build-doc"
|}
let files =
[
satysfi_grcnum_opam;
"Satyristes", satyristes;
"README.md", "@@README.md@@";
"fonts.satysfi-hash", fontHash;
"grcnum.satyh", "@@grcnum.satyh@@";
"font.ttf", "@@font.ttf@@";
"doc-grcnum.saty", "@@doc-grcnum.saty@@";
"doc-example.saty", "@@doc-example.saty@@";
"Makefile", makefile;
]
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> prepare_files pkg_dir files
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "fonts.satysfi-hash") (echo fontHash)
>> stdout_to (FilePath.concat pkg_dir "grcnum.satyh") (echo "@@grcnum.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "font.ttf") (echo "@@font.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "doc-grcnum.saty") (echo "@@doc-grcnum.saty@@")
>> stdout_to (FilePath.concat pkg_dir "doc-example.saty") (echo "@@doc-example.saty@@")
>> stdout_to (FilePath.concat pkg_dir "Makefile") (echo makefile)
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let log_file = exec_log_file_path temp_dir in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
let bin = FilePath.concat temp_dir "bin" in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>> PrepareBin.prepare_bin bin log_file
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = false in
let main env ~dest_dir:_ ~temp_dir ~outf =
let names = Some ["example-doc"] in
let dest_dir = FilePath.concat dest_dir " dest " in
Satyrographos_command.Build.build_command
~outf
~verbose
~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes")
~build_dir:(FilePath.concat temp_dir "pkg/_build" |> Core.Option.some)
~env
~names
in
eval (test_install env main)
| |
76aad9fb7275f707c6512bfc574a8133b870672848717b51c1dc0a8827e948c0 | clojure/data.xml | node.cljc | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.data.xml.node
"Data types for xml nodes: Element, CData and Comment"
{:author "Herwig Hochleitner"}
(:require [clojure.data.xml.name :refer [as-qname]])
#?(:clj (:import (clojure.lang IHashEq IObj ILookup IKeywordLookup Counted
Associative Seqable IPersistentMap
APersistentMap RT MapEquivalence MapEntry)
(java.io Serializable Writer)
(java.util Map Iterator))))
data format
;; Represents a node of an XML tree
;; We implement a custom deftype for elements
it is similar to ( defrecord Element [ tag attrs content ] )
;; but we override its hash and equality to be compatible with
;; clojure's hash-maps
see -2084
;; also, elements don't have an extmap and degrade to hash-maps also
;; when assoc'ing unknown keys
;; FIXME hash caching cannot be used: -2092
#?
(:clj
(deftype ElementIterator [el ^:volatile-mutable fields]
Iterator
(hasNext [_] (boolean (seq fields)))
(next [_]
(let [f (first fields)]
(set! fields (next fields))
(MapEntry. f (get el f))))))
(deftype Element [tag attrs content meta]
;; serializing/cloning, hashing, equality, iteration
#?@
(:clj
[Serializable
MapEquivalence
IHashEq
(hasheq [this] (APersistentMap/mapHasheq this))
Iterable
(iterator [this] (ElementIterator. this '(:tag :attrs :content)))]
:cljs
[ICloneable
(-clone [_] (Element. tag attrs content meta))
IHash
(-hash [this] (hash-unordered-coll this))
IEquiv
(-equiv [this other] (or (identical? this other)
^boolean (js/cljs.core.equiv_map this other)))
IIterable
(-iterator [this] (RecordIter. 0 this 3 [:tag :attrs :content] (nil-iter)))])
Object
(toString [_]
(let [qname (as-qname tag)]
(apply str (concat ["<" qname]
(mapcat (fn [[n a]]
[" " (as-qname n) "=" (pr-str a)])
attrs)
(if (seq content)
(concat [">"] content ["</" qname ">"])
["/>"])))))
#?@(:clj
[(hashCode [this] (APersistentMap/mapHash this))
(equals [this other] (APersistentMap/mapEquals this other))
IPersistentMap
(equiv [this other] (APersistentMap/mapEquals this other))])
;; Main collection interfaces, that are included in IPersistentMap,
but are separate protocols in cljs
#?(:cljs ILookup)
(#?(:clj valAt :cljs -lookup) [this k]
(#?(:clj .valAt :cljs -lookup)
this k nil))
(#?(:clj valAt :cljs -lookup) [this k nf]
(case k
:tag tag
:attrs attrs
:content content
nf))
#?(:cljs ICounted)
(#?(:clj count :cljs -count) [this] 3)
#?(:cljs ICollection)
(#?(:clj cons :cljs -conj) [this entry]
(conj (with-meta {:tag tag :attrs attrs :content content} meta)
entry))
#?(:cljs IAssociative)
(#?(:clj assoc :cljs -assoc) [this k v]
(case k
:tag (Element. v attrs content meta)
:attrs (Element. tag v content meta)
:content (Element. tag attrs v meta)
(with-meta {:tag tag :attrs attrs :content content k v} meta)))
#?(:cljs IMap)
(#?(:clj without :cljs -dissoc) [this k]
(with-meta
(case k
:tag {:attrs attrs :content content}
:attrs {:tag tag :content content}
:content {:tag tag :attrs attrs}
this)
meta))
#?@(:cljs
[ISeqable
(-seq [this]
(seq [[:tag tag] [:attrs attrs] [:content content]]))]
:clj
[(seq [this] (iterator-seq (.iterator this)))])
#?(:clj (empty [_] (Element. tag {} [] {})))
#?@(:cljs
[IEmptyableCollection
(-empty [_] (Element. tag {} [] {}))])
;; j.u.Map and included interfaces
#?@(:clj
[Map
(entrySet [this] (set this))
(values [this] (vals this))
(keySet [this] (set (keys this)))
(get [this k] (.valAt this k))
(containsKey [this k] (case k (:tag :attrs :content) true false))
(containsValue [this v] (boolean (some #{v} (vals this))))
(isEmpty [this] false)
(size [this] 3)])
Metadata interface
#?(:clj IObj :cljs IMeta)
(#?(:clj meta :cljs -meta) [this] meta)
#?(:cljs IWithMeta)
(#?(:clj withMeta :cljs -with-meta) [this next-meta]
(Element. tag attrs content next-meta))
;; cljs printing is protocol-based
#?@
(:cljs
[IPrintWithWriter
(-pr-writer [this writer opts]
(-write writer "#xml/element{:tag ")
(pr-writer tag writer opts)
(when-not (empty? attrs)
(-write writer ", :attrs ")
(pr-writer attrs writer opts))
(when-not (empty? content)
(-write writer ", :content ")
(pr-sequential-writer writer pr-writer "[" " " "]" opts content))
(-write writer "}"))]))
;; clj printing is a multimethod
#?
(:clj
(defmethod print-method Element [{:keys [tag attrs content]} ^Writer writer]
(.write writer "#xml/element{:tag ")
(print-method tag writer)
(when-not (empty? attrs)
(.write writer ", :attrs ")
(print-method attrs writer))
(when-not (empty? content)
(.write writer ", :content [")
(print-method (first content) writer)
(doseq [c (next content)]
(.write writer " ")
(print-method c writer))
(.write writer "]"))
(.write writer "}")))
(defrecord CData [content])
(defrecord Comment [content])
(defn element*
"Create an xml element from a content collection and optional metadata"
([tag attrs content meta]
(Element. tag (or attrs {}) (remove nil? content) meta))
([tag attrs content]
(Element. tag (or attrs {}) (remove nil? content) nil)))
#?(:clj
Compiler macro for inlining the two constructors
(alter-meta! #'element* assoc :inline
(fn
([tag attrs content meta]
`(Element. ~tag (or ~attrs {}) (remove nil? ~content) ~meta))
([tag attrs content]
`(Element. ~tag (or ~attrs {}) (remove nil? ~content) nil)))))
(defn element
"Create an xml Element from content varargs"
([tag] (element* tag nil nil))
([tag attrs] (element* tag attrs nil))
([tag attrs & content] (element* tag attrs content)))
(defn cdata
"Create a CData node"
[content]
(CData. content))
(defn xml-comment
"Create a Comment node"
[content]
(Comment. content))
(defn map->Element [{:keys [tag attrs content] :as el}]
(element* tag attrs content (meta el)))
(defn tagged-element [el]
(cond (map? el) (map->Element el)
TODO support hiccup syntax
:else (throw (ex-info "Unsupported element representation"
{:element el}))))
(defn element? [el]
(and (map? el) (some? (:tag el))))
| null | https://raw.githubusercontent.com/clojure/data.xml/12cc9934607de6cb4d75eddb1fcae30829fa4156/src/main/clojure/clojure/data/xml/node.cljc | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
Represents a node of an XML tree
We implement a custom deftype for elements
but we override its hash and equality to be compatible with
clojure's hash-maps
also, elements don't have an extmap and degrade to hash-maps also
when assoc'ing unknown keys
FIXME hash caching cannot be used: -2092
serializing/cloning, hashing, equality, iteration
Main collection interfaces, that are included in IPersistentMap,
j.u.Map and included interfaces
cljs printing is protocol-based
clj printing is a multimethod | Copyright ( c ) . All rights reserved .
(ns clojure.data.xml.node
"Data types for xml nodes: Element, CData and Comment"
{:author "Herwig Hochleitner"}
(:require [clojure.data.xml.name :refer [as-qname]])
#?(:clj (:import (clojure.lang IHashEq IObj ILookup IKeywordLookup Counted
Associative Seqable IPersistentMap
APersistentMap RT MapEquivalence MapEntry)
(java.io Serializable Writer)
(java.util Map Iterator))))
data format
it is similar to ( defrecord Element [ tag attrs content ] )
see -2084
#?
(:clj
(deftype ElementIterator [el ^:volatile-mutable fields]
Iterator
(hasNext [_] (boolean (seq fields)))
(next [_]
(let [f (first fields)]
(set! fields (next fields))
(MapEntry. f (get el f))))))
(deftype Element [tag attrs content meta]
#?@
(:clj
[Serializable
MapEquivalence
IHashEq
(hasheq [this] (APersistentMap/mapHasheq this))
Iterable
(iterator [this] (ElementIterator. this '(:tag :attrs :content)))]
:cljs
[ICloneable
(-clone [_] (Element. tag attrs content meta))
IHash
(-hash [this] (hash-unordered-coll this))
IEquiv
(-equiv [this other] (or (identical? this other)
^boolean (js/cljs.core.equiv_map this other)))
IIterable
(-iterator [this] (RecordIter. 0 this 3 [:tag :attrs :content] (nil-iter)))])
Object
(toString [_]
(let [qname (as-qname tag)]
(apply str (concat ["<" qname]
(mapcat (fn [[n a]]
[" " (as-qname n) "=" (pr-str a)])
attrs)
(if (seq content)
(concat [">"] content ["</" qname ">"])
["/>"])))))
#?@(:clj
[(hashCode [this] (APersistentMap/mapHash this))
(equals [this other] (APersistentMap/mapEquals this other))
IPersistentMap
(equiv [this other] (APersistentMap/mapEquals this other))])
but are separate protocols in cljs
#?(:cljs ILookup)
(#?(:clj valAt :cljs -lookup) [this k]
(#?(:clj .valAt :cljs -lookup)
this k nil))
(#?(:clj valAt :cljs -lookup) [this k nf]
(case k
:tag tag
:attrs attrs
:content content
nf))
#?(:cljs ICounted)
(#?(:clj count :cljs -count) [this] 3)
#?(:cljs ICollection)
(#?(:clj cons :cljs -conj) [this entry]
(conj (with-meta {:tag tag :attrs attrs :content content} meta)
entry))
#?(:cljs IAssociative)
(#?(:clj assoc :cljs -assoc) [this k v]
(case k
:tag (Element. v attrs content meta)
:attrs (Element. tag v content meta)
:content (Element. tag attrs v meta)
(with-meta {:tag tag :attrs attrs :content content k v} meta)))
#?(:cljs IMap)
(#?(:clj without :cljs -dissoc) [this k]
(with-meta
(case k
:tag {:attrs attrs :content content}
:attrs {:tag tag :content content}
:content {:tag tag :attrs attrs}
this)
meta))
#?@(:cljs
[ISeqable
(-seq [this]
(seq [[:tag tag] [:attrs attrs] [:content content]]))]
:clj
[(seq [this] (iterator-seq (.iterator this)))])
#?(:clj (empty [_] (Element. tag {} [] {})))
#?@(:cljs
[IEmptyableCollection
(-empty [_] (Element. tag {} [] {}))])
#?@(:clj
[Map
(entrySet [this] (set this))
(values [this] (vals this))
(keySet [this] (set (keys this)))
(get [this k] (.valAt this k))
(containsKey [this k] (case k (:tag :attrs :content) true false))
(containsValue [this v] (boolean (some #{v} (vals this))))
(isEmpty [this] false)
(size [this] 3)])
Metadata interface
#?(:clj IObj :cljs IMeta)
(#?(:clj meta :cljs -meta) [this] meta)
#?(:cljs IWithMeta)
(#?(:clj withMeta :cljs -with-meta) [this next-meta]
(Element. tag attrs content next-meta))
#?@
(:cljs
[IPrintWithWriter
(-pr-writer [this writer opts]
(-write writer "#xml/element{:tag ")
(pr-writer tag writer opts)
(when-not (empty? attrs)
(-write writer ", :attrs ")
(pr-writer attrs writer opts))
(when-not (empty? content)
(-write writer ", :content ")
(pr-sequential-writer writer pr-writer "[" " " "]" opts content))
(-write writer "}"))]))
#?
(:clj
(defmethod print-method Element [{:keys [tag attrs content]} ^Writer writer]
(.write writer "#xml/element{:tag ")
(print-method tag writer)
(when-not (empty? attrs)
(.write writer ", :attrs ")
(print-method attrs writer))
(when-not (empty? content)
(.write writer ", :content [")
(print-method (first content) writer)
(doseq [c (next content)]
(.write writer " ")
(print-method c writer))
(.write writer "]"))
(.write writer "}")))
(defrecord CData [content])
(defrecord Comment [content])
(defn element*
"Create an xml element from a content collection and optional metadata"
([tag attrs content meta]
(Element. tag (or attrs {}) (remove nil? content) meta))
([tag attrs content]
(Element. tag (or attrs {}) (remove nil? content) nil)))
#?(:clj
Compiler macro for inlining the two constructors
(alter-meta! #'element* assoc :inline
(fn
([tag attrs content meta]
`(Element. ~tag (or ~attrs {}) (remove nil? ~content) ~meta))
([tag attrs content]
`(Element. ~tag (or ~attrs {}) (remove nil? ~content) nil)))))
(defn element
"Create an xml Element from content varargs"
([tag] (element* tag nil nil))
([tag attrs] (element* tag attrs nil))
([tag attrs & content] (element* tag attrs content)))
(defn cdata
"Create a CData node"
[content]
(CData. content))
(defn xml-comment
"Create a Comment node"
[content]
(Comment. content))
(defn map->Element [{:keys [tag attrs content] :as el}]
(element* tag attrs content (meta el)))
(defn tagged-element [el]
(cond (map? el) (map->Element el)
TODO support hiccup syntax
:else (throw (ex-info "Unsupported element representation"
{:element el}))))
(defn element? [el]
(and (map? el) (some? (:tag el))))
|
20e1d48fbfbc1c98f2b1a65005e748871d2d20544ef85209be9a3b17c875cb8c | racket/typed-racket | struct-options.rkt | #lang typed/racket/base
;; Tests for constructor options for struct
(struct s1 ([x : Integer]) #:constructor-name cons-s1)
(define-struct s2 ([x : Integer]) #:constructor-name cons-s2)
(struct s3 ([x : Integer]) #:extra-constructor-name cons-s3)
(define-struct s4 ([x : Integer]) #:extra-constructor-name cons-s4)
(cons-s1 1)
(cons-s2 2)
(s3 3)
(cons-s3 3)
(s4 4)
(cons-s4 4)
| null | https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/succeed/struct-options.rkt | racket | Tests for constructor options for struct | #lang typed/racket/base
(struct s1 ([x : Integer]) #:constructor-name cons-s1)
(define-struct s2 ([x : Integer]) #:constructor-name cons-s2)
(struct s3 ([x : Integer]) #:extra-constructor-name cons-s3)
(define-struct s4 ([x : Integer]) #:extra-constructor-name cons-s4)
(cons-s1 1)
(cons-s2 2)
(s3 3)
(cons-s3 3)
(s4 4)
(cons-s4 4)
|
6be70000b458654ab898037b745e1a8a87f1d9c2498ca0d826103acd612c42cb | racket/racklog | info.rkt | #lang info
(define collection "racklog")
(define scribblings
'(("racklog.scrbl" (multi-page) (tool))))
(define deps '("base"
"datalog"))
(define build-deps '("eli-tester"
"rackunit-lib"
"racket-doc"
"scribble-lib"))
(define pkg-desc "The implementation of the Racklog (embedded Prolog) language")
(define pkg-authors '(jay))
(define license
'(Apache-2.0 OR MIT))
| null | https://raw.githubusercontent.com/racket/racklog/4bad4b9e9bcc363df453ae5e4211641cddc29e4b/info.rkt | racket | #lang info
(define collection "racklog")
(define scribblings
'(("racklog.scrbl" (multi-page) (tool))))
(define deps '("base"
"datalog"))
(define build-deps '("eli-tester"
"rackunit-lib"
"racket-doc"
"scribble-lib"))
(define pkg-desc "The implementation of the Racklog (embedded Prolog) language")
(define pkg-authors '(jay))
(define license
'(Apache-2.0 OR MIT))
| |
eca6976fef7196c7a7b363eda7396859a693afa6e4724c8867fe38af43c3aa85 | vikram/lisplibraries | bracket-reader.lisp | ;; -*- lisp -*-
(in-package :it.bese.yaclml)
;;;; * The [ reader
A read macro for easily embedding text and YACLML markup in lisp
;;;; code.
(defun |[ reader| (stream char)
"Read a form using YACLML's [ syntax.
Everything between the #\[ and the #\] is read as text. ~FORM
prints (using <:as-html) the value returned by FORM while $FORM
simply evaluates FORM and ignore the result."
(declare (ignore char))
(with-collector (forms)
(loop
for char = (read-char stream t nil t)
do (case char
(#\\ (forms (read-char stream t nil t)))
(#\] (return-from |[ reader| `(yaclml-quote ,@(forms))))
(#\$ (forms (read stream t nil t)))
(#\~ (forms `(<:as-html ,(read stream t nil t))))
(t (forms char))))))
(defvar *readers* '())
(defun enable-yaclml-syntax ()
(set-macro-character #\[ #'|[ reader| nil)
(set-syntax-from-char #\] #\)))
(defun disable-yaclml-syntax ()
(setf *readtable* (copy-readtable nil nil)))
Copyright ( c ) 2002 - 2005 ,
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
- Neither the name of , nor , 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
OWNER OR 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.
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/dependencies/yaclml/src/bracket-reader.lisp | lisp | -*- lisp -*-
* The [ reader
code.
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.
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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(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 :it.bese.yaclml)
A read macro for easily embedding text and YACLML markup in lisp
(defun |[ reader| (stream char)
"Read a form using YACLML's [ syntax.
Everything between the #\[ and the #\] is read as text. ~FORM
prints (using <:as-html) the value returned by FORM while $FORM
simply evaluates FORM and ignore the result."
(declare (ignore char))
(with-collector (forms)
(loop
for char = (read-char stream t nil t)
do (case char
(#\\ (forms (read-char stream t nil t)))
(#\] (return-from |[ reader| `(yaclml-quote ,@(forms))))
(#\$ (forms (read stream t nil t)))
(#\~ (forms `(<:as-html ,(read stream t nil t))))
(t (forms char))))))
(defvar *readers* '())
(defun enable-yaclml-syntax ()
(set-macro-character #\[ #'|[ reader| nil)
(set-syntax-from-char #\] #\)))
(defun disable-yaclml-syntax ()
(setf *readtable* (copy-readtable nil nil)))
Copyright ( c ) 2002 - 2005 ,
- Neither the name of , nor , nor the names
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
|
bf4370eae58ceb01700764104abed9ce6af4db583d440d9c0778b37e506b5315 | jarvinet/scheme | regsim.scm | Structure and Interpretation of Computer Programs , 2nd edition
Register machine simulator
;----------------------------------------------------------------------
; The machine model
(define (make-machine register-names ops controller-text)
(let ((machine (make-new-machine)))
(for-each (lambda (register-name)
((machine 'allocate-register) register-name))
register-names)
((machine 'install-operations) ops)
((machine 'install-instruction-sequence)
(assemble controller-text machine))
machine))
;----------------------------------------------------------------------
Register
(define (make-register name)
(let ((contents '*unassigned*))
(define (dispatch message)
(cond ((eq? message 'get) contents)
((eq? message 'set) (lambda (value) (set! contents value)))
(else
(error "Unknown request -- REGISTER", message))))
dispatch))
(define (get-contents register)
(register 'get))
(define (set-contents! register value)
((register 'set) value))
;----------------------------------------------------------------------
Stack
(define (make-stack)
(let ((stack '()))
(define (push x)
(set! stack (cons x stack)))
(define (pop)
(if (null? stack)
(error "Pop from empty stack -- STACK")
(let ((top (car stack)))
(set! stack (cdr stack))
top)))
(define (initialize)
(set! stack '()))
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
(else
(error "Unknown request -- STACK", message))))
dispatch))
(define (initialize stack)
(stack 'initialize))
(define (push stack value)
((stack 'push) value))
(define (pop stack)
(stack 'pop))
;----------------------------------------------------------------------
(define (make-new-machine)
(let ((stack (make-stack))
(pc (make-register 'pc))
(flag (make-register 'flag))
(the-instruction-sequence '()))
(let ((the-ops
(list (list 'initialize-stack
(lambda () (stack 'initialize)))))
(register-table
(list (list 'pc pc) (list 'flag flag))))
(define (execute)
(let ((insts (get-contents pc)))
(if (null? insts)
'done
(begin
((instruction-execution-proc (car insts)))
(execute)))))
(define (allocate-register name)
(if (assoc name register-table)
(error "Multiply defined register: " name)
(set! register-table
(cons (list name (make-register name))
register-table))))
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(error "Undefined register: " name))))
(define (dispatch message)
(cond ((eq? message 'start)
(set-contents! pc the-instruction-sequence)
(execute))
((eq? message 'install-instruction-sequence)
(lambda (seq) (set! the-instruction-sequence seq)))
((eq? message 'allocate-register) allocate-register)
((eq? message 'get-register) lookup-register)
((eq? message 'install-operations)
(lambda (ops) (set! the-ops (append the-ops ops))))
((eq? message 'stack) stack)
((eq? message 'operations) the-ops)
(else (error "Unknown request -- MACHINE" message))))
dispatch)))
(define (start machine)
(machine 'start))
(define (get-register-contents machine register-name)
(get-contents (get-register machine register-name)))
(define (set-register-contents! machine register-name value)
(set-contents! (get-register machine register-name) value)
'done)
(define (get-register machine register-name)
((machine 'get-register) register-name))
;----------------------------------------------------------------------
The Assembler
(define (assemble controller-text machine)
(extract-labels controller-text
(lambda (insts labels)
(update-insts! insts labels machine)
insts)))
(define (extract-labels text receive)
(if (null? text)
(receive '() '())
(extract-labels (cdr text)
(lambda (insts labels)
(let ((next-inst (car text)))
(if (symbol? next-inst)
(receive insts
(cons (make-label-entry next-inst
insts)
labels))
(receive (cons (make-instruction next-inst)
insts)
labels)))))))
(define (update-insts! insts labels machine)
(let ((pc (get-register machine 'pc))
(flag (get-register machine 'flag))
(stack (machine 'stack))
(ops (machine 'operations)))
(for-each
(lambda (inst)
(set-instruction-execution-proc!
inst
(make-execution-procedure
(instruction-text inst) labels machine
pc flag stack ops)))
insts)))
(define (make-instruction text)
(cons text '()))
(define (instruction-text inst)
(car inst))
(define (instruction-execution-proc inst)
(cdr inst))
(define (set-instruction-execution-proc! inst proc)
(set-cdr! inst proc))
(define (make-label-entry label-name insts)
(cons label-name insts))
(define (lookup-label labels label-name)
(let ((val (assoc label-name labels)))
(if val
(cdr val)
(error "Undefined label -- ASSEMBLE" label-name))))
;----------------------------------------------------------------------
; Generating execution procedures for instructions
(define (make-execution-procedure inst labels machine
pc flag stack ops)
(cond ((eq? (car inst) 'assign)
(make-assign inst machine labels ops pc))
((eq? (car inst) 'test)
(make-test inst machine labels ops flag pc))
((eq? (car inst) 'branch)
(make-branch inst machine labels flag pc))
((eq? (car inst) 'goto)
(make-goto inst machine labels pc))
((eq? (car inst) 'save)
(make-save inst machine stack pc))
((eq? (car inst) 'restore)
(make-restore inst machine stack pc))
((eq? (car inst) 'perform)
(make-perform inst machine labels ops pc))
(else (error "Unknown instruction type -- ASSEMBLE" inst))))
; (assign n (reg val))
( assign ( op + ) ( reg val ) ( reg n ) )
(define (make-assign inst machine labels operations pc)
(let ((target
(get-register machine (assign-reg-name inst)))
(value-exp (assign-value-exp inst)))
(let ((value-proc
(if (operation-exp? value-exp)
(make-operation-exp
value-exp machine labels operations)
(make-primitive-exp
(car value-exp) machine labels))))
(lambda ()
(set-contents! target (value-proc))
(advance-pc pc)))))
(define (assign-reg-name assign-instruction)
(cadr assign-instruction))
(define (assign-value-exp assign-instruction)
(cddr assign-instruction))
(define (advance-pc pc)
(set-contents! pc (cdr (get-contents pc))))
; (test (op =) (reg b) (const 0))
(define (make-test inst machine labels operations flag pc)
(let ((condition (test-condition inst)))
(if (operation-exp? condition)
(let ((condition-proc
(make-operation-exp
condition machine labels operations)))
(lambda ()
(set-contents! flag (condition-proc))
(advance-pc pc)))
(error "Bad TEST instruction -- ASSEMBLE" inst))))
(define (test-condition test-instruction)
(cdr test-instruction))
; (branch (label foo))
(define (make-branch inst machine labels flag pc)
(let ((dest (branch-dest inst)))
(if (label-exp? dest)
(let ((insts
(lookup-label labels (label-exp-label dest))))
(lambda ()
(if (get-contents flag)
(set-contents! pc insts)
(advance-pc pc))))
(error "Bad BRANCH instruction -- ASSEMBLE" inst))))
(define (branch-dest branch-instruction)
(cadr branch-instruction))
( goto ( reg continue ) )
( goto ( label foo ) )
(define (make-goto inst machine labels pc)
(let ((dest (goto-dest inst)))
(cond ((label-exp? dest)
(let ((insts
(lookup-label labels
(label-exp-label dest))))
(lambda ()
(set-contents! pc insts))))
((register-exp? dest)
(let ((reg
(get-register machine
(register-exp-reg dest))))
(lambda ()
(set-contents! pc (get-contents reg)))))
(else (error "Bad GOTO instruction -- ASSEMBLE" inst)))))
(define (goto-dest goto-instruction)
(cadr goto-instruction))
;----------------------------------------------------------------------
; Other instructions
(define (make-save inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(push stack (get-contents reg))
(advance-pc pc))))
(define (make-restore inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(set-contents! reg (pop stack))
(advance-pc pc))))
(define (stack-inst-reg-name stack-instruction)
(cadr stack-instruction))
(define (make-perform inst machine labels operations pc)
(let ((action (perform-action inst)))
(if (operation-exp? action)
(let ((action-proc
(make-operation-exp
action machine labels operations)))
(lambda ()
(action-proc)
(advance-pc pc)))
(error "Bad PERFORM instruction -- ASSEMBLE" inst))))
(define (perform-action inst) (cdr inst))
(define (make-primitive-exp exp machine labels)
(cond ((constant-exp? exp)
(let ((c (constant-exp-value exp)))
(lambda () c)))
((label-exp? exp)
(let ((insts
(lookup-label labels
(label-exp-label exp))))
(lambda () insts)))
((register-exp? exp)
(let ((r (get-register machine
(register-exp-reg exp))))
(lambda () (get-contents r))))
(else
(error "Unknown expresson type -- ASSEMBLE" exp))))
(define (register-exp? exp) (tagged-list? exp 'reg))
(define (register-exp-reg exp) (cadr exp))
(define (constant-exp? exp) (tagged-list? exp 'const))
(define (constant-exp-value exp) (cadr exp))
(define (label-exp? exp) (tagged-list? exp 'label))
(define (label-exp-label exp) (cadr exp))
(define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp) operations))
(aprocs
(map (lambda (e)
(make-primitive-exp e machine labels))
(operation-exp-operands exp))))
(lambda ()
(apply op (map (lambda (p) (p)) aprocs)))))
(define (operation-exp? exp)
(and (pair? exp) (tagged-list? (car exp) 'op)))
(define (operation-exp-op operation-exp)
(cadr (car operation-exp)))
(define (operation-exp-operands operation-exp)
(cdr operation-exp))
(define (lookup-prim symbol operations)
(let ((val (assoc symbol operations)))
(if val
(cadr val)
(error "Unknown operation -- ASSEMBLE" symbol))))
;----------------------------------------------------------------------
; Misc
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
;----------------------------------------------------------------------
(define gcd-machine
(make-machine
'(a b t)
(list (list 'rem remainder) (list '= =))
'(test-b
(test (op =) (reg b) (const 0))
(branch (label gcd-done))
(assign t (op rem) (reg a) (reg b))
(assign a (reg b))
(assign b (reg t))
(goto (label test-b))
gcd-done)))
(set-register-contents! gcd-machine 'a 206)
(set-register-contents! gcd-machine 'b 40)
;(start gcd-machine)
(get-register-contents gcd-machine 'a)
| null | https://raw.githubusercontent.com/jarvinet/scheme/47633d7fc4d82d739a62ceec75c111f6549b1650/Book/eval/regsim.scm | scheme | ----------------------------------------------------------------------
The machine model
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Generating execution procedures for instructions
(assign n (reg val))
(test (op =) (reg b) (const 0))
(branch (label foo))
----------------------------------------------------------------------
Other instructions
----------------------------------------------------------------------
Misc
----------------------------------------------------------------------
(start gcd-machine) | Structure and Interpretation of Computer Programs , 2nd edition
Register machine simulator
(define (make-machine register-names ops controller-text)
(let ((machine (make-new-machine)))
(for-each (lambda (register-name)
((machine 'allocate-register) register-name))
register-names)
((machine 'install-operations) ops)
((machine 'install-instruction-sequence)
(assemble controller-text machine))
machine))
Register
(define (make-register name)
(let ((contents '*unassigned*))
(define (dispatch message)
(cond ((eq? message 'get) contents)
((eq? message 'set) (lambda (value) (set! contents value)))
(else
(error "Unknown request -- REGISTER", message))))
dispatch))
(define (get-contents register)
(register 'get))
(define (set-contents! register value)
((register 'set) value))
Stack
(define (make-stack)
(let ((stack '()))
(define (push x)
(set! stack (cons x stack)))
(define (pop)
(if (null? stack)
(error "Pop from empty stack -- STACK")
(let ((top (car stack)))
(set! stack (cdr stack))
top)))
(define (initialize)
(set! stack '()))
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
(else
(error "Unknown request -- STACK", message))))
dispatch))
(define (initialize stack)
(stack 'initialize))
(define (push stack value)
((stack 'push) value))
(define (pop stack)
(stack 'pop))
(define (make-new-machine)
(let ((stack (make-stack))
(pc (make-register 'pc))
(flag (make-register 'flag))
(the-instruction-sequence '()))
(let ((the-ops
(list (list 'initialize-stack
(lambda () (stack 'initialize)))))
(register-table
(list (list 'pc pc) (list 'flag flag))))
(define (execute)
(let ((insts (get-contents pc)))
(if (null? insts)
'done
(begin
((instruction-execution-proc (car insts)))
(execute)))))
(define (allocate-register name)
(if (assoc name register-table)
(error "Multiply defined register: " name)
(set! register-table
(cons (list name (make-register name))
register-table))))
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(error "Undefined register: " name))))
(define (dispatch message)
(cond ((eq? message 'start)
(set-contents! pc the-instruction-sequence)
(execute))
((eq? message 'install-instruction-sequence)
(lambda (seq) (set! the-instruction-sequence seq)))
((eq? message 'allocate-register) allocate-register)
((eq? message 'get-register) lookup-register)
((eq? message 'install-operations)
(lambda (ops) (set! the-ops (append the-ops ops))))
((eq? message 'stack) stack)
((eq? message 'operations) the-ops)
(else (error "Unknown request -- MACHINE" message))))
dispatch)))
(define (start machine)
(machine 'start))
(define (get-register-contents machine register-name)
(get-contents (get-register machine register-name)))
(define (set-register-contents! machine register-name value)
(set-contents! (get-register machine register-name) value)
'done)
(define (get-register machine register-name)
((machine 'get-register) register-name))
The Assembler
(define (assemble controller-text machine)
(extract-labels controller-text
(lambda (insts labels)
(update-insts! insts labels machine)
insts)))
(define (extract-labels text receive)
(if (null? text)
(receive '() '())
(extract-labels (cdr text)
(lambda (insts labels)
(let ((next-inst (car text)))
(if (symbol? next-inst)
(receive insts
(cons (make-label-entry next-inst
insts)
labels))
(receive (cons (make-instruction next-inst)
insts)
labels)))))))
(define (update-insts! insts labels machine)
(let ((pc (get-register machine 'pc))
(flag (get-register machine 'flag))
(stack (machine 'stack))
(ops (machine 'operations)))
(for-each
(lambda (inst)
(set-instruction-execution-proc!
inst
(make-execution-procedure
(instruction-text inst) labels machine
pc flag stack ops)))
insts)))
(define (make-instruction text)
(cons text '()))
(define (instruction-text inst)
(car inst))
(define (instruction-execution-proc inst)
(cdr inst))
(define (set-instruction-execution-proc! inst proc)
(set-cdr! inst proc))
(define (make-label-entry label-name insts)
(cons label-name insts))
(define (lookup-label labels label-name)
(let ((val (assoc label-name labels)))
(if val
(cdr val)
(error "Undefined label -- ASSEMBLE" label-name))))
(define (make-execution-procedure inst labels machine
pc flag stack ops)
(cond ((eq? (car inst) 'assign)
(make-assign inst machine labels ops pc))
((eq? (car inst) 'test)
(make-test inst machine labels ops flag pc))
((eq? (car inst) 'branch)
(make-branch inst machine labels flag pc))
((eq? (car inst) 'goto)
(make-goto inst machine labels pc))
((eq? (car inst) 'save)
(make-save inst machine stack pc))
((eq? (car inst) 'restore)
(make-restore inst machine stack pc))
((eq? (car inst) 'perform)
(make-perform inst machine labels ops pc))
(else (error "Unknown instruction type -- ASSEMBLE" inst))))
( assign ( op + ) ( reg val ) ( reg n ) )
(define (make-assign inst machine labels operations pc)
(let ((target
(get-register machine (assign-reg-name inst)))
(value-exp (assign-value-exp inst)))
(let ((value-proc
(if (operation-exp? value-exp)
(make-operation-exp
value-exp machine labels operations)
(make-primitive-exp
(car value-exp) machine labels))))
(lambda ()
(set-contents! target (value-proc))
(advance-pc pc)))))
(define (assign-reg-name assign-instruction)
(cadr assign-instruction))
(define (assign-value-exp assign-instruction)
(cddr assign-instruction))
(define (advance-pc pc)
(set-contents! pc (cdr (get-contents pc))))
(define (make-test inst machine labels operations flag pc)
(let ((condition (test-condition inst)))
(if (operation-exp? condition)
(let ((condition-proc
(make-operation-exp
condition machine labels operations)))
(lambda ()
(set-contents! flag (condition-proc))
(advance-pc pc)))
(error "Bad TEST instruction -- ASSEMBLE" inst))))
(define (test-condition test-instruction)
(cdr test-instruction))
(define (make-branch inst machine labels flag pc)
(let ((dest (branch-dest inst)))
(if (label-exp? dest)
(let ((insts
(lookup-label labels (label-exp-label dest))))
(lambda ()
(if (get-contents flag)
(set-contents! pc insts)
(advance-pc pc))))
(error "Bad BRANCH instruction -- ASSEMBLE" inst))))
(define (branch-dest branch-instruction)
(cadr branch-instruction))
( goto ( reg continue ) )
( goto ( label foo ) )
(define (make-goto inst machine labels pc)
(let ((dest (goto-dest inst)))
(cond ((label-exp? dest)
(let ((insts
(lookup-label labels
(label-exp-label dest))))
(lambda ()
(set-contents! pc insts))))
((register-exp? dest)
(let ((reg
(get-register machine
(register-exp-reg dest))))
(lambda ()
(set-contents! pc (get-contents reg)))))
(else (error "Bad GOTO instruction -- ASSEMBLE" inst)))))
(define (goto-dest goto-instruction)
(cadr goto-instruction))
(define (make-save inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(push stack (get-contents reg))
(advance-pc pc))))
(define (make-restore inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(set-contents! reg (pop stack))
(advance-pc pc))))
(define (stack-inst-reg-name stack-instruction)
(cadr stack-instruction))
(define (make-perform inst machine labels operations pc)
(let ((action (perform-action inst)))
(if (operation-exp? action)
(let ((action-proc
(make-operation-exp
action machine labels operations)))
(lambda ()
(action-proc)
(advance-pc pc)))
(error "Bad PERFORM instruction -- ASSEMBLE" inst))))
(define (perform-action inst) (cdr inst))
(define (make-primitive-exp exp machine labels)
(cond ((constant-exp? exp)
(let ((c (constant-exp-value exp)))
(lambda () c)))
((label-exp? exp)
(let ((insts
(lookup-label labels
(label-exp-label exp))))
(lambda () insts)))
((register-exp? exp)
(let ((r (get-register machine
(register-exp-reg exp))))
(lambda () (get-contents r))))
(else
(error "Unknown expresson type -- ASSEMBLE" exp))))
(define (register-exp? exp) (tagged-list? exp 'reg))
(define (register-exp-reg exp) (cadr exp))
(define (constant-exp? exp) (tagged-list? exp 'const))
(define (constant-exp-value exp) (cadr exp))
(define (label-exp? exp) (tagged-list? exp 'label))
(define (label-exp-label exp) (cadr exp))
(define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp) operations))
(aprocs
(map (lambda (e)
(make-primitive-exp e machine labels))
(operation-exp-operands exp))))
(lambda ()
(apply op (map (lambda (p) (p)) aprocs)))))
(define (operation-exp? exp)
(and (pair? exp) (tagged-list? (car exp) 'op)))
(define (operation-exp-op operation-exp)
(cadr (car operation-exp)))
(define (operation-exp-operands operation-exp)
(cdr operation-exp))
(define (lookup-prim symbol operations)
(let ((val (assoc symbol operations)))
(if val
(cadr val)
(error "Unknown operation -- ASSEMBLE" symbol))))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define gcd-machine
(make-machine
'(a b t)
(list (list 'rem remainder) (list '= =))
'(test-b
(test (op =) (reg b) (const 0))
(branch (label gcd-done))
(assign t (op rem) (reg a) (reg b))
(assign a (reg b))
(assign b (reg t))
(goto (label test-b))
gcd-done)))
(set-register-contents! gcd-machine 'a 206)
(set-register-contents! gcd-machine 'b 40)
(get-register-contents gcd-machine 'a)
|
94d194753ba79caf59c0d8d4ca6c312f4e2d64c166af86aedc8fdd372aa2ffe4 | jrh13/hol-light | make.ml | (* ========================================================================= *)
Permuted lists , finite permutations and quick sort .
(* *)
Author :
University of Florence , Italy
(* /~maggesi/ *)
(* *)
( c ) Copyright , , 2005 - 2007
(* ========================================================================= *)
loadt "Permutation/morelist.ml";;
loadt "Permutation/permuted.ml";;
loadt "Permutation/permutation.ml";;
loadt "Permutation/qsort.ml";;
| null | https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/Permutation/make.ml | ocaml | =========================================================================
/~maggesi/
========================================================================= | Permuted lists , finite permutations and quick sort .
Author :
University of Florence , Italy
( c ) Copyright , , 2005 - 2007
loadt "Permutation/morelist.ml";;
loadt "Permutation/permuted.ml";;
loadt "Permutation/permutation.ml";;
loadt "Permutation/qsort.ml";;
|
661d858aadd1b2d830039a3597667f0f1c5daf7484f0ac88f8633833ca8c607a | camsaul/lein-check-namespace-decls | core.clj | (ns project.invalid-file.core
(:require [clojure.string :as str]))
(defn hello []
(str/join ["HEL" "LO"]))
| null | https://raw.githubusercontent.com/camsaul/lein-check-namespace-decls/56f8ddd1b5654862073565287bceac008d7c37ce/test-namespaces/invalid_file/core.clj | clojure | (ns project.invalid-file.core
(:require [clojure.string :as str]))
(defn hello []
(str/join ["HEL" "LO"]))
| |
e4330edb3c4162b7a999934db350fea0c9b44db9328d664331a6ba0fc43dbd4b | swarmpit/swarmpit | info.cljs | (ns swarmpit.component.volume.info
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.form :as form]
[material.component.label :as label]
[material.component.list.basic :as list]
[swarmpit.component.dialog :as dialog]
[swarmpit.component.message :as message]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.state :as state]
[swarmpit.component.progress :as progress]
[swarmpit.component.toolbar :as toolbar]
[swarmpit.component.service.list :as services]
[swarmpit.component.common :as common]
[swarmpit.url :refer [dispatch!]]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[clojure.contrib.humanize :as humanize]
[rum.core :as rum]))
(enable-console-print!)
(defn- volume-services-handler
[volume-name]
(ajax/get
(routes/path-for-backend :volume-services {:name volume-name})
{:on-success (fn [{:keys [response]}]
(state/update-value [:services] response state/form-value-cursor))}))
(defn- volume-handler
[volume-name]
(ajax/get
(routes/path-for-backend :volume {:name volume-name})
{:state [:loading?]
:on-success (fn [{:keys [response]}]
(state/update-value [:volume] response state/form-value-cursor))}))
(defn- delete-volume-handler
[volume-name]
(ajax/delete
(routes/path-for-backend :volume {:name volume-name})
{:on-success (fn [_]
(dispatch!
(routes/path-for-frontend :volume-list))
(message/info
(str "Volume " volume-name " has been removed.")))
:on-error (fn [{:keys [response]}]
(message/error
(str "Volume removing failed. " (:error response))))}))
(def form-driver-opts-render-metadata
{:primary (fn [item] (:name item))
:secondary (fn [item] (:value item))})
(rum/defc form-general < rum/static [{:keys [id stack volumeName driver mountpoint scope]}
services]
(comp/card
{:className "Swarmpit-form-card"}
(form/item-main "Driver" driver false)
(form/item-main "Scope" scope)
(form/item-main "Mountpoint" mountpoint)
(when (and stack (not-empty services))
(comp/box
{}
(comp/divider {})
(comp/card-actions
{}
(comp/button
{:size "small"
:color "primary"
:href (routes/path-for-frontend :stack-info {:name stack})}
"See stack"))))))
(rum/defc form-driver < rum/static [{:keys [driver options]}]
(comp/card
{:className "Swarmpit-card"}
(comp/card-header
{:className "Swarmpit-table-card-header Swarmpit-card-header-responsive-title"
:title (comp/typography {:variant "h6"} "Driver settings")})
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/list
form-driver-opts-render-metadata
options
nil))))
(def form-actions
[{:onClick #(state/update-value [:open] true dialog/dialog-cursor)
:icon (comp/svg icon/trash-path)
:color "default"
:variant "outlined"
:name "Delete"}])
(defn- init-form-state
[]
(state/set-value {:loading? true} state/form-state-cursor))
(def mixin-init-form
(mixin/init-form
(fn [{{:keys [name]} :params}]
(init-form-state)
(volume-handler name)
(volume-services-handler name))))
(rum/defc form-info < rum/static [{:keys [volume services]}]
(comp/mui
(html
[:div.Swarmpit-form
(dialog/confirm-dialog
#(delete-volume-handler (:volumeName volume))
"Delete volume?"
"Delete")
(comp/container
{:maxWidth "md"
:className "Swarmpit-container"}
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/toolbar "Volume" (:volumeName volume) form-actions))
(comp/grid
{:item true
:xs 12}
(form-general volume services))
(when (not-empty (:options volume))
(comp/grid
{:item true
:xs 12}
(form-driver volume)))
(comp/grid
{:item true
:xs 12}
(services/linked services))))])))
(rum/defc form < rum/reactive
mixin-init-form
mixin/subscribe-form [_]
(let [state (state/react state/form-state-cursor)
item (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-info item))))
| null | https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/cljs/swarmpit/component/volume/info.cljs | clojure | (ns swarmpit.component.volume.info
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.form :as form]
[material.component.label :as label]
[material.component.list.basic :as list]
[swarmpit.component.dialog :as dialog]
[swarmpit.component.message :as message]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.state :as state]
[swarmpit.component.progress :as progress]
[swarmpit.component.toolbar :as toolbar]
[swarmpit.component.service.list :as services]
[swarmpit.component.common :as common]
[swarmpit.url :refer [dispatch!]]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[sablono.core :refer-macros [html]]
[clojure.contrib.humanize :as humanize]
[rum.core :as rum]))
(enable-console-print!)
(defn- volume-services-handler
[volume-name]
(ajax/get
(routes/path-for-backend :volume-services {:name volume-name})
{:on-success (fn [{:keys [response]}]
(state/update-value [:services] response state/form-value-cursor))}))
(defn- volume-handler
[volume-name]
(ajax/get
(routes/path-for-backend :volume {:name volume-name})
{:state [:loading?]
:on-success (fn [{:keys [response]}]
(state/update-value [:volume] response state/form-value-cursor))}))
(defn- delete-volume-handler
[volume-name]
(ajax/delete
(routes/path-for-backend :volume {:name volume-name})
{:on-success (fn [_]
(dispatch!
(routes/path-for-frontend :volume-list))
(message/info
(str "Volume " volume-name " has been removed.")))
:on-error (fn [{:keys [response]}]
(message/error
(str "Volume removing failed. " (:error response))))}))
(def form-driver-opts-render-metadata
{:primary (fn [item] (:name item))
:secondary (fn [item] (:value item))})
(rum/defc form-general < rum/static [{:keys [id stack volumeName driver mountpoint scope]}
services]
(comp/card
{:className "Swarmpit-form-card"}
(form/item-main "Driver" driver false)
(form/item-main "Scope" scope)
(form/item-main "Mountpoint" mountpoint)
(when (and stack (not-empty services))
(comp/box
{}
(comp/divider {})
(comp/card-actions
{}
(comp/button
{:size "small"
:color "primary"
:href (routes/path-for-frontend :stack-info {:name stack})}
"See stack"))))))
(rum/defc form-driver < rum/static [{:keys [driver options]}]
(comp/card
{:className "Swarmpit-card"}
(comp/card-header
{:className "Swarmpit-table-card-header Swarmpit-card-header-responsive-title"
:title (comp/typography {:variant "h6"} "Driver settings")})
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/list
form-driver-opts-render-metadata
options
nil))))
(def form-actions
[{:onClick #(state/update-value [:open] true dialog/dialog-cursor)
:icon (comp/svg icon/trash-path)
:color "default"
:variant "outlined"
:name "Delete"}])
(defn- init-form-state
[]
(state/set-value {:loading? true} state/form-state-cursor))
(def mixin-init-form
(mixin/init-form
(fn [{{:keys [name]} :params}]
(init-form-state)
(volume-handler name)
(volume-services-handler name))))
(rum/defc form-info < rum/static [{:keys [volume services]}]
(comp/mui
(html
[:div.Swarmpit-form
(dialog/confirm-dialog
#(delete-volume-handler (:volumeName volume))
"Delete volume?"
"Delete")
(comp/container
{:maxWidth "md"
:className "Swarmpit-container"}
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/toolbar "Volume" (:volumeName volume) form-actions))
(comp/grid
{:item true
:xs 12}
(form-general volume services))
(when (not-empty (:options volume))
(comp/grid
{:item true
:xs 12}
(form-driver volume)))
(comp/grid
{:item true
:xs 12}
(services/linked services))))])))
(rum/defc form < rum/reactive
mixin-init-form
mixin/subscribe-form [_]
(let [state (state/react state/form-state-cursor)
item (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-info item))))
| |
c215b02fb75f460df8b2662163c21771fc56b202b0c1db703382ad0a0f15883e | erlang/percept | percept_html.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2007 - 2016 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
-module(percept_html).
-export([page/3,
codelocation_page/3,
databases_page/3,
load_database_page/3,
processes_page/3,
concurrency_page/3,
process_info_page/3]).
-export([value2pid/1,
pid2value/1,
get_option_value/2,
join_strings_with/2]).
-include("percept.hrl").
-include_lib("kernel/include/file.hrl").
%% API
page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, overview_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
processes_page(SessionID, _, _) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, processes_content()),
ok = mod_esi:deliver(SessionID, footer()).
concurrency_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, concurrency_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
databases_page(SessionID, _, _) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, databases_content()),
ok = mod_esi:deliver(SessionID, footer()).
codelocation_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, codelocation_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
process_info_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, process_info_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
load_database_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
% Very dynamic page, handled differently
load_database_content(SessionID, Env, Input),
ok = mod_esi:deliver(SessionID, footer()).
%%% --------------------------- %%%
Content pages % % %
%%% --------------------------- %%%
overview_content(_Env, Input) ->
Query = httpd:parse_query(Input),
Min = get_option_value("range_min", Query),
Max = get_option_value("range_max", Query),
Width = 1200,
Height = 600,
TotalProfileTime = ?seconds( percept_db:select({system, stop_ts}),
percept_db:select({system, start_ts})),
RegisteredProcs = length(percept_db:select({information, procs})),
RegisteredPorts = length(percept_db:select({information, ports})),
InformationTable =
"<table>" ++
table_line(["Profile time:", TotalProfileTime]) ++
table_line(["Processes:", RegisteredProcs]) ++
table_line(["Ports:", RegisteredPorts]) ++
table_line(["Min. range:", Min]) ++
table_line(["Max. range:", Max]) ++
"</table>",
Header = "
<div id=\"content\">
<div>" ++ InformationTable ++ "</div>\n
<form name=form_area method=POST action=/cgi-bin/percept_html/page>
<input name=data_min type=hidden value=" ++ term2html(float(Min)) ++ ">
<input name=data_max type=hidden value=" ++ term2html(float(Max)) ++ ">\n",
RangeTable =
"<table>"++
table_line([
"Min:",
"<input name=range_min value=" ++ term2html(float(Min)) ++">",
"<select name=\"graph_select\" onChange=\"select_image()\">
<option disabled=true value=\""++ url_graph(Width, Height, Min, Max, []) ++"\" />Ports
<option disabled=true value=\""++ url_graph(Width, Height, Min, Max, []) ++"\" />Processes
<option value=\""++ url_graph(Width, Height, Min, Max, []) ++"\" />Ports & Processes
</select>",
"<input type=submit value=Update>"
]) ++
table_line([
"Max:",
"<input name=range_max value=" ++ term2html(float(Max)) ++">",
"",
"<a href=/cgi-bin/percept_html/codelocation_page?range_min=" ++
term2html(Min) ++ "&range_max=" ++ term2html(Max) ++ ">Code location</a>"
]) ++
"</table>",
MainTable =
"<table>" ++
table_line([div_tag_graph()]) ++
table_line([RangeTable]) ++
"</table>",
Footer = "</div></form>",
Header ++ MainTable ++ Footer.
div_tag_graph() ->
%background:url('/images/loader.gif') no-repeat center;
"<div id=\"percept_graph\"
onMouseDown=\"select_down(event)\"
onMouseMove=\"select_move(event)\"
onMouseUp=\"select_up(event)\"
style=\"
background-size: 100%;
background-origin: content;
width: 100%;
position:relative;
\">
<div id=\"percept_areaselect\"
style=\"background-color:#ef0909;
position:relative;
visibility:hidden;
border-left: 1px solid #101010;
border-right: 1px solid #101010;
z-index:2;
width:40px;
height:40px;\"></div></div>".
-spec url_graph(
Widht :: non_neg_integer(),
Height :: non_neg_integer(),
Min :: float(),
Max :: float(),
Pids :: [pid()]) -> string().
url_graph(W, H, Min, Max, []) ->
"/cgi-bin/percept_graph/graph?range_min=" ++ term2html(float(Min))
++ "&range_max=" ++ term2html(float(Max))
++ "&width=" ++ term2html(float(W))
++ "&height=" ++ term2html(float(H)).
%%% process_info_content
process_info_content(_Env, Input) ->
Query = httpd:parse_query(Input),
Pid = get_option_value("pid", Query),
[I] = percept_db:select({information, Pid}),
ArgumentString = case I#information.entry of
{_, _, Arguments} -> lists:flatten( [term2html(Arg) ++ "<br>" || Arg <- Arguments]);
_ -> ""
end,
TimeTable = html_table([
[{th, ""},
{th, "Timestamp"},
{th, "Profile Time"}],
[{td, "Start"},
term2html(I#information.start),
term2html(procstarttime(I#information.start))],
[{td, "Stop"},
term2html(I#information.stop),
term2html(procstoptime(I#information.stop))]
]),
InfoTable = html_table([
[{th, "Pid"}, term2html(I#information.id)],
[{th, "Name"}, term2html(I#information.name)],
[{th, "Entrypoint"}, mfa2html(I#information.entry)],
[{th, "Arguments"}, ArgumentString],
[{th, "Timetable"}, TimeTable],
[{th, "Parent"}, pid2html(I#information.parent)],
[{th, "Children"}, lists:flatten(lists:map(fun(Child) -> pid2html(Child) ++ " " end, I#information.children))]
]),
PidActivities = percept_db:select({activity, [{id, Pid}]}),
WaitingMfas = percept_analyzer:waiting_activities(PidActivities),
TotalWaitTime = lists:sum( [T || {T, _, _} <- WaitingMfas] ),
MfaTable = html_table([
[{th, "percentage"},
{th, "total"},
{th, "mean"},
{th, "stddev"},
{th, "#recv"},
{th, "module:function/arity"}]] ++ [
[{td, image_string(percentage, [{width, 100}, {height, 10}, {percentage, Time/TotalWaitTime}])},
{td, term2html(Time)},
{td, term2html(Mean)},
{td, term2html(StdDev)},
{td, term2html(N)},
{td, mfa2html(MFA)} ] || {Time, MFA, {Mean, StdDev, N}} <- WaitingMfas]),
"<div id=\"content\">" ++
InfoTable ++ "<br>" ++
MfaTable ++
"</div>".
%%% concurrency content
concurrency_content(_Env, Input) ->
%% Get query
Query = httpd:parse_query(Input),
%% Collect selected pids and generate id tags
Pids = [value2pid(PidValue) || {PidValue, Case} <- Query, Case == "on", PidValue /= "select_all"],
IDs = [{id, Pid} || Pid <- Pids],
% FIXME: A lot of extra work here, redo
%% Analyze activities and calculate area bounds
Activities = percept_db:select({activity, IDs}),
StartTs = percept_db:select({system, start_ts}),
Counts = [{Time, Y1 + Y2} || {Time, Y1, Y2} <- percept_analyzer:activities2count2(Activities, StartTs)],
{T0,_,T1,_} = percept_analyzer:minmax(Counts),
% FIXME: End
PidValues = [pid2value(Pid) || Pid <- Pids],
%% Generate activity bar requests
ActivityBarTable = lists:foldl(
fun(Pid, Out) ->
ValueString = pid2value(Pid),
Out ++
table_line([
pid2html(Pid),
"<img onload=\"size_image(this, '" ++
image_string_head("activity", [{"pid", ValueString}, {range_min, T0},{range_max, T1},{height, 10}], []) ++
"')\" src=/images/white.png border=0 />"
])
end, [], Pids),
%% Make pids request string
PidsRequest = join_strings_with(PidValues, ":"),
"<div id=\"content\">
<table cellspacing=0 cellpadding=0 border=0>" ++
table_line([
"",
"<img onload=\"size_image(this, '" ++
image_string_head("graph", [{"pids", PidsRequest},{range_min, T0}, {range_max, T1}, {height, 400}], []) ++
"')\" src=/images/white.png border=0 />"
]) ++
ActivityBarTable ++
"</table></div>\n".
processes_content() ->
Ports = percept_db:select({information, ports}),
UnsortedProcesses = percept_db:select({information, procs}),
SystemStartTS = percept_db:select({system, start_ts}),
SystemStopTS = percept_db:select({system, stop_ts}),
ProfileTime = ?seconds( SystemStopTS,
SystemStartTS),
Processes = lists:sort(
fun (A, B) ->
if
A#information.id > B#information.id -> true;
true -> false
end
end, UnsortedProcesses),
ProcsHtml = lists:foldl(
fun (I, Out) ->
StartTime = procstarttime(I#information.start),
EndTime = procstoptime(I#information.stop),
Prepare =
table_line([
"<input type=checkbox name=" ++ pid2value(I#information.id) ++ ">",
pid2html(I#information.id),
image_string(proc_lifetime, [
{profiletime, ProfileTime},
{start, StartTime},
{"end", term2html(float(EndTime))},
{width, 100},
{height, 10}]),
mfa2html(I#information.entry),
term2html(I#information.name),
pid2html(I#information.parent)
]),
[Prepare|Out]
end, [], Processes),
PortsHtml = lists:foldl(
fun (I, Out) ->
StartTime = procstarttime(I#information.start),
EndTime = procstoptime(I#information.stop),
Prepare =
table_line([
"",
pid2html(I#information.id),
image_string(proc_lifetime, [
{profiletime, ProfileTime},
{start, StartTime},
{"end", term2html(float(EndTime))},
{width, 100},
{height, 10}]),
mfa2html(I#information.entry),
term2html(I#information.name),
pid2html(I#information.parent)
]),
[Prepare|Out]
end, [], Ports),
Selector = "<table>" ++
table_line([
"<input onClick='selectall()' type=checkbox name=select_all>Select all"]) ++
table_line([
"<input type=submit value=Compare>"]) ++
"</table>",
if
length(ProcsHtml) > 0 ->
ProcsHtmlResult =
"<tr><td><b>Processes</b></td></tr>
<tr><td>
<table width=700 cellspacing=0 border=0>
<tr>
<td align=middle width=40><b>Select</b></td>
<td align=middle width=40><b>Pid</b></td>
<td><b>Lifetime</b></td>
<td><b>Entrypoint</b></td>
<td><b>Name</b></td>
<td><b>Parent</b></td>
</tr>" ++
lists:flatten(ProcsHtml) ++
"</table>
</td></tr>";
true ->
ProcsHtmlResult = ""
end,
if
length(PortsHtml) > 0 ->
PortsHtmlResult = "
<tr><td><b>Ports</b></td></tr>
<tr><td>
<table width=700 cellspacing=0 border=0>
<tr>
<td align=middle width=40><b>Select</b></td>
<td align=left width=40><b>Pid</b></td>
<td><b>Lifetime</b></td>
<td><b>Entrypoint</b></td>
<td><b>Name</b></td>
<td><b>Parent</b></td>
</tr>" ++
lists:flatten(PortsHtml) ++
"</table>
</td></tr>";
true ->
PortsHtmlResult = ""
end,
Right = "<div>"
++ Selector ++
"</div>\n",
Middle = "<div id=\"content\">
<table>" ++
ProcsHtmlResult ++
PortsHtmlResult ++
"</table>" ++
Right ++
"</div>\n",
"<form name=process_select method=POST action=/cgi-bin/percept_html/concurrency_page>" ++
Middle ++
"</form>".
procstarttime(TS) ->
case TS of
undefined -> 0.0;
TS -> ?seconds(TS,percept_db:select({system, start_ts}))
end.
procstoptime(TS) ->
case TS of
undefined -> ?seconds( percept_db:select({system, stop_ts}),
percept_db:select({system, start_ts}));
TS -> ?seconds(TS, percept_db:select({system, start_ts}))
end.
databases_content() ->
"<div id=\"content\">
<form name=load_percept_file method=post action=/cgi-bin/percept_html/load_database_page>
<center>
<table>
<tr><td>Enter file to analyse:</td><td><input type=hidden name=path /></td></tr>
<tr><td><input type=file name=file size=40 /></td><td><input type=submit value=Load onClick=\"path.value = file.value;\" /></td></tr>
</table>
</center>
</form>
</div>".
load_database_content(SessionId, _Env, Input) ->
Query = httpd:parse_query(Input),
{_,{_,Path}} = lists:keysearch("file", 1, Query),
{_,{_,File}} = lists:keysearch("path", 1, Query),
Filename = filename:join(Path, File),
% Check path/file/filename
ok = mod_esi:deliver(SessionId, "<div id=\"content\">"),
case file:read_file_info(Filename) of
{ok, _} ->
Content = "<center>
Parsing: " ++ Filename ++ "<br>
</center>",
ok = mod_esi:deliver(SessionId, Content),
case percept:analyze(Filename) of
{error, Reason} ->
ok = mod_esi:deliver(SessionId, error_msg("Analyze" ++ term2html(Reason)));
_ ->
Complete = "<center><a href=\"/cgi-bin/percept_html/page\">View</a></center>",
ok = mod_esi:deliver(SessionId, Complete)
end;
{error, Reason} ->
ok = mod_esi:deliver(SessionId, error_msg("File" ++ term2html(Reason)))
end,
ok = mod_esi:deliver(SessionId, "</div>").
codelocation_content(_Env, Input) ->
Query = httpd:parse_query(Input),
Min = get_option_value("range_min", Query),
Max = get_option_value("range_max", Query),
StartTs = percept_db:select({system, start_ts}),
TsMin = percept_analyzer:seconds2ts(Min, StartTs),
TsMax = percept_analyzer:seconds2ts(Max, StartTs),
Acts = percept_db:select({activity, [{ts_min, TsMin}, {ts_max, TsMax}]}),
Secs = [timer:now_diff(A#activity.timestamp,StartTs)/1000 || A <- Acts],
Delta = cl_deltas(Secs),
Zip = lists:zip(Acts, Delta),
Table = html_table([
[{th, "delta [ms]"},
{th, "time [ms]"},
{th, " pid "},
{th, "activity"},
{th, "module:function/arity"},
{th, "#runnables"}]] ++ [
[{td, term2html(D)},
{td, term2html(timer:now_diff(A#activity.timestamp,StartTs)/1000)},
{td, pid2html(A#activity.id)},
{td, term2html(A#activity.state)},
{td, mfa2html(A#activity.where)},
{td, term2html(A#activity.runnable_count)}] || {A, D} <- Zip ]),
"<div id=\"content\">" ++
Table ++
"</div>".
cl_deltas([]) -> [];
cl_deltas(List) -> cl_deltas(List, [0.0]).
cl_deltas([_], Out) -> lists:reverse(Out);
cl_deltas([A,B|Ls], Out) -> cl_deltas([B|Ls], [B - A | Out]).
%%% --------------------------- %%%
%%% Utility functions %%%
%%% --------------------------- %%%
%% Should be in string stdlib?
join_strings(Strings) ->
lists:flatten(Strings).
-spec join_strings_with(Strings :: [string()], Separator :: string()) -> string().
join_strings_with([S1, S2 | R], S) ->
join_strings_with([join_strings_with(S1,S2,S) | R], S);
join_strings_with([S], _) ->
S.
join_strings_with(S1, S2, S) ->
join_strings([S1,S,S2]).
Generic erlang2html
-spec html_table(Rows :: [[string() | {'td' | 'th', string()}]]) -> string().
html_table(Rows) -> "<table>" ++ html_table_row(Rows) ++ "</table>".
html_table_row(Rows) -> html_table_row(Rows, odd).
html_table_row([], _) -> "";
html_table_row([Row|Rows], odd ) -> "<tr class=\"odd\">" ++ html_table_data(Row) ++ "</tr>" ++ html_table_row(Rows, even);
html_table_row([Row|Rows], even) -> "<tr class=\"even\">" ++ html_table_data(Row) ++ "</tr>" ++ html_table_row(Rows, odd ).
html_table_data([]) -> "";
html_table_data([{td, Data}|Row]) -> "<td>" ++ Data ++ "</td>" ++ html_table_data(Row);
html_table_data([{th, Data}|Row]) -> "<th>" ++ Data ++ "</th>" ++ html_table_data(Row);
html_table_data([Data|Row]) -> "<td>" ++ Data ++ "</td>" ++ html_table_data(Row).
-spec table_line(Table :: [any()]) -> string().
table_line(List) -> table_line(List, ["<tr>"]).
table_line([], Out) -> lists:flatten(lists:reverse(["</tr>\n"|Out]));
table_line([Element | Elements], Out) when is_list(Element) ->
table_line(Elements, ["<td>" ++ Element ++ "</td>" |Out]);
table_line([Element | Elements], Out) ->
table_line(Elements, ["<td>" ++ term2html(Element) ++ "</td>"|Out]).
-spec term2html(any()) -> string().
term2html(Term) when is_float(Term) -> lists:flatten(io_lib:format("~.4f", [Term]));
term2html(Term) -> lists:flatten(io_lib:format("~p", [Term])).
-spec mfa2html(MFA :: {atom(), atom(), list() | integer()}) -> string().
mfa2html({Module, Function, Arguments}) when is_list(Arguments) ->
lists:flatten(io_lib:format("~p:~p/~p", [Module, Function, length(Arguments)]));
mfa2html({Module, Function, Arity}) when is_integer(Arity) ->
lists:flatten(io_lib:format("~p:~p/~p", [Module, Function, Arity]));
mfa2html(_) ->
"undefined".
-spec pid2html(Pid :: pid() | port()) -> string().
pid2html(Pid) when is_pid(Pid) ->
PidString = term2html(Pid),
PidValue = pid2value(Pid),
"<a href=\"/cgi-bin/percept_html/process_info_page?pid="++PidValue++"\">"++PidString++"</a>";
pid2html(Pid) when is_port(Pid) ->
term2html(Pid);
pid2html(_) ->
"undefined".
-spec image_string(Request :: string()) -> string().
image_string(Request) ->
"<img border=0 src=\"/cgi-bin/percept_graph/" ++
Request ++
" \">".
-spec image_string(atom() | string(), list()) -> string().
image_string(Request, Options) when is_atom(Request), is_list(Options) ->
image_string(image_string_head(erlang:atom_to_list(Request), Options, []));
image_string(Request, Options) when is_list(Options) ->
image_string(image_string_head(Request, Options, [])).
image_string_head(Request, [{Type, Value} | Opts], Out) when is_atom(Type), is_number(Value) ->
Opt = join_strings(["?",term2html(Type),"=",term2html(Value)]),
image_string_tail(Request, Opts, [Opt|Out]);
image_string_head(Request, [{Type, Value} | Opts], Out) ->
Opt = join_strings(["?",Type,"=",Value]),
image_string_tail(Request, Opts, [Opt|Out]).
image_string_tail(Request, [], Out) ->
join_strings([Request | lists:reverse(Out)]);
image_string_tail(Request, [{Type, Value} | Opts], Out) when is_atom(Type), is_number(Value) ->
Opt = join_strings(["&",term2html(Type),"=",term2html(Value)]),
image_string_tail(Request, Opts, [Opt|Out]);
image_string_tail(Request, [{Type, Value} | Opts], Out) ->
Opt = join_strings(["&",Type,"=",Value]),
image_string_tail(Request, Opts, [Opt|Out]).
%%% percept conversions
-spec pid2value(Pid :: pid()) -> string().
pid2value(Pid) ->
String = lists:flatten(io_lib:format("~p", [Pid])),
lists:sublist(String, 2, erlang:length(String)-2).
-spec value2pid(Value :: string()) -> pid().
value2pid(Value) ->
String = lists:flatten("<" ++ Value ++ ">"),
erlang:list_to_pid(String).
%%% get value
-spec get_option_value(Option :: string(), Options :: [{string(),any()}]) ->
{'error', any()} | boolean() | pid() | [pid()] | number().
get_option_value(Option, Options) ->
case catch get_option_value0(Option, Options) of
{'EXIT', Reason} -> {error, Reason};
Value -> Value
end.
get_option_value0(Option, Options) ->
case lists:keysearch(Option, 1, Options) of
false -> get_default_option_value(Option);
{value, {Option, _Value}} when Option == "fillcolor" -> true;
{value, {Option, Value}} when Option == "pid" -> value2pid(Value);
{value, {Option, Value}} when Option == "pids" ->
[value2pid(PidValue) || PidValue <- string:tokens(Value,":")];
{value, {Option, Value}} -> get_number_value(Value);
_ -> {error, undefined}
end.
get_default_option_value(Option) ->
case Option of
"fillcolor" -> false;
"range_min" -> float(0.0);
"pids" -> [];
"range_max" ->
Acts = percept_db:select({activity, []}),
#activity{ timestamp = Start } = hd(Acts),
#activity{ timestamp = Stop } = hd(lists:reverse(Acts)),
?seconds(Stop,Start);
"width" -> 700;
"height" -> 400;
_ -> {error, {undefined_default_option, Option}}
end.
-spec get_number_value(string()) -> number() | {'error', 'illegal_number'}.
get_number_value(Value) ->
% Try float
case string:to_float(Value) of
{error, no_float} ->
% Try integer
case string:to_integer(Value) of
{error, _} -> {error, illegal_number};
{Integer, _} -> Integer
end;
{error, _} -> {error, illegal_number};
{Float, _} -> Float
end.
%%% --------------------------- %%%
%%% html prime functions %%%
%%% --------------------------- %%%
header() -> header([]).
header(HeaderData) ->
"Content-Type: text/html\r\n\r\n" ++
"<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">
<title>percept</title>
<link href=\"/css/percept.css\" rel=\"stylesheet\" type=\"text/css\">
<script type=\"text/javascript\" src=\"/javascript/percept_error_handler.js\"></script>
<script type=\"text/javascript\" src=\"/javascript/percept_select_all.js\"></script>
<script type=\"text/javascript\" src=\"/javascript/percept_area_select.js\"></script>
" ++ HeaderData ++"
</head>
<body onLoad=\"load_image()\">
<div id=\"header\"><a href=/index.html>percept</a></div>\n".
footer() ->
"</body>
</html>\n".
menu() ->
"<div id=\"menu\" class=\"menu_tabs\">
<ul>
<li><a href=/cgi-bin/percept_html/databases_page>databases</a></li>
<li><a href=/cgi-bin/percept_html/processes_page>processes</a></li>
<li><a href=/cgi-bin/percept_html/page>overview</a></li>
</ul></div>\n".
-spec error_msg(Error :: string()) -> string().
error_msg(Error) ->
"<table width=300>
<tr height=5><td></td> <td></td></tr>
<tr><td width=150 align=right><b>Error: </b></td> <td align=left>"++ Error ++ "</td></tr>
<tr height=5><td></td> <td></td></tr>
</table>\n".
| null | https://raw.githubusercontent.com/erlang/percept/44ee3ca98bcd37dfab691072e953131107ebec55/src/percept_html.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
API
Very dynamic page, handled differently
--------------------------- %%%
% %
--------------------------- %%%
background:url('/images/loader.gif') no-repeat center;
;
;
process_info_content
concurrency content
Get query
Collect selected pids and generate id tags
FIXME: A lot of extra work here, redo
Analyze activities and calculate area bounds
FIXME: End
Generate activity bar requests
Make pids request string
Check path/file/filename
--------------------------- %%%
Utility functions %%%
--------------------------- %%%
Should be in string stdlib?
percept conversions
get value
Try float
Try integer
--------------------------- %%%
html prime functions %%%
--------------------------- %%% | Copyright Ericsson AB 2007 - 2016 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(percept_html).
-export([page/3,
codelocation_page/3,
databases_page/3,
load_database_page/3,
processes_page/3,
concurrency_page/3,
process_info_page/3]).
-export([value2pid/1,
pid2value/1,
get_option_value/2,
join_strings_with/2]).
-include("percept.hrl").
-include_lib("kernel/include/file.hrl").
page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, overview_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
processes_page(SessionID, _, _) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, processes_content()),
ok = mod_esi:deliver(SessionID, footer()).
concurrency_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, concurrency_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
databases_page(SessionID, _, _) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, databases_content()),
ok = mod_esi:deliver(SessionID, footer()).
codelocation_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, codelocation_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
process_info_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
ok = mod_esi:deliver(SessionID, menu()),
ok = mod_esi:deliver(SessionID, process_info_content(Env, Input)),
ok = mod_esi:deliver(SessionID, footer()).
load_database_page(SessionID, Env, Input) ->
ok = mod_esi:deliver(SessionID, header()),
load_database_content(SessionID, Env, Input),
ok = mod_esi:deliver(SessionID, footer()).
overview_content(_Env, Input) ->
Query = httpd:parse_query(Input),
Min = get_option_value("range_min", Query),
Max = get_option_value("range_max", Query),
Width = 1200,
Height = 600,
TotalProfileTime = ?seconds( percept_db:select({system, stop_ts}),
percept_db:select({system, start_ts})),
RegisteredProcs = length(percept_db:select({information, procs})),
RegisteredPorts = length(percept_db:select({information, ports})),
InformationTable =
"<table>" ++
table_line(["Profile time:", TotalProfileTime]) ++
table_line(["Processes:", RegisteredProcs]) ++
table_line(["Ports:", RegisteredPorts]) ++
table_line(["Min. range:", Min]) ++
table_line(["Max. range:", Max]) ++
"</table>",
Header = "
<div id=\"content\">
<div>" ++ InformationTable ++ "</div>\n
<form name=form_area method=POST action=/cgi-bin/percept_html/page>
<input name=data_min type=hidden value=" ++ term2html(float(Min)) ++ ">
<input name=data_max type=hidden value=" ++ term2html(float(Max)) ++ ">\n",
RangeTable =
"<table>"++
table_line([
"Min:",
"<input name=range_min value=" ++ term2html(float(Min)) ++">",
"<select name=\"graph_select\" onChange=\"select_image()\">
<option disabled=true value=\""++ url_graph(Width, Height, Min, Max, []) ++"\" />Ports
<option disabled=true value=\""++ url_graph(Width, Height, Min, Max, []) ++"\" />Processes
<option value=\""++ url_graph(Width, Height, Min, Max, []) ++"\" />Ports & Processes
</select>",
"<input type=submit value=Update>"
]) ++
table_line([
"Max:",
"<input name=range_max value=" ++ term2html(float(Max)) ++">",
"",
"<a href=/cgi-bin/percept_html/codelocation_page?range_min=" ++
term2html(Min) ++ "&range_max=" ++ term2html(Max) ++ ">Code location</a>"
]) ++
"</table>",
MainTable =
"<table>" ++
table_line([div_tag_graph()]) ++
table_line([RangeTable]) ++
"</table>",
Footer = "</div></form>",
Header ++ MainTable ++ Footer.
div_tag_graph() ->
"<div id=\"percept_graph\"
onMouseDown=\"select_down(event)\"
onMouseMove=\"select_move(event)\"
onMouseUp=\"select_up(event)\"
style=\"
background-origin: content;
position:relative;
\">
<div id=\"percept_areaselect\"
style=\"background-color:#ef0909;
position:relative;
visibility:hidden;
border-left: 1px solid #101010;
border-right: 1px solid #101010;
z-index:2;
width:40px;
height:40px;\"></div></div>".
-spec url_graph(
Widht :: non_neg_integer(),
Height :: non_neg_integer(),
Min :: float(),
Max :: float(),
Pids :: [pid()]) -> string().
url_graph(W, H, Min, Max, []) ->
"/cgi-bin/percept_graph/graph?range_min=" ++ term2html(float(Min))
++ "&range_max=" ++ term2html(float(Max))
++ "&width=" ++ term2html(float(W))
++ "&height=" ++ term2html(float(H)).
process_info_content(_Env, Input) ->
Query = httpd:parse_query(Input),
Pid = get_option_value("pid", Query),
[I] = percept_db:select({information, Pid}),
ArgumentString = case I#information.entry of
{_, _, Arguments} -> lists:flatten( [term2html(Arg) ++ "<br>" || Arg <- Arguments]);
_ -> ""
end,
TimeTable = html_table([
[{th, ""},
{th, "Timestamp"},
{th, "Profile Time"}],
[{td, "Start"},
term2html(I#information.start),
term2html(procstarttime(I#information.start))],
[{td, "Stop"},
term2html(I#information.stop),
term2html(procstoptime(I#information.stop))]
]),
InfoTable = html_table([
[{th, "Pid"}, term2html(I#information.id)],
[{th, "Name"}, term2html(I#information.name)],
[{th, "Entrypoint"}, mfa2html(I#information.entry)],
[{th, "Arguments"}, ArgumentString],
[{th, "Timetable"}, TimeTable],
[{th, "Parent"}, pid2html(I#information.parent)],
[{th, "Children"}, lists:flatten(lists:map(fun(Child) -> pid2html(Child) ++ " " end, I#information.children))]
]),
PidActivities = percept_db:select({activity, [{id, Pid}]}),
WaitingMfas = percept_analyzer:waiting_activities(PidActivities),
TotalWaitTime = lists:sum( [T || {T, _, _} <- WaitingMfas] ),
MfaTable = html_table([
[{th, "percentage"},
{th, "total"},
{th, "mean"},
{th, "stddev"},
{th, "#recv"},
{th, "module:function/arity"}]] ++ [
[{td, image_string(percentage, [{width, 100}, {height, 10}, {percentage, Time/TotalWaitTime}])},
{td, term2html(Time)},
{td, term2html(Mean)},
{td, term2html(StdDev)},
{td, term2html(N)},
{td, mfa2html(MFA)} ] || {Time, MFA, {Mean, StdDev, N}} <- WaitingMfas]),
"<div id=\"content\">" ++
InfoTable ++ "<br>" ++
MfaTable ++
"</div>".
concurrency_content(_Env, Input) ->
Query = httpd:parse_query(Input),
Pids = [value2pid(PidValue) || {PidValue, Case} <- Query, Case == "on", PidValue /= "select_all"],
IDs = [{id, Pid} || Pid <- Pids],
Activities = percept_db:select({activity, IDs}),
StartTs = percept_db:select({system, start_ts}),
Counts = [{Time, Y1 + Y2} || {Time, Y1, Y2} <- percept_analyzer:activities2count2(Activities, StartTs)],
{T0,_,T1,_} = percept_analyzer:minmax(Counts),
PidValues = [pid2value(Pid) || Pid <- Pids],
ActivityBarTable = lists:foldl(
fun(Pid, Out) ->
ValueString = pid2value(Pid),
Out ++
table_line([
pid2html(Pid),
"<img onload=\"size_image(this, '" ++
image_string_head("activity", [{"pid", ValueString}, {range_min, T0},{range_max, T1},{height, 10}], []) ++
"')\" src=/images/white.png border=0 />"
])
end, [], Pids),
PidsRequest = join_strings_with(PidValues, ":"),
"<div id=\"content\">
<table cellspacing=0 cellpadding=0 border=0>" ++
table_line([
"",
"<img onload=\"size_image(this, '" ++
image_string_head("graph", [{"pids", PidsRequest},{range_min, T0}, {range_max, T1}, {height, 400}], []) ++
"')\" src=/images/white.png border=0 />"
]) ++
ActivityBarTable ++
"</table></div>\n".
processes_content() ->
Ports = percept_db:select({information, ports}),
UnsortedProcesses = percept_db:select({information, procs}),
SystemStartTS = percept_db:select({system, start_ts}),
SystemStopTS = percept_db:select({system, stop_ts}),
ProfileTime = ?seconds( SystemStopTS,
SystemStartTS),
Processes = lists:sort(
fun (A, B) ->
if
A#information.id > B#information.id -> true;
true -> false
end
end, UnsortedProcesses),
ProcsHtml = lists:foldl(
fun (I, Out) ->
StartTime = procstarttime(I#information.start),
EndTime = procstoptime(I#information.stop),
Prepare =
table_line([
"<input type=checkbox name=" ++ pid2value(I#information.id) ++ ">",
pid2html(I#information.id),
image_string(proc_lifetime, [
{profiletime, ProfileTime},
{start, StartTime},
{"end", term2html(float(EndTime))},
{width, 100},
{height, 10}]),
mfa2html(I#information.entry),
term2html(I#information.name),
pid2html(I#information.parent)
]),
[Prepare|Out]
end, [], Processes),
PortsHtml = lists:foldl(
fun (I, Out) ->
StartTime = procstarttime(I#information.start),
EndTime = procstoptime(I#information.stop),
Prepare =
table_line([
"",
pid2html(I#information.id),
image_string(proc_lifetime, [
{profiletime, ProfileTime},
{start, StartTime},
{"end", term2html(float(EndTime))},
{width, 100},
{height, 10}]),
mfa2html(I#information.entry),
term2html(I#information.name),
pid2html(I#information.parent)
]),
[Prepare|Out]
end, [], Ports),
Selector = "<table>" ++
table_line([
"<input onClick='selectall()' type=checkbox name=select_all>Select all"]) ++
table_line([
"<input type=submit value=Compare>"]) ++
"</table>",
if
length(ProcsHtml) > 0 ->
ProcsHtmlResult =
"<tr><td><b>Processes</b></td></tr>
<tr><td>
<table width=700 cellspacing=0 border=0>
<tr>
<td align=middle width=40><b>Select</b></td>
<td align=middle width=40><b>Pid</b></td>
<td><b>Lifetime</b></td>
<td><b>Entrypoint</b></td>
<td><b>Name</b></td>
<td><b>Parent</b></td>
</tr>" ++
lists:flatten(ProcsHtml) ++
"</table>
</td></tr>";
true ->
ProcsHtmlResult = ""
end,
if
length(PortsHtml) > 0 ->
PortsHtmlResult = "
<tr><td><b>Ports</b></td></tr>
<tr><td>
<table width=700 cellspacing=0 border=0>
<tr>
<td align=middle width=40><b>Select</b></td>
<td align=left width=40><b>Pid</b></td>
<td><b>Lifetime</b></td>
<td><b>Entrypoint</b></td>
<td><b>Name</b></td>
<td><b>Parent</b></td>
</tr>" ++
lists:flatten(PortsHtml) ++
"</table>
</td></tr>";
true ->
PortsHtmlResult = ""
end,
Right = "<div>"
++ Selector ++
"</div>\n",
Middle = "<div id=\"content\">
<table>" ++
ProcsHtmlResult ++
PortsHtmlResult ++
"</table>" ++
Right ++
"</div>\n",
"<form name=process_select method=POST action=/cgi-bin/percept_html/concurrency_page>" ++
Middle ++
"</form>".
procstarttime(TS) ->
case TS of
undefined -> 0.0;
TS -> ?seconds(TS,percept_db:select({system, start_ts}))
end.
procstoptime(TS) ->
case TS of
undefined -> ?seconds( percept_db:select({system, stop_ts}),
percept_db:select({system, start_ts}));
TS -> ?seconds(TS, percept_db:select({system, start_ts}))
end.
databases_content() ->
"<div id=\"content\">
<form name=load_percept_file method=post action=/cgi-bin/percept_html/load_database_page>
<center>
<table>
<tr><td>Enter file to analyse:</td><td><input type=hidden name=path /></td></tr>
<tr><td><input type=file name=file size=40 /></td><td><input type=submit value=Load onClick=\"path.value = file.value;\" /></td></tr>
</table>
</center>
</form>
</div>".
load_database_content(SessionId, _Env, Input) ->
Query = httpd:parse_query(Input),
{_,{_,Path}} = lists:keysearch("file", 1, Query),
{_,{_,File}} = lists:keysearch("path", 1, Query),
Filename = filename:join(Path, File),
ok = mod_esi:deliver(SessionId, "<div id=\"content\">"),
case file:read_file_info(Filename) of
{ok, _} ->
Content = "<center>
Parsing: " ++ Filename ++ "<br>
</center>",
ok = mod_esi:deliver(SessionId, Content),
case percept:analyze(Filename) of
{error, Reason} ->
ok = mod_esi:deliver(SessionId, error_msg("Analyze" ++ term2html(Reason)));
_ ->
Complete = "<center><a href=\"/cgi-bin/percept_html/page\">View</a></center>",
ok = mod_esi:deliver(SessionId, Complete)
end;
{error, Reason} ->
ok = mod_esi:deliver(SessionId, error_msg("File" ++ term2html(Reason)))
end,
ok = mod_esi:deliver(SessionId, "</div>").
codelocation_content(_Env, Input) ->
Query = httpd:parse_query(Input),
Min = get_option_value("range_min", Query),
Max = get_option_value("range_max", Query),
StartTs = percept_db:select({system, start_ts}),
TsMin = percept_analyzer:seconds2ts(Min, StartTs),
TsMax = percept_analyzer:seconds2ts(Max, StartTs),
Acts = percept_db:select({activity, [{ts_min, TsMin}, {ts_max, TsMax}]}),
Secs = [timer:now_diff(A#activity.timestamp,StartTs)/1000 || A <- Acts],
Delta = cl_deltas(Secs),
Zip = lists:zip(Acts, Delta),
Table = html_table([
[{th, "delta [ms]"},
{th, "time [ms]"},
{th, " pid "},
{th, "activity"},
{th, "module:function/arity"},
{th, "#runnables"}]] ++ [
[{td, term2html(D)},
{td, term2html(timer:now_diff(A#activity.timestamp,StartTs)/1000)},
{td, pid2html(A#activity.id)},
{td, term2html(A#activity.state)},
{td, mfa2html(A#activity.where)},
{td, term2html(A#activity.runnable_count)}] || {A, D} <- Zip ]),
"<div id=\"content\">" ++
Table ++
"</div>".
cl_deltas([]) -> [];
cl_deltas(List) -> cl_deltas(List, [0.0]).
cl_deltas([_], Out) -> lists:reverse(Out);
cl_deltas([A,B|Ls], Out) -> cl_deltas([B|Ls], [B - A | Out]).
join_strings(Strings) ->
lists:flatten(Strings).
-spec join_strings_with(Strings :: [string()], Separator :: string()) -> string().
join_strings_with([S1, S2 | R], S) ->
join_strings_with([join_strings_with(S1,S2,S) | R], S);
join_strings_with([S], _) ->
S.
join_strings_with(S1, S2, S) ->
join_strings([S1,S,S2]).
Generic erlang2html
-spec html_table(Rows :: [[string() | {'td' | 'th', string()}]]) -> string().
html_table(Rows) -> "<table>" ++ html_table_row(Rows) ++ "</table>".
html_table_row(Rows) -> html_table_row(Rows, odd).
html_table_row([], _) -> "";
html_table_row([Row|Rows], odd ) -> "<tr class=\"odd\">" ++ html_table_data(Row) ++ "</tr>" ++ html_table_row(Rows, even);
html_table_row([Row|Rows], even) -> "<tr class=\"even\">" ++ html_table_data(Row) ++ "</tr>" ++ html_table_row(Rows, odd ).
html_table_data([]) -> "";
html_table_data([{td, Data}|Row]) -> "<td>" ++ Data ++ "</td>" ++ html_table_data(Row);
html_table_data([{th, Data}|Row]) -> "<th>" ++ Data ++ "</th>" ++ html_table_data(Row);
html_table_data([Data|Row]) -> "<td>" ++ Data ++ "</td>" ++ html_table_data(Row).
-spec table_line(Table :: [any()]) -> string().
table_line(List) -> table_line(List, ["<tr>"]).
table_line([], Out) -> lists:flatten(lists:reverse(["</tr>\n"|Out]));
table_line([Element | Elements], Out) when is_list(Element) ->
table_line(Elements, ["<td>" ++ Element ++ "</td>" |Out]);
table_line([Element | Elements], Out) ->
table_line(Elements, ["<td>" ++ term2html(Element) ++ "</td>"|Out]).
-spec term2html(any()) -> string().
term2html(Term) when is_float(Term) -> lists:flatten(io_lib:format("~.4f", [Term]));
term2html(Term) -> lists:flatten(io_lib:format("~p", [Term])).
-spec mfa2html(MFA :: {atom(), atom(), list() | integer()}) -> string().
mfa2html({Module, Function, Arguments}) when is_list(Arguments) ->
lists:flatten(io_lib:format("~p:~p/~p", [Module, Function, length(Arguments)]));
mfa2html({Module, Function, Arity}) when is_integer(Arity) ->
lists:flatten(io_lib:format("~p:~p/~p", [Module, Function, Arity]));
mfa2html(_) ->
"undefined".
-spec pid2html(Pid :: pid() | port()) -> string().
pid2html(Pid) when is_pid(Pid) ->
PidString = term2html(Pid),
PidValue = pid2value(Pid),
"<a href=\"/cgi-bin/percept_html/process_info_page?pid="++PidValue++"\">"++PidString++"</a>";
pid2html(Pid) when is_port(Pid) ->
term2html(Pid);
pid2html(_) ->
"undefined".
-spec image_string(Request :: string()) -> string().
image_string(Request) ->
"<img border=0 src=\"/cgi-bin/percept_graph/" ++
Request ++
" \">".
-spec image_string(atom() | string(), list()) -> string().
image_string(Request, Options) when is_atom(Request), is_list(Options) ->
image_string(image_string_head(erlang:atom_to_list(Request), Options, []));
image_string(Request, Options) when is_list(Options) ->
image_string(image_string_head(Request, Options, [])).
image_string_head(Request, [{Type, Value} | Opts], Out) when is_atom(Type), is_number(Value) ->
Opt = join_strings(["?",term2html(Type),"=",term2html(Value)]),
image_string_tail(Request, Opts, [Opt|Out]);
image_string_head(Request, [{Type, Value} | Opts], Out) ->
Opt = join_strings(["?",Type,"=",Value]),
image_string_tail(Request, Opts, [Opt|Out]).
image_string_tail(Request, [], Out) ->
join_strings([Request | lists:reverse(Out)]);
image_string_tail(Request, [{Type, Value} | Opts], Out) when is_atom(Type), is_number(Value) ->
Opt = join_strings(["&",term2html(Type),"=",term2html(Value)]),
image_string_tail(Request, Opts, [Opt|Out]);
image_string_tail(Request, [{Type, Value} | Opts], Out) ->
Opt = join_strings(["&",Type,"=",Value]),
image_string_tail(Request, Opts, [Opt|Out]).
-spec pid2value(Pid :: pid()) -> string().
pid2value(Pid) ->
String = lists:flatten(io_lib:format("~p", [Pid])),
lists:sublist(String, 2, erlang:length(String)-2).
-spec value2pid(Value :: string()) -> pid().
value2pid(Value) ->
String = lists:flatten("<" ++ Value ++ ">"),
erlang:list_to_pid(String).
-spec get_option_value(Option :: string(), Options :: [{string(),any()}]) ->
{'error', any()} | boolean() | pid() | [pid()] | number().
get_option_value(Option, Options) ->
case catch get_option_value0(Option, Options) of
{'EXIT', Reason} -> {error, Reason};
Value -> Value
end.
get_option_value0(Option, Options) ->
case lists:keysearch(Option, 1, Options) of
false -> get_default_option_value(Option);
{value, {Option, _Value}} when Option == "fillcolor" -> true;
{value, {Option, Value}} when Option == "pid" -> value2pid(Value);
{value, {Option, Value}} when Option == "pids" ->
[value2pid(PidValue) || PidValue <- string:tokens(Value,":")];
{value, {Option, Value}} -> get_number_value(Value);
_ -> {error, undefined}
end.
get_default_option_value(Option) ->
case Option of
"fillcolor" -> false;
"range_min" -> float(0.0);
"pids" -> [];
"range_max" ->
Acts = percept_db:select({activity, []}),
#activity{ timestamp = Start } = hd(Acts),
#activity{ timestamp = Stop } = hd(lists:reverse(Acts)),
?seconds(Stop,Start);
"width" -> 700;
"height" -> 400;
_ -> {error, {undefined_default_option, Option}}
end.
-spec get_number_value(string()) -> number() | {'error', 'illegal_number'}.
get_number_value(Value) ->
case string:to_float(Value) of
{error, no_float} ->
case string:to_integer(Value) of
{error, _} -> {error, illegal_number};
{Integer, _} -> Integer
end;
{error, _} -> {error, illegal_number};
{Float, _} -> Float
end.
header() -> header([]).
header(HeaderData) ->
"Content-Type: text/html\r\n\r\n" ++
"<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">
<title>percept</title>
<link href=\"/css/percept.css\" rel=\"stylesheet\" type=\"text/css\">
<script type=\"text/javascript\" src=\"/javascript/percept_error_handler.js\"></script>
<script type=\"text/javascript\" src=\"/javascript/percept_select_all.js\"></script>
<script type=\"text/javascript\" src=\"/javascript/percept_area_select.js\"></script>
" ++ HeaderData ++"
</head>
<body onLoad=\"load_image()\">
<div id=\"header\"><a href=/index.html>percept</a></div>\n".
footer() ->
"</body>
</html>\n".
menu() ->
"<div id=\"menu\" class=\"menu_tabs\">
<ul>
<li><a href=/cgi-bin/percept_html/databases_page>databases</a></li>
<li><a href=/cgi-bin/percept_html/processes_page>processes</a></li>
<li><a href=/cgi-bin/percept_html/page>overview</a></li>
</ul></div>\n".
-spec error_msg(Error :: string()) -> string().
error_msg(Error) ->
"<table width=300>
<tr height=5><td></td> <td></td></tr>
<tr><td width=150 align=right><b>Error: </b></td> <td align=left>"++ Error ++ "</td></tr>
<tr height=5><td></td> <td></td></tr>
</table>\n".
|
f6504a25e3c46a736e6dbc0e075572b313850bc4087147595ffb46461753ede2 | the-dr-lazy/cascade | Char.hs | |
Module : Test . Cascade . Data . : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! !
Copyright : ( c ) 2020 - 2021 Cascade
License : MPL 2.0
Maintainer : < > ( the-dr-lazy.github.io )
Stability : Stable
Portability : POSIX
! ! ! INSERT MODULE LONG DESCRIPTION ! ! !
Module : Test.Cascade.Data.Char
Description : !!! INSERT MODULE SHORT DESCRIPTION !!!
Copyright : (c) 2020-2021 Cascade
License : MPL 2.0
Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io)
Stability : Stable
Portability : POSIX
!!! INSERT MODULE LONG DESCRIPTION !!!
-}
module Test.Cascade.Data.Char
( tests
) where
import Cascade.Data.Char
import qualified Data.Char as Char
import Hedgehog
import qualified Hedgehog.Gen as Gen
import Test.Tasty
import Test.Tasty.Hedgehog
tests :: TestTree
tests = testGroup "Cascade.Data.Char" [isAlphaNumUnderscoreTests]
isAlphaNumUnderscoreTests :: TestTree
isAlphaNumUnderscoreTests = testGroup
"isAlphaNumUnderscore"
[ testProperty "on non-(alphanumeric + underscore) input returns False" prop_false
, testProperty "on alphanumeric + underscore input returns True" prop_true
]
where
prop_false = property do
char <- forAll $ Gen.filter ((/= '_') *> not . Char.isAlphaNum) Gen.unicodeAll
isAlphaNumUnderscore char === False
prop_true = property do
char <- forAll $ Gen.choice [Gen.alphaNum, pure '_']
isAlphaNumUnderscore char === True
| null | https://raw.githubusercontent.com/the-dr-lazy/cascade/014a5589a2763ce373e8c84a211cddc479872b44/cascade-prelude/test/Test/Cascade/Data/Char.hs | haskell | |
Module : Test . Cascade . Data . : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! !
Copyright : ( c ) 2020 - 2021 Cascade
License : MPL 2.0
Maintainer : < > ( the-dr-lazy.github.io )
Stability : Stable
Portability : POSIX
! ! ! INSERT MODULE LONG DESCRIPTION ! ! !
Module : Test.Cascade.Data.Char
Description : !!! INSERT MODULE SHORT DESCRIPTION !!!
Copyright : (c) 2020-2021 Cascade
License : MPL 2.0
Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io)
Stability : Stable
Portability : POSIX
!!! INSERT MODULE LONG DESCRIPTION !!!
-}
module Test.Cascade.Data.Char
( tests
) where
import Cascade.Data.Char
import qualified Data.Char as Char
import Hedgehog
import qualified Hedgehog.Gen as Gen
import Test.Tasty
import Test.Tasty.Hedgehog
tests :: TestTree
tests = testGroup "Cascade.Data.Char" [isAlphaNumUnderscoreTests]
isAlphaNumUnderscoreTests :: TestTree
isAlphaNumUnderscoreTests = testGroup
"isAlphaNumUnderscore"
[ testProperty "on non-(alphanumeric + underscore) input returns False" prop_false
, testProperty "on alphanumeric + underscore input returns True" prop_true
]
where
prop_false = property do
char <- forAll $ Gen.filter ((/= '_') *> not . Char.isAlphaNum) Gen.unicodeAll
isAlphaNumUnderscore char === False
prop_true = property do
char <- forAll $ Gen.choice [Gen.alphaNum, pure '_']
isAlphaNumUnderscore char === True
| |
f9de85ffdd6fe81d255293763fe98898a495bb49d9fec0331d96f989c791c032 | facebook/flow | statusCommands.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open CommandInfo
open CommandUtils
(***********************************************************************)
(* flow status (report current error set) command impl *)
(***********************************************************************)
module type CONFIG = sig
(* explicit == called with "flow status ..."
rather than simply "flow ..." *)
val explicit : bool
end
module Impl (CommandList : COMMAND_LIST) (Config : CONFIG) = struct
let spec =
if Config.explicit then
{
CommandSpec.name = "status";
doc = "(default) Shows current Flow errors by asking the Flow server";
usage =
Printf.sprintf
"Usage: %s status [OPTION]... [ROOT]\nShows current Flow errors by asking the Flow server.\n\nFlow will search upward for a .flowconfig file, beginning at ROOT.\nROOT is assumed to be the current directory if unspecified.\nA server will be started if none is running over ROOT.\n\nStatus command options:"
exe_name;
args =
CommandSpec.ArgSpec.(
empty
|> base_flags
|> connect_and_json_flags
|> json_version_flag
|> offset_style_flag
|> error_flags
|> strip_root_flag
|> from_flag
|> dummy false (* match --version below *)
|> anon "root" (optional string)
);
}
else
let command_info =
CommandList.commands
|> Base.List.map ~f:(fun command -> (CommandSpec.name command, CommandSpec.doc command))
|> List.filter (fun (cmd, doc) -> cmd <> "" && doc <> "")
|> List.sort (fun (a, _) (b, _) -> String.compare a b)
in
let cmd_usage = CommandSpec.format_two_columns ~col_pad:1 command_info in
{
CommandSpec.name = "default";
doc = "";
usage =
Printf.sprintf
"Usage: %s [COMMAND] \n\nValid values for COMMAND:\n%s\n\nDefault values if unspecified:\n\ \ COMMAND\tstatus\n\nStatus command options:"
exe_name
cmd_usage;
args =
CommandSpec.ArgSpec.(
empty
|> base_flags
|> connect_and_json_flags
|> json_version_flag
|> offset_style_flag
|> error_flags
|> strip_root_flag
|> from_flag
|> flag "--version" truthy ~doc:"Print version number and exit"
|> anon "root" (optional string)
);
}
type args = {
root: Path.t;
output_json: bool;
output_json_version: Errors.Json_output.json_version option;
offset_style: CommandUtils.offset_style option;
pretty: bool;
error_flags: Errors.Cli_output.error_flags;
strip_root: bool;
}
let check_status flowconfig_name (args : args) connect_flags =
let include_warnings = args.error_flags.Errors.Cli_output.include_warnings in
let request = ServerProt.Request.STATUS { include_warnings } in
let (response, lazy_stats) =
match connect_and_make_request flowconfig_name connect_flags args.root request with
| ServerProt.Response.STATUS { status_response; lazy_stats } -> (status_response, lazy_stats)
| response -> failwith_bad_response ~request ~response
in
let strip_root =
if args.strip_root then
Some args.root
else
None
in
let offset_kind = CommandUtils.offset_kind_of_offset_style args.offset_style in
let print_json =
Errors.Json_output.print_errors
~out_channel:stdout
~strip_root
~pretty:args.pretty
?version:args.output_json_version
~offset_kind
in
let lazy_msg =
match lazy_stats.ServerProt.Response.lazy_mode with
| false -> None
| true ->
Some
(Printf.sprintf
("The Flow server is currently in lazy mode and is only checking %d/%d files.\n"
^^ "To learn more, visit flow.org/en/docs/lang/lazy-modes"
)
lazy_stats.ServerProt.Response.checked_files
lazy_stats.ServerProt.Response.total_files
)
in
match response with
| ServerProt.Response.ERRORS { errors; warnings; suppressed_errors } ->
let error_flags = args.error_flags in
let from = FlowEventLogger.get_from_I_AM_A_CLOWN () in
begin
if args.output_json then
print_json ~errors ~warnings ~suppressed_errors ()
else if from = Some "vim" || from = Some "emacs" then
Errors.Vim_emacs_output.print_errors ~strip_root stdout ~errors ~warnings ()
else
let errors =
List.fold_left
(fun acc (error, _) -> Errors.ConcreteLocPrintableErrorSet.add error acc)
errors
suppressed_errors
in
Errors.Cli_output.print_errors
~strip_root
~flags:error_flags
~out_channel:stdout
~errors
~warnings
~lazy_msg
()
end;
Exit.exit
(get_check_or_status_exit_code errors warnings error_flags.Errors.Cli_output.max_warnings)
| ServerProt.Response.NO_ERRORS ->
if args.output_json then
print_json
~errors:Errors.ConcreteLocPrintableErrorSet.empty
~warnings:Errors.ConcreteLocPrintableErrorSet.empty
~suppressed_errors:[]
()
else (
Printf.printf "No errors!\n%!";
Base.Option.iter lazy_msg ~f:(Printf.printf "\n%s\n%!")
);
Exit.(exit No_error)
| ServerProt.Response.NOT_COVERED ->
let msg = "Why on earth did the server respond with NOT_COVERED?" in
Exit.(exit ~msg Unknown_error)
let main
base_flags
connect_flags
json
pretty
json_version
offset_style
error_flags
strip_root
version
root
() =
if version then (
print_version ();
Exit.(exit No_error)
);
let flowconfig_name = base_flags.Base_flags.flowconfig_name in
let root = guess_root flowconfig_name root in
let json = json || Base.Option.is_some json_version || pretty in
let args =
{
root;
output_json = json;
output_json_version = json_version;
offset_style;
pretty;
error_flags;
strip_root;
}
in
check_status flowconfig_name args connect_flags
end
module Status (CommandList : COMMAND_LIST) = struct
module Main =
Impl
(CommandList)
(struct
let explicit = true
end)
let command = CommandSpec.command Main.spec Main.main
end
module Default (CommandList : COMMAND_LIST) = struct
module Main =
Impl
(CommandList)
(struct
let explicit = false
end)
let command = CommandSpec.command Main.spec Main.main
end
| null | https://raw.githubusercontent.com/facebook/flow/b918b06104ac1489b516988707431d98833ce99f/src/commands/statusCommands.ml | ocaml | *********************************************************************
flow status (report current error set) command impl
*********************************************************************
explicit == called with "flow status ..."
rather than simply "flow ..."
match --version below |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open CommandInfo
open CommandUtils
module type CONFIG = sig
val explicit : bool
end
module Impl (CommandList : COMMAND_LIST) (Config : CONFIG) = struct
let spec =
if Config.explicit then
{
CommandSpec.name = "status";
doc = "(default) Shows current Flow errors by asking the Flow server";
usage =
Printf.sprintf
"Usage: %s status [OPTION]... [ROOT]\nShows current Flow errors by asking the Flow server.\n\nFlow will search upward for a .flowconfig file, beginning at ROOT.\nROOT is assumed to be the current directory if unspecified.\nA server will be started if none is running over ROOT.\n\nStatus command options:"
exe_name;
args =
CommandSpec.ArgSpec.(
empty
|> base_flags
|> connect_and_json_flags
|> json_version_flag
|> offset_style_flag
|> error_flags
|> strip_root_flag
|> from_flag
|> anon "root" (optional string)
);
}
else
let command_info =
CommandList.commands
|> Base.List.map ~f:(fun command -> (CommandSpec.name command, CommandSpec.doc command))
|> List.filter (fun (cmd, doc) -> cmd <> "" && doc <> "")
|> List.sort (fun (a, _) (b, _) -> String.compare a b)
in
let cmd_usage = CommandSpec.format_two_columns ~col_pad:1 command_info in
{
CommandSpec.name = "default";
doc = "";
usage =
Printf.sprintf
"Usage: %s [COMMAND] \n\nValid values for COMMAND:\n%s\n\nDefault values if unspecified:\n\ \ COMMAND\tstatus\n\nStatus command options:"
exe_name
cmd_usage;
args =
CommandSpec.ArgSpec.(
empty
|> base_flags
|> connect_and_json_flags
|> json_version_flag
|> offset_style_flag
|> error_flags
|> strip_root_flag
|> from_flag
|> flag "--version" truthy ~doc:"Print version number and exit"
|> anon "root" (optional string)
);
}
type args = {
root: Path.t;
output_json: bool;
output_json_version: Errors.Json_output.json_version option;
offset_style: CommandUtils.offset_style option;
pretty: bool;
error_flags: Errors.Cli_output.error_flags;
strip_root: bool;
}
let check_status flowconfig_name (args : args) connect_flags =
let include_warnings = args.error_flags.Errors.Cli_output.include_warnings in
let request = ServerProt.Request.STATUS { include_warnings } in
let (response, lazy_stats) =
match connect_and_make_request flowconfig_name connect_flags args.root request with
| ServerProt.Response.STATUS { status_response; lazy_stats } -> (status_response, lazy_stats)
| response -> failwith_bad_response ~request ~response
in
let strip_root =
if args.strip_root then
Some args.root
else
None
in
let offset_kind = CommandUtils.offset_kind_of_offset_style args.offset_style in
let print_json =
Errors.Json_output.print_errors
~out_channel:stdout
~strip_root
~pretty:args.pretty
?version:args.output_json_version
~offset_kind
in
let lazy_msg =
match lazy_stats.ServerProt.Response.lazy_mode with
| false -> None
| true ->
Some
(Printf.sprintf
("The Flow server is currently in lazy mode and is only checking %d/%d files.\n"
^^ "To learn more, visit flow.org/en/docs/lang/lazy-modes"
)
lazy_stats.ServerProt.Response.checked_files
lazy_stats.ServerProt.Response.total_files
)
in
match response with
| ServerProt.Response.ERRORS { errors; warnings; suppressed_errors } ->
let error_flags = args.error_flags in
let from = FlowEventLogger.get_from_I_AM_A_CLOWN () in
begin
if args.output_json then
print_json ~errors ~warnings ~suppressed_errors ()
else if from = Some "vim" || from = Some "emacs" then
Errors.Vim_emacs_output.print_errors ~strip_root stdout ~errors ~warnings ()
else
let errors =
List.fold_left
(fun acc (error, _) -> Errors.ConcreteLocPrintableErrorSet.add error acc)
errors
suppressed_errors
in
Errors.Cli_output.print_errors
~strip_root
~flags:error_flags
~out_channel:stdout
~errors
~warnings
~lazy_msg
()
end;
Exit.exit
(get_check_or_status_exit_code errors warnings error_flags.Errors.Cli_output.max_warnings)
| ServerProt.Response.NO_ERRORS ->
if args.output_json then
print_json
~errors:Errors.ConcreteLocPrintableErrorSet.empty
~warnings:Errors.ConcreteLocPrintableErrorSet.empty
~suppressed_errors:[]
()
else (
Printf.printf "No errors!\n%!";
Base.Option.iter lazy_msg ~f:(Printf.printf "\n%s\n%!")
);
Exit.(exit No_error)
| ServerProt.Response.NOT_COVERED ->
let msg = "Why on earth did the server respond with NOT_COVERED?" in
Exit.(exit ~msg Unknown_error)
let main
base_flags
connect_flags
json
pretty
json_version
offset_style
error_flags
strip_root
version
root
() =
if version then (
print_version ();
Exit.(exit No_error)
);
let flowconfig_name = base_flags.Base_flags.flowconfig_name in
let root = guess_root flowconfig_name root in
let json = json || Base.Option.is_some json_version || pretty in
let args =
{
root;
output_json = json;
output_json_version = json_version;
offset_style;
pretty;
error_flags;
strip_root;
}
in
check_status flowconfig_name args connect_flags
end
module Status (CommandList : COMMAND_LIST) = struct
module Main =
Impl
(CommandList)
(struct
let explicit = true
end)
let command = CommandSpec.command Main.spec Main.main
end
module Default (CommandList : COMMAND_LIST) = struct
module Main =
Impl
(CommandList)
(struct
let explicit = false
end)
let command = CommandSpec.command Main.spec Main.main
end
|
45d4267ec0202fa8dc0b68538ba97108548e410fc74f5d6bef1f4704ce87cb24 | laser/cis-194-winter-2016 | Types.hs | # LANGUAGE GeneralizedNewtypeDeriving #
module Homework.Week11.Types where
import Data.Int (Int64)
import Data.Text (Text)
import Database.SQLite.Simple (FromRow (..), field)
import Database.SQLite.Simple.FromField (FromField)
import Database.SQLite.Simple.ToField (ToField)
newtype UserId = UserId Int64 deriving (Eq, Show, ToField, FromField)
newtype FullName = FullName Text deriving (Eq, Show, ToField, FromField)
newtype EmailAddress = EmailAddress Text deriving (Eq, Show, ToField, FromField)
data User = User { userId :: UserId
, userFullName :: FullName
, userEmailAddress :: EmailAddress } deriving (Eq, Show)
instance FromRow User where
fromRow = User <$> field
<*> field
<*> field
| null | https://raw.githubusercontent.com/laser/cis-194-winter-2016/6a9b7c958c896cd9f31a5d1dffb3f03145efb597/src/Homework/Week11/Types.hs | haskell | # LANGUAGE GeneralizedNewtypeDeriving #
module Homework.Week11.Types where
import Data.Int (Int64)
import Data.Text (Text)
import Database.SQLite.Simple (FromRow (..), field)
import Database.SQLite.Simple.FromField (FromField)
import Database.SQLite.Simple.ToField (ToField)
newtype UserId = UserId Int64 deriving (Eq, Show, ToField, FromField)
newtype FullName = FullName Text deriving (Eq, Show, ToField, FromField)
newtype EmailAddress = EmailAddress Text deriving (Eq, Show, ToField, FromField)
data User = User { userId :: UserId
, userFullName :: FullName
, userEmailAddress :: EmailAddress } deriving (Eq, Show)
instance FromRow User where
fromRow = User <$> field
<*> field
<*> field
| |
53fe6ae5bd1387a5d26eaa2d35e0a8c519c3164c1d7b9472999c40d956fd361e | ocaml/ocaml | events.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
OCaml port by and
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(********************************* Events ******************************)
open Instruct
type code_event =
{ ev_frag : int;
ev_ev : Instruct.debug_event }
let get_pos ev =
match ev.ev_kind with
| Event_before -> ev.ev_loc.Location.loc_start
| Event_after _ -> ev.ev_loc.Location.loc_end
| _ -> ev.ev_loc.Location.loc_start
(*** Current events. ***)
(* Event at current position *)
let current_event =
ref (None : code_event option)
(* Current position in source. *)
(* Raise `Not_found' if not on an event (beginning or end of program). *)
let get_current_event () =
match !current_event with
| None -> raise Not_found
| Some ev -> ev
let current_event_is_before () =
match !current_event with
None ->
raise Not_found
| Some {ev_ev = {ev_kind = Event_before}} ->
true
| _ ->
false
| null | https://raw.githubusercontent.com/ocaml/ocaml/04ddddd0e1d2bf2acb5091f434b93387243d4624/debugger/events.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.
************************************************************************
******************************** Events *****************************
** Current events. **
Event at current position
Current position in source.
Raise `Not_found' if not on an event (beginning or end of program). | , projet Cristal , INRIA Rocquencourt
OCaml port by and
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Instruct
type code_event =
{ ev_frag : int;
ev_ev : Instruct.debug_event }
let get_pos ev =
match ev.ev_kind with
| Event_before -> ev.ev_loc.Location.loc_start
| Event_after _ -> ev.ev_loc.Location.loc_end
| _ -> ev.ev_loc.Location.loc_start
let current_event =
ref (None : code_event option)
let get_current_event () =
match !current_event with
| None -> raise Not_found
| Some ev -> ev
let current_event_is_before () =
match !current_event with
None ->
raise Not_found
| Some {ev_ev = {ev_kind = Event_before}} ->
true
| _ ->
false
|
440a6d176f632a1a3065b122dd9f879398ab1fc107074ddda4ba15325c6bbe27 | lispgames/perfectstorm | toolbox.lisp | (in-package :toolbox)
;;
;; a mapcar that wraps
;;
(defun mapwrap (fn list &rest lists)
(let* ((input-lists (cons list lists))
(length (apply #'max (mapcar #'length input-lists)))
(lists (make-list length :initial-element ())))
(loop for i from 0 to (- length 1)
do (format t "~a~%" i)
do (setf lists
(mapcar (lambda (list input-list)
(or (cdr list)
(copy-list input-list)))
lists
input-lists))
collect (apply fn (mapcar #'first lists)))))
;;
;; cycle something by a given offset
;;
(defgeneric cycle (thing &optional i j))
(defgeneric cycle! (thing &optional i j))
(defmethod cycle ((list cons) &optional (i 1) (j 0))
(declare (ignore j))
(let ((i (mod i (length list))))
(append (subseq list i) (subseq list 0 i))))
named -inner because interfaces might want to have the atan2 name
"somewhat awful but stolen, tested and working atan2"
(if (= y 0.0)
(if (< x 0.0)
(+ PI (/ PI 2.0))
(/ PI 2.0))
(if (= x 0.0)
(if (> y 0.0)
0.0
PI)
(let ((at (atan (/ x y))))
(if (> x 0.0)
(if (> y 0.0)
at
(+ PI at))
(if (> y 0.0)
(+ PI PI at)
(+ PI at)))))))
;;
two useful macro - writing macros from pcl :
;;
(defmacro with-gensyms ((&rest names) &body body)
`(let ,(loop for n in names collect `(,n (gensym)))
,@body))
stolen from pcl
(let ((gensyms (loop for n in names collect (gensym))))
`(let (,@(loop for g in gensyms collect `(,g (gensym))))
`(let (,,@(loop for g in gensyms for n in names collect ``(,,g ,,n)))
,(let (,@(loop for n in names for g in gensyms collect `(,n ,g)))
,@body)))))
(defun choose (list)
(when list
(nth (random (length list)) list)))
(defun elt-mod (sequence index)
(elt sequence (mod index (length sequence))))
(defun sqr (number)
(* number number))
( defun crop ( number max & optional ( min ( - max ) ) )
( max ( min number ) min ) )
(defmacro setf-crop (place max &optional (min `(- ,max)))
`(setf ,place (crop ,place ,max ,min)))
(defmacro print-vars (&rest rest)
`(format t ,(format nil "~{~a:~~a~^, ~}~~%" rest) ,@rest)) ;self-explanatory :)
| null | https://raw.githubusercontent.com/lispgames/perfectstorm/a21e0420deb3ec83e9d776241ab37e78c5f29b94/toolbox/toolbox.lisp | lisp |
a mapcar that wraps
cycle something by a given offset
self-explanatory :) | (in-package :toolbox)
(defun mapwrap (fn list &rest lists)
(let* ((input-lists (cons list lists))
(length (apply #'max (mapcar #'length input-lists)))
(lists (make-list length :initial-element ())))
(loop for i from 0 to (- length 1)
do (format t "~a~%" i)
do (setf lists
(mapcar (lambda (list input-list)
(or (cdr list)
(copy-list input-list)))
lists
input-lists))
collect (apply fn (mapcar #'first lists)))))
(defgeneric cycle (thing &optional i j))
(defgeneric cycle! (thing &optional i j))
(defmethod cycle ((list cons) &optional (i 1) (j 0))
(declare (ignore j))
(let ((i (mod i (length list))))
(append (subseq list i) (subseq list 0 i))))
named -inner because interfaces might want to have the atan2 name
"somewhat awful but stolen, tested and working atan2"
(if (= y 0.0)
(if (< x 0.0)
(+ PI (/ PI 2.0))
(/ PI 2.0))
(if (= x 0.0)
(if (> y 0.0)
0.0
PI)
(let ((at (atan (/ x y))))
(if (> x 0.0)
(if (> y 0.0)
at
(+ PI at))
(if (> y 0.0)
(+ PI PI at)
(+ PI at)))))))
two useful macro - writing macros from pcl :
(defmacro with-gensyms ((&rest names) &body body)
`(let ,(loop for n in names collect `(,n (gensym)))
,@body))
stolen from pcl
(let ((gensyms (loop for n in names collect (gensym))))
`(let (,@(loop for g in gensyms collect `(,g (gensym))))
`(let (,,@(loop for g in gensyms for n in names collect ``(,,g ,,n)))
,(let (,@(loop for n in names for g in gensyms collect `(,n ,g)))
,@body)))))
(defun choose (list)
(when list
(nth (random (length list)) list)))
(defun elt-mod (sequence index)
(elt sequence (mod index (length sequence))))
(defun sqr (number)
(* number number))
( defun crop ( number max & optional ( min ( - max ) ) )
( max ( min number ) min ) )
(defmacro setf-crop (place max &optional (min `(- ,max)))
`(setf ,place (crop ,place ,max ,min)))
(defmacro print-vars (&rest rest)
|
13fb7e9ff475eb3d8810379d500a59d1d74fdb66decc09ece414e12334cc3524 | coccinelle/coccinelle | context_neg.ml |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
(* Detects subtrees that are all minus/plus and nodes that are "binding
context nodes". The latter is a node whose structure and immediate tokens
are the same in the minus and plus trees, and such that for every child,
the set of context nodes in the child subtree is the same in the minus and
plus subtrees. *)
module Ast = Ast_cocci
module Ast0 = Ast0_cocci
module V0 = Visitor_ast0
module VT0 = Visitor_ast0_types
module U = Unparse_ast0
(* --------------------------------------------------------------------- *)
Generic access to code
let set_mcodekind x mcodekind =
match x with
Ast0.DotsExprTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsInitTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsParamTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsStmtTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsDeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsFieldTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsEnumDeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsCaseTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsDefParamTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.IdentTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ExprTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.AssignOpTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.BinaryOpTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ArgExprTag(d) | Ast0.TestExprTag(d) ->
failwith "not possible - iso only"
| Ast0.TypeCTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ParamTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.FieldTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.EnumDeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.InitTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.StmtTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ForInfoTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.CaseLineTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.StringFragmentTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.AttributeTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.AttrArgTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.TopTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.IsoWhenTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenTTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenFTag(_) -> failwith "only within iso phase"
| Ast0.MetaPosTag(p) -> failwith "invisible at this stage"
| Ast0.HiddenVarTag(p) -> failwith "hiddenvar only within iso phase"
| Ast0.WhenTag _ -> failwith "whentag only within iso phase"
let set_index x index =
match x with
Ast0.DotsExprTag(d) -> Ast0.set_index d index
| Ast0.DotsInitTag(d) -> Ast0.set_index d index
| Ast0.DotsParamTag(d) -> Ast0.set_index d index
| Ast0.DotsStmtTag(d) -> Ast0.set_index d index
| Ast0.DotsDeclTag(d) -> Ast0.set_index d index
| Ast0.DotsFieldTag(d) -> Ast0.set_index d index
| Ast0.DotsEnumDeclTag(d) -> Ast0.set_index d index
| Ast0.DotsCaseTag(d) -> Ast0.set_index d index
| Ast0.DotsDefParamTag(d) -> Ast0.set_index d index
| Ast0.IdentTag(d) -> Ast0.set_index d index
| Ast0.ExprTag(d) -> Ast0.set_index d index
| Ast0.AssignOpTag(d) -> Ast0.set_index d index
| Ast0.BinaryOpTag(d) -> Ast0.set_index d index
| Ast0.ArgExprTag(d) | Ast0.TestExprTag(d) ->
failwith "not possible - iso only"
| Ast0.TypeCTag(d) -> Ast0.set_index d index
| Ast0.ParamTag(d) -> Ast0.set_index d index
| Ast0.InitTag(d) -> Ast0.set_index d index
| Ast0.DeclTag(d) -> Ast0.set_index d index
| Ast0.FieldTag(d) -> Ast0.set_index d index
| Ast0.EnumDeclTag(d) -> Ast0.set_index d index
| Ast0.StmtTag(d) -> Ast0.set_index d index
| Ast0.ForInfoTag(d) -> Ast0.set_index d index
| Ast0.CaseLineTag(d) -> Ast0.set_index d index
| Ast0.StringFragmentTag(d) -> Ast0.set_index d index
| Ast0.AttributeTag(d) -> Ast0.set_index d index
| Ast0.AttrArgTag(d) -> Ast0.set_index d index
| Ast0.TopTag(d) -> Ast0.set_index d index
| Ast0.IsoWhenTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenTTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenFTag(_) -> failwith "only within iso phase"
| Ast0.MetaPosTag(p) -> failwith "invisible at this stage"
| Ast0.HiddenVarTag(p) -> failwith "hiddenvar only within iso phase"
| Ast0.WhenTag _ -> failwith "whentag only within iso phase"
let get_index = function
Ast0.DotsExprTag(d) -> Index.expression_dots d
| Ast0.DotsInitTag(d) -> Index.initialiser_dots d
| Ast0.DotsParamTag(d) -> Index.parameter_dots d
| Ast0.DotsStmtTag(d) -> Index.statement_dots d
| Ast0.DotsDeclTag(d) -> Index.declaration_dots d
| Ast0.DotsFieldTag(d) -> Index.field_dots d
| Ast0.DotsEnumDeclTag(d) -> Index.enum_decl_dots d
| Ast0.DotsCaseTag(d) -> Index.case_line_dots d
| Ast0.DotsDefParamTag(d) -> Index.define_param_dots d
| Ast0.IdentTag(d) -> Index.ident d
| Ast0.ExprTag(d) -> Index.expression d
| Ast0.AssignOpTag(d) -> Index.assignOp d
| Ast0.BinaryOpTag(d) -> Index.binaryOp d
| Ast0.ArgExprTag(d) | Ast0.TestExprTag(d) ->
failwith "not possible - iso only"
| Ast0.TypeCTag(d) -> Index.typeC d
| Ast0.ParamTag(d) -> Index.parameterTypeDef d
| Ast0.InitTag(d) -> Index.initialiser d
| Ast0.DeclTag(d) -> Index.declaration d
| Ast0.FieldTag(d) -> Index.field d
| Ast0.EnumDeclTag(d) -> Index.enum_decl d
| Ast0.StmtTag(d) -> Index.statement d
| Ast0.ForInfoTag(d) -> Index.forinfo d
| Ast0.CaseLineTag(d) -> Index.case_line d
| Ast0.StringFragmentTag(d) -> Index.string_fragment d
| Ast0.AttributeTag(d) -> Index.attribute d
| Ast0.AttrArgTag(d) -> Index.attr_arg d
| Ast0.TopTag(d) -> Index.top_level d
| Ast0.IsoWhenTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenTTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenFTag(_) -> failwith "only within iso phase"
| Ast0.MetaPosTag(p) -> failwith "invisible at this stage"
| Ast0.HiddenVarTag(p) -> failwith "hiddenvar only within iso phase"
| Ast0.WhenTag _ -> failwith "whentag only within iso phase"
(* --------------------------------------------------------------------- *)
(* Collect the line numbers of the plus code. This is used for disjunctions.
It is not completely clear why this is necessary, but it seems like an easy
fix for whatever is the problem that is discussed in disj_cases *)
let plus_lines = ref ([] : int list)
let insert n =
let rec loop = function
[] -> [n]
| x::xs ->
match compare n x with
1 -> x::(loop xs)
| 0 -> x::xs
| -1 -> n::x::xs
| _ -> failwith "not possible" in
plus_lines := loop !plus_lines
let find n min max =
let rec loop = function
[] -> (min,max)
| [x] -> if n < x then (min,x) else (x,max)
| x1::x2::rest ->
if n < x1
then (min,x1)
else if n > x1 && n < x2 then (x1,x2) else loop (x2::rest) in
loop !plus_lines
let collect_plus_lines top =
plus_lines := [];
let bind x y = () in
let option_default = () in
let donothing r k e = k e in
let mcode (_,_,info,mcodekind,_,_) =
match mcodekind with
Ast0.PLUS _ -> insert info.Ast0.pos_info.Ast0.line_start
| _ -> () in
let statement r k s =
let mcode info bef = mcode ((),(),info,bef,(),-1) in
match Ast0.unwrap s with
(* cases for everything with extra mcode *)
| Ast0.Decl((info,bef),_) ->
bind (mcode info bef) (k s)
| Ast0.FunDecl((info,bef),_,_,_,_,_,_,_,_,_,_,(ainfo,aft)) ->
bind (mcode info bef) (bind (k s) (mcode ainfo aft))
| Ast0.IfThen(_,_,_,_,_,(info,aft,adj))
| Ast0.IfThenElse(_,_,_,_,_,_,_,(info,aft,adj))
| Ast0.Iterator(_,_,_,_,_,(info,aft,adj))
| Ast0.While(_,_,_,_,_,(info,aft,adj))
| Ast0.For(_,_,_,_,_,(info,aft,adj)) ->
bind (k s) (mcode info aft)
| _ -> k s in
let fn =
V0.flat_combiner bind option_default
mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode
mcode mcode
donothing donothing donothing donothing donothing donothing donothing
donothing donothing
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing statement donothing donothing donothing
donothing donothing donothing in
fn.VT0.combiner_rec_top_level top
(* --------------------------------------------------------------------- *)
type kind =
Neutral | AllMarked of Ast.count | NotAllMarked (* marked means + or - *)
(* --------------------------------------------------------------------- *)
The first part analyzes each of the minus tree and the plus tree
separately
separately *)
(* ints are unique token indices (offset field) *)
type node =
Token (* tokens *) of kind * int (* unique index *) * Ast0.mcodekind *
int list (* context tokens *)
| Recursor (* children *) of kind *
int list (* indices of all tokens at the level below *) *
Ast0.mcodekind list (* tokens at the level below *) *
int list
| Bind (* neighbors *) of kind *
int list (* indices of all tokens at current level *) *
Ast0.mcodekind list (* tokens at current level *) *
int list (* indices of all tokens at the level below *) *
Ast0.mcodekind list (* tokens at the level below *)
* int list list
let kind2c = function
Neutral -> "neutral"
| AllMarked _ -> "allmarked"
| NotAllMarked -> "notallmarked"
let node2c = function
Token(k,_,_,_) -> Printf.sprintf "token %s\n" (kind2c k)
| Recursor(k,_,_,_) -> Printf.sprintf "recursor %s\n" (kind2c k)
| Bind(k,_,_,_,_,_) -> Printf.sprintf "bind %s\n" (kind2c k)
(* goal: detect negative in both tokens and recursors, or context only in
tokens *)
let bind c1 c2 =
let lub = function
(k1,k2) when k1 = k2 -> k1
| (Neutral,AllMarked c) -> AllMarked c
| (AllMarked c,Neutral) -> AllMarked c
| _ -> NotAllMarked in
match (c1,c2) with
(* token/token *)
(* there are tokens at this level, so ignore the level below *)
(Token(k1,i1,t1,l1),Token(k2,i2,t2,l2)) ->
Bind(lub(k1,k2),[i1;i2],[t1;t2],[],[],[l1;l2])
(* token/recursor *)
(* there are tokens at this level, so ignore the level below *)
| (Token(k1,i1,t1,l1),Recursor(k2,_,_,l2)) ->
Bind(lub(k1,k2),[i1],[t1],[],[],[l1;l2])
| (Recursor(k1,_,_,l1),Token(k2,i2,t2,l2)) ->
Bind(lub(k1,k2),[i2],[t2],[],[],[l1;l2])
(* token/bind *)
(* there are tokens at this level, so ignore the level below *)
| (Token(k1,i1,t1,l1),Bind(k2,i2,t2,_,_,l2)) ->
Bind(lub(k1,k2),i1::i2,t1::t2,[],[],l1::l2)
| (Bind(k1,i1,t1,_,_,l1),Token(k2,i2,t2,l2)) ->
Bind(lub(k1,k2),i1@[i2],t1@[t2],[],[],l1@[l2])
(* recursor/bind *)
| (Recursor(k1,bi1,bt1,l1),Bind(k2,i2,t2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),i2,t2,bi1@bi2,bt1@bt2,l1::l2)
| (Bind(k1,i1,t1,bi1,bt1,l1),Recursor(k2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),i1,t1,bi1@bi2,bt1@bt2,l1@[l2])
(* recursor/recursor and bind/bind - not likely to ever occur *)
| (Recursor(k1,bi1,bt1,l1),Recursor(k2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),[],[],bi1@bi2,bt1@bt2,[l1;l2])
| (Bind(k1,i1,t1,bi1,bt1,l1),Bind(k2,i2,t2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),i1@i2,t1@t2,bi1@bi2,bt1@bt2,l1@l2)
let option_default = (*Bind(Neutral,[],[],[],[],[])*)
Recursor(Neutral,[],[],[])
let contains_added_strings info =
let unsafe l =
List.exists
(fun (str,_) ->
match str with
(Ast.Noindent s | Ast.Indent s) -> not (Stdcompat.String.trim s = "")
| Ast.Space _ -> true (* adds a thing with space around it *))
l in
If this is true , eg if ( x ) return 0 ; will be broken up into
two rule elems . Not sure why that is needed , but surely it is not needed
when it is just whitespace that is added .
two rule elems. Not sure why that is needed, but surely it is not needed
when it is just whitespace that is added. *)
unsafe info.Ast0.strings_before || unsafe info.Ast0.strings_after
let mcode (_,_,info,mcodekind,pos,_) =
let offset = info.Ast0.pos_info.Ast0.offset in
match mcodekind with
Ast0.MINUS(_) -> Token(AllMarked Ast.ONE,offset,mcodekind,[])
| Ast0.PLUS c -> Token(AllMarked c,offset,mcodekind,[])
| Ast0.CONTEXT(_) -> Token(NotAllMarked,offset,mcodekind,[offset])
| _ -> failwith "not possible"
let neutral_mcode (_,_,info,mcodekind,pos,_) =
let offset = info.Ast0.pos_info.Ast0.offset in
match mcodekind with
Ast0.MINUS(_) -> Token(Neutral,offset,mcodekind,[])
| Ast0.PLUS _ -> Token(Neutral,offset,mcodekind,[])
| Ast0.CONTEXT(_) -> Token(Neutral,offset,mcodekind,[offset])
| _ -> failwith "not possible"
neutral for context ; used for mcode in bef aft nodes that do n't represent
anything if they do n't contain some information
anything if they don't contain some information *)
let nc_mcode (_,_,info,mcodekind,pos,_) =
(* distinguish from the offset of some real token *)
let offset = (-1) * info.Ast0.pos_info.Ast0.offset in
match mcodekind with
Ast0.MINUS(_) -> Token(AllMarked Ast.ONE,offset,mcodekind,[])
| Ast0.PLUS c -> Token(AllMarked c,offset,mcodekind,[])
| Ast0.CONTEXT(_) ->
(* Unlike the other mcode cases, we drop the offset from the context
offsets. This is because we don't know whether the term this is
associated with is - or context. In any case, the context offsets are
used for identification, and this invisible node should not be needed
for this purpose. *)
if contains_added_strings info
then
(* can we have ++ for strings? *)
Token(NotAllMarked,offset,mcodekind,[])
else Token(Neutral,offset,mcodekind,[])
| _ -> failwith "not possible"
let is_context = function Ast0.CONTEXT(_) -> true | _ -> false
let union_all l = List.fold_left Common.union_set [] l
(* is minus is true when we are processing minus code that might be
intermingled with plus code. it is used in disj_cases *)
let classify is_minus all_marked table code =
let mkres builder k il tl bil btl l e =
(match k with
AllMarked count ->
Ast0.set_mcodekind e (all_marked count) (* definitive *)
| _ ->
let check_index il tl =
if List.for_all is_context tl
then
(let e1 = builder e in
let index = (get_index e1)@il in
try
let _ = Hashtbl.find table index in
failwith
(Printf.sprintf "line %d: index %s already used\n"
(Ast0.get_info e).Ast0.pos_info.Ast0.line_start
(String.concat " " (List.map string_of_int index)))
with Not_found -> Hashtbl.add table index (e1,l)) in
if il = [] then check_index bil btl else check_index il tl);
if il = []
then Recursor(k, bil, btl, union_all l)
else Recursor(k, il, tl, union_all l) in
let compute_result builder e = function
Bind(k,il,tl,bil,btl,l) -> mkres builder k il tl bil btl l e
| Token(k,il,tl,l) -> mkres builder k [il] [tl] [] [] [l] e
| Recursor(k,bil,btl,l) -> mkres builder k [] [] bil btl [l] e in
let make_not_marked = function
Bind(k,il,tl,bil,btl,l) -> Bind(NotAllMarked,il,tl,bil,btl,l)
| Token(k,il,tl,l) -> Token(NotAllMarked,il,tl,l)
| Recursor(k,bil,btl,l) -> Recursor(NotAllMarked,bil,btl,l) in
let do_nothing builder r k e = compute_result builder e (k e) in
let disj_cases disj starter code fn ender =
neutral_mcode used so starter and ender do n't have an affect on
whether the code is considered all plus / minus , but so that they are
consider in the index list , which is needed to make a disj with
something in one branch and nothing in the other different from code
that just has the something ( starter / ender enough , mids not needed
for this ) . Can not agglomerate + code over | boundaries , because two -
cases might have different + code , and do n't want to put the + code
together into one unit .
whether the code is considered all plus/minus, but so that they are
consider in the index list, which is needed to make a disj with
something in one branch and nothing in the other different from code
that just has the something (starter/ender enough, mids not needed
for this). Cannot agglomerate + code over | boundaries, because two -
cases might have different + code, and don't want to put the + code
together into one unit. *)
let make_not_marked =
if is_minus
then
(let min = Ast0.get_line disj in
let max = Ast0.get_line_end disj in
let (plus_min,plus_max) = find min (min-1) (max+1) in
if max > plus_max then make_not_marked else (function x -> x))
else make_not_marked in
bind (neutral_mcode starter)
(bind (List.fold_right bind
(List.map make_not_marked (List.map fn code))
option_default)
(neutral_mcode ender)) in
(* no whencode in plus tree so have to drop it *)
need special cases for dots , nests , and disjs
let ident r k e =
compute_result Ast0.ident e
(match Ast0.unwrap e with
Ast0.DisjId(starter,id_list,_,ender)
| Ast0.ConjId(starter,id_list,_,ender) ->
disj_cases e starter id_list r.VT0.combiner_rec_ident ender
| _ -> k e) in
let expression r k e =
compute_result Ast0.expr e
(match Ast0.unwrap e with
Ast0.NestExpr(starter,exp,ender,whencode,multi) ->
k (Ast0.rewrap e (Ast0.NestExpr(starter,exp,ender,None,multi)))
| Ast0.Edots(dots,whencode) ->
k (Ast0.rewrap e (Ast0.Edots(dots,None)))
| Ast0.DisjExpr(starter,expr_list,_,ender)
| Ast0.ConjExpr(starter,expr_list,_,ender) ->
disj_cases e starter expr_list r.VT0.combiner_rec_expression ender
| _ -> k e) in
(* not clear why we have the next cases, since DisjDecl and
as it only comes from isos *)
(* actually, DisjDecl now allowed in source struct decls *)
let declaration r k e =
compute_result Ast0.decl e
(match Ast0.unwrap e with
Ast0.DisjDecl(starter,decls,_,ender)
| Ast0.ConjDecl(starter,decls,_,ender) ->
disj_cases e starter decls r.VT0.combiner_rec_declaration ender
(* Need special cases for the following so that the type will be
considered as a unit, rather than distributed around the
declared variable. This needs to be done because of the call to
compute_result, ie the processing of each term should make a
side-effect on the complete term structure as well as collecting
some information about it. So we have to visit each complete
term structure. In (all?) other such cases, we visit the terms
using rebuilder, which just visits the subterms, rather than
reordering their components. *)
| Ast0.Init(stg,ty,midattr,id,endattr,eq,ini,sem) ->
bind (match stg with Some stg -> mcode stg | _ -> option_default)
(bind (r.VT0.combiner_rec_typeC ty)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute midattr)
option_default)
(bind (r.VT0.combiner_rec_ident id)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute endattr)
option_default)
(bind (mcode eq)
(bind (r.VT0.combiner_rec_initialiser ini)
(mcode sem)))))))
| Ast0.UnInit(stg,ty,midattr,id,endattr,sem) ->
bind (match stg with Some stg -> mcode stg | _ -> option_default)
(bind (r.VT0.combiner_rec_typeC ty)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute midattr)
option_default)
(bind (r.VT0.combiner_rec_ident id)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute endattr)
option_default)
(mcode sem)))))
| _ -> k e) in
let field r k e =
compute_result Ast0.field e
(match Ast0.unwrap e with
Ast0.DisjField(starter,decls,_,ender)
| Ast0.ConjField(starter,decls,_,ender) ->
disj_cases e starter decls r.VT0.combiner_rec_field ender
| Ast0.Fdots(dots,whencode) ->
k (Ast0.rewrap e (Ast0.Fdots(dots,None)))
| Ast0.Field(ty,id,bf,sem) ->
let bitfield (_c, e) = r.VT0.combiner_rec_expression e in
bind (r.VT0.combiner_rec_typeC ty)
(bind (Common.default option_default r.VT0.combiner_rec_ident id)
(bind (Common.default option_default bitfield bf) (mcode sem)))
| _ -> k e) in
let enum_decl r k e =
compute_result Ast0.enum_decl e
(match Ast0.unwrap e with
Ast0.Enum(name,Some(eq,eval)) ->
bind (r.VT0.combiner_rec_ident name)
(bind (mcode eq) (r.VT0.combiner_rec_expression eval))
| Ast0.EnumDots(dots,whencode) ->
k (Ast0.rewrap e (Ast0.EnumDots(dots,None)))
| _ -> k e) in
let param r k e =
compute_result Ast0.param e
(match Ast0.unwrap e with
Ast0.Param(ty,midattr,Some id,attr) ->
needed for the same reason as in the Init and UnInit cases
bind (r.VT0.combiner_rec_typeC ty)
(bind (List.fold_right bind
(List.map r.VT0.combiner_rec_attribute midattr)
option_default)
(bind (r.VT0.combiner_rec_ident id)
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute attr)
option_default)))
| _ -> k e) in
let typeC r k e =
compute_result Ast0.typeC e
(match Ast0.unwrap e with
Ast0.DisjType(starter,types,_,ender)
| Ast0.ConjType(starter,types,_,ender) ->
disj_cases e starter types r.VT0.combiner_rec_typeC ender
| _ -> k e) in
let initialiser r k i =
compute_result Ast0.ini i
(match Ast0.unwrap i with
Ast0.Idots(dots,whencode) ->
k (Ast0.rewrap i (Ast0.Idots(dots,None)))
| _ -> k i) in
let case_line r k e =
compute_result Ast0.case_line e
(match Ast0.unwrap e with
Ast0.DisjCase(starter,case_list,_,ender) ->
disj_cases e starter case_list r.VT0.combiner_rec_case_line ender
| _ -> k e) in
let statement r k s =
compute_result Ast0.stmt s
(match Ast0.unwrap s with
Ast0.Nest(started,stm_dots,ender,whencode,multi) ->
k (Ast0.rewrap s (Ast0.Nest(started,stm_dots,ender,[],multi)))
| Ast0.Dots(dots,whencode) ->
k (Ast0.rewrap s (Ast0.Dots(dots,[])))
| Ast0.Disj(starter,statement_dots_list,_,ender)
| Ast0.Conj(starter,statement_dots_list,_,ender) ->
disj_cases s starter statement_dots_list
r.VT0.combiner_rec_statement_dots
ender
(* cases for everything with extra mcode *)
| Ast0.Decl((info,bef),_) ->
bind (nc_mcode ((),(),info,bef,(),-1)) (k s)
| Ast0.FunDecl((info,bef),_,_,_,_,_,_,_,_,_,_,(ainfo,aft)) ->
(* not sure that the use of start is relevant here *)
let a1 = nc_mcode ((),(),info,bef,(),-1) in
let a2 = nc_mcode ((),(),ainfo,aft,(),-1) in
let b = k s in
bind a1 (bind b a2)
(* For these, the info of the aft mcode is derived from the else
branch. These might not correspond for a context if, eg if
only the else branch is replaced. Thus we take instead the
info of the starting keyword. In a context case, these will be
the same on the - and + sides. All that is used as an offset,
and it is only used as a key, so this is safe to do. For an
iterator, we take the left parenthesis, which should have the
same property. *)
| Ast0.IfThen(start,_,_,_,_,(info,aft,adj))
| Ast0.IfThenElse(start,_,_,_,_,_,_,(info,aft,adj))
| Ast0.Iterator(_,start,_,_,_,(info,aft,adj))
| Ast0.While(start,_,_,_,_,(info,aft,adj))
| Ast0.For(start,_,_,_,_,(info,aft,adj)) ->
let mcode_info (_,_,info,_,_,_) = info in
bind (k s) (nc_mcode ((),(),mcode_info start,aft,(),adj))
| _ -> k s) in
let string_fragment r k s =
compute_result Ast0.string_fragment s (k s) in
let do_top builder r k e = compute_result builder e (k e) in
let combiner =
V0.flat_combiner bind option_default
mcode mcode mcode mcode mcode mcode mcode mcode mcode
mcode mcode mcode mcode mcode
(do_nothing Ast0.dotsExpr) (do_nothing Ast0.dotsInit)
(do_nothing Ast0.dotsParam) (do_nothing Ast0.dotsStmt)
(do_nothing Ast0.dotsDecl) (do_nothing Ast0.dotsField)
(do_nothing Ast0.dotsEnumDecl) (do_nothing Ast0.dotsCase)
(do_nothing Ast0.dotsDefParam)
ident expression (do_nothing Ast0.assignOp) (do_nothing Ast0.binaryOp)
typeC initialiser param declaration field enum_decl
statement (do_nothing Ast0.forinfo) case_line string_fragment
(do_nothing Ast0.attr) (do_nothing Ast0.attr_arg) (do_top Ast0.top) in
combiner.VT0.combiner_rec_top_level code
(* --------------------------------------------------------------------- *)
Traverse the hash tables and find corresponding context nodes that have
the same context children
the same context children *)
(* this is just a sanity check - really only need to look at the top-level
structure *)
let equal_mcode (_,_,info1,_,_,_) (_,_,info2,_,_,_) =
info1.Ast0.pos_info.Ast0.offset = info2.Ast0.pos_info.Ast0.offset
let assignOp_equal_mcode op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
Ast0.SimpleAssign op1', Ast0.SimpleAssign op2' -> equal_mcode op1' op2'
| Ast0.OpAssign op1', Ast0.OpAssign op2' -> equal_mcode op1' op2'
| Ast0.MetaAssign(mv1,_,_), Ast0.MetaAssign(mv2,_,_) -> equal_mcode mv1 mv2
| _ -> false
let binaryOp_equal_mcode op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
Ast0.Arith op1', Ast0.Arith op2' -> equal_mcode op1' op2'
| Ast0.Logical op1', Ast0.Logical op2' -> equal_mcode op1' op2'
| Ast0.MetaBinary(mv1,_,_), Ast0.MetaBinary(mv2,_,_) -> equal_mcode mv1 mv2
| _ -> false
let equal_option e1 e2 =
match (e1,e2) with
(Some x, Some y) -> equal_mcode x y
| (None, None) -> true
| _ -> false
let equal_args args1 args2=
match (args1, args2) with
| (Some args1, Some args2) ->
let (lp1,_,rp1) = args1 in
let (lp2,_,rp2) = args2 in
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (None, None) -> true
| _ -> false
let dots fn d1 d2 =
List.length (Ast0.unwrap d1) = List.length (Ast0.unwrap d2)
let equal_attr_arg a1 a2 =
match (Ast0.unwrap a1, Ast0.unwrap a2) with
(Ast0.MacroAttr(name1),Ast0.MacroAttr(name2)) ->
equal_mcode name1 name2
| (Ast0.MacroAttrArgs(attr1,lp1,args1,rp1),Ast0.MacroAttrArgs(attr2,lp2,args2,rp2)) ->
equal_mcode attr1 attr2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.MetaAttr(name1,_,_),Ast0.MetaAttr(name2,_,_)) ->
equal_mcode name1 name2
| _ -> false
let equal_attribute a1 a2 =
match (Ast0.unwrap a1, Ast0.unwrap a2) with
(Ast0.Attribute(attr1),Ast0.Attribute(attr2)) ->
equal_attr_arg attr1 attr2
| (Ast0.GccAttribute(attr_1,lp11,lp21,arg1,rp11,rp21),
Ast0.GccAttribute(attr_2,lp12,lp22,arg2,rp12,rp22)) ->
equal_mcode attr_1 attr_2 &&
equal_mcode lp11 lp12 && equal_mcode lp21 lp22 &&
equal_mcode rp11 rp12 && equal_mcode rp21 rp22
| _ -> false
let equal_ident i1 i2 =
match (Ast0.unwrap i1,Ast0.unwrap i2) with
(Ast0.Id(name1),Ast0.Id(name2)) -> equal_mcode name1 name2
| (Ast0.MetaId(name1,_,_,_),Ast0.MetaId(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.MetaFunc(name1,_,_),Ast0.MetaFunc(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.MetaLocalFunc(name1,_,_),Ast0.MetaLocalFunc(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.DisjId(starter1,_,mids1,ender1),
Ast0.DisjId(starter2,_,mids2,ender2))
| (Ast0.ConjId(starter1,_,mids1,ender1),
Ast0.ConjId(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.OptIdent(_),Ast0.OptIdent(_)) -> true
| _ -> false
let rec equal_expression e1 e2 =
match (Ast0.unwrap e1,Ast0.unwrap e2) with
(Ast0.Ident(_),Ast0.Ident(_)) -> true
| (Ast0.Constant(const1),Ast0.Constant(const2)) -> equal_mcode const1 const2
| (Ast0.StringConstant(lq1,const1,rq1,isWchar1),Ast0.StringConstant(lq2,const2,rq2,isWchar2))->
equal_mcode lq1 lq2 && equal_mcode rq1 rq2 && isWchar1 = isWchar2
| (Ast0.FunCall(_,lp1,_,rp1),Ast0.FunCall(_,lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Assignment(_,op1,_,_),Ast0.Assignment(_,op2,_,_)) ->
assignOp_equal op1 op2
| (Ast0.Sequence(_,op1,_),Ast0.Sequence(_,op2,_)) ->
equal_mcode op1 op2
| (Ast0.CondExpr(_,why1,_,colon1,_),Ast0.CondExpr(_,why2,_,colon2,_)) ->
equal_mcode why1 why2 && equal_mcode colon1 colon2
| (Ast0.Postfix(_,op1),Ast0.Postfix(_,op2)) -> equal_mcode op1 op2
| (Ast0.Infix(_,op1),Ast0.Infix(_,op2)) -> equal_mcode op1 op2
| (Ast0.Unary(_,op1),Ast0.Unary(_,op2)) -> equal_mcode op1 op2
| (Ast0.Binary(_,op1,_),Ast0.Binary(_,op2,_)) -> binaryOp_equal op1 op2
| (Ast0.Paren(lp1,_,rp1),Ast0.Paren(lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.ArrayAccess(_,lb1,_,rb1),Ast0.ArrayAccess(_,lb2,_,rb2)) ->
equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.RecordAccess(_,pt1,_),Ast0.RecordAccess(_,pt2,_)) ->
equal_mcode pt1 pt2
| (Ast0.RecordPtAccess(_,ar1,_),Ast0.RecordPtAccess(_,ar2,_)) ->
equal_mcode ar1 ar2
| (Ast0.Cast(lp1,_,ar1,rp1,_),Ast0.Cast(lp2,_,ar2,rp2,_)) ->
equal_mcode lp1 lp2 &&
(List.length ar1) = (List.length ar2) &&
List.for_all2 equal_attribute ar1 ar2 &&
equal_mcode rp1 rp2
| (Ast0.SizeOfExpr(szf1,_),Ast0.SizeOfExpr(szf2,_)) ->
equal_mcode szf1 szf2
| (Ast0.SizeOfType(szf1,lp1,_,rp1),Ast0.SizeOfType(szf2,lp2,_,rp2)) ->
equal_mcode szf1 szf2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Delete(dlt1,_),Ast0.Delete(dlt2,_)) ->
equal_mcode dlt1 dlt2
| (Ast0.DeleteArr(dlt1,lb1,rb1,_),Ast0.DeleteArr(dlt2,lb2,rb2,_)) ->
equal_mcode dlt1 dlt2 && equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.New(new1,pp1_opt,lp1,_,rp1,args1_opt), Ast0.New(new2,pp2_opt,lp2,_,rp2,args2_opt)) ->
equal_mcode new1 new2 && equal_args pp1_opt pp2_opt &&
equal_option lp1 lp2 && equal_option rp1 rp2 && equal_args args1_opt args2_opt
| (Ast0.TypeExp(_),Ast0.TypeExp(_)) -> true
| (Ast0.Constructor(lp1,_,rp1,_),Ast0.Constructor(lp2,_,rp2,_)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.MetaErr(name1,_,_),Ast0.MetaErr(name2,_,_))
| (Ast0.MetaExpr(name1,_,_,_,_,_),Ast0.MetaExpr(name2,_,_,_,_,_))
| (Ast0.MetaExprList(name1,_,_,_),Ast0.MetaExprList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.EComma(cm1),Ast0.EComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.DisjExpr(starter1,_,mids1,ender1),
Ast0.DisjExpr(starter2,_,mids2,ender2))
| (Ast0.ConjExpr(starter1,_,mids1,ender1),
Ast0.ConjExpr(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.NestExpr(starter1,_,ender1,_,m1),
Ast0.NestExpr(starter2,_,ender2,_,m2)) ->
equal_mcode starter1 starter2 && equal_mcode ender1 ender2 && m1 = m2
| (Ast0.Edots(dots1,_),Ast0.Edots(dots2,_)) -> equal_mcode dots1 dots2
| (Ast0.OptExp(_),Ast0.OptExp(_)) -> true
| _ -> false
and assignOp_equal op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
| Ast0.SimpleAssign o1, Ast0.SimpleAssign o2 -> equal_mcode o1 o2
| Ast0.OpAssign o1, Ast0.OpAssign o2 -> equal_mcode o1 o2
| Ast0.MetaAssign(mv1,_,_), Ast0.MetaAssign(mv2,_,_) ->
equal_mcode mv1 mv2
| _ -> false
and binaryOp_equal op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
| Ast0.Arith o1, Ast0.Arith o2 -> equal_mcode o1 o2
| Ast0.Logical o1, Ast0.Logical o2 -> equal_mcode o1 o2
| Ast0.MetaBinary(mv1,_,_), Ast0.MetaBinary(mv2,_,_) ->
equal_mcode mv1 mv2
| _ -> false
let equal_typeC t1 t2 =
match (Ast0.unwrap t1,Ast0.unwrap t2) with
(Ast0.ConstVol(cv1,_),Ast0.ConstVol(cv2,_)) -> List.for_all2 equal_mcode cv1 cv2
| (Ast0.BaseType(ty1,stringsa),Ast0.BaseType(ty2,stringsb)) ->
List.for_all2 equal_mcode stringsa stringsb
| (Ast0.Signed(sign1,_),Ast0.Signed(sign2,_)) ->
equal_mcode sign1 sign2
| (Ast0.Pointer(_,star1),Ast0.Pointer(_,star2)) ->
equal_mcode star1 star2
| (Ast0.ParenType(lp1,_,rp1),Ast0.ParenType(lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.FunctionType(_,lp1,_,rp1),Ast0.FunctionType(_,lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Array(_,lb1,_,rb1),Ast0.Array(_,lb2,_,rb2)) ->
equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.Decimal(dec1,lp1,_,comma1,_,rp1),
Ast0.Decimal(dec2,lp2,_,comma2,_,rp2)) ->
equal_mcode dec1 dec2 && equal_mcode lp1 lp2 &&
equal_option comma1 comma2 && equal_mcode rp1 rp2
| (Ast0.EnumName(kind1,key1,_),Ast0.EnumName(kind2,key2,_)) ->
equal_mcode kind1 kind2 && equal_option key1 key2
| (Ast0.EnumDef(_,base1,lb1,_,rb1),Ast0.EnumDef(_,base2,lb2,_,rb2)) ->
let tru1 = equal_mcode lb1 lb2 in
let tru2 = (match (base1,base2) with
(None, None) -> true
| (Some (td1, _), Some (td2, _)) -> equal_mcode td1 td2
| _ -> false) in
let tru3 = equal_mcode rb1 rb2 in
tru1 && tru2 && tru3
| (Ast0.StructUnionName(kind1,_),Ast0.StructUnionName(kind2,_)) ->
equal_mcode kind1 kind2
| (Ast0.StructUnionDef(_,lb1,_,rb1),
Ast0.StructUnionDef(_,lb2,_,rb2)) ->
equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.TypeOfExpr(tf1,lp1,_,rp1),Ast0.TypeOfExpr(tf2,lp2,_,rp2)) ->
equal_mcode tf1 tf2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.TypeOfType(tf1,lp1,_,rp1),Ast0.TypeOfType(tf2,lp2,_,rp2)) ->
equal_mcode tf1 tf2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.TypeName(name1),Ast0.TypeName(name2)) -> equal_mcode name1 name2
| (Ast0.AutoType(auto1),Ast0.AutoType(auto2)) -> equal_mcode auto1 auto2
| (Ast0.MetaType(name1,_,_),Ast0.MetaType(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.DisjType(starter1,_,mids1,ender1),
Ast0.DisjType(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.ConjType(starter1,_,mids1,ender1),
Ast0.ConjType(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.OptType(_),Ast0.OptType(_)) -> true
| _ -> false
let equal_fninfo x y =
match (x,y) with
(Ast0.FStorage(s1),Ast0.FStorage(s2)) -> equal_mcode s1 s2
| (Ast0.FType(_),Ast0.FType(_)) -> true
| (Ast0.FInline(i1),Ast0.FInline(i2)) -> equal_mcode i1 i2
| (Ast0.FAttr(i1),Ast0.FAttr(i2)) -> equal_attribute i1 i2
| _ -> false
let equal_declaration d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.MetaDecl(name1,_,_),Ast0.MetaDecl(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.Init(stg1,_,midattr1,_,endattr1,eq1,_,sem1),
Ast0.Init(stg2,_,midattr2,_,endattr2,eq2,_,sem2)) ->
equal_option stg1 stg2 &&
(List.length midattr1) = (List.length midattr2) &&
List.for_all2 equal_attribute midattr1 midattr2 &&
(List.length endattr1) = (List.length endattr2) &&
List.for_all2 equal_attribute endattr1 endattr2 &&
equal_mcode eq1 eq2 && equal_mcode sem1 sem2
| (Ast0.UnInit(stg1,_,midattr1,_,endattr1,sem1),Ast0.UnInit(stg2,_,midattr2,_,endattr2,sem2)) ->
equal_option stg1 stg2 &&
(List.length midattr1) = (List.length midattr2) &&
List.for_all2 equal_attribute midattr1 midattr2 &&
(List.length endattr1) = (List.length endattr2) &&
List.for_all2 equal_attribute endattr1 endattr2 &&
equal_mcode sem1 sem2
| (Ast0.FunProto(fninfo1,attr1,name1,lp1,p1,va1,rp1,sem1),
Ast0.FunProto(fninfo2,attr2,name2,lp2,p2,va2,rp2,sem2)) ->
let equal_varargs va1 va2 = match (va1,va2) with
| None, None -> true
| Some (c1, e1), Some (c2, e2) ->
equal_mcode c1 c2 && equal_mcode e1 e2
| _ -> false in
(List.length fninfo1) = (List.length fninfo2) &&
List.for_all2 equal_fninfo fninfo1 fninfo2 &&
(List.length attr1) = (List.length attr2) &&
List.for_all2 equal_attribute attr1 attr2 &&
equal_mcode lp1 lp2 && equal_varargs va1 va2 &&
equal_mcode rp1 rp2 && equal_mcode sem1 sem2
| (Ast0.MacroDecl(stg1,nm1,lp1,_,rp1,attr1,sem1),
Ast0.MacroDecl(stg2,nm2,lp2,_,rp2,attr2,sem2)) ->
equal_option stg1 stg2 &&
(List.length attr1) = (List.length attr2) &&
List.for_all2 equal_attribute attr1 attr2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode sem1 sem2
| (Ast0.MacroDeclInit(stg1,nm1,lp1,_,rp1,eq1,_,sem1),
Ast0.MacroDeclInit(stg2,nm2,lp2,_,rp2,eq2,_,sem2)) ->
equal_option stg1 stg2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode eq1 eq2
&& equal_mcode sem1 sem2
| (Ast0.TyDecl(_,attr1,sem1),Ast0.TyDecl(_,attr2,sem2)) ->
(List.length attr1) = (List.length attr2) &&
List.for_all2 equal_attribute attr1 attr2 && equal_mcode sem1 sem2
| (Ast0.OptDecl(_),Ast0.OptDecl(_)) -> true
| (Ast0.DisjDecl(starter1,_,mids1,ender1),
Ast0.DisjDecl(starter2,_,mids2,ender2))
| (Ast0.ConjDecl(starter1,_,mids1,ender1),
Ast0.ConjDecl(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| _ -> false
let equal_field d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.MetaField(name1,_,_),Ast0.MetaField(name2,_,_))
| (Ast0.MetaFieldList(name1,_,_,_),Ast0.MetaFieldList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.Field(_,_,_bf1,sem1),Ast0.Field(_,_,_bf2,sem2)) ->
equal_mcode sem1 sem2
| (Ast0.Fdots(dots1,_),Ast0.Fdots(dots2,_)) -> equal_mcode dots1 dots2
| (Ast0.OptField(_),Ast0.OptField(_)) -> true
| (Ast0.DisjField(starter1,_,mids1,ender1),
Ast0.DisjField(starter2,_,mids2,ender2))
| (Ast0.ConjField(starter1,_,mids1,ender1),
Ast0.ConjField(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| _ -> false
let equal_enum_decl d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.Enum(name1,enum_val1),Ast0.Enum(name2,enum_val2)) ->
equal_ident name1 name2 &&
(match enum_val1,enum_val2 with
None,None -> true
| Some (eq1,val1),Some(eq2,val2) ->
equal_mcode eq1 eq2 && equal_expression val1 val2
| _ -> false)
| (Ast0.EnumComma(cm1),Ast0.EnumComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.EnumDots(dots1,_),Ast0.EnumDots(dots2,_)) -> equal_mcode dots1 dots2
| _ -> false
let equal_designator d1 d2 =
match (d1,d2) with
(Ast0.DesignatorField(dot1,_),Ast0.DesignatorField(dot2,_)) ->
equal_mcode dot1 dot2
| (Ast0.DesignatorIndex(lb1,_,rb1),Ast0.DesignatorIndex(lb2,_,rb2)) ->
(equal_mcode lb1 lb2) && (equal_mcode rb1 rb2)
| (Ast0.DesignatorRange(lb1,_,dots1,_,rb1),
Ast0.DesignatorRange(lb2,_,dots2,_,rb2)) ->
(equal_mcode lb1 lb2) && (equal_mcode dots1 dots2) &&
(equal_mcode rb1 rb2)
| _ -> false
let equal_initialiser i1 i2 =
match (Ast0.unwrap i1,Ast0.unwrap i2) with
(Ast0.MetaInit(name1,_,_),Ast0.MetaInit(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.MetaInitList(name1,_,_,_),Ast0.MetaInitList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.InitExpr(_),Ast0.InitExpr(_)) -> true
| (Ast0.InitList(lb1,_,rb1,o1),Ast0.InitList(lb2,_,rb2,o2)) ->
(* can't compare orderedness, because this can differ between -
and + code *)
(equal_mcode lb1 lb2) && (equal_mcode rb1 rb2)
| (Ast0.InitGccExt(designators1,eq1,_),
Ast0.InitGccExt(designators2,eq2,_)) ->
(List.for_all2 equal_designator designators1 designators2) &&
(equal_mcode eq1 eq2)
| (Ast0.InitGccName(_,eq1,_),Ast0.InitGccName(_,eq2,_)) ->
equal_mcode eq1 eq2
| (Ast0.IComma(cm1),Ast0.IComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.Idots(d1,_),Ast0.Idots(d2,_)) -> equal_mcode d1 d2
| (Ast0.OptIni(_),Ast0.OptIni(_)) -> true
| _ -> false
let equal_parameterTypeDef p1 p2 =
match (Ast0.unwrap p1,Ast0.unwrap p2) with
(Ast0.Param(_,mar1,_,ar1),Ast0.Param(_,mar2,_,ar2)) ->
(List.length ar1) = (List.length ar2) &&
List.for_all2 equal_attribute ar1 ar2 &&
(List.length mar1) = (List.length mar2) &&
List.for_all2 equal_attribute mar1 mar2
| (Ast0.MetaParam(name1,_,_),Ast0.MetaParam(name2,_,_))
| (Ast0.MetaParamList(name1,_,_,_),Ast0.MetaParamList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.PComma(cm1),Ast0.PComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.Pdots(dots1),Ast0.Pdots(dots2)) -> equal_mcode dots1 dots2
| (Ast0.OptParam(_),Ast0.OptParam(_)) -> true
| _ -> false
let equal_statement s1 s2 =
match (Ast0.unwrap s1,Ast0.unwrap s2) with
(Ast0.FunDecl(_,fninfo1,_,lp1,_,_,rp1,_,lbrace1,_,rbrace1,_),
Ast0.FunDecl(_,fninfo2,_,lp2,_,_,rp2,_,lbrace2,_,rbrace2,_)) ->
(List.length fninfo1) = (List.length fninfo2) &&
List.for_all2 equal_fninfo fninfo1 fninfo2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 &&
equal_mcode lbrace1 lbrace2 && equal_mcode rbrace1 rbrace2
| (Ast0.Decl(_,_),Ast0.Decl(_,_)) -> true
| (Ast0.Seq(lbrace1,_,rbrace1),Ast0.Seq(lbrace2,_,rbrace2)) ->
equal_mcode lbrace1 lbrace2 && equal_mcode rbrace1 rbrace2
| (Ast0.ExprStatement(_,sem1),Ast0.ExprStatement(_,sem2)) ->
equal_mcode sem1 sem2
| (Ast0.IfThen(iff1,lp1,_,rp1,_,_),Ast0.IfThen(iff2,lp2,_,rp2,_,_)) ->
equal_mcode iff1 iff2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.IfThenElse(iff1,lp1,_,rp1,_,els1,_,_),
Ast0.IfThenElse(iff2,lp2,_,rp2,_,els2,_,_)) ->
equal_mcode iff1 iff2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode els1 els2
| (Ast0.While(whl1,lp1,_,rp1,_,_),Ast0.While(whl2,lp2,_,rp2,_,_)) ->
equal_mcode whl1 whl2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Do(d1,_,whl1,lp1,_,rp1,sem1),Ast0.Do(d2,_,whl2,lp2,_,rp2,sem2)) ->
equal_mcode whl1 whl2 && equal_mcode d1 d2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode sem1 sem2
| (Ast0.For(fr1,lp1,first1,rp1,_,_),
Ast0.For(fr2,lp2,first2,rp2,_,_)) ->
let first =
match (Ast0.unwrap first1,Ast0.unwrap first2) with
(Ast0.ForExp(_,sem1,_,sem21,_),Ast0.ForExp(_,sem2,_,sem22,_)) ->
equal_mcode sem1 sem2 && equal_mcode sem21 sem22
| (Ast0.ForDecl(_,_,_,sem21,_),Ast0.ForDecl(_,_,_,sem22,_)) ->
equal_mcode sem21 sem22
| (Ast0.ForRange(_,_,_),Ast0.ForRange(_,_,_)) -> true
| _ -> false in
equal_mcode fr1 fr2 && equal_mcode lp1 lp2 &&
first && equal_mcode rp1 rp2
| (Ast0.Iterator(nm1,lp1,_,rp1,_,_),Ast0.Iterator(nm2,lp2,_,rp2,_,_)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Switch(switch1,lp1,_,rp1,lb1,_,_,rb1),
Ast0.Switch(switch2,lp2,_,rp2,lb2,_,_,rb2)) ->
equal_mcode switch1 switch2 && equal_mcode lp1 lp2 &&
equal_mcode rp1 rp2 && equal_mcode lb1 lb2 &&
equal_mcode rb1 rb2
| (Ast0.Break(br1,sem1),Ast0.Break(br2,sem2)) ->
equal_mcode br1 br2 && equal_mcode sem1 sem2
| (Ast0.Continue(cont1,sem1),Ast0.Continue(cont2,sem2)) ->
equal_mcode cont1 cont2 && equal_mcode sem1 sem2
| (Ast0.Label(_,dd1),Ast0.Label(_,dd2)) ->
equal_mcode dd1 dd2
| (Ast0.Goto(g1,_,sem1),Ast0.Goto(g2,_,sem2)) ->
equal_mcode g1 g2 && equal_mcode sem1 sem2
| (Ast0.Return(ret1,sem1),Ast0.Return(ret2,sem2)) ->
equal_mcode ret1 ret2 && equal_mcode sem1 sem2
| (Ast0.ReturnExpr(ret1,_,sem1),Ast0.ReturnExpr(ret2,_,sem2)) ->
equal_mcode ret1 ret2 && equal_mcode sem1 sem2
| (Ast0.Exec(exec1,lang1,_,sem1),Ast0.Exec(exec2,lang2,_,sem2)) ->
equal_mcode exec1 exec2 && equal_mcode lang1 lang2 &&
equal_mcode sem1 sem2
| (Ast0.MetaStmt(name1,_,_),Ast0.MetaStmt(name2,_,_))
| (Ast0.MetaStmtList(name1,_,_,_),Ast0.MetaStmtList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.Disj(starter1,_,mids1,ender1),Ast0.Disj(starter2,_,mids2,ender2))
| (Ast0.Conj(starter1,_,mids1,ender1),Ast0.Conj(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.Nest(starter1,_,ender1,_,m1),Ast0.Nest(starter2,_,ender2,_,m2)) ->
equal_mcode starter1 starter2 && equal_mcode ender1 ender2 && m1 = m2
| (Ast0.Exp(_),Ast0.Exp(_)) -> true
| (Ast0.TopExp(_),Ast0.TopExp(_)) -> true
| (Ast0.Ty(_),Ast0.Ty(_)) -> true
| (Ast0.TopId(_),Ast0.TopId(_)) -> true
| (Ast0.TopInit(_),Ast0.TopInit(_)) -> true
| (Ast0.Dots(d1,_),Ast0.Dots(d2,_)) -> equal_mcode d1 d2
| (Ast0.Include(inc1,name1),Ast0.Include(inc2,name2)) ->
equal_mcode inc1 inc2 && equal_mcode name1 name2
| (Ast0.MetaInclude(inc1,name1),Ast0.MetaInclude(inc2,name2)) ->
equal_mcode inc1 inc2
| (Ast0.Undef(def1,_),Ast0.Undef(def2,_)) ->
equal_mcode def1 def2
| (Ast0.Define(def1,_,_,_),Ast0.Define(def2,_,_,_)) ->
equal_mcode def1 def2
| (Ast0.Pragma(prg1,_,_),Ast0.Pragma(prg2,_,_)) ->
equal_mcode prg1 prg2
| (Ast0.OptStm(_),Ast0.OptStm(_)) -> true
| _ -> false
let equal_case_line c1 c2 =
match (Ast0.unwrap c1,Ast0.unwrap c2) with
(Ast0.Default(def1,colon1,_),Ast0.Default(def2,colon2,_)) ->
equal_mcode def1 def2 && equal_mcode colon1 colon2
| (Ast0.Case(case1,_,colon1,_),Ast0.Case(case2,_,colon2,_)) ->
equal_mcode case1 case2 && equal_mcode colon1 colon2
| (Ast0.DisjCase(starter1,_,mids1,ender1),
Ast0.DisjCase(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.OptCase(_),Ast0.OptCase(_)) -> true
| _ -> false
let equal_define_param d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.DParam _,Ast0.DParam _) -> true
| (Ast0.MetaDParamList(name1,_,_,_),Ast0.MetaDParamList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.DPComma cm1,Ast0.DPComma cm2) -> equal_mcode cm1 cm2
| (Ast0.DPdots d1,Ast0.DPdots d2) -> equal_mcode d1 d2
| (Ast0.OptDParam(_),Ast0.OptDParam(_)) -> true
| _ -> false
let equal_top_level t1 t2 =
match (Ast0.unwrap t1,Ast0.unwrap t2) with
(Ast0.NONDECL(_),Ast0.NONDECL(_)) -> true
| (Ast0.FILEINFO(old_file1,new_file1),Ast0.FILEINFO(old_file2,new_file2)) ->
equal_mcode old_file1 old_file2 && equal_mcode new_file1 new_file2
| (Ast0.CODE(_),Ast0.CODE(_)) -> true
| (Ast0.ERRORWORDS(_),Ast0.ERRORWORDS(_)) -> true
| _ -> false
let root_equal e1 e2 =
match (e1,e2) with
(Ast0.DotsExprTag(d1),Ast0.DotsExprTag(d2)) -> dots equal_expression d1 d2
| (Ast0.DotsParamTag(d1),Ast0.DotsParamTag(d2)) ->
dots equal_parameterTypeDef d1 d2
| (Ast0.DotsStmtTag(d1),Ast0.DotsStmtTag(d2)) -> dots equal_statement d1 d2
| (Ast0.DotsDeclTag(d1),Ast0.DotsDeclTag(d2)) -> dots equal_declaration d1 d2
| (Ast0.DotsFieldTag(d1),Ast0.DotsFieldTag(d2)) -> dots equal_field d1 d2
| (Ast0.DotsEnumDeclTag(d1),Ast0.DotsEnumDeclTag(d2)) ->
dots equal_field d1 d2
| (Ast0.DotsCaseTag(d1),Ast0.DotsCaseTag(d2)) -> dots equal_case_line d1 d2
| (Ast0.DotsDefParamTag(d1),Ast0.DotsDefParamTag(d2)) ->
dots equal_define_param d1 d2
| (Ast0.IdentTag(i1),Ast0.IdentTag(i2)) -> equal_ident i1 i2
| (Ast0.ExprTag(e1),Ast0.ExprTag(e2)) -> equal_expression e1 e2
| (Ast0.AssignOpTag(e1),Ast0.AssignOpTag(e2)) -> assignOp_equal e1 e2
| (Ast0.BinaryOpTag(e1),Ast0.BinaryOpTag(e2)) -> binaryOp_equal e1 e2
| (Ast0.ArgExprTag(d),_) -> failwith "not possible - iso only"
| (Ast0.TypeCTag(t1),Ast0.TypeCTag(t2)) -> equal_typeC t1 t2
| (Ast0.ParamTag(p1),Ast0.ParamTag(p2)) -> equal_parameterTypeDef p1 p2
| (Ast0.InitTag(d1),Ast0.InitTag(d2)) -> equal_initialiser d1 d2
| (Ast0.DeclTag(d1),Ast0.DeclTag(d2)) -> equal_declaration d1 d2
| (Ast0.FieldTag(d1),Ast0.FieldTag(d2)) -> equal_field d1 d2
| (Ast0.EnumDeclTag(d1),Ast0.EnumDeclTag(d2)) -> equal_enum_decl d1 d2
| (Ast0.StmtTag(s1),Ast0.StmtTag(s2)) -> equal_statement s1 s2
| (Ast0.TopTag(t1),Ast0.TopTag(t2)) -> equal_top_level t1 t2
| (Ast0.IsoWhenTag(_),_) | (_,Ast0.IsoWhenTag(_))
| (Ast0.IsoWhenTTag(_),_) | (_,Ast0.IsoWhenTTag(_))
| (Ast0.IsoWhenFTag(_),_) | (_,Ast0.IsoWhenFTag(_)) ->
failwith "only within iso phase"
| _ -> false
let default_context _ =
Ast0.CONTEXT(ref(Ast.NOTHING,
Ast0.default_token_info,Ast0.default_token_info))
let traverse minus_table plus_table =
Hashtbl.iter
(function key ->
function (e,l) ->
try
let (plus_e,plus_l) = Hashtbl.find plus_table key in
if root_equal e plus_e &&
List.for_all (function x -> x)
(List.map2 Common.equal_set l plus_l)
then
let i = Ast0.fresh_index() in
(set_index e i; set_index plus_e i;
set_mcodekind e (default_context());
set_mcodekind plus_e (default_context()))
with Not_found -> ())
minus_table
(* --------------------------------------------------------------------- *)
contextify the whencode
let contextify_all =
let bind x y = () in
let option_default = () in
let mcode x = () in
let donothing r k e = Ast0.set_mcodekind e (default_context()); k e in
V0.flat_combiner bind option_default
mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode
mcode mcode
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing
let contextify_whencode =
let bind x y = () in
let option_default = () in
let expression r k e =
k e;
match Ast0.unwrap e with
Ast0.NestExpr(_,_,_,Some (_,_,whencode),_)
| Ast0.Edots(_,Some (_,_,whencode)) ->
contextify_all.VT0.combiner_rec_expression whencode
| _ -> () in
let initialiser r k i =
match Ast0.unwrap i with
Ast0.Idots(dots,Some (_,_,whencode)) ->
contextify_all.VT0.combiner_rec_initialiser whencode
| _ -> k i in
let whencode = function
Ast0.WhenNot (_,_,sd) ->
contextify_all.VT0.combiner_rec_statement_dots sd
| Ast0.WhenAlways (_,_,s) -> contextify_all.VT0.combiner_rec_statement s
| Ast0.WhenModifier _ -> ()
| Ast0.WhenNotTrue(_,_,e) -> contextify_all.VT0.combiner_rec_expression e
| Ast0.WhenNotFalse(_,_,e) -> contextify_all.VT0.combiner_rec_expression e
in
let statement r k (s : Ast0.statement) =
k s;
match Ast0.unwrap s with
Ast0.Nest(_,_,_,whn,_)
| Ast0.Dots(_,whn) -> List.iter whencode whn
| _ -> () in
let combiner =
V0.combiner bind option_default
{V0.combiner_functions with
VT0.combiner_exprfn = expression;
VT0.combiner_initfn = initialiser;
VT0.combiner_stmtfn = statement} in
combiner.VT0.combiner_rec_top_level
(* --------------------------------------------------------------------- *)
the first int list is the tokens in the node , the second is the tokens
in the descendants
in the descendants *)
let minus_table =
(Hashtbl.create(50) : (int list, Ast0.anything * int list list) Hashtbl.t)
let plus_table =
(Hashtbl.create(50) : (int list, Ast0.anything * int list list) Hashtbl.t)
let iscode t =
match Ast0.unwrap t with
Ast0.NONDECL(_) -> true
| Ast0.FILEINFO(_) -> true
| Ast0.ERRORWORDS(_) -> false
| Ast0.CODE(_) -> true
| Ast0.TOPCODE(_)
| Ast0.OTHER(_) -> failwith "unexpected top level code"
(* ------------------------------------------------------------------- *)
(* alignment of minus and plus *)
let concat = function
[] -> []
| [s] -> [s]
| l ->
let rec loop = function
[] -> []
| x::rest ->
(match Ast0.unwrap x with
Ast0.NONDECL(s) -> let stms = loop rest in s::stms
| Ast0.CODE(ss) ->
let stms = loop rest in
(Ast0.unwrap ss)@stms
| _ -> failwith "plus code is being discarded") in
let res =
Compute_lines.compute_statement_dots_lines false
(Ast0.rewrap (List.hd l) (loop l)) in
[Ast0.rewrap res (Ast0.CODE res)]
let collect_up_to m plus =
let minfo = Ast0.get_info m in
let mend = minfo.Ast0.pos_info.Ast0.logical_end in
let rec loop = function
[] -> ([],[])
| p::plus ->
let pinfo = Ast0.get_info p in
let pstart = pinfo.Ast0.pos_info.Ast0.logical_start in
if pstart > mend
then ([],p::plus)
else let (plus,rest) = loop plus in (p::plus,rest) in
let (plus,rest) = loop plus in
(concat plus,rest)
let realign minus plus =
let rec loop = function
([],_) -> failwith "not possible, some context required"
| ([m],p) -> ([m],concat p)
| (m::minus,plus) ->
let (p,plus) = collect_up_to m plus in
let (minus,plus) = loop (minus,plus) in
(m::minus,p@plus) in
loop (minus,plus)
(* ------------------------------------------------------------------- *)
(* check compatible: check that at the top level the minus and plus code is
of the same kind. Could go further and make the correspondence between the
code between ...s. *)
let isonly f l = match Ast0.unwrap l with [s] -> f s | _ -> false
let isall f l = List.for_all (isonly f) l
let isany f l = List.exists (isonly f) l
let rec is_exp s =
match Ast0.unwrap s with
Ast0.Exp(e) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_exp stmts
| Ast0.Conj(_,s::_,_,_) ->
the parser ensures that if the matches a
statement , the statement is in the first position
statement, the statement is in the first position *)
isonly is_exp s
| _ -> false
let rec is_ty s =
match Ast0.unwrap s with
Ast0.Ty(e) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_ty stmts
| Ast0.Conj(_,s::_,_,_) ->
the parser ensures that if the matches a
statement , the statement is in the first position
statement, the statement is in the first position *)
isonly is_ty s
| _ -> false
let rec is_init s =
match Ast0.unwrap s with
Ast0.TopInit(e) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_init stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_init stmts
| _ -> false
let rec is_decl s =
match Ast0.unwrap s with
Ast0.Decl(_,e) -> true
| Ast0.FunDecl(_,_,_,_,_,_,_,_,_,_,_,_) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_decl stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_decl stmts
| _ -> false
let rec is_fndecl s =
match Ast0.unwrap s with
Ast0.FunDecl(_,_,_,_,_,_,_,_,_,_,_,_) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_fndecl stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_fndecl stmts
| _ -> false
let rec is_toplevel s =
match Ast0.unwrap s with
Ast0.Decl(_,e) -> true
| Ast0.FunDecl(_,_,_,_,_,_,_,_,_,_,_,_) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_toplevel stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_toplevel stmts
| Ast0.ExprStatement(Some fc,_) ->
(match Ast0.unwrap fc with
Ast0.FunCall(_,_,_,_) -> true
| _ -> false)
| Ast0.Include(_,_) -> true
| Ast0.Undef(_,_) -> true
| Ast0.Pragma(_,_,_) -> true
| Ast0.Define(_,_,_,_) -> true
| _ -> false
consider code and topcode to be the same ; difference handled
in top_level.ml
in top_level.ml *)
let check_compatible m p =
let fail _ =
failwith
(Printf.sprintf
"incompatible minus and plus code starting on lines %d and %d"
(Ast0.get_line m) (Ast0.get_line p)) in
match (Ast0.unwrap m, Ast0.unwrap p) with
(Ast0.NONDECL(decl1),Ast0.NONDECL(decl2)) ->
if not (is_decl decl1 && is_decl decl2)
then fail()
| (Ast0.NONDECL(decl1),Ast0.CODE(code2)) ->
(* This is probably the only important case. We don't want to
replace top-level declarations by arbitrary code. *)
let v1 = is_decl decl1 in
let v2 = List.for_all is_toplevel (Ast0.unwrap code2) in
if !Flag.make_hrule = None && v1 && not v2
then fail()
| (Ast0.CODE(code1),Ast0.NONDECL(decl2)) ->
let v1 = List.for_all is_toplevel (Ast0.unwrap code1) in
let v2 = is_decl decl2 in
if v1 && not v2
then fail()
| (Ast0.CODE(code1),Ast0.CODE(code2)) ->
let v1 = isonly is_init code1 in
let v2a = isonly is_init code2 in
let v2b = isonly is_exp code2 in
if v1
then (if not (v2a || v2b) then fail())
else
let testers = [is_exp;is_ty] in
List.iter
(function tester ->
let v1 = isonly tester code1 in
let v2 = isonly tester code2 in
if (v1 && not v2) || (!Flag.make_hrule = None && v2 && not v1)
then fail())
testers;
let v1 = isonly is_fndecl code1 in
let v2 = List.for_all is_toplevel (Ast0.unwrap code2) in
if !Flag.make_hrule = None && v1 && not v2
then fail()
| (Ast0.FILEINFO(_,_),Ast0.FILEINFO(_,_)) -> ()
| (Ast0.OTHER(_),Ast0.OTHER(_)) -> ()
| _ -> fail()
(* can't just remove expressions or types, not sure if all cases are needed. *)
let check_complete m =
match Ast0.unwrap m with
Ast0.NONDECL(code) ->
if is_exp code || is_ty code
then
failwith
(Printf.sprintf "invalid minus starting on line %d"
(Ast0.get_line m))
| Ast0.CODE(code) ->
if isonly is_exp code || isonly is_ty code
then
failwith
(Printf.sprintf "invalid minus starting on line %d"
(Ast0.get_line m))
| _ -> ()
(* ------------------------------------------------------------------- *)
(* returns a list of corresponding minus and plus trees *)
let context_neg minus plus =
Hashtbl.clear minus_table;
Hashtbl.clear plus_table;
List.iter contextify_whencode minus;
let (minus,plus) = realign minus plus in
let rec loop = function
([],[]) -> []
| ([],l) ->
failwith (Printf.sprintf "%d plus things remaining" (List.length l))
| (minus,[]) ->
List.iter check_complete minus;
plus_lines := [];
let _ =
List.map
(function m ->
classify true
(function _ ->
Ast0.MINUS(ref(Ast.NOREPLACEMENT,Ast0.default_token_info)))
minus_table m)
minus in
[]
| (((m::minus) as mall),((p::plus) as pall)) ->
let minfo = Ast0.get_info m in
let pinfo = Ast0.get_info p in
let mstart = minfo.Ast0.pos_info.Ast0.logical_start in
let mend = minfo.Ast0.pos_info.Ast0.logical_end in
let pstart = pinfo.Ast0.pos_info.Ast0.logical_start in
let pend = pinfo.Ast0.pos_info.Ast0.logical_end in
if (iscode m || iscode p) &&
(mend + 1 = pstart || pend + 1 = mstart || (* adjacent *)
(mstart <= pstart && mend >= pstart) ||
(pstart <= mstart && pend >= mstart)) (* overlapping or nested *)
then
begin
(* ensure that the root of each tree has a unique index,
although it might get overwritten if the node is a context
node *)
let i = Ast0.fresh_index() in
Ast0.set_index m i; Ast0.set_index p i;
check_compatible m p;
collect_plus_lines p;
let _ =
classify true
(function _ ->
Ast0.MINUS(ref(Ast.NOREPLACEMENT,Ast0.default_token_info)))
minus_table m in
let _ = classify false (function c -> Ast0.PLUS c) plus_table p in
traverse minus_table plus_table;
(m,p)::loop(minus,plus)
end
else
if not(iscode m || iscode p)
then loop(minus,plus)
else
if mstart < pstart
then
begin
plus_lines := [];
let _ =
classify true
(function _ ->
Ast0.MINUS(ref(Ast.NOREPLACEMENT,
Ast0.default_token_info)))
minus_table m in
loop(minus,pall)
end
else loop(mall,plus) in
loop(minus,plus)
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/2d0014efa4c67f4c3b4687cbcddef7456bad9aac/parsing_cocci/context_neg.ml | ocaml | Detects subtrees that are all minus/plus and nodes that are "binding
context nodes". The latter is a node whose structure and immediate tokens
are the same in the minus and plus trees, and such that for every child,
the set of context nodes in the child subtree is the same in the minus and
plus subtrees.
---------------------------------------------------------------------
---------------------------------------------------------------------
Collect the line numbers of the plus code. This is used for disjunctions.
It is not completely clear why this is necessary, but it seems like an easy
fix for whatever is the problem that is discussed in disj_cases
cases for everything with extra mcode
---------------------------------------------------------------------
marked means + or -
---------------------------------------------------------------------
ints are unique token indices (offset field)
tokens
unique index
context tokens
children
indices of all tokens at the level below
tokens at the level below
neighbors
indices of all tokens at current level
tokens at current level
indices of all tokens at the level below
tokens at the level below
goal: detect negative in both tokens and recursors, or context only in
tokens
token/token
there are tokens at this level, so ignore the level below
token/recursor
there are tokens at this level, so ignore the level below
token/bind
there are tokens at this level, so ignore the level below
recursor/bind
recursor/recursor and bind/bind - not likely to ever occur
Bind(Neutral,[],[],[],[],[])
adds a thing with space around it
distinguish from the offset of some real token
Unlike the other mcode cases, we drop the offset from the context
offsets. This is because we don't know whether the term this is
associated with is - or context. In any case, the context offsets are
used for identification, and this invisible node should not be needed
for this purpose.
can we have ++ for strings?
is minus is true when we are processing minus code that might be
intermingled with plus code. it is used in disj_cases
definitive
no whencode in plus tree so have to drop it
not clear why we have the next cases, since DisjDecl and
as it only comes from isos
actually, DisjDecl now allowed in source struct decls
Need special cases for the following so that the type will be
considered as a unit, rather than distributed around the
declared variable. This needs to be done because of the call to
compute_result, ie the processing of each term should make a
side-effect on the complete term structure as well as collecting
some information about it. So we have to visit each complete
term structure. In (all?) other such cases, we visit the terms
using rebuilder, which just visits the subterms, rather than
reordering their components.
cases for everything with extra mcode
not sure that the use of start is relevant here
For these, the info of the aft mcode is derived from the else
branch. These might not correspond for a context if, eg if
only the else branch is replaced. Thus we take instead the
info of the starting keyword. In a context case, these will be
the same on the - and + sides. All that is used as an offset,
and it is only used as a key, so this is safe to do. For an
iterator, we take the left parenthesis, which should have the
same property.
---------------------------------------------------------------------
this is just a sanity check - really only need to look at the top-level
structure
can't compare orderedness, because this can differ between -
and + code
---------------------------------------------------------------------
---------------------------------------------------------------------
-------------------------------------------------------------------
alignment of minus and plus
-------------------------------------------------------------------
check compatible: check that at the top level the minus and plus code is
of the same kind. Could go further and make the correspondence between the
code between ...s.
This is probably the only important case. We don't want to
replace top-level declarations by arbitrary code.
can't just remove expressions or types, not sure if all cases are needed.
-------------------------------------------------------------------
returns a list of corresponding minus and plus trees
adjacent
overlapping or nested
ensure that the root of each tree has a unique index,
although it might get overwritten if the node is a context
node |
* This file is part of Coccinelle , licensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, licensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
module Ast = Ast_cocci
module Ast0 = Ast0_cocci
module V0 = Visitor_ast0
module VT0 = Visitor_ast0_types
module U = Unparse_ast0
Generic access to code
let set_mcodekind x mcodekind =
match x with
Ast0.DotsExprTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsInitTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsParamTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsStmtTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsDeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsFieldTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsEnumDeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsCaseTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DotsDefParamTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.IdentTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ExprTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.AssignOpTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.BinaryOpTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ArgExprTag(d) | Ast0.TestExprTag(d) ->
failwith "not possible - iso only"
| Ast0.TypeCTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ParamTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.DeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.FieldTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.EnumDeclTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.InitTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.StmtTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.ForInfoTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.CaseLineTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.StringFragmentTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.AttributeTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.AttrArgTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.TopTag(d) -> Ast0.set_mcodekind d mcodekind
| Ast0.IsoWhenTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenTTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenFTag(_) -> failwith "only within iso phase"
| Ast0.MetaPosTag(p) -> failwith "invisible at this stage"
| Ast0.HiddenVarTag(p) -> failwith "hiddenvar only within iso phase"
| Ast0.WhenTag _ -> failwith "whentag only within iso phase"
let set_index x index =
match x with
Ast0.DotsExprTag(d) -> Ast0.set_index d index
| Ast0.DotsInitTag(d) -> Ast0.set_index d index
| Ast0.DotsParamTag(d) -> Ast0.set_index d index
| Ast0.DotsStmtTag(d) -> Ast0.set_index d index
| Ast0.DotsDeclTag(d) -> Ast0.set_index d index
| Ast0.DotsFieldTag(d) -> Ast0.set_index d index
| Ast0.DotsEnumDeclTag(d) -> Ast0.set_index d index
| Ast0.DotsCaseTag(d) -> Ast0.set_index d index
| Ast0.DotsDefParamTag(d) -> Ast0.set_index d index
| Ast0.IdentTag(d) -> Ast0.set_index d index
| Ast0.ExprTag(d) -> Ast0.set_index d index
| Ast0.AssignOpTag(d) -> Ast0.set_index d index
| Ast0.BinaryOpTag(d) -> Ast0.set_index d index
| Ast0.ArgExprTag(d) | Ast0.TestExprTag(d) ->
failwith "not possible - iso only"
| Ast0.TypeCTag(d) -> Ast0.set_index d index
| Ast0.ParamTag(d) -> Ast0.set_index d index
| Ast0.InitTag(d) -> Ast0.set_index d index
| Ast0.DeclTag(d) -> Ast0.set_index d index
| Ast0.FieldTag(d) -> Ast0.set_index d index
| Ast0.EnumDeclTag(d) -> Ast0.set_index d index
| Ast0.StmtTag(d) -> Ast0.set_index d index
| Ast0.ForInfoTag(d) -> Ast0.set_index d index
| Ast0.CaseLineTag(d) -> Ast0.set_index d index
| Ast0.StringFragmentTag(d) -> Ast0.set_index d index
| Ast0.AttributeTag(d) -> Ast0.set_index d index
| Ast0.AttrArgTag(d) -> Ast0.set_index d index
| Ast0.TopTag(d) -> Ast0.set_index d index
| Ast0.IsoWhenTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenTTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenFTag(_) -> failwith "only within iso phase"
| Ast0.MetaPosTag(p) -> failwith "invisible at this stage"
| Ast0.HiddenVarTag(p) -> failwith "hiddenvar only within iso phase"
| Ast0.WhenTag _ -> failwith "whentag only within iso phase"
let get_index = function
Ast0.DotsExprTag(d) -> Index.expression_dots d
| Ast0.DotsInitTag(d) -> Index.initialiser_dots d
| Ast0.DotsParamTag(d) -> Index.parameter_dots d
| Ast0.DotsStmtTag(d) -> Index.statement_dots d
| Ast0.DotsDeclTag(d) -> Index.declaration_dots d
| Ast0.DotsFieldTag(d) -> Index.field_dots d
| Ast0.DotsEnumDeclTag(d) -> Index.enum_decl_dots d
| Ast0.DotsCaseTag(d) -> Index.case_line_dots d
| Ast0.DotsDefParamTag(d) -> Index.define_param_dots d
| Ast0.IdentTag(d) -> Index.ident d
| Ast0.ExprTag(d) -> Index.expression d
| Ast0.AssignOpTag(d) -> Index.assignOp d
| Ast0.BinaryOpTag(d) -> Index.binaryOp d
| Ast0.ArgExprTag(d) | Ast0.TestExprTag(d) ->
failwith "not possible - iso only"
| Ast0.TypeCTag(d) -> Index.typeC d
| Ast0.ParamTag(d) -> Index.parameterTypeDef d
| Ast0.InitTag(d) -> Index.initialiser d
| Ast0.DeclTag(d) -> Index.declaration d
| Ast0.FieldTag(d) -> Index.field d
| Ast0.EnumDeclTag(d) -> Index.enum_decl d
| Ast0.StmtTag(d) -> Index.statement d
| Ast0.ForInfoTag(d) -> Index.forinfo d
| Ast0.CaseLineTag(d) -> Index.case_line d
| Ast0.StringFragmentTag(d) -> Index.string_fragment d
| Ast0.AttributeTag(d) -> Index.attribute d
| Ast0.AttrArgTag(d) -> Index.attr_arg d
| Ast0.TopTag(d) -> Index.top_level d
| Ast0.IsoWhenTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenTTag(_) -> failwith "only within iso phase"
| Ast0.IsoWhenFTag(_) -> failwith "only within iso phase"
| Ast0.MetaPosTag(p) -> failwith "invisible at this stage"
| Ast0.HiddenVarTag(p) -> failwith "hiddenvar only within iso phase"
| Ast0.WhenTag _ -> failwith "whentag only within iso phase"
let plus_lines = ref ([] : int list)
let insert n =
let rec loop = function
[] -> [n]
| x::xs ->
match compare n x with
1 -> x::(loop xs)
| 0 -> x::xs
| -1 -> n::x::xs
| _ -> failwith "not possible" in
plus_lines := loop !plus_lines
let find n min max =
let rec loop = function
[] -> (min,max)
| [x] -> if n < x then (min,x) else (x,max)
| x1::x2::rest ->
if n < x1
then (min,x1)
else if n > x1 && n < x2 then (x1,x2) else loop (x2::rest) in
loop !plus_lines
let collect_plus_lines top =
plus_lines := [];
let bind x y = () in
let option_default = () in
let donothing r k e = k e in
let mcode (_,_,info,mcodekind,_,_) =
match mcodekind with
Ast0.PLUS _ -> insert info.Ast0.pos_info.Ast0.line_start
| _ -> () in
let statement r k s =
let mcode info bef = mcode ((),(),info,bef,(),-1) in
match Ast0.unwrap s with
| Ast0.Decl((info,bef),_) ->
bind (mcode info bef) (k s)
| Ast0.FunDecl((info,bef),_,_,_,_,_,_,_,_,_,_,(ainfo,aft)) ->
bind (mcode info bef) (bind (k s) (mcode ainfo aft))
| Ast0.IfThen(_,_,_,_,_,(info,aft,adj))
| Ast0.IfThenElse(_,_,_,_,_,_,_,(info,aft,adj))
| Ast0.Iterator(_,_,_,_,_,(info,aft,adj))
| Ast0.While(_,_,_,_,_,(info,aft,adj))
| Ast0.For(_,_,_,_,_,(info,aft,adj)) ->
bind (k s) (mcode info aft)
| _ -> k s in
let fn =
V0.flat_combiner bind option_default
mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode
mcode mcode
donothing donothing donothing donothing donothing donothing donothing
donothing donothing
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing statement donothing donothing donothing
donothing donothing donothing in
fn.VT0.combiner_rec_top_level top
type kind =
The first part analyzes each of the minus tree and the plus tree
separately
separately *)
type node =
int list
* int list list
let kind2c = function
Neutral -> "neutral"
| AllMarked _ -> "allmarked"
| NotAllMarked -> "notallmarked"
let node2c = function
Token(k,_,_,_) -> Printf.sprintf "token %s\n" (kind2c k)
| Recursor(k,_,_,_) -> Printf.sprintf "recursor %s\n" (kind2c k)
| Bind(k,_,_,_,_,_) -> Printf.sprintf "bind %s\n" (kind2c k)
let bind c1 c2 =
let lub = function
(k1,k2) when k1 = k2 -> k1
| (Neutral,AllMarked c) -> AllMarked c
| (AllMarked c,Neutral) -> AllMarked c
| _ -> NotAllMarked in
match (c1,c2) with
(Token(k1,i1,t1,l1),Token(k2,i2,t2,l2)) ->
Bind(lub(k1,k2),[i1;i2],[t1;t2],[],[],[l1;l2])
| (Token(k1,i1,t1,l1),Recursor(k2,_,_,l2)) ->
Bind(lub(k1,k2),[i1],[t1],[],[],[l1;l2])
| (Recursor(k1,_,_,l1),Token(k2,i2,t2,l2)) ->
Bind(lub(k1,k2),[i2],[t2],[],[],[l1;l2])
| (Token(k1,i1,t1,l1),Bind(k2,i2,t2,_,_,l2)) ->
Bind(lub(k1,k2),i1::i2,t1::t2,[],[],l1::l2)
| (Bind(k1,i1,t1,_,_,l1),Token(k2,i2,t2,l2)) ->
Bind(lub(k1,k2),i1@[i2],t1@[t2],[],[],l1@[l2])
| (Recursor(k1,bi1,bt1,l1),Bind(k2,i2,t2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),i2,t2,bi1@bi2,bt1@bt2,l1::l2)
| (Bind(k1,i1,t1,bi1,bt1,l1),Recursor(k2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),i1,t1,bi1@bi2,bt1@bt2,l1@[l2])
| (Recursor(k1,bi1,bt1,l1),Recursor(k2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),[],[],bi1@bi2,bt1@bt2,[l1;l2])
| (Bind(k1,i1,t1,bi1,bt1,l1),Bind(k2,i2,t2,bi2,bt2,l2)) ->
Bind(lub(k1,k2),i1@i2,t1@t2,bi1@bi2,bt1@bt2,l1@l2)
Recursor(Neutral,[],[],[])
let contains_added_strings info =
let unsafe l =
List.exists
(fun (str,_) ->
match str with
(Ast.Noindent s | Ast.Indent s) -> not (Stdcompat.String.trim s = "")
l in
If this is true , eg if ( x ) return 0 ; will be broken up into
two rule elems . Not sure why that is needed , but surely it is not needed
when it is just whitespace that is added .
two rule elems. Not sure why that is needed, but surely it is not needed
when it is just whitespace that is added. *)
unsafe info.Ast0.strings_before || unsafe info.Ast0.strings_after
let mcode (_,_,info,mcodekind,pos,_) =
let offset = info.Ast0.pos_info.Ast0.offset in
match mcodekind with
Ast0.MINUS(_) -> Token(AllMarked Ast.ONE,offset,mcodekind,[])
| Ast0.PLUS c -> Token(AllMarked c,offset,mcodekind,[])
| Ast0.CONTEXT(_) -> Token(NotAllMarked,offset,mcodekind,[offset])
| _ -> failwith "not possible"
let neutral_mcode (_,_,info,mcodekind,pos,_) =
let offset = info.Ast0.pos_info.Ast0.offset in
match mcodekind with
Ast0.MINUS(_) -> Token(Neutral,offset,mcodekind,[])
| Ast0.PLUS _ -> Token(Neutral,offset,mcodekind,[])
| Ast0.CONTEXT(_) -> Token(Neutral,offset,mcodekind,[offset])
| _ -> failwith "not possible"
neutral for context ; used for mcode in bef aft nodes that do n't represent
anything if they do n't contain some information
anything if they don't contain some information *)
let nc_mcode (_,_,info,mcodekind,pos,_) =
let offset = (-1) * info.Ast0.pos_info.Ast0.offset in
match mcodekind with
Ast0.MINUS(_) -> Token(AllMarked Ast.ONE,offset,mcodekind,[])
| Ast0.PLUS c -> Token(AllMarked c,offset,mcodekind,[])
| Ast0.CONTEXT(_) ->
if contains_added_strings info
then
Token(NotAllMarked,offset,mcodekind,[])
else Token(Neutral,offset,mcodekind,[])
| _ -> failwith "not possible"
let is_context = function Ast0.CONTEXT(_) -> true | _ -> false
let union_all l = List.fold_left Common.union_set [] l
let classify is_minus all_marked table code =
let mkres builder k il tl bil btl l e =
(match k with
AllMarked count ->
| _ ->
let check_index il tl =
if List.for_all is_context tl
then
(let e1 = builder e in
let index = (get_index e1)@il in
try
let _ = Hashtbl.find table index in
failwith
(Printf.sprintf "line %d: index %s already used\n"
(Ast0.get_info e).Ast0.pos_info.Ast0.line_start
(String.concat " " (List.map string_of_int index)))
with Not_found -> Hashtbl.add table index (e1,l)) in
if il = [] then check_index bil btl else check_index il tl);
if il = []
then Recursor(k, bil, btl, union_all l)
else Recursor(k, il, tl, union_all l) in
let compute_result builder e = function
Bind(k,il,tl,bil,btl,l) -> mkres builder k il tl bil btl l e
| Token(k,il,tl,l) -> mkres builder k [il] [tl] [] [] [l] e
| Recursor(k,bil,btl,l) -> mkres builder k [] [] bil btl [l] e in
let make_not_marked = function
Bind(k,il,tl,bil,btl,l) -> Bind(NotAllMarked,il,tl,bil,btl,l)
| Token(k,il,tl,l) -> Token(NotAllMarked,il,tl,l)
| Recursor(k,bil,btl,l) -> Recursor(NotAllMarked,bil,btl,l) in
let do_nothing builder r k e = compute_result builder e (k e) in
let disj_cases disj starter code fn ender =
neutral_mcode used so starter and ender do n't have an affect on
whether the code is considered all plus / minus , but so that they are
consider in the index list , which is needed to make a disj with
something in one branch and nothing in the other different from code
that just has the something ( starter / ender enough , mids not needed
for this ) . Can not agglomerate + code over | boundaries , because two -
cases might have different + code , and do n't want to put the + code
together into one unit .
whether the code is considered all plus/minus, but so that they are
consider in the index list, which is needed to make a disj with
something in one branch and nothing in the other different from code
that just has the something (starter/ender enough, mids not needed
for this). Cannot agglomerate + code over | boundaries, because two -
cases might have different + code, and don't want to put the + code
together into one unit. *)
let make_not_marked =
if is_minus
then
(let min = Ast0.get_line disj in
let max = Ast0.get_line_end disj in
let (plus_min,plus_max) = find min (min-1) (max+1) in
if max > plus_max then make_not_marked else (function x -> x))
else make_not_marked in
bind (neutral_mcode starter)
(bind (List.fold_right bind
(List.map make_not_marked (List.map fn code))
option_default)
(neutral_mcode ender)) in
need special cases for dots , nests , and disjs
let ident r k e =
compute_result Ast0.ident e
(match Ast0.unwrap e with
Ast0.DisjId(starter,id_list,_,ender)
| Ast0.ConjId(starter,id_list,_,ender) ->
disj_cases e starter id_list r.VT0.combiner_rec_ident ender
| _ -> k e) in
let expression r k e =
compute_result Ast0.expr e
(match Ast0.unwrap e with
Ast0.NestExpr(starter,exp,ender,whencode,multi) ->
k (Ast0.rewrap e (Ast0.NestExpr(starter,exp,ender,None,multi)))
| Ast0.Edots(dots,whencode) ->
k (Ast0.rewrap e (Ast0.Edots(dots,None)))
| Ast0.DisjExpr(starter,expr_list,_,ender)
| Ast0.ConjExpr(starter,expr_list,_,ender) ->
disj_cases e starter expr_list r.VT0.combiner_rec_expression ender
| _ -> k e) in
let declaration r k e =
compute_result Ast0.decl e
(match Ast0.unwrap e with
Ast0.DisjDecl(starter,decls,_,ender)
| Ast0.ConjDecl(starter,decls,_,ender) ->
disj_cases e starter decls r.VT0.combiner_rec_declaration ender
| Ast0.Init(stg,ty,midattr,id,endattr,eq,ini,sem) ->
bind (match stg with Some stg -> mcode stg | _ -> option_default)
(bind (r.VT0.combiner_rec_typeC ty)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute midattr)
option_default)
(bind (r.VT0.combiner_rec_ident id)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute endattr)
option_default)
(bind (mcode eq)
(bind (r.VT0.combiner_rec_initialiser ini)
(mcode sem)))))))
| Ast0.UnInit(stg,ty,midattr,id,endattr,sem) ->
bind (match stg with Some stg -> mcode stg | _ -> option_default)
(bind (r.VT0.combiner_rec_typeC ty)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute midattr)
option_default)
(bind (r.VT0.combiner_rec_ident id)
(bind
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute endattr)
option_default)
(mcode sem)))))
| _ -> k e) in
let field r k e =
compute_result Ast0.field e
(match Ast0.unwrap e with
Ast0.DisjField(starter,decls,_,ender)
| Ast0.ConjField(starter,decls,_,ender) ->
disj_cases e starter decls r.VT0.combiner_rec_field ender
| Ast0.Fdots(dots,whencode) ->
k (Ast0.rewrap e (Ast0.Fdots(dots,None)))
| Ast0.Field(ty,id,bf,sem) ->
let bitfield (_c, e) = r.VT0.combiner_rec_expression e in
bind (r.VT0.combiner_rec_typeC ty)
(bind (Common.default option_default r.VT0.combiner_rec_ident id)
(bind (Common.default option_default bitfield bf) (mcode sem)))
| _ -> k e) in
let enum_decl r k e =
compute_result Ast0.enum_decl e
(match Ast0.unwrap e with
Ast0.Enum(name,Some(eq,eval)) ->
bind (r.VT0.combiner_rec_ident name)
(bind (mcode eq) (r.VT0.combiner_rec_expression eval))
| Ast0.EnumDots(dots,whencode) ->
k (Ast0.rewrap e (Ast0.EnumDots(dots,None)))
| _ -> k e) in
let param r k e =
compute_result Ast0.param e
(match Ast0.unwrap e with
Ast0.Param(ty,midattr,Some id,attr) ->
needed for the same reason as in the Init and UnInit cases
bind (r.VT0.combiner_rec_typeC ty)
(bind (List.fold_right bind
(List.map r.VT0.combiner_rec_attribute midattr)
option_default)
(bind (r.VT0.combiner_rec_ident id)
(List.fold_right bind
(List.map r.VT0.combiner_rec_attribute attr)
option_default)))
| _ -> k e) in
let typeC r k e =
compute_result Ast0.typeC e
(match Ast0.unwrap e with
Ast0.DisjType(starter,types,_,ender)
| Ast0.ConjType(starter,types,_,ender) ->
disj_cases e starter types r.VT0.combiner_rec_typeC ender
| _ -> k e) in
let initialiser r k i =
compute_result Ast0.ini i
(match Ast0.unwrap i with
Ast0.Idots(dots,whencode) ->
k (Ast0.rewrap i (Ast0.Idots(dots,None)))
| _ -> k i) in
let case_line r k e =
compute_result Ast0.case_line e
(match Ast0.unwrap e with
Ast0.DisjCase(starter,case_list,_,ender) ->
disj_cases e starter case_list r.VT0.combiner_rec_case_line ender
| _ -> k e) in
let statement r k s =
compute_result Ast0.stmt s
(match Ast0.unwrap s with
Ast0.Nest(started,stm_dots,ender,whencode,multi) ->
k (Ast0.rewrap s (Ast0.Nest(started,stm_dots,ender,[],multi)))
| Ast0.Dots(dots,whencode) ->
k (Ast0.rewrap s (Ast0.Dots(dots,[])))
| Ast0.Disj(starter,statement_dots_list,_,ender)
| Ast0.Conj(starter,statement_dots_list,_,ender) ->
disj_cases s starter statement_dots_list
r.VT0.combiner_rec_statement_dots
ender
| Ast0.Decl((info,bef),_) ->
bind (nc_mcode ((),(),info,bef,(),-1)) (k s)
| Ast0.FunDecl((info,bef),_,_,_,_,_,_,_,_,_,_,(ainfo,aft)) ->
let a1 = nc_mcode ((),(),info,bef,(),-1) in
let a2 = nc_mcode ((),(),ainfo,aft,(),-1) in
let b = k s in
bind a1 (bind b a2)
| Ast0.IfThen(start,_,_,_,_,(info,aft,adj))
| Ast0.IfThenElse(start,_,_,_,_,_,_,(info,aft,adj))
| Ast0.Iterator(_,start,_,_,_,(info,aft,adj))
| Ast0.While(start,_,_,_,_,(info,aft,adj))
| Ast0.For(start,_,_,_,_,(info,aft,adj)) ->
let mcode_info (_,_,info,_,_,_) = info in
bind (k s) (nc_mcode ((),(),mcode_info start,aft,(),adj))
| _ -> k s) in
let string_fragment r k s =
compute_result Ast0.string_fragment s (k s) in
let do_top builder r k e = compute_result builder e (k e) in
let combiner =
V0.flat_combiner bind option_default
mcode mcode mcode mcode mcode mcode mcode mcode mcode
mcode mcode mcode mcode mcode
(do_nothing Ast0.dotsExpr) (do_nothing Ast0.dotsInit)
(do_nothing Ast0.dotsParam) (do_nothing Ast0.dotsStmt)
(do_nothing Ast0.dotsDecl) (do_nothing Ast0.dotsField)
(do_nothing Ast0.dotsEnumDecl) (do_nothing Ast0.dotsCase)
(do_nothing Ast0.dotsDefParam)
ident expression (do_nothing Ast0.assignOp) (do_nothing Ast0.binaryOp)
typeC initialiser param declaration field enum_decl
statement (do_nothing Ast0.forinfo) case_line string_fragment
(do_nothing Ast0.attr) (do_nothing Ast0.attr_arg) (do_top Ast0.top) in
combiner.VT0.combiner_rec_top_level code
Traverse the hash tables and find corresponding context nodes that have
the same context children
the same context children *)
let equal_mcode (_,_,info1,_,_,_) (_,_,info2,_,_,_) =
info1.Ast0.pos_info.Ast0.offset = info2.Ast0.pos_info.Ast0.offset
let assignOp_equal_mcode op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
Ast0.SimpleAssign op1', Ast0.SimpleAssign op2' -> equal_mcode op1' op2'
| Ast0.OpAssign op1', Ast0.OpAssign op2' -> equal_mcode op1' op2'
| Ast0.MetaAssign(mv1,_,_), Ast0.MetaAssign(mv2,_,_) -> equal_mcode mv1 mv2
| _ -> false
let binaryOp_equal_mcode op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
Ast0.Arith op1', Ast0.Arith op2' -> equal_mcode op1' op2'
| Ast0.Logical op1', Ast0.Logical op2' -> equal_mcode op1' op2'
| Ast0.MetaBinary(mv1,_,_), Ast0.MetaBinary(mv2,_,_) -> equal_mcode mv1 mv2
| _ -> false
let equal_option e1 e2 =
match (e1,e2) with
(Some x, Some y) -> equal_mcode x y
| (None, None) -> true
| _ -> false
let equal_args args1 args2=
match (args1, args2) with
| (Some args1, Some args2) ->
let (lp1,_,rp1) = args1 in
let (lp2,_,rp2) = args2 in
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (None, None) -> true
| _ -> false
let dots fn d1 d2 =
List.length (Ast0.unwrap d1) = List.length (Ast0.unwrap d2)
let equal_attr_arg a1 a2 =
match (Ast0.unwrap a1, Ast0.unwrap a2) with
(Ast0.MacroAttr(name1),Ast0.MacroAttr(name2)) ->
equal_mcode name1 name2
| (Ast0.MacroAttrArgs(attr1,lp1,args1,rp1),Ast0.MacroAttrArgs(attr2,lp2,args2,rp2)) ->
equal_mcode attr1 attr2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.MetaAttr(name1,_,_),Ast0.MetaAttr(name2,_,_)) ->
equal_mcode name1 name2
| _ -> false
let equal_attribute a1 a2 =
match (Ast0.unwrap a1, Ast0.unwrap a2) with
(Ast0.Attribute(attr1),Ast0.Attribute(attr2)) ->
equal_attr_arg attr1 attr2
| (Ast0.GccAttribute(attr_1,lp11,lp21,arg1,rp11,rp21),
Ast0.GccAttribute(attr_2,lp12,lp22,arg2,rp12,rp22)) ->
equal_mcode attr_1 attr_2 &&
equal_mcode lp11 lp12 && equal_mcode lp21 lp22 &&
equal_mcode rp11 rp12 && equal_mcode rp21 rp22
| _ -> false
let equal_ident i1 i2 =
match (Ast0.unwrap i1,Ast0.unwrap i2) with
(Ast0.Id(name1),Ast0.Id(name2)) -> equal_mcode name1 name2
| (Ast0.MetaId(name1,_,_,_),Ast0.MetaId(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.MetaFunc(name1,_,_),Ast0.MetaFunc(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.MetaLocalFunc(name1,_,_),Ast0.MetaLocalFunc(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.DisjId(starter1,_,mids1,ender1),
Ast0.DisjId(starter2,_,mids2,ender2))
| (Ast0.ConjId(starter1,_,mids1,ender1),
Ast0.ConjId(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.OptIdent(_),Ast0.OptIdent(_)) -> true
| _ -> false
let rec equal_expression e1 e2 =
match (Ast0.unwrap e1,Ast0.unwrap e2) with
(Ast0.Ident(_),Ast0.Ident(_)) -> true
| (Ast0.Constant(const1),Ast0.Constant(const2)) -> equal_mcode const1 const2
| (Ast0.StringConstant(lq1,const1,rq1,isWchar1),Ast0.StringConstant(lq2,const2,rq2,isWchar2))->
equal_mcode lq1 lq2 && equal_mcode rq1 rq2 && isWchar1 = isWchar2
| (Ast0.FunCall(_,lp1,_,rp1),Ast0.FunCall(_,lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Assignment(_,op1,_,_),Ast0.Assignment(_,op2,_,_)) ->
assignOp_equal op1 op2
| (Ast0.Sequence(_,op1,_),Ast0.Sequence(_,op2,_)) ->
equal_mcode op1 op2
| (Ast0.CondExpr(_,why1,_,colon1,_),Ast0.CondExpr(_,why2,_,colon2,_)) ->
equal_mcode why1 why2 && equal_mcode colon1 colon2
| (Ast0.Postfix(_,op1),Ast0.Postfix(_,op2)) -> equal_mcode op1 op2
| (Ast0.Infix(_,op1),Ast0.Infix(_,op2)) -> equal_mcode op1 op2
| (Ast0.Unary(_,op1),Ast0.Unary(_,op2)) -> equal_mcode op1 op2
| (Ast0.Binary(_,op1,_),Ast0.Binary(_,op2,_)) -> binaryOp_equal op1 op2
| (Ast0.Paren(lp1,_,rp1),Ast0.Paren(lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.ArrayAccess(_,lb1,_,rb1),Ast0.ArrayAccess(_,lb2,_,rb2)) ->
equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.RecordAccess(_,pt1,_),Ast0.RecordAccess(_,pt2,_)) ->
equal_mcode pt1 pt2
| (Ast0.RecordPtAccess(_,ar1,_),Ast0.RecordPtAccess(_,ar2,_)) ->
equal_mcode ar1 ar2
| (Ast0.Cast(lp1,_,ar1,rp1,_),Ast0.Cast(lp2,_,ar2,rp2,_)) ->
equal_mcode lp1 lp2 &&
(List.length ar1) = (List.length ar2) &&
List.for_all2 equal_attribute ar1 ar2 &&
equal_mcode rp1 rp2
| (Ast0.SizeOfExpr(szf1,_),Ast0.SizeOfExpr(szf2,_)) ->
equal_mcode szf1 szf2
| (Ast0.SizeOfType(szf1,lp1,_,rp1),Ast0.SizeOfType(szf2,lp2,_,rp2)) ->
equal_mcode szf1 szf2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Delete(dlt1,_),Ast0.Delete(dlt2,_)) ->
equal_mcode dlt1 dlt2
| (Ast0.DeleteArr(dlt1,lb1,rb1,_),Ast0.DeleteArr(dlt2,lb2,rb2,_)) ->
equal_mcode dlt1 dlt2 && equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.New(new1,pp1_opt,lp1,_,rp1,args1_opt), Ast0.New(new2,pp2_opt,lp2,_,rp2,args2_opt)) ->
equal_mcode new1 new2 && equal_args pp1_opt pp2_opt &&
equal_option lp1 lp2 && equal_option rp1 rp2 && equal_args args1_opt args2_opt
| (Ast0.TypeExp(_),Ast0.TypeExp(_)) -> true
| (Ast0.Constructor(lp1,_,rp1,_),Ast0.Constructor(lp2,_,rp2,_)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.MetaErr(name1,_,_),Ast0.MetaErr(name2,_,_))
| (Ast0.MetaExpr(name1,_,_,_,_,_),Ast0.MetaExpr(name2,_,_,_,_,_))
| (Ast0.MetaExprList(name1,_,_,_),Ast0.MetaExprList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.EComma(cm1),Ast0.EComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.DisjExpr(starter1,_,mids1,ender1),
Ast0.DisjExpr(starter2,_,mids2,ender2))
| (Ast0.ConjExpr(starter1,_,mids1,ender1),
Ast0.ConjExpr(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.NestExpr(starter1,_,ender1,_,m1),
Ast0.NestExpr(starter2,_,ender2,_,m2)) ->
equal_mcode starter1 starter2 && equal_mcode ender1 ender2 && m1 = m2
| (Ast0.Edots(dots1,_),Ast0.Edots(dots2,_)) -> equal_mcode dots1 dots2
| (Ast0.OptExp(_),Ast0.OptExp(_)) -> true
| _ -> false
and assignOp_equal op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
| Ast0.SimpleAssign o1, Ast0.SimpleAssign o2 -> equal_mcode o1 o2
| Ast0.OpAssign o1, Ast0.OpAssign o2 -> equal_mcode o1 o2
| Ast0.MetaAssign(mv1,_,_), Ast0.MetaAssign(mv2,_,_) ->
equal_mcode mv1 mv2
| _ -> false
and binaryOp_equal op1 op2 =
match (Ast0.unwrap op1, Ast0.unwrap op2) with
| Ast0.Arith o1, Ast0.Arith o2 -> equal_mcode o1 o2
| Ast0.Logical o1, Ast0.Logical o2 -> equal_mcode o1 o2
| Ast0.MetaBinary(mv1,_,_), Ast0.MetaBinary(mv2,_,_) ->
equal_mcode mv1 mv2
| _ -> false
let equal_typeC t1 t2 =
match (Ast0.unwrap t1,Ast0.unwrap t2) with
(Ast0.ConstVol(cv1,_),Ast0.ConstVol(cv2,_)) -> List.for_all2 equal_mcode cv1 cv2
| (Ast0.BaseType(ty1,stringsa),Ast0.BaseType(ty2,stringsb)) ->
List.for_all2 equal_mcode stringsa stringsb
| (Ast0.Signed(sign1,_),Ast0.Signed(sign2,_)) ->
equal_mcode sign1 sign2
| (Ast0.Pointer(_,star1),Ast0.Pointer(_,star2)) ->
equal_mcode star1 star2
| (Ast0.ParenType(lp1,_,rp1),Ast0.ParenType(lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.FunctionType(_,lp1,_,rp1),Ast0.FunctionType(_,lp2,_,rp2)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Array(_,lb1,_,rb1),Ast0.Array(_,lb2,_,rb2)) ->
equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.Decimal(dec1,lp1,_,comma1,_,rp1),
Ast0.Decimal(dec2,lp2,_,comma2,_,rp2)) ->
equal_mcode dec1 dec2 && equal_mcode lp1 lp2 &&
equal_option comma1 comma2 && equal_mcode rp1 rp2
| (Ast0.EnumName(kind1,key1,_),Ast0.EnumName(kind2,key2,_)) ->
equal_mcode kind1 kind2 && equal_option key1 key2
| (Ast0.EnumDef(_,base1,lb1,_,rb1),Ast0.EnumDef(_,base2,lb2,_,rb2)) ->
let tru1 = equal_mcode lb1 lb2 in
let tru2 = (match (base1,base2) with
(None, None) -> true
| (Some (td1, _), Some (td2, _)) -> equal_mcode td1 td2
| _ -> false) in
let tru3 = equal_mcode rb1 rb2 in
tru1 && tru2 && tru3
| (Ast0.StructUnionName(kind1,_),Ast0.StructUnionName(kind2,_)) ->
equal_mcode kind1 kind2
| (Ast0.StructUnionDef(_,lb1,_,rb1),
Ast0.StructUnionDef(_,lb2,_,rb2)) ->
equal_mcode lb1 lb2 && equal_mcode rb1 rb2
| (Ast0.TypeOfExpr(tf1,lp1,_,rp1),Ast0.TypeOfExpr(tf2,lp2,_,rp2)) ->
equal_mcode tf1 tf2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.TypeOfType(tf1,lp1,_,rp1),Ast0.TypeOfType(tf2,lp2,_,rp2)) ->
equal_mcode tf1 tf2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.TypeName(name1),Ast0.TypeName(name2)) -> equal_mcode name1 name2
| (Ast0.AutoType(auto1),Ast0.AutoType(auto2)) -> equal_mcode auto1 auto2
| (Ast0.MetaType(name1,_,_),Ast0.MetaType(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.DisjType(starter1,_,mids1,ender1),
Ast0.DisjType(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.ConjType(starter1,_,mids1,ender1),
Ast0.ConjType(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.OptType(_),Ast0.OptType(_)) -> true
| _ -> false
let equal_fninfo x y =
match (x,y) with
(Ast0.FStorage(s1),Ast0.FStorage(s2)) -> equal_mcode s1 s2
| (Ast0.FType(_),Ast0.FType(_)) -> true
| (Ast0.FInline(i1),Ast0.FInline(i2)) -> equal_mcode i1 i2
| (Ast0.FAttr(i1),Ast0.FAttr(i2)) -> equal_attribute i1 i2
| _ -> false
let equal_declaration d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.MetaDecl(name1,_,_),Ast0.MetaDecl(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.Init(stg1,_,midattr1,_,endattr1,eq1,_,sem1),
Ast0.Init(stg2,_,midattr2,_,endattr2,eq2,_,sem2)) ->
equal_option stg1 stg2 &&
(List.length midattr1) = (List.length midattr2) &&
List.for_all2 equal_attribute midattr1 midattr2 &&
(List.length endattr1) = (List.length endattr2) &&
List.for_all2 equal_attribute endattr1 endattr2 &&
equal_mcode eq1 eq2 && equal_mcode sem1 sem2
| (Ast0.UnInit(stg1,_,midattr1,_,endattr1,sem1),Ast0.UnInit(stg2,_,midattr2,_,endattr2,sem2)) ->
equal_option stg1 stg2 &&
(List.length midattr1) = (List.length midattr2) &&
List.for_all2 equal_attribute midattr1 midattr2 &&
(List.length endattr1) = (List.length endattr2) &&
List.for_all2 equal_attribute endattr1 endattr2 &&
equal_mcode sem1 sem2
| (Ast0.FunProto(fninfo1,attr1,name1,lp1,p1,va1,rp1,sem1),
Ast0.FunProto(fninfo2,attr2,name2,lp2,p2,va2,rp2,sem2)) ->
let equal_varargs va1 va2 = match (va1,va2) with
| None, None -> true
| Some (c1, e1), Some (c2, e2) ->
equal_mcode c1 c2 && equal_mcode e1 e2
| _ -> false in
(List.length fninfo1) = (List.length fninfo2) &&
List.for_all2 equal_fninfo fninfo1 fninfo2 &&
(List.length attr1) = (List.length attr2) &&
List.for_all2 equal_attribute attr1 attr2 &&
equal_mcode lp1 lp2 && equal_varargs va1 va2 &&
equal_mcode rp1 rp2 && equal_mcode sem1 sem2
| (Ast0.MacroDecl(stg1,nm1,lp1,_,rp1,attr1,sem1),
Ast0.MacroDecl(stg2,nm2,lp2,_,rp2,attr2,sem2)) ->
equal_option stg1 stg2 &&
(List.length attr1) = (List.length attr2) &&
List.for_all2 equal_attribute attr1 attr2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode sem1 sem2
| (Ast0.MacroDeclInit(stg1,nm1,lp1,_,rp1,eq1,_,sem1),
Ast0.MacroDeclInit(stg2,nm2,lp2,_,rp2,eq2,_,sem2)) ->
equal_option stg1 stg2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode eq1 eq2
&& equal_mcode sem1 sem2
| (Ast0.TyDecl(_,attr1,sem1),Ast0.TyDecl(_,attr2,sem2)) ->
(List.length attr1) = (List.length attr2) &&
List.for_all2 equal_attribute attr1 attr2 && equal_mcode sem1 sem2
| (Ast0.OptDecl(_),Ast0.OptDecl(_)) -> true
| (Ast0.DisjDecl(starter1,_,mids1,ender1),
Ast0.DisjDecl(starter2,_,mids2,ender2))
| (Ast0.ConjDecl(starter1,_,mids1,ender1),
Ast0.ConjDecl(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| _ -> false
let equal_field d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.MetaField(name1,_,_),Ast0.MetaField(name2,_,_))
| (Ast0.MetaFieldList(name1,_,_,_),Ast0.MetaFieldList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.Field(_,_,_bf1,sem1),Ast0.Field(_,_,_bf2,sem2)) ->
equal_mcode sem1 sem2
| (Ast0.Fdots(dots1,_),Ast0.Fdots(dots2,_)) -> equal_mcode dots1 dots2
| (Ast0.OptField(_),Ast0.OptField(_)) -> true
| (Ast0.DisjField(starter1,_,mids1,ender1),
Ast0.DisjField(starter2,_,mids2,ender2))
| (Ast0.ConjField(starter1,_,mids1,ender1),
Ast0.ConjField(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| _ -> false
let equal_enum_decl d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.Enum(name1,enum_val1),Ast0.Enum(name2,enum_val2)) ->
equal_ident name1 name2 &&
(match enum_val1,enum_val2 with
None,None -> true
| Some (eq1,val1),Some(eq2,val2) ->
equal_mcode eq1 eq2 && equal_expression val1 val2
| _ -> false)
| (Ast0.EnumComma(cm1),Ast0.EnumComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.EnumDots(dots1,_),Ast0.EnumDots(dots2,_)) -> equal_mcode dots1 dots2
| _ -> false
let equal_designator d1 d2 =
match (d1,d2) with
(Ast0.DesignatorField(dot1,_),Ast0.DesignatorField(dot2,_)) ->
equal_mcode dot1 dot2
| (Ast0.DesignatorIndex(lb1,_,rb1),Ast0.DesignatorIndex(lb2,_,rb2)) ->
(equal_mcode lb1 lb2) && (equal_mcode rb1 rb2)
| (Ast0.DesignatorRange(lb1,_,dots1,_,rb1),
Ast0.DesignatorRange(lb2,_,dots2,_,rb2)) ->
(equal_mcode lb1 lb2) && (equal_mcode dots1 dots2) &&
(equal_mcode rb1 rb2)
| _ -> false
let equal_initialiser i1 i2 =
match (Ast0.unwrap i1,Ast0.unwrap i2) with
(Ast0.MetaInit(name1,_,_),Ast0.MetaInit(name2,_,_)) ->
equal_mcode name1 name2
| (Ast0.MetaInitList(name1,_,_,_),Ast0.MetaInitList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.InitExpr(_),Ast0.InitExpr(_)) -> true
| (Ast0.InitList(lb1,_,rb1,o1),Ast0.InitList(lb2,_,rb2,o2)) ->
(equal_mcode lb1 lb2) && (equal_mcode rb1 rb2)
| (Ast0.InitGccExt(designators1,eq1,_),
Ast0.InitGccExt(designators2,eq2,_)) ->
(List.for_all2 equal_designator designators1 designators2) &&
(equal_mcode eq1 eq2)
| (Ast0.InitGccName(_,eq1,_),Ast0.InitGccName(_,eq2,_)) ->
equal_mcode eq1 eq2
| (Ast0.IComma(cm1),Ast0.IComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.Idots(d1,_),Ast0.Idots(d2,_)) -> equal_mcode d1 d2
| (Ast0.OptIni(_),Ast0.OptIni(_)) -> true
| _ -> false
let equal_parameterTypeDef p1 p2 =
match (Ast0.unwrap p1,Ast0.unwrap p2) with
(Ast0.Param(_,mar1,_,ar1),Ast0.Param(_,mar2,_,ar2)) ->
(List.length ar1) = (List.length ar2) &&
List.for_all2 equal_attribute ar1 ar2 &&
(List.length mar1) = (List.length mar2) &&
List.for_all2 equal_attribute mar1 mar2
| (Ast0.MetaParam(name1,_,_),Ast0.MetaParam(name2,_,_))
| (Ast0.MetaParamList(name1,_,_,_),Ast0.MetaParamList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.PComma(cm1),Ast0.PComma(cm2)) -> equal_mcode cm1 cm2
| (Ast0.Pdots(dots1),Ast0.Pdots(dots2)) -> equal_mcode dots1 dots2
| (Ast0.OptParam(_),Ast0.OptParam(_)) -> true
| _ -> false
let equal_statement s1 s2 =
match (Ast0.unwrap s1,Ast0.unwrap s2) with
(Ast0.FunDecl(_,fninfo1,_,lp1,_,_,rp1,_,lbrace1,_,rbrace1,_),
Ast0.FunDecl(_,fninfo2,_,lp2,_,_,rp2,_,lbrace2,_,rbrace2,_)) ->
(List.length fninfo1) = (List.length fninfo2) &&
List.for_all2 equal_fninfo fninfo1 fninfo2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 &&
equal_mcode lbrace1 lbrace2 && equal_mcode rbrace1 rbrace2
| (Ast0.Decl(_,_),Ast0.Decl(_,_)) -> true
| (Ast0.Seq(lbrace1,_,rbrace1),Ast0.Seq(lbrace2,_,rbrace2)) ->
equal_mcode lbrace1 lbrace2 && equal_mcode rbrace1 rbrace2
| (Ast0.ExprStatement(_,sem1),Ast0.ExprStatement(_,sem2)) ->
equal_mcode sem1 sem2
| (Ast0.IfThen(iff1,lp1,_,rp1,_,_),Ast0.IfThen(iff2,lp2,_,rp2,_,_)) ->
equal_mcode iff1 iff2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.IfThenElse(iff1,lp1,_,rp1,_,els1,_,_),
Ast0.IfThenElse(iff2,lp2,_,rp2,_,els2,_,_)) ->
equal_mcode iff1 iff2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode els1 els2
| (Ast0.While(whl1,lp1,_,rp1,_,_),Ast0.While(whl2,lp2,_,rp2,_,_)) ->
equal_mcode whl1 whl2 && equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Do(d1,_,whl1,lp1,_,rp1,sem1),Ast0.Do(d2,_,whl2,lp2,_,rp2,sem2)) ->
equal_mcode whl1 whl2 && equal_mcode d1 d2 &&
equal_mcode lp1 lp2 && equal_mcode rp1 rp2 && equal_mcode sem1 sem2
| (Ast0.For(fr1,lp1,first1,rp1,_,_),
Ast0.For(fr2,lp2,first2,rp2,_,_)) ->
let first =
match (Ast0.unwrap first1,Ast0.unwrap first2) with
(Ast0.ForExp(_,sem1,_,sem21,_),Ast0.ForExp(_,sem2,_,sem22,_)) ->
equal_mcode sem1 sem2 && equal_mcode sem21 sem22
| (Ast0.ForDecl(_,_,_,sem21,_),Ast0.ForDecl(_,_,_,sem22,_)) ->
equal_mcode sem21 sem22
| (Ast0.ForRange(_,_,_),Ast0.ForRange(_,_,_)) -> true
| _ -> false in
equal_mcode fr1 fr2 && equal_mcode lp1 lp2 &&
first && equal_mcode rp1 rp2
| (Ast0.Iterator(nm1,lp1,_,rp1,_,_),Ast0.Iterator(nm2,lp2,_,rp2,_,_)) ->
equal_mcode lp1 lp2 && equal_mcode rp1 rp2
| (Ast0.Switch(switch1,lp1,_,rp1,lb1,_,_,rb1),
Ast0.Switch(switch2,lp2,_,rp2,lb2,_,_,rb2)) ->
equal_mcode switch1 switch2 && equal_mcode lp1 lp2 &&
equal_mcode rp1 rp2 && equal_mcode lb1 lb2 &&
equal_mcode rb1 rb2
| (Ast0.Break(br1,sem1),Ast0.Break(br2,sem2)) ->
equal_mcode br1 br2 && equal_mcode sem1 sem2
| (Ast0.Continue(cont1,sem1),Ast0.Continue(cont2,sem2)) ->
equal_mcode cont1 cont2 && equal_mcode sem1 sem2
| (Ast0.Label(_,dd1),Ast0.Label(_,dd2)) ->
equal_mcode dd1 dd2
| (Ast0.Goto(g1,_,sem1),Ast0.Goto(g2,_,sem2)) ->
equal_mcode g1 g2 && equal_mcode sem1 sem2
| (Ast0.Return(ret1,sem1),Ast0.Return(ret2,sem2)) ->
equal_mcode ret1 ret2 && equal_mcode sem1 sem2
| (Ast0.ReturnExpr(ret1,_,sem1),Ast0.ReturnExpr(ret2,_,sem2)) ->
equal_mcode ret1 ret2 && equal_mcode sem1 sem2
| (Ast0.Exec(exec1,lang1,_,sem1),Ast0.Exec(exec2,lang2,_,sem2)) ->
equal_mcode exec1 exec2 && equal_mcode lang1 lang2 &&
equal_mcode sem1 sem2
| (Ast0.MetaStmt(name1,_,_),Ast0.MetaStmt(name2,_,_))
| (Ast0.MetaStmtList(name1,_,_,_),Ast0.MetaStmtList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.Disj(starter1,_,mids1,ender1),Ast0.Disj(starter2,_,mids2,ender2))
| (Ast0.Conj(starter1,_,mids1,ender1),Ast0.Conj(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.Nest(starter1,_,ender1,_,m1),Ast0.Nest(starter2,_,ender2,_,m2)) ->
equal_mcode starter1 starter2 && equal_mcode ender1 ender2 && m1 = m2
| (Ast0.Exp(_),Ast0.Exp(_)) -> true
| (Ast0.TopExp(_),Ast0.TopExp(_)) -> true
| (Ast0.Ty(_),Ast0.Ty(_)) -> true
| (Ast0.TopId(_),Ast0.TopId(_)) -> true
| (Ast0.TopInit(_),Ast0.TopInit(_)) -> true
| (Ast0.Dots(d1,_),Ast0.Dots(d2,_)) -> equal_mcode d1 d2
| (Ast0.Include(inc1,name1),Ast0.Include(inc2,name2)) ->
equal_mcode inc1 inc2 && equal_mcode name1 name2
| (Ast0.MetaInclude(inc1,name1),Ast0.MetaInclude(inc2,name2)) ->
equal_mcode inc1 inc2
| (Ast0.Undef(def1,_),Ast0.Undef(def2,_)) ->
equal_mcode def1 def2
| (Ast0.Define(def1,_,_,_),Ast0.Define(def2,_,_,_)) ->
equal_mcode def1 def2
| (Ast0.Pragma(prg1,_,_),Ast0.Pragma(prg2,_,_)) ->
equal_mcode prg1 prg2
| (Ast0.OptStm(_),Ast0.OptStm(_)) -> true
| _ -> false
let equal_case_line c1 c2 =
match (Ast0.unwrap c1,Ast0.unwrap c2) with
(Ast0.Default(def1,colon1,_),Ast0.Default(def2,colon2,_)) ->
equal_mcode def1 def2 && equal_mcode colon1 colon2
| (Ast0.Case(case1,_,colon1,_),Ast0.Case(case2,_,colon2,_)) ->
equal_mcode case1 case2 && equal_mcode colon1 colon2
| (Ast0.DisjCase(starter1,_,mids1,ender1),
Ast0.DisjCase(starter2,_,mids2,ender2)) ->
equal_mcode starter1 starter2 &&
List.for_all2 equal_mcode mids1 mids2 &&
equal_mcode ender1 ender2
| (Ast0.OptCase(_),Ast0.OptCase(_)) -> true
| _ -> false
let equal_define_param d1 d2 =
match (Ast0.unwrap d1,Ast0.unwrap d2) with
(Ast0.DParam _,Ast0.DParam _) -> true
| (Ast0.MetaDParamList(name1,_,_,_),Ast0.MetaDParamList(name2,_,_,_)) ->
equal_mcode name1 name2
| (Ast0.DPComma cm1,Ast0.DPComma cm2) -> equal_mcode cm1 cm2
| (Ast0.DPdots d1,Ast0.DPdots d2) -> equal_mcode d1 d2
| (Ast0.OptDParam(_),Ast0.OptDParam(_)) -> true
| _ -> false
let equal_top_level t1 t2 =
match (Ast0.unwrap t1,Ast0.unwrap t2) with
(Ast0.NONDECL(_),Ast0.NONDECL(_)) -> true
| (Ast0.FILEINFO(old_file1,new_file1),Ast0.FILEINFO(old_file2,new_file2)) ->
equal_mcode old_file1 old_file2 && equal_mcode new_file1 new_file2
| (Ast0.CODE(_),Ast0.CODE(_)) -> true
| (Ast0.ERRORWORDS(_),Ast0.ERRORWORDS(_)) -> true
| _ -> false
let root_equal e1 e2 =
match (e1,e2) with
(Ast0.DotsExprTag(d1),Ast0.DotsExprTag(d2)) -> dots equal_expression d1 d2
| (Ast0.DotsParamTag(d1),Ast0.DotsParamTag(d2)) ->
dots equal_parameterTypeDef d1 d2
| (Ast0.DotsStmtTag(d1),Ast0.DotsStmtTag(d2)) -> dots equal_statement d1 d2
| (Ast0.DotsDeclTag(d1),Ast0.DotsDeclTag(d2)) -> dots equal_declaration d1 d2
| (Ast0.DotsFieldTag(d1),Ast0.DotsFieldTag(d2)) -> dots equal_field d1 d2
| (Ast0.DotsEnumDeclTag(d1),Ast0.DotsEnumDeclTag(d2)) ->
dots equal_field d1 d2
| (Ast0.DotsCaseTag(d1),Ast0.DotsCaseTag(d2)) -> dots equal_case_line d1 d2
| (Ast0.DotsDefParamTag(d1),Ast0.DotsDefParamTag(d2)) ->
dots equal_define_param d1 d2
| (Ast0.IdentTag(i1),Ast0.IdentTag(i2)) -> equal_ident i1 i2
| (Ast0.ExprTag(e1),Ast0.ExprTag(e2)) -> equal_expression e1 e2
| (Ast0.AssignOpTag(e1),Ast0.AssignOpTag(e2)) -> assignOp_equal e1 e2
| (Ast0.BinaryOpTag(e1),Ast0.BinaryOpTag(e2)) -> binaryOp_equal e1 e2
| (Ast0.ArgExprTag(d),_) -> failwith "not possible - iso only"
| (Ast0.TypeCTag(t1),Ast0.TypeCTag(t2)) -> equal_typeC t1 t2
| (Ast0.ParamTag(p1),Ast0.ParamTag(p2)) -> equal_parameterTypeDef p1 p2
| (Ast0.InitTag(d1),Ast0.InitTag(d2)) -> equal_initialiser d1 d2
| (Ast0.DeclTag(d1),Ast0.DeclTag(d2)) -> equal_declaration d1 d2
| (Ast0.FieldTag(d1),Ast0.FieldTag(d2)) -> equal_field d1 d2
| (Ast0.EnumDeclTag(d1),Ast0.EnumDeclTag(d2)) -> equal_enum_decl d1 d2
| (Ast0.StmtTag(s1),Ast0.StmtTag(s2)) -> equal_statement s1 s2
| (Ast0.TopTag(t1),Ast0.TopTag(t2)) -> equal_top_level t1 t2
| (Ast0.IsoWhenTag(_),_) | (_,Ast0.IsoWhenTag(_))
| (Ast0.IsoWhenTTag(_),_) | (_,Ast0.IsoWhenTTag(_))
| (Ast0.IsoWhenFTag(_),_) | (_,Ast0.IsoWhenFTag(_)) ->
failwith "only within iso phase"
| _ -> false
let default_context _ =
Ast0.CONTEXT(ref(Ast.NOTHING,
Ast0.default_token_info,Ast0.default_token_info))
let traverse minus_table plus_table =
Hashtbl.iter
(function key ->
function (e,l) ->
try
let (plus_e,plus_l) = Hashtbl.find plus_table key in
if root_equal e plus_e &&
List.for_all (function x -> x)
(List.map2 Common.equal_set l plus_l)
then
let i = Ast0.fresh_index() in
(set_index e i; set_index plus_e i;
set_mcodekind e (default_context());
set_mcodekind plus_e (default_context()))
with Not_found -> ())
minus_table
contextify the whencode
let contextify_all =
let bind x y = () in
let option_default = () in
let mcode x = () in
let donothing r k e = Ast0.set_mcodekind e (default_context()); k e in
V0.flat_combiner bind option_default
mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode mcode
mcode mcode
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing donothing donothing
donothing donothing donothing donothing donothing
let contextify_whencode =
let bind x y = () in
let option_default = () in
let expression r k e =
k e;
match Ast0.unwrap e with
Ast0.NestExpr(_,_,_,Some (_,_,whencode),_)
| Ast0.Edots(_,Some (_,_,whencode)) ->
contextify_all.VT0.combiner_rec_expression whencode
| _ -> () in
let initialiser r k i =
match Ast0.unwrap i with
Ast0.Idots(dots,Some (_,_,whencode)) ->
contextify_all.VT0.combiner_rec_initialiser whencode
| _ -> k i in
let whencode = function
Ast0.WhenNot (_,_,sd) ->
contextify_all.VT0.combiner_rec_statement_dots sd
| Ast0.WhenAlways (_,_,s) -> contextify_all.VT0.combiner_rec_statement s
| Ast0.WhenModifier _ -> ()
| Ast0.WhenNotTrue(_,_,e) -> contextify_all.VT0.combiner_rec_expression e
| Ast0.WhenNotFalse(_,_,e) -> contextify_all.VT0.combiner_rec_expression e
in
let statement r k (s : Ast0.statement) =
k s;
match Ast0.unwrap s with
Ast0.Nest(_,_,_,whn,_)
| Ast0.Dots(_,whn) -> List.iter whencode whn
| _ -> () in
let combiner =
V0.combiner bind option_default
{V0.combiner_functions with
VT0.combiner_exprfn = expression;
VT0.combiner_initfn = initialiser;
VT0.combiner_stmtfn = statement} in
combiner.VT0.combiner_rec_top_level
the first int list is the tokens in the node , the second is the tokens
in the descendants
in the descendants *)
let minus_table =
(Hashtbl.create(50) : (int list, Ast0.anything * int list list) Hashtbl.t)
let plus_table =
(Hashtbl.create(50) : (int list, Ast0.anything * int list list) Hashtbl.t)
let iscode t =
match Ast0.unwrap t with
Ast0.NONDECL(_) -> true
| Ast0.FILEINFO(_) -> true
| Ast0.ERRORWORDS(_) -> false
| Ast0.CODE(_) -> true
| Ast0.TOPCODE(_)
| Ast0.OTHER(_) -> failwith "unexpected top level code"
let concat = function
[] -> []
| [s] -> [s]
| l ->
let rec loop = function
[] -> []
| x::rest ->
(match Ast0.unwrap x with
Ast0.NONDECL(s) -> let stms = loop rest in s::stms
| Ast0.CODE(ss) ->
let stms = loop rest in
(Ast0.unwrap ss)@stms
| _ -> failwith "plus code is being discarded") in
let res =
Compute_lines.compute_statement_dots_lines false
(Ast0.rewrap (List.hd l) (loop l)) in
[Ast0.rewrap res (Ast0.CODE res)]
let collect_up_to m plus =
let minfo = Ast0.get_info m in
let mend = minfo.Ast0.pos_info.Ast0.logical_end in
let rec loop = function
[] -> ([],[])
| p::plus ->
let pinfo = Ast0.get_info p in
let pstart = pinfo.Ast0.pos_info.Ast0.logical_start in
if pstart > mend
then ([],p::plus)
else let (plus,rest) = loop plus in (p::plus,rest) in
let (plus,rest) = loop plus in
(concat plus,rest)
let realign minus plus =
let rec loop = function
([],_) -> failwith "not possible, some context required"
| ([m],p) -> ([m],concat p)
| (m::minus,plus) ->
let (p,plus) = collect_up_to m plus in
let (minus,plus) = loop (minus,plus) in
(m::minus,p@plus) in
loop (minus,plus)
let isonly f l = match Ast0.unwrap l with [s] -> f s | _ -> false
let isall f l = List.for_all (isonly f) l
let isany f l = List.exists (isonly f) l
let rec is_exp s =
match Ast0.unwrap s with
Ast0.Exp(e) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_exp stmts
| Ast0.Conj(_,s::_,_,_) ->
the parser ensures that if the matches a
statement , the statement is in the first position
statement, the statement is in the first position *)
isonly is_exp s
| _ -> false
let rec is_ty s =
match Ast0.unwrap s with
Ast0.Ty(e) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_ty stmts
| Ast0.Conj(_,s::_,_,_) ->
the parser ensures that if the matches a
statement , the statement is in the first position
statement, the statement is in the first position *)
isonly is_ty s
| _ -> false
let rec is_init s =
match Ast0.unwrap s with
Ast0.TopInit(e) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_init stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_init stmts
| _ -> false
let rec is_decl s =
match Ast0.unwrap s with
Ast0.Decl(_,e) -> true
| Ast0.FunDecl(_,_,_,_,_,_,_,_,_,_,_,_) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_decl stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_decl stmts
| _ -> false
let rec is_fndecl s =
match Ast0.unwrap s with
Ast0.FunDecl(_,_,_,_,_,_,_,_,_,_,_,_) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_fndecl stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_fndecl stmts
| _ -> false
let rec is_toplevel s =
match Ast0.unwrap s with
Ast0.Decl(_,e) -> true
| Ast0.FunDecl(_,_,_,_,_,_,_,_,_,_,_,_) -> true
| Ast0.Disj(_,stmts,_,_) -> isall is_toplevel stmts
| Ast0.Conj(_,stmts,_,_) -> isany is_toplevel stmts
| Ast0.ExprStatement(Some fc,_) ->
(match Ast0.unwrap fc with
Ast0.FunCall(_,_,_,_) -> true
| _ -> false)
| Ast0.Include(_,_) -> true
| Ast0.Undef(_,_) -> true
| Ast0.Pragma(_,_,_) -> true
| Ast0.Define(_,_,_,_) -> true
| _ -> false
consider code and topcode to be the same ; difference handled
in top_level.ml
in top_level.ml *)
let check_compatible m p =
let fail _ =
failwith
(Printf.sprintf
"incompatible minus and plus code starting on lines %d and %d"
(Ast0.get_line m) (Ast0.get_line p)) in
match (Ast0.unwrap m, Ast0.unwrap p) with
(Ast0.NONDECL(decl1),Ast0.NONDECL(decl2)) ->
if not (is_decl decl1 && is_decl decl2)
then fail()
| (Ast0.NONDECL(decl1),Ast0.CODE(code2)) ->
let v1 = is_decl decl1 in
let v2 = List.for_all is_toplevel (Ast0.unwrap code2) in
if !Flag.make_hrule = None && v1 && not v2
then fail()
| (Ast0.CODE(code1),Ast0.NONDECL(decl2)) ->
let v1 = List.for_all is_toplevel (Ast0.unwrap code1) in
let v2 = is_decl decl2 in
if v1 && not v2
then fail()
| (Ast0.CODE(code1),Ast0.CODE(code2)) ->
let v1 = isonly is_init code1 in
let v2a = isonly is_init code2 in
let v2b = isonly is_exp code2 in
if v1
then (if not (v2a || v2b) then fail())
else
let testers = [is_exp;is_ty] in
List.iter
(function tester ->
let v1 = isonly tester code1 in
let v2 = isonly tester code2 in
if (v1 && not v2) || (!Flag.make_hrule = None && v2 && not v1)
then fail())
testers;
let v1 = isonly is_fndecl code1 in
let v2 = List.for_all is_toplevel (Ast0.unwrap code2) in
if !Flag.make_hrule = None && v1 && not v2
then fail()
| (Ast0.FILEINFO(_,_),Ast0.FILEINFO(_,_)) -> ()
| (Ast0.OTHER(_),Ast0.OTHER(_)) -> ()
| _ -> fail()
let check_complete m =
match Ast0.unwrap m with
Ast0.NONDECL(code) ->
if is_exp code || is_ty code
then
failwith
(Printf.sprintf "invalid minus starting on line %d"
(Ast0.get_line m))
| Ast0.CODE(code) ->
if isonly is_exp code || isonly is_ty code
then
failwith
(Printf.sprintf "invalid minus starting on line %d"
(Ast0.get_line m))
| _ -> ()
let context_neg minus plus =
Hashtbl.clear minus_table;
Hashtbl.clear plus_table;
List.iter contextify_whencode minus;
let (minus,plus) = realign minus plus in
let rec loop = function
([],[]) -> []
| ([],l) ->
failwith (Printf.sprintf "%d plus things remaining" (List.length l))
| (minus,[]) ->
List.iter check_complete minus;
plus_lines := [];
let _ =
List.map
(function m ->
classify true
(function _ ->
Ast0.MINUS(ref(Ast.NOREPLACEMENT,Ast0.default_token_info)))
minus_table m)
minus in
[]
| (((m::minus) as mall),((p::plus) as pall)) ->
let minfo = Ast0.get_info m in
let pinfo = Ast0.get_info p in
let mstart = minfo.Ast0.pos_info.Ast0.logical_start in
let mend = minfo.Ast0.pos_info.Ast0.logical_end in
let pstart = pinfo.Ast0.pos_info.Ast0.logical_start in
let pend = pinfo.Ast0.pos_info.Ast0.logical_end in
if (iscode m || iscode p) &&
(mstart <= pstart && mend >= pstart) ||
then
begin
let i = Ast0.fresh_index() in
Ast0.set_index m i; Ast0.set_index p i;
check_compatible m p;
collect_plus_lines p;
let _ =
classify true
(function _ ->
Ast0.MINUS(ref(Ast.NOREPLACEMENT,Ast0.default_token_info)))
minus_table m in
let _ = classify false (function c -> Ast0.PLUS c) plus_table p in
traverse minus_table plus_table;
(m,p)::loop(minus,plus)
end
else
if not(iscode m || iscode p)
then loop(minus,plus)
else
if mstart < pstart
then
begin
plus_lines := [];
let _ =
classify true
(function _ ->
Ast0.MINUS(ref(Ast.NOREPLACEMENT,
Ast0.default_token_info)))
minus_table m in
loop(minus,pall)
end
else loop(mall,plus) in
loop(minus,plus)
|
9f2b14a105b255d553f50e04ca971100f93ad3a814cc39da1beeb8161d878660 | tschady/advent-of-code | d06.clj | (ns aoc.2017.d06
(:require [aoc.coll-util :refer [first-duplicate]]
[aoc.file-util :as file-util]))
(def input (file-util/read-ints "2017/d06.txt"))
(defn realloc-blocks
"Return next cycle of balancing memory blocks, by redistributing the
blocks from the max bank, one-by-one, in order of index after the
maximum bank, wrapping around the memory vector."
[memory]
(let [blocks (apply max memory)
max-bank (.indexOf memory blocks)
inc-banks (->> (range (count memory))
cycle
(drop (inc max-bank))
(take blocks))
cleared-memory (assoc memory max-bank 0)]
(reduce #(update % %2 inc) cleared-memory inc-banks)))
(defn part-1 [memory] (->> memory
(iterate realloc-blocks)
first-duplicate
second
second))
(defn part-2 [memory] (->> memory
(iterate realloc-blocks)
first-duplicate
second
(#(- (second %) (first %)))))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/63db07edf0c60f2a575f9f4a1852d3b06dbb82f9/src/aoc/2017/d06.clj | clojure | (ns aoc.2017.d06
(:require [aoc.coll-util :refer [first-duplicate]]
[aoc.file-util :as file-util]))
(def input (file-util/read-ints "2017/d06.txt"))
(defn realloc-blocks
"Return next cycle of balancing memory blocks, by redistributing the
blocks from the max bank, one-by-one, in order of index after the
maximum bank, wrapping around the memory vector."
[memory]
(let [blocks (apply max memory)
max-bank (.indexOf memory blocks)
inc-banks (->> (range (count memory))
cycle
(drop (inc max-bank))
(take blocks))
cleared-memory (assoc memory max-bank 0)]
(reduce #(update % %2 inc) cleared-memory inc-banks)))
(defn part-1 [memory] (->> memory
(iterate realloc-blocks)
first-duplicate
second
second))
(defn part-2 [memory] (->> memory
(iterate realloc-blocks)
first-duplicate
second
(#(- (second %) (first %)))))
| |
5201cd6452e70896f6f61ba01ba04a2644ab3098e11a3c4170d19e3a15b3d7c4 | tommaisey/aeon | pv-conformal-map.help.scm | ;; (pv-conformal-map buffer real imag)
;; Applies the conformal mapping z send (z-a)/(1-za*) to the phase
;; vocoder bins z with a given by the real and imag imputs to the
UGen .
;; See
;; buffer - buffer number of buffer to act on, passed in through a chain
;; real - real part of a.
;; imag - imaginary part of a.
(with-sc3
(lambda (fd)
(async fd (b-alloc 10 1024 1))
(async fd (b-alloc 0 2048 1))))
(audition
(out 0 (pan2
(ifft*
(pv-conformal-map
(fft* 10 (mul (sound-in 0) 0.5)) (mouse-x kr -1 1 0 0.1)
(mouse-y kr -1 1 0 0.1)))
0
1)))
(let* ((signal (lambda (n)
(let* ((o (sin-osc kr (mix-fill n (lambda (_) (rand 0.1 0.5))) 0))
(a (mul (make-mce (list 1 1.1 1.5 1.78 2.45 6.7)) 220))
(f (mul-add o 10 a)))
(mix (mul (lf-saw ar f 0) 0.3)))))
(mapped (lambda (n)
(let* ((c0 (fft* 0 (signal n)))
(x (mouse-x kr 0.01 2.0 1.0 0.1))
(y (mouse-y kr 0.01 10.0 1.0 0.1))
(c1 (pv-conformal-map c0 x y)))
(ifft* c1))))
(s (mapped 3))
(t (mul-add (comb-n s 0.1 0.1 10) 0.5 s)))
(audition (out 0 (pan2 t 0 1))))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/fft/pv-conformal-map.help.scm | scheme | (pv-conformal-map buffer real imag)
Applies the conformal mapping z send (z-a)/(1-za*) to the phase
vocoder bins z with a given by the real and imag imputs to the
See
buffer - buffer number of buffer to act on, passed in through a chain
real - real part of a.
imag - imaginary part of a. |
UGen .
(with-sc3
(lambda (fd)
(async fd (b-alloc 10 1024 1))
(async fd (b-alloc 0 2048 1))))
(audition
(out 0 (pan2
(ifft*
(pv-conformal-map
(fft* 10 (mul (sound-in 0) 0.5)) (mouse-x kr -1 1 0 0.1)
(mouse-y kr -1 1 0 0.1)))
0
1)))
(let* ((signal (lambda (n)
(let* ((o (sin-osc kr (mix-fill n (lambda (_) (rand 0.1 0.5))) 0))
(a (mul (make-mce (list 1 1.1 1.5 1.78 2.45 6.7)) 220))
(f (mul-add o 10 a)))
(mix (mul (lf-saw ar f 0) 0.3)))))
(mapped (lambda (n)
(let* ((c0 (fft* 0 (signal n)))
(x (mouse-x kr 0.01 2.0 1.0 0.1))
(y (mouse-y kr 0.01 10.0 1.0 0.1))
(c1 (pv-conformal-map c0 x y)))
(ifft* c1))))
(s (mapped 3))
(t (mul-add (comb-n s 0.1 0.1 10) 0.5 s)))
(audition (out 0 (pan2 t 0 1))))
|
6c85c576e08f981907e3359d5480f6a81e8ddd7fa704152c8157dc267130d365 | ocsigen/lwt | try_1.ml | let _ =
try%lwt
5
with _ -> Lwt.return_unit;;
| null | https://raw.githubusercontent.com/ocsigen/lwt/aa9d18a550da444e1a889867dad52a32f162b262/test/ppx_expect/cases/try_1.ml | ocaml | let _ =
try%lwt
5
with _ -> Lwt.return_unit;;
| |
698ca3672f4b68d68b0da2399bcd55b0157657713e4b84b0f949f46ac63b1934 | hidaris/thinking-dumps | num.rkt | #lang typed/racket
(define-type num
(U Zero
One_more_than))
(struct Zero () #:transparent)
(struct One_more_than ([v : num])
#:transparent)
| null | https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/typed-racket/01-building-blocks/num.rkt | racket | #lang typed/racket
(define-type num
(U Zero
One_more_than))
(struct Zero () #:transparent)
(struct One_more_than ([v : num])
#:transparent)
| |
aab62d12c0d2ecabfdb5e4165a1ff7815b21ff451de104d31b0ae9f2249a839c | jayunit100/RudolF | vennnmr.clj |
(use 'clojure.contrib.str-utils2
; 'clojure.contrib.generic.functor
'clojure.stacktrace)
parse bmrb shift
;; parse shiftx shifts
;; compare shifts
;; load structure
;; display structure in jmol
;; plot comparison on jmol structure
(defn convert-types
""
[the-map]
{:id (Integer/parseInt (the-map :id))
:resid (Integer/parseInt (the-map :resid))
:restype (the-map :restype)
:atomtype (the-map :atomtype)
:nucleus (the-map :nucleus)
:shift (Float/parseFloat (the-map :shift))
:error (the-map :error)
:ambiguity (Integer/parseInt (the-map :ambiguity))})
(defn parse-bmrb
"String -> [BMRBLine]"
[string]
(let [lines (split-lines string)
header (first lines) ; ignore header ??
headings [:id :resid :restype :atomtype :nucleus :shift :error :ambiguity]]
continue with the second line
(convert-types
(zipmap headings (.split (trim line) "\\s+"))))))
(defn semantic-bmrb ;; is this function right?
"[BMRBLine] -> Something"
[p]
(let [f (fn [b n] (assoc-in b [(p :resid) (p :atomtype)] (p :shift)))]
(reduce f {} parsed)))
(def shiftx-parsed (parse-bmrb (slurp "data/venn_nmr_pre/2L8L_shifts_shiftx.txt")))
(def bmrb-parsed (parse-bmrb (slurp "data/venn_nmr_pre/2L8L_shifts_bmrb.txt")))
(defn my-example
""
[mpath]
(parse-bmrb (slurp mpath)))
| null | https://raw.githubusercontent.com/jayunit100/RudolF/8936bafbb30c65c78b820062dec550ceeea4b3a4/bioclojure/src/sandbox/vennnmr.clj | clojure | 'clojure.contrib.generic.functor
parse shiftx shifts
compare shifts
load structure
display structure in jmol
plot comparison on jmol structure
ignore header ??
is this function right? |
(use 'clojure.contrib.str-utils2
'clojure.stacktrace)
parse bmrb shift
(defn convert-types
""
[the-map]
{:id (Integer/parseInt (the-map :id))
:resid (Integer/parseInt (the-map :resid))
:restype (the-map :restype)
:atomtype (the-map :atomtype)
:nucleus (the-map :nucleus)
:shift (Float/parseFloat (the-map :shift))
:error (the-map :error)
:ambiguity (Integer/parseInt (the-map :ambiguity))})
(defn parse-bmrb
"String -> [BMRBLine]"
[string]
(let [lines (split-lines string)
headings [:id :resid :restype :atomtype :nucleus :shift :error :ambiguity]]
continue with the second line
(convert-types
(zipmap headings (.split (trim line) "\\s+"))))))
"[BMRBLine] -> Something"
[p]
(let [f (fn [b n] (assoc-in b [(p :resid) (p :atomtype)] (p :shift)))]
(reduce f {} parsed)))
(def shiftx-parsed (parse-bmrb (slurp "data/venn_nmr_pre/2L8L_shifts_shiftx.txt")))
(def bmrb-parsed (parse-bmrb (slurp "data/venn_nmr_pre/2L8L_shifts_bmrb.txt")))
(defn my-example
""
[mpath]
(parse-bmrb (slurp mpath)))
|
cf3a4b03e9c7018d5c8dc99d8b1e78eed00b32e76cf8b9ea8f4677d800f58069 | duo-lang/duo-lang | Typecheck.hs | module Typecheck where
import Options (DebugFlags(..))
import Syntax.CST.Names
import Driver.Driver (runCompilationModule, defaultInferenceOptions, adjustModulePath)
import Driver.Definition (defaultDriverState, execDriverM, DriverState(..), setPrintGraphOpts, setDebugOpts, addModule)
import Pretty.Errors (printLocatedReport)
import Data.Text qualified as T
import System.Exit (exitWith, ExitCode (ExitFailure))
import Data.List (intersperse)
import Data.Foldable (fold)
import Data.Text.IO qualified as T
import Control.Monad.IO.Class (liftIO)
import Parser.Definition (runFileParser)
import Syntax.CST.Program ( Module (..))
import Parser.Program (moduleP)
import Control.Monad.Except (throwError)
import Errors
runTypecheck :: DebugFlags -> Either FilePath ModuleName -> IO ()
runTypecheck flags modId = do
(res ,warnings) <- case modId of
Left fp -> do
file <- liftIO $ T.readFile fp
execDriverM driverState $ do
mod <- runFileParser fp (moduleP fp) file ErrParser
case adjustModulePath mod fp of
Right mod -> do
let mn = mod.mod_name
addModule mod
res <- runCompilationModule mn
pure (mn,res)
Left e -> throwError e
Right mn -> execDriverM driverState $ runCompilationModule mn >>= \res -> pure (mn, res)
mapM_ printLocatedReport warnings
case res of
Left errs -> do
mapM_ printLocatedReport errs
exitWith (ExitFailure 1)
Right ((mn,_), MkDriverState {}) -> do
putStrLn $ "Module " <> T.unpack (fold (intersperse "." (mn.mn_path ++ [mn.mn_base]))) <> " typechecks"
return ()
where
driverState = defaultDriverState { drvOpts = infOpts }
infOpts = (if flags.df_printGraphs then setPrintGraphOpts else id) infOpts'
infOpts' = (if flags.df_debug then setDebugOpts else id) defaultInferenceOptions
| null | https://raw.githubusercontent.com/duo-lang/duo-lang/62305c16e219477d6e33287a7752c258b5342c3e/app/Typecheck.hs | haskell | module Typecheck where
import Options (DebugFlags(..))
import Syntax.CST.Names
import Driver.Driver (runCompilationModule, defaultInferenceOptions, adjustModulePath)
import Driver.Definition (defaultDriverState, execDriverM, DriverState(..), setPrintGraphOpts, setDebugOpts, addModule)
import Pretty.Errors (printLocatedReport)
import Data.Text qualified as T
import System.Exit (exitWith, ExitCode (ExitFailure))
import Data.List (intersperse)
import Data.Foldable (fold)
import Data.Text.IO qualified as T
import Control.Monad.IO.Class (liftIO)
import Parser.Definition (runFileParser)
import Syntax.CST.Program ( Module (..))
import Parser.Program (moduleP)
import Control.Monad.Except (throwError)
import Errors
runTypecheck :: DebugFlags -> Either FilePath ModuleName -> IO ()
runTypecheck flags modId = do
(res ,warnings) <- case modId of
Left fp -> do
file <- liftIO $ T.readFile fp
execDriverM driverState $ do
mod <- runFileParser fp (moduleP fp) file ErrParser
case adjustModulePath mod fp of
Right mod -> do
let mn = mod.mod_name
addModule mod
res <- runCompilationModule mn
pure (mn,res)
Left e -> throwError e
Right mn -> execDriverM driverState $ runCompilationModule mn >>= \res -> pure (mn, res)
mapM_ printLocatedReport warnings
case res of
Left errs -> do
mapM_ printLocatedReport errs
exitWith (ExitFailure 1)
Right ((mn,_), MkDriverState {}) -> do
putStrLn $ "Module " <> T.unpack (fold (intersperse "." (mn.mn_path ++ [mn.mn_base]))) <> " typechecks"
return ()
where
driverState = defaultDriverState { drvOpts = infOpts }
infOpts = (if flags.df_printGraphs then setPrintGraphOpts else id) infOpts'
infOpts' = (if flags.df_debug then setDebugOpts else id) defaultInferenceOptions
| |
09ccdde28ce272c7c0d7a1c5235f08a9b2a58832b59565d80a7e54796595cf89 | janestreet/base_quickcheck | test_test.ml | open! Import
module type S = Test.S
module Config = Test.Config
let default_config = Test.default_config
let%expect_test ("default_config" [@tags "64-bits-only"]) =
Ref.set_temporarily sexp_style To_string_hum ~f:(fun () ->
print_s [%sexp (default_config : Config.t)]);
[%expect
{|
((seed (Deterministic "an arbitrary but deterministic string"))
(test_count 10000) (shrink_count 10000)
(sizes
(0 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 0 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 0 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 0 1 2 3 4 5 6 ...))) |}]
;;
let%expect_test ("default_config" [@tags "32-bits-only"]) =
Ref.set_temporarily sexp_style To_string_hum ~f:(fun () ->
print_s [%sexp (default_config : Config.t)]);
[%expect
{|
((seed (Deterministic "an arbitrary but deterministic string"))
(test_count 1000) (shrink_count 10000)
(sizes
(0 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 0 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 0 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 0 1 2 3 4 5 6 ...))) |}]
;;
let run = Test.run
let result = Test.result
let run_exn = Test.run_exn
let%expect_test "run_exn" =
let module M = struct
type t = bool option list [@@deriving sexp_of]
let quickcheck_generator = Generator.list (Generator.option Generator.bool)
let quickcheck_shrinker = Shrinker.list (Shrinker.option Shrinker.bool)
end
in
let module M_without_shrinker = struct
include M
let quickcheck_shrinker = Shrinker.atomic
end
in
(* success *)
let count = ref 0 in
require_does_not_raise [%here] (fun () ->
Test.run_exn (module M) ~f:(fun _ -> Int.incr count));
require
[%here]
(!count = Test.default_config.test_count)
~if_false_then_print_s:(lazy [%message (!count : int)]);
[%expect {| |}];
(* failure *)
let failure list = assert (List.is_sorted list ~compare:[%compare: bool option]) in
(* large sizes to demonstrate shrinking *)
let config =
{ Test.default_config with sizes = Sequence.cycle_list_exn [ 10; 20; 30 ] }
in
(* simple failure *)
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn ~config ~f:failure (module M));
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input ((false) ()))
(error "Assert_failure test_test.ml:LINE:COL")) |}];
(* failure without shrinking *)
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn ~config ~f:failure (module M_without_shrinker));
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input (() () (false) (true) (false) ()))
(error "Assert_failure test_test.ml:LINE:COL")) |}];
(* failure from examples *)
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn
~config
~f:failure
~examples:[ [ Some true; Some true; None; Some true; Some true ] ]
(module M));
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input ((true) ()))
(error "Assert_failure test_test.ml:LINE:COL")) |}];
(* failure from examples without shrinking *)
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn
~config
~f:failure
(module M_without_shrinker)
~examples:[ [ Some true; Some true; None; Some true; Some true ] ]);
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input ((true) (true) () (true) (true)))
(error "Assert_failure test_test.ml:LINE:COL")) |}]
;;
let with_sample = Test.with_sample
let with_sample_exn = Test.with_sample_exn
let%expect_test "with_sample_exn" =
let generator = Generator.list (Generator.option Generator.bool) in
with_sample_exn
generator
~config:{ Test.default_config with test_count = 20 }
~f:(fun sample ->
Sequence.iter sample ~f:(fun value ->
Core.print_s [%sexp (value : bool option list)]));
[%expect
{|
()
()
(() (true))
(() (true) (false))
()
((true))
((true))
((true))
()
(() (false) (true))
(() () (false) (true) () (true) () ())
((true) () () () (true) (false) ())
(() () (true) () () (false) (false))
(() () (true) (true) (false) () (true) ())
()
()
((true) (true) () (false) (false) () () () () (true) () () (true) (false)
(false) ())
((true) (false) (true))
((false) () () (false) () () () (false) (false) () (true) () () () ()
(false))
() |}]
;;
| null | https://raw.githubusercontent.com/janestreet/base_quickcheck/b7f9c75fa9fdc8b8897880f3253ff60ec26131e7/test/src/test_test.ml | ocaml | success
failure
large sizes to demonstrate shrinking
simple failure
failure without shrinking
failure from examples
failure from examples without shrinking | open! Import
module type S = Test.S
module Config = Test.Config
let default_config = Test.default_config
let%expect_test ("default_config" [@tags "64-bits-only"]) =
Ref.set_temporarily sexp_style To_string_hum ~f:(fun () ->
print_s [%sexp (default_config : Config.t)]);
[%expect
{|
((seed (Deterministic "an arbitrary but deterministic string"))
(test_count 10000) (shrink_count 10000)
(sizes
(0 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 0 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 0 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 0 1 2 3 4 5 6 ...))) |}]
;;
let%expect_test ("default_config" [@tags "32-bits-only"]) =
Ref.set_temporarily sexp_style To_string_hum ~f:(fun () ->
print_s [%sexp (default_config : Config.t)]);
[%expect
{|
((seed (Deterministic "an arbitrary but deterministic string"))
(test_count 1000) (shrink_count 10000)
(sizes
(0 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 0 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 0 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 0 1 2 3 4 5 6 ...))) |}]
;;
let run = Test.run
let result = Test.result
let run_exn = Test.run_exn
let%expect_test "run_exn" =
let module M = struct
type t = bool option list [@@deriving sexp_of]
let quickcheck_generator = Generator.list (Generator.option Generator.bool)
let quickcheck_shrinker = Shrinker.list (Shrinker.option Shrinker.bool)
end
in
let module M_without_shrinker = struct
include M
let quickcheck_shrinker = Shrinker.atomic
end
in
let count = ref 0 in
require_does_not_raise [%here] (fun () ->
Test.run_exn (module M) ~f:(fun _ -> Int.incr count));
require
[%here]
(!count = Test.default_config.test_count)
~if_false_then_print_s:(lazy [%message (!count : int)]);
[%expect {| |}];
let failure list = assert (List.is_sorted list ~compare:[%compare: bool option]) in
let config =
{ Test.default_config with sizes = Sequence.cycle_list_exn [ 10; 20; 30 ] }
in
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn ~config ~f:failure (module M));
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input ((false) ()))
(error "Assert_failure test_test.ml:LINE:COL")) |}];
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn ~config ~f:failure (module M_without_shrinker));
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input (() () (false) (true) (false) ()))
(error "Assert_failure test_test.ml:LINE:COL")) |}];
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn
~config
~f:failure
~examples:[ [ Some true; Some true; None; Some true; Some true ] ]
(module M));
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input ((true) ()))
(error "Assert_failure test_test.ml:LINE:COL")) |}];
require_does_raise [%here] ~hide_positions:true (fun () ->
Test.run_exn
~config
~f:failure
(module M_without_shrinker)
~examples:[ [ Some true; Some true; None; Some true; Some true ] ]);
[%expect
{|
("Base_quickcheck.Test.run: test failed"
(input ((true) (true) () (true) (true)))
(error "Assert_failure test_test.ml:LINE:COL")) |}]
;;
let with_sample = Test.with_sample
let with_sample_exn = Test.with_sample_exn
let%expect_test "with_sample_exn" =
let generator = Generator.list (Generator.option Generator.bool) in
with_sample_exn
generator
~config:{ Test.default_config with test_count = 20 }
~f:(fun sample ->
Sequence.iter sample ~f:(fun value ->
Core.print_s [%sexp (value : bool option list)]));
[%expect
{|
()
()
(() (true))
(() (true) (false))
()
((true))
((true))
((true))
()
(() (false) (true))
(() () (false) (true) () (true) () ())
((true) () () () (true) (false) ())
(() () (true) () () (false) (false))
(() () (true) (true) (false) () (true) ())
()
()
((true) (true) () (false) (false) () () () () (true) () () (true) (false)
(false) ())
((true) (false) (true))
((false) () () (false) () () () (false) (false) () (true) () () () ()
(false))
() |}]
;;
|
5ef0cb10e6a46c1a95b941b831f12dfc120c0be8fa71412061a361d98bfc09b9 | clojure-interop/java-jdk | TreeCellRenderer.clj | (ns javax.swing.tree.TreeCellRenderer
"Defines the requirements for an object that displays a tree node.
See How to Use Trees
in The Java Tutorial
for an example of implementing a tree cell renderer
that displays custom icons."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.tree TreeCellRenderer]))
(defn get-tree-cell-renderer-component
"Sets the value of the current tree cell to value.
If selected is true, the cell will be drawn as if
selected. If expanded is true the node is currently
expanded and if leaf is true the node represents a
leaf and if hasFocus is true the node currently has
focus. tree is the JTree the receiver is being
configured for. Returns the Component that the renderer
uses to draw the value.
The TreeCellRenderer is also responsible for rendering the
the cell representing the tree's current DnD drop location if
it has one. If this renderer cares about rendering
the DnD drop location, it should query the tree directly to
see if the given row represents the drop location:
JTree.DropLocation dropLocation = tree.getDropLocation();
if (dropLocation != null
&& dropLocation.getChildIndex() == -1
&& tree.getRowForPath(dropLocation.getPath()) == row) {
// this row represents the current drop location
// so render it specially, perhaps with a different color
}
tree - `javax.swing.JTree`
value - `java.lang.Object`
selected - `boolean`
expanded - `boolean`
leaf - `boolean`
row - `int`
has-focus - `boolean`
returns: the Component that the renderer uses to draw the value - `java.awt.Component`"
(^java.awt.Component [^TreeCellRenderer this ^javax.swing.JTree tree ^java.lang.Object value ^Boolean selected ^Boolean expanded ^Boolean leaf ^Integer row ^Boolean has-focus]
(-> this (.getTreeCellRendererComponent tree value selected expanded leaf row has-focus))))
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/tree/TreeCellRenderer.clj | clojure | (ns javax.swing.tree.TreeCellRenderer
"Defines the requirements for an object that displays a tree node.
See How to Use Trees
in The Java Tutorial
for an example of implementing a tree cell renderer
that displays custom icons."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.tree TreeCellRenderer]))
(defn get-tree-cell-renderer-component
"Sets the value of the current tree cell to value.
If selected is true, the cell will be drawn as if
selected. If expanded is true the node is currently
expanded and if leaf is true the node represents a
leaf and if hasFocus is true the node currently has
focus. tree is the JTree the receiver is being
configured for. Returns the Component that the renderer
uses to draw the value.
The TreeCellRenderer is also responsible for rendering the
the cell representing the tree's current DnD drop location if
it has one. If this renderer cares about rendering
the DnD drop location, it should query the tree directly to
see if the given row represents the drop location:
if (dropLocation != null
&& dropLocation.getChildIndex() == -1
&& tree.getRowForPath(dropLocation.getPath()) == row) {
// this row represents the current drop location
// so render it specially, perhaps with a different color
}
tree - `javax.swing.JTree`
value - `java.lang.Object`
selected - `boolean`
expanded - `boolean`
leaf - `boolean`
row - `int`
has-focus - `boolean`
returns: the Component that the renderer uses to draw the value - `java.awt.Component`"
(^java.awt.Component [^TreeCellRenderer this ^javax.swing.JTree tree ^java.lang.Object value ^Boolean selected ^Boolean expanded ^Boolean leaf ^Integer row ^Boolean has-focus]
(-> this (.getTreeCellRendererComponent tree value selected expanded leaf row has-focus))))
| |
99a0f57ec3717e05c4e3bea7781351a20a73a74fc6899c2247d01c2a08cebb3a | cffi/cffi | funcall.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
funcall.lisp -- FOREIGN - FUNCALL implementation using libffi
;;;
Copyright ( C ) 2009 , 2010 , 2011
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
;;;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi)
(define-condition libffi-error (cffi-error)
((function-name
:initarg :function-name :reader function-name)))
(define-condition simple-libffi-error (simple-error libffi-error)
())
(defun libffi-error (function-name format-control &rest format-arguments)
(error 'simple-libffi-error
:function-name function-name
:format-control format-control
:format-arguments format-arguments))
(defun make-libffi-cif (function-name return-type argument-types
&optional (abi :default-abi))
"Generate or retrieve the Call InterFace needed to call the function through libffi."
(let* ((argument-count (length argument-types))
(cif (foreign-alloc '(:struct ffi-cif)))
(ffi-argtypes (foreign-alloc :pointer :count argument-count)))
(loop
:for type :in argument-types
:for index :from 0
:do (setf (mem-aref ffi-argtypes :pointer index)
(make-libffi-type-descriptor (parse-type type))))
(unless (eql :ok (libffi/prep-cif cif abi argument-count
(make-libffi-type-descriptor (parse-type return-type))
ffi-argtypes))
(libffi-error function-name
"The 'ffi_prep_cif' libffi call failed for function ~S."
function-name))
cif))
(defun free-libffi-cif (ptr)
(foreign-free (foreign-slot-value ptr '(:struct ffi-cif) 'argument-types))
(foreign-free ptr))
(defun translate-objects-ret (symbols function-arguments types return-type call-form)
(translate-objects
symbols
function-arguments
types
return-type
(if (or (eql return-type :void)
(typep (parse-type return-type) 'translatable-foreign-type))
call-form
;; built-in types won't be translated by
;; expand-from-foreign, we have to do it here
`(mem-ref
,call-form
',(canonicalize-foreign-type return-type)))
t))
(defun foreign-funcall-form/fsbv-with-libffi (function function-arguments symbols types
return-type argument-types
&optional pointerp (abi :default-abi))
"A body of foreign-funcall calling the libffi function #'call (ffi_call)."
(let ((argument-count (length argument-types)))
`(with-foreign-objects ((argument-values :pointer ,argument-count)
,@(unless (eql return-type :void)
`((result ',return-type))))
,(translate-objects-ret
symbols function-arguments types return-type
NOTE : We must delay the creation until the first call
;; because it's FOREIGN-ALLOC'd, i.e. it gets corrupted by an
;; image save/restore cycle. This way a lib will remain usable
;; through a save/restore cycle if the save happens before any
FFI calls will have been made , i.e. nothing is malloc'd yet .
`(progn
(loop
:for arg :in (list ,@symbols)
:for count :from 0
:do (setf (mem-aref argument-values :pointer count) arg))
(let* ((libffi-cif-cache (load-time-value (cons 'libffi-cif-cache nil)))
(libffi-cif (or (cdr libffi-cif-cache)
TODO use compare - and - swap to set it and call
FREE - LIBFFI - CIF when someone else did already .
(setf (cdr libffi-cif-cache)
;; FIXME we should install a finalizer on the cons cell
that calls FREE - LIBFFI - CIF on the ( when the function
gets redefined , and the becomes unreachable ) . but a
;; finite world is full of compromises... - attila
(make-libffi-cif ,function ',return-type
',argument-types ',abi)))))
(libffi/call libffi-cif
,(if pointerp
function
`(foreign-symbol-pointer ,function))
,(if (eql return-type :void) '(null-pointer) 'result)
argument-values)
,(if (eql return-type :void)
'(values)
'result)))))))
(setf *foreign-structures-by-value* 'foreign-funcall-form/fsbv-with-libffi)
DEPRECATED Its presence encourages the use of # + fsbv which may lead to the
;; situation where a fasl was produced by an image that has fsbv feature
;; and then ends up being loaded into an image later that has no fsbv support
;; loaded. Use explicit ASDF dependencies instead and assume the presence
;; of the feature accordingly.
(pushnew :fsbv *features*)
;; DEPRECATED This is here only for backwards compatibility until its fate is
;; decided. See the mailing list discussion for details.
(defctype :sizet size-t)
| null | https://raw.githubusercontent.com/cffi/cffi/03c3e4fecf210614eef878256972de1949969a07/libffi/funcall.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
built-in types won't be translated by
expand-from-foreign, we have to do it here
because it's FOREIGN-ALLOC'd, i.e. it gets corrupted by an
image save/restore cycle. This way a lib will remain usable
through a save/restore cycle if the save happens before any
FIXME we should install a finalizer on the cons cell
finite world is full of compromises... - attila
situation where a fasl was produced by an image that has fsbv feature
and then ends up being loaded into an image later that has no fsbv support
loaded. Use explicit ASDF dependencies instead and assume the presence
of the feature accordingly.
DEPRECATED This is here only for backwards compatibility until its fate is
decided. See the mailing list discussion for details. | funcall.lisp -- FOREIGN - FUNCALL implementation using libffi
Copyright ( C ) 2009 , 2010 , 2011
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package #:cffi)
(define-condition libffi-error (cffi-error)
((function-name
:initarg :function-name :reader function-name)))
(define-condition simple-libffi-error (simple-error libffi-error)
())
(defun libffi-error (function-name format-control &rest format-arguments)
(error 'simple-libffi-error
:function-name function-name
:format-control format-control
:format-arguments format-arguments))
(defun make-libffi-cif (function-name return-type argument-types
&optional (abi :default-abi))
"Generate or retrieve the Call InterFace needed to call the function through libffi."
(let* ((argument-count (length argument-types))
(cif (foreign-alloc '(:struct ffi-cif)))
(ffi-argtypes (foreign-alloc :pointer :count argument-count)))
(loop
:for type :in argument-types
:for index :from 0
:do (setf (mem-aref ffi-argtypes :pointer index)
(make-libffi-type-descriptor (parse-type type))))
(unless (eql :ok (libffi/prep-cif cif abi argument-count
(make-libffi-type-descriptor (parse-type return-type))
ffi-argtypes))
(libffi-error function-name
"The 'ffi_prep_cif' libffi call failed for function ~S."
function-name))
cif))
(defun free-libffi-cif (ptr)
(foreign-free (foreign-slot-value ptr '(:struct ffi-cif) 'argument-types))
(foreign-free ptr))
(defun translate-objects-ret (symbols function-arguments types return-type call-form)
(translate-objects
symbols
function-arguments
types
return-type
(if (or (eql return-type :void)
(typep (parse-type return-type) 'translatable-foreign-type))
call-form
`(mem-ref
,call-form
',(canonicalize-foreign-type return-type)))
t))
(defun foreign-funcall-form/fsbv-with-libffi (function function-arguments symbols types
return-type argument-types
&optional pointerp (abi :default-abi))
"A body of foreign-funcall calling the libffi function #'call (ffi_call)."
(let ((argument-count (length argument-types)))
`(with-foreign-objects ((argument-values :pointer ,argument-count)
,@(unless (eql return-type :void)
`((result ',return-type))))
,(translate-objects-ret
symbols function-arguments types return-type
NOTE : We must delay the creation until the first call
FFI calls will have been made , i.e. nothing is malloc'd yet .
`(progn
(loop
:for arg :in (list ,@symbols)
:for count :from 0
:do (setf (mem-aref argument-values :pointer count) arg))
(let* ((libffi-cif-cache (load-time-value (cons 'libffi-cif-cache nil)))
(libffi-cif (or (cdr libffi-cif-cache)
TODO use compare - and - swap to set it and call
FREE - LIBFFI - CIF when someone else did already .
(setf (cdr libffi-cif-cache)
that calls FREE - LIBFFI - CIF on the ( when the function
gets redefined , and the becomes unreachable ) . but a
(make-libffi-cif ,function ',return-type
',argument-types ',abi)))))
(libffi/call libffi-cif
,(if pointerp
function
`(foreign-symbol-pointer ,function))
,(if (eql return-type :void) '(null-pointer) 'result)
argument-values)
,(if (eql return-type :void)
'(values)
'result)))))))
(setf *foreign-structures-by-value* 'foreign-funcall-form/fsbv-with-libffi)
DEPRECATED Its presence encourages the use of # + fsbv which may lead to the
(pushnew :fsbv *features*)
(defctype :sizet size-t)
|
17cc7970f7b12986553ff5e6a9f2a6a9885cf9c2552f9ea8b761ee93204c9c52 | google/hrepl | Chain1.hs | Copyright 2020 Google LLC
--
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- -2.0
--
-- Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Chain1 where
chain1 f = appendFile f "d"
| null | https://raw.githubusercontent.com/google/hrepl/2648a55cc38407c5b60a3a086217e2d827ca6cb6/hrepl/tests/dupes/Chain1.hs | haskell |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright 2020 Google LLC
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
module Chain1 where
chain1 f = appendFile f "d"
|
a54f251c6742c555bdadf07ad1475346db204e7d61ec4ff99f608a0538300f10 | cubicle-model-checker/cubicle | gc.ml |
type control = {
mutable minor_heap_size : int;
mutable major_heap_increment : int;
mutable space_overhead : int;
mutable verbose : int;
mutable max_overhead : int;
mutable stack_limit : int;
}
let gc = {
minor_heap_size = 0;
major_heap_increment = 0;
space_overhead = 0;
verbose = 0;
max_overhead = 0;
stack_limit = 0;
}
let get () = gc
let set gc = ()
let minor () = ()
let major () = ()
let major_slice _ = 0
let full_major () = ()
let compact () = ()
| null | https://raw.githubusercontent.com/cubicle-model-checker/cubicle/00f09bb2d4bb496549775e770d7ada08bc1e4866/try-cubicle/gc.ml | ocaml |
type control = {
mutable minor_heap_size : int;
mutable major_heap_increment : int;
mutable space_overhead : int;
mutable verbose : int;
mutable max_overhead : int;
mutable stack_limit : int;
}
let gc = {
minor_heap_size = 0;
major_heap_increment = 0;
space_overhead = 0;
verbose = 0;
max_overhead = 0;
stack_limit = 0;
}
let get () = gc
let set gc = ()
let minor () = ()
let major () = ()
let major_slice _ = 0
let full_major () = ()
let compact () = ()
| |
62a8287863bde3b3f4f0ffd76eec16b76d1d0f56968729e9409a36ac9dc97ac9 | chrishowejones/blog-film-ratings | index.clj | (ns film-ratings.views.index
(:require [film-ratings.views.template :refer [page]]))
(defn list-options []
(page
[:div.container.jumbotron.bg-white.text-center
[:row
[:p
[:a.btn.btn-primary {:href "/add-film"} "Add a Film"]]]
[:row
[:p
[:a.btn.btn-primary {:href "/list-films"} "List Films"]]]]))
| null | https://raw.githubusercontent.com/chrishowejones/blog-film-ratings/652ca2aec583db4b91e60ef4008b08b388cca80a/src/film_ratings/views/index.clj | clojure | (ns film-ratings.views.index
(:require [film-ratings.views.template :refer [page]]))
(defn list-options []
(page
[:div.container.jumbotron.bg-white.text-center
[:row
[:p
[:a.btn.btn-primary {:href "/add-film"} "Add a Film"]]]
[:row
[:p
[:a.btn.btn-primary {:href "/list-films"} "List Films"]]]]))
| |
72667d03f3bfe7723ae7e41a0f48b1668c3c4656af6a052e52fdb884b110b8bb | AbstractMachinesLab/caramel | emitter.ml | open MenhirSdk.Cmly_api
open Utils
open Attributes
open Synthesis
open Recovery_intf
let menhir = "MenhirInterpreter"
(* Generation scheme doing checks and failing at runtime, or not ... *)
let safe = false
type var = int
module Codesharing
(G : GRAMMAR)
(S : SYNTHESIZER with module G := G)
(R : RECOVERY with module G := G) : sig
type instr =
| IRef of var
| IAbort
| IReduce of G.production
| IShift of G.symbol
val compile : R.item list -> instr list list * (R.item -> instr list)
end = struct
open S
(* Rewrite trivial indirections:
Seq [x] => x
ys @ [Seq xs] => ys @ xs
*)
let rec normalize_actions = function
| [] -> []
| [ Seq v ] -> normalize_actions v
| x :: xs -> normalize_action x :: normalize_actions xs
and normalize_action = function
| (Abort | Reduce _ | Shift _) as a -> a
| Seq [ v ] -> normalize_action v
| Seq v -> ( match normalize_actions v with [ x ] -> x | xs -> Seq xs )
(* Find sharing opportunities.
If the same sequence of action occurs multiple times, the funtion
will associate a unique identifier to the sequence.
[share actions] returns a pair
[(bindings, lookup) : action list array * (action list -> int option)]
The [bindings] array contains all action lists that are worth sharing.
The [lookup] function returns the index of an action list if is
is in the array.
*)
let share actions =
let occurrence_table = Hashtbl.create 113 in
(let order = ref 0 in
let rec iter_list = function
| [] | [ _ ] -> ()
| x :: xs as xxs -> (
match Hashtbl.find occurrence_table xxs with
| occurrences, _index -> incr occurrences
| exception Not_found ->
let index = ref (-1) in
Hashtbl.add occurrence_table xxs (ref 1, index);
iter x;
iter_list xs;
index := !order;
incr order )
and iter = function
| Abort | Reduce _ | Shift _ -> ()
| Seq xs -> iter_list xs
in
List.iter iter_list actions);
let bindings =
let register actions (occurrences, index) to_share =
if !occurrences > 1 then (!index, actions) :: to_share else to_share
in
let to_share = Hashtbl.fold register occurrence_table [] in
let order_actions (o1, _) (o2, _) = compare o1 (o2 : int) in
List.map snd (List.sort order_actions to_share)
in
let binding_table = Hashtbl.create 113 in
List.iteri
(fun idx actions -> Hashtbl.add binding_table actions idx)
bindings;
let lookup actions =
match Hashtbl.find binding_table actions with
| exception Not_found -> None
| index -> Some index
in
(bindings, lookup)
let item_to_actions (st, prod, pos) =
normalize_actions (snd (S.solve (Tail (st, prod, pos))))
type instr =
| IRef of int
| IAbort
| IReduce of G.production
| IShift of G.symbol
let rec compile_one ~sharing = function
| Abort -> [ IAbort ]
| Reduce p -> [ IReduce p ]
| Shift s -> [ IShift s ]
| Seq xs -> share_seq ~sharing xs
and share_seq ~sharing seq =
match sharing seq with
| None -> compile_seq ~sharing seq
| Some index -> [ IRef index ]
and compile_seq ~sharing = function
| [] -> []
| x :: xs ->
let x' = compile_one ~sharing x in
let xs' = share_seq ~sharing xs in
x' @ xs'
let compile items =
let actions = List.map item_to_actions items in
let bindings, sharing = share actions in
let bindings = List.map (compile_seq ~sharing) bindings in
let compile_item item = share_seq ~sharing (item_to_actions item) in
(bindings, compile_item)
end
module Make
(G : GRAMMAR)
(A : ATTRIBUTES with module G := G)
(S : SYNTHESIZER with module G := G)
(R : RECOVERY with module G := G) : sig
val emit : Format.formatter -> unit
end = struct
open G
open Format
let emit_default_value ppf =
fprintf ppf "open %s\n\n"
(String.capitalize (Filename.basename Grammar.basename))
[@ocaml.warning "-3"];
fprintf ppf "module Default = struct\n";
A.default_prelude ppf;
fprintf ppf " let value (type a) : a %s.symbol -> a = function\n" menhir;
Terminal.iter (fun t ->
match A.default_terminal t with
| None -> ()
| Some str ->
fprintf ppf " | %s.T %s.T_%s -> %s\n" menhir menhir
(Terminal.name t) str);
Nonterminal.iter (fun n ->
match A.default_nonterminal n with
| None -> ()
| Some str ->
fprintf ppf " | %s.N %s.N_%s -> %s\n" menhir menhir
(Nonterminal.mangled_name n)
str);
ppf " | _ - > raise Not_found\n " ; should be exhaustive
fprintf ppf "end\n\n";
fprintf ppf "let default_value = Default.value\n\n"
let emit_defs ppf =
fprintf ppf "open %s\n\n" menhir;
fprintf ppf
"type action =\n\
\ | Abort\n\
\ | R of int\n\
\ | S : 'a symbol -> action\n\
\ | Sub of action list\n\n";
fprintf ppf
"type decision =\n\
\ | Nothing\n\
\ | One of action list\n\
\ | Select of (int -> action list)\n\n"
let emit_depth ppf =
let open Format in
fprintf ppf "let depth =\n [|";
Lr1.iter (fun st ->
let items = G.Lr0.items (G.Lr1.lr0 st) in
let positions = List.map snd items in
let depth = List.fold_left max 0 positions in
fprintf ppf "%d;" depth);
fprintf ppf "|]\n\n"
let emit_can_pop ppf =
Format.fprintf ppf "let can_pop (type a) : a terminal -> bool = function\n";
G.Terminal.iter (fun t ->
if G.Terminal.kind t = `REGULAR && G.Terminal.typ t = None then
Format.fprintf ppf " | T_%s -> true\n" (G.Terminal.name t));
Format.fprintf ppf " | _ -> false\n\n"
module C = Codesharing (G) (S) (R)
let emit_recoveries ppf =
let all_cases =
Lr1.fold
(fun st acc ->
try
let { R.cases; _ } = R.recover st in
let cases =
List.map
(fun (st', items) ->
( list_last items,
match st' with None -> -1 | Some st' -> Lr1.to_int st' ))
cases
in
let cases =
match group_assoc cases with
| [] -> `Nothing
| [ (instr, _) ] -> `One instr
| xs -> `Select xs
in
(cases, Lr1.to_int st) :: acc
with _ -> acc)
[]
in
let all_cases = group_assoc all_cases in
let all_items =
let items_in_case (case, _states) =
match case with
| `Nothing -> []
| `One item -> [ item ]
| `Select items -> List.map fst items
in
List.flatten (List.map items_in_case all_cases)
in
let globals, get_instr = C.compile all_items in
let open Format in
fprintf ppf "let recover =\n";
let emit_instr ppf = function
| C.IAbort -> fprintf ppf "Abort"
| C.IReduce prod -> fprintf ppf "R %d" (Production.to_int prod)
| C.IShift (T t) -> fprintf ppf "S (T T_%s)" (Terminal.name t)
| C.IShift (N n) -> fprintf ppf "S (N N_%s)" (Nonterminal.mangled_name n)
| C.IRef r -> fprintf ppf "r%d" r
in
let emit_instrs ppf = Utils.pp_list emit_instr ppf in
let emit_shared index instrs =
fprintf ppf " let r%d = Sub %a in\n" index emit_instrs instrs
in
List.iteri emit_shared globals;
let emit_item ppf item = emit_instrs ppf (get_instr item) in
fprintf ppf " function\n";
List.iter
(fun (cases, states) ->
fprintf ppf " ";
List.iter (fprintf ppf "| %d ") states;
fprintf ppf "-> ";
match cases with
| `Nothing -> fprintf ppf "Nothing\n"
| `One item -> fprintf ppf "One %a\n" emit_item item
| `Select xs -> (
fprintf ppf "Select (function\n";
if safe then (
List.iter
(fun (item, cases) ->
fprintf ppf " ";
List.iter (fprintf ppf "| %d ") cases;
fprintf ppf "-> %a\n" emit_item item)
xs;
fprintf ppf " | _ -> raise Not_found)\n" )
else
match
List.sort
(fun (_, a) (_, b) -> compare (List.length b) (List.length a))
xs
with
| (item, _) :: xs ->
List.iter
(fun (item, cases) ->
fprintf ppf " ";
List.iter (fprintf ppf "| %d ") cases;
fprintf ppf "-> %a\n" emit_item item)
xs;
fprintf ppf " | _ -> %a)\n" emit_item item
| [] -> assert false ))
all_cases;
fprintf ppf " | _ -> raise Not_found\n"
let emit_token_of_terminal ppf =
let case t =
match Terminal.kind t with
| `REGULAR | `EOF ->
fprintf ppf " | %s.T_%s -> %s%s\n" menhir (Terminal.name t)
(Terminal.name t)
(if Terminal.typ t <> None then " v" else "")
| `ERROR ->
fprintf ppf " | %s.T_%s -> assert false\n" menhir (Terminal.name t)
| `PSEUDO -> ()
in
fprintf ppf
"let token_of_terminal (type a) (t : a %s.terminal) (v : a) : token =\n\
\ match t with\n"
menhir;
Terminal.iter case
let emit_nullable ppf =
let print_n n =
if Nonterminal.nullable n then
fprintf ppf " | N_%s -> true\n" (Nonterminal.mangled_name n)
in
fprintf ppf
"let nullable (type a) : a MenhirInterpreter.nonterminal -> bool =\n\
\ let open MenhirInterpreter in function\n";
Nonterminal.iter print_n;
fprintf ppf " | _ -> false\n"
let emit ppf =
emit_default_value ppf;
emit_defs ppf;
emit_depth ppf;
emit_can_pop ppf;
emit_recoveries ppf;
emit_token_of_terminal ppf;
emit_nullable ppf
end
| null | https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocamlformat-0.17.0/vendor/parse-wyc/menhir-recover/emitter.ml | ocaml | Generation scheme doing checks and failing at runtime, or not ...
Rewrite trivial indirections:
Seq [x] => x
ys @ [Seq xs] => ys @ xs
Find sharing opportunities.
If the same sequence of action occurs multiple times, the funtion
will associate a unique identifier to the sequence.
[share actions] returns a pair
[(bindings, lookup) : action list array * (action list -> int option)]
The [bindings] array contains all action lists that are worth sharing.
The [lookup] function returns the index of an action list if is
is in the array.
| open MenhirSdk.Cmly_api
open Utils
open Attributes
open Synthesis
open Recovery_intf
let menhir = "MenhirInterpreter"
let safe = false
type var = int
module Codesharing
(G : GRAMMAR)
(S : SYNTHESIZER with module G := G)
(R : RECOVERY with module G := G) : sig
type instr =
| IRef of var
| IAbort
| IReduce of G.production
| IShift of G.symbol
val compile : R.item list -> instr list list * (R.item -> instr list)
end = struct
open S
let rec normalize_actions = function
| [] -> []
| [ Seq v ] -> normalize_actions v
| x :: xs -> normalize_action x :: normalize_actions xs
and normalize_action = function
| (Abort | Reduce _ | Shift _) as a -> a
| Seq [ v ] -> normalize_action v
| Seq v -> ( match normalize_actions v with [ x ] -> x | xs -> Seq xs )
let share actions =
let occurrence_table = Hashtbl.create 113 in
(let order = ref 0 in
let rec iter_list = function
| [] | [ _ ] -> ()
| x :: xs as xxs -> (
match Hashtbl.find occurrence_table xxs with
| occurrences, _index -> incr occurrences
| exception Not_found ->
let index = ref (-1) in
Hashtbl.add occurrence_table xxs (ref 1, index);
iter x;
iter_list xs;
index := !order;
incr order )
and iter = function
| Abort | Reduce _ | Shift _ -> ()
| Seq xs -> iter_list xs
in
List.iter iter_list actions);
let bindings =
let register actions (occurrences, index) to_share =
if !occurrences > 1 then (!index, actions) :: to_share else to_share
in
let to_share = Hashtbl.fold register occurrence_table [] in
let order_actions (o1, _) (o2, _) = compare o1 (o2 : int) in
List.map snd (List.sort order_actions to_share)
in
let binding_table = Hashtbl.create 113 in
List.iteri
(fun idx actions -> Hashtbl.add binding_table actions idx)
bindings;
let lookup actions =
match Hashtbl.find binding_table actions with
| exception Not_found -> None
| index -> Some index
in
(bindings, lookup)
let item_to_actions (st, prod, pos) =
normalize_actions (snd (S.solve (Tail (st, prod, pos))))
type instr =
| IRef of int
| IAbort
| IReduce of G.production
| IShift of G.symbol
let rec compile_one ~sharing = function
| Abort -> [ IAbort ]
| Reduce p -> [ IReduce p ]
| Shift s -> [ IShift s ]
| Seq xs -> share_seq ~sharing xs
and share_seq ~sharing seq =
match sharing seq with
| None -> compile_seq ~sharing seq
| Some index -> [ IRef index ]
and compile_seq ~sharing = function
| [] -> []
| x :: xs ->
let x' = compile_one ~sharing x in
let xs' = share_seq ~sharing xs in
x' @ xs'
let compile items =
let actions = List.map item_to_actions items in
let bindings, sharing = share actions in
let bindings = List.map (compile_seq ~sharing) bindings in
let compile_item item = share_seq ~sharing (item_to_actions item) in
(bindings, compile_item)
end
module Make
(G : GRAMMAR)
(A : ATTRIBUTES with module G := G)
(S : SYNTHESIZER with module G := G)
(R : RECOVERY with module G := G) : sig
val emit : Format.formatter -> unit
end = struct
open G
open Format
let emit_default_value ppf =
fprintf ppf "open %s\n\n"
(String.capitalize (Filename.basename Grammar.basename))
[@ocaml.warning "-3"];
fprintf ppf "module Default = struct\n";
A.default_prelude ppf;
fprintf ppf " let value (type a) : a %s.symbol -> a = function\n" menhir;
Terminal.iter (fun t ->
match A.default_terminal t with
| None -> ()
| Some str ->
fprintf ppf " | %s.T %s.T_%s -> %s\n" menhir menhir
(Terminal.name t) str);
Nonterminal.iter (fun n ->
match A.default_nonterminal n with
| None -> ()
| Some str ->
fprintf ppf " | %s.N %s.N_%s -> %s\n" menhir menhir
(Nonterminal.mangled_name n)
str);
ppf " | _ - > raise Not_found\n " ; should be exhaustive
fprintf ppf "end\n\n";
fprintf ppf "let default_value = Default.value\n\n"
let emit_defs ppf =
fprintf ppf "open %s\n\n" menhir;
fprintf ppf
"type action =\n\
\ | Abort\n\
\ | R of int\n\
\ | S : 'a symbol -> action\n\
\ | Sub of action list\n\n";
fprintf ppf
"type decision =\n\
\ | Nothing\n\
\ | One of action list\n\
\ | Select of (int -> action list)\n\n"
let emit_depth ppf =
let open Format in
fprintf ppf "let depth =\n [|";
Lr1.iter (fun st ->
let items = G.Lr0.items (G.Lr1.lr0 st) in
let positions = List.map snd items in
let depth = List.fold_left max 0 positions in
fprintf ppf "%d;" depth);
fprintf ppf "|]\n\n"
let emit_can_pop ppf =
Format.fprintf ppf "let can_pop (type a) : a terminal -> bool = function\n";
G.Terminal.iter (fun t ->
if G.Terminal.kind t = `REGULAR && G.Terminal.typ t = None then
Format.fprintf ppf " | T_%s -> true\n" (G.Terminal.name t));
Format.fprintf ppf " | _ -> false\n\n"
module C = Codesharing (G) (S) (R)
let emit_recoveries ppf =
let all_cases =
Lr1.fold
(fun st acc ->
try
let { R.cases; _ } = R.recover st in
let cases =
List.map
(fun (st', items) ->
( list_last items,
match st' with None -> -1 | Some st' -> Lr1.to_int st' ))
cases
in
let cases =
match group_assoc cases with
| [] -> `Nothing
| [ (instr, _) ] -> `One instr
| xs -> `Select xs
in
(cases, Lr1.to_int st) :: acc
with _ -> acc)
[]
in
let all_cases = group_assoc all_cases in
let all_items =
let items_in_case (case, _states) =
match case with
| `Nothing -> []
| `One item -> [ item ]
| `Select items -> List.map fst items
in
List.flatten (List.map items_in_case all_cases)
in
let globals, get_instr = C.compile all_items in
let open Format in
fprintf ppf "let recover =\n";
let emit_instr ppf = function
| C.IAbort -> fprintf ppf "Abort"
| C.IReduce prod -> fprintf ppf "R %d" (Production.to_int prod)
| C.IShift (T t) -> fprintf ppf "S (T T_%s)" (Terminal.name t)
| C.IShift (N n) -> fprintf ppf "S (N N_%s)" (Nonterminal.mangled_name n)
| C.IRef r -> fprintf ppf "r%d" r
in
let emit_instrs ppf = Utils.pp_list emit_instr ppf in
let emit_shared index instrs =
fprintf ppf " let r%d = Sub %a in\n" index emit_instrs instrs
in
List.iteri emit_shared globals;
let emit_item ppf item = emit_instrs ppf (get_instr item) in
fprintf ppf " function\n";
List.iter
(fun (cases, states) ->
fprintf ppf " ";
List.iter (fprintf ppf "| %d ") states;
fprintf ppf "-> ";
match cases with
| `Nothing -> fprintf ppf "Nothing\n"
| `One item -> fprintf ppf "One %a\n" emit_item item
| `Select xs -> (
fprintf ppf "Select (function\n";
if safe then (
List.iter
(fun (item, cases) ->
fprintf ppf " ";
List.iter (fprintf ppf "| %d ") cases;
fprintf ppf "-> %a\n" emit_item item)
xs;
fprintf ppf " | _ -> raise Not_found)\n" )
else
match
List.sort
(fun (_, a) (_, b) -> compare (List.length b) (List.length a))
xs
with
| (item, _) :: xs ->
List.iter
(fun (item, cases) ->
fprintf ppf " ";
List.iter (fprintf ppf "| %d ") cases;
fprintf ppf "-> %a\n" emit_item item)
xs;
fprintf ppf " | _ -> %a)\n" emit_item item
| [] -> assert false ))
all_cases;
fprintf ppf " | _ -> raise Not_found\n"
let emit_token_of_terminal ppf =
let case t =
match Terminal.kind t with
| `REGULAR | `EOF ->
fprintf ppf " | %s.T_%s -> %s%s\n" menhir (Terminal.name t)
(Terminal.name t)
(if Terminal.typ t <> None then " v" else "")
| `ERROR ->
fprintf ppf " | %s.T_%s -> assert false\n" menhir (Terminal.name t)
| `PSEUDO -> ()
in
fprintf ppf
"let token_of_terminal (type a) (t : a %s.terminal) (v : a) : token =\n\
\ match t with\n"
menhir;
Terminal.iter case
let emit_nullable ppf =
let print_n n =
if Nonterminal.nullable n then
fprintf ppf " | N_%s -> true\n" (Nonterminal.mangled_name n)
in
fprintf ppf
"let nullable (type a) : a MenhirInterpreter.nonterminal -> bool =\n\
\ let open MenhirInterpreter in function\n";
Nonterminal.iter print_n;
fprintf ppf " | _ -> false\n"
let emit ppf =
emit_default_value ppf;
emit_defs ppf;
emit_depth ppf;
emit_can_pop ppf;
emit_recoveries ppf;
emit_token_of_terminal ppf;
emit_nullable ppf
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.