_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
bb250290a835bdffd1e0cfcf2143bce1fafb748150de1cb12486b245a3fe9d2c
privet-kitty/dufy
illuminants.lisp
;;; ;;; Supplemental data of standard illuminants All the illuminants are defined under DUFY:+OBS - CIE1931 + ( 2 - degree observer ) ;;; (originally contributed by wasserwerk) ;;; (in-package :dufy/extra-data) ;; The white points of illuminants A, B, C, and D in dufy are calculated with 5 nm intervals . ( See the comment in the file with the same name in dufy / core package . ) (defparameter +illum-d55+ (make-illuminant :spectrum (gen-illum-d-spectrum 5500 :rectify t) :begin-wl 380 :end-wl 780 :band 5 :compile-time t)) (defparameter +illum-d75+ (make-illuminant :spectrum (gen-illum-d-spectrum 7500 :rectify t) :begin-wl 380 :end-wl 780 :band 5 :compile-time t)) ;;; illuminant B (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter +illum-b-table+ (make-array 97 :element-type 'double-float :initial-contents '(0.0d0 0.0d0 0.0d0 0.0d0 0.02d0 0.26d0 0.50d0 1.45d0 2.40d0 4.00d0 5.60d0 7.60d0 9.60d0 12.40d0 15.20d0 18.8d0 22.40d0 26.85d0 31.30d0 36.18d0 41.30d0 46.62d0 52.10d0 57.70d0 63.20d0 68.37d0 73.10d0 77.31d0 80.80d0 83.44d0 85.40d0 86.88d0 88.30d0 90.08d0 92.00d0 93.75d0 95.20d0 96.23d0 96.50d0 95.71d0 94.20d0 92.37d0 90.70d0 89.95d0 89.50d0 90.43d0 92.20d0 94.46d0 96.90d0 99.16d0 101.00d0 102.20d0 102.80d0 102.92d0 102.60d0 101.90d0 101.00d0 100.07d0 99.20d0 98.44d0 98.00d0 98.08d0 98.50d0 99.06d0 99.70d0 100.36d0 101.00d0 101.56d0 102.20d0 103.05d0 103.90d0 104.59d0 105.00d0 105.08d0 104.90d0 104.55d0 103.90d0 102.84d0 101.60d0 100.38d0 99.10d0 97.70d0 96.20d0 94.60d0 92.90d0 91.10d0 89.40d0 88.00d0 86.90d0 85.90d0 85.20d0 84.80d0 84.70d0 84.90d0 85.40d0 86.10d0 87.00d0)))) (defparameter +illum-b+ (make-illuminant :spectrum (gen-spectrum +illum-b-table+ 300 780) :begin-wl 380 :end-wl 780 :band 5 :compile-time t)) F series ( without 3.x ) Wavelength range for SPD is from 380 nm to 780 nm . Unfortunately , I could not find any sources with a range from 300 nm to 830 nm . ;;; Source for SPD : ;;; Source 1 : ;;; Source 2 : ;;; -data -mcsl.org/UsefulData/Fluorescents.xls ;;; Source 2 seems to have some typos . See the value for F10 for 385 nm - ;;; the same value as for F11 in next columns. ;;; (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter +illum-f1-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.87d0 2.36d0 2.94d0 3.47d0 5.17d0 19.49d0 6.13d0 6.24d0 7.01d0 7.79d0 8.56d0 43.67d0 16.94d0 10.72d0 11.35d0 11.89d0 12.37d0 12.75d0 13d0 13.15d0 13.23d0 13.17d0 13.13d0 12.85d0 12.52d0 12.2d0 11.83d0 11.5d0 11.22d0 11.05d0 11.03d0 11.18d0 11.53d0 27.74d0 17.05d0 13.55d0 14.33d0 15.01d0 15.52d0 18.29d0 19.55d0 15.48d0 14.91d0 14.15d0 13.22d0 12.19d0 11.12d0 10.03d0 8.95d0 7.96d0 7.02d0 6.2d0 5.42d0 4.73d0 4.15d0 3.64d0 3.2d0 2.81d0 2.47d0 2.18d0 1.93d0 1.72d0 1.67d0 1.43d0 1.29d0 1.19d0 1.08d0 0.96d0 0.88d0 0.81d0 0.77d0 0.75d0 0.73d0 0.68d0 0.69d0 0.64d0 0.68d0 0.69d0 0.61d0 0.52d0 0.43d0))) (defparameter +illum-f2-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.18d0 1.48d0 1.84d0 2.15d0 3.44d0 15.69d0 3.85d0 3.74d0 4.19d0 4.62d0 5.06d0 34.98d0 11.81d0 6.27d0 6.63d0 6.93d0 7.19d0 7.4d0 7.54d0 7.62d0 7.65d0 7.62d0 7.62d0 7.45d0 7.28d0 7.15d0 7.05d0 7.04d0 7.16d0 7.47d0 8.04d0 8.88d0 10.01d0 24.88d0 16.64d0 14.59d0 16.16d0 17.56d0 18.62d0 21.47d0 22.79d0 19.29d0 18.66d0 17.73d0 16.54d0 15.21d0 13.8d0 12.36d0 10.95d0 9.65d0 8.4d0 7.32d0 6.31d0 5.43d0 4.68d0 4.02d0 3.45d0 2.96d0 2.55d0 2.19d0 1.89d0 1.64d0 1.53d0 1.27d0 1.1d0 0.99d0 0.88d0 0.76d0 0.68d0 0.61d0 0.56d0 0.54d0 0.51d0 0.47d0 0.47d0 0.43d0 0.46d0 0.47d0 0.4d0 0.33d0 0.27d0))) (defparameter +illum-f3-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.82d0 1.02d0 1.26d0 1.44d0 2.57d0 14.36d0 2.7d0 2.45d0 2.73d0 3d0 3.28d0 31.85d0 9.47d0 4.02d0 4.25d0 4.44d0 4.59d0 4.72d0 4.8d0 4.86d0 4.87d0 4.85d0 4.88d0 4.77d0 4.67d0 4.62d0 4.62d0 4.73d0 4.99d0 5.48d0 6.25d0 7.34d0 8.78d0 23.82d0 16.14d0 14.59d0 16.63d0 18.49d0 19.95d0 23.11d0 24.69d0 21.41d0 20.85d0 19.93d0 18.67d0 17.22d0 15.65d0 14.04d0 12.45d0 10.95d0 9.51d0 8.27d0 7.11d0 6.09d0 5.22d0 4.45d0 3.8d0 3.23d0 2.75d0 2.33d0 1.99d0 1.7d0 1.55d0 1.27d0 1.09d0 0.96d0 0.83d0 0.71d0 0.62d0 0.54d0 0.49d0 0.46d0 0.43d0 0.39d0 0.39d0 0.35d0 0.38d0 0.39d0 0.33d0 0.28d0 0.21d0))) (defparameter +illum-f4-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.57d0 0.7d0 0.87d0 0.98d0 2.01d0 13.75d0 1.95d0 1.59d0 1.76d0 1.93d0 2.1d0 30.28d0 8.03d0 2.55d0 2.7d0 2.82d0 2.91d0 2.99d0 3.04d0 3.08d0 3.09d0 3.09d0 3.14d0 3.06d0 3d0 2.98d0 3.01d0 3.14d0 3.41d0 3.9d0 4.69d0 5.81d0 7.32d0 22.59d0 15.11d0 13.88d0 16.33d0 18.68d0 20.64d0 24.28d0 26.26d0 23.28d0 22.94d0 22.14d0 20.91d0 19.43d0 17.74d0 16d0 14.42d0 12.56d0 10.93d0 9.52d0 8.18d0 7.01d0 6d0 5.11d0 4.36d0 3.69d0 3.13d0 2.64d0 2.24d0 1.91d0 1.7d0 1.39d0 1.18d0 1.03d0 0.88d0 0.74d0 0.64d0 0.54d0 0.49d0 0.46d0 0.42d0 0.37d0 0.37d0 0.33d0 0.35d0 0.36d0 0.31d0 0.26d0 0.19d0))) (defparameter +illum-f5-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.87d0 2.35d0 2.92d0 3.45d0 5.1d0 18.91d0 6d0 6.11d0 6.85d0 7.58d0 8.31d0 40.76d0 16.06d0 10.32d0 10.91d0 11.4d0 11.83d0 12.17d0 12.4d0 12.54d0 12.58d0 12.52d0 12.47d0 12.2d0 11.89d0 11.61d0 11.33d0 11.1d0 10.96d0 10.97d0 11.16d0 11.54d0 12.12d0 27.78d0 17.73d0 14.47d0 15.2d0 15.77d0 16.1d0 18.54d0 19.5d0 15.39d0 14.64d0 13.72d0 12.69d0 11.57d0 10.45d0 9.35d0 8.29d0 7.32d0 6.41d0 5.63d0 4.9d0 4.26d0 3.72d0 3.25d0 2.83d0 2.49d0 2.19d0 1.93d0 1.71d0 1.52d0 1.48d0 1.26d0 1.13d0 1.05d0 0.96d0 0.85d0 0.78d0 0.72d0 0.68d0 0.67d0 0.65d0 0.61d0 0.62d0 0.59d0 0.62d0 0.64d0 0.55d0 0.47d0 0.4d0))) (defparameter +illum-f6-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.05d0 1.31d0 1.63d0 1.9d0 3.11d0 14.8d0 3.43d0 3.3d0 3.68d0 4.07d0 4.45d0 32.61d0 10.74d0 5.48d0 5.78d0 6.03d0 6.25d0 6.41d0 6.52d0 6.58d0 6.59d0 6.56d0 6.56d0 6.42d0 6.28d0 6.2d0 6.19d0 6.3d0 6.6d0 7.12d0 7.94d0 9.07d0 10.49d0 25.22d0 17.46d0 15.63d0 17.22d0 18.53d0 19.43d0 21.97d0 23.01d0 19.41d0 18.56d0 17.42d0 16.09d0 14.64d0 13.15d0 11.68d0 10.25d0 8.95d0 7.74d0 6.69d0 5.71d0 4.87d0 4.16d0 3.55d0 3.02d0 2.57d0 2.2d0 1.87d0 1.6d0 1.37d0 1.29d0 1.05d0 0.91d0 0.81d0 0.71d0 0.61d0 0.54d0 0.48d0 0.44d0 0.43d0 0.4d0 0.37d0 0.38d0 0.35d0 0.39d0 0.41d0 0.33d0 0.26d0 0.21d0))) (defparameter +illum-f7-table+ (make-array 81 :element-type 'double-float :initial-contents '(2.56d0 3.18d0 3.84d0 4.53d0 6.15d0 19.37d0 7.37d0 7.05d0 7.71d0 8.41d0 9.15d0 44.14d0 17.52d0 11.35d0 12d0 12.58d0 13.08d0 13.45d0 13.71d0 13.88d0 13.95d0 13.93d0 13.82d0 13.64d0 13.43d0 13.25d0 13.08d0 12.93d0 12.78d0 12.6d0 12.44d0 12.33d0 12.26d0 29.52d0 17.05d0 12.44d0 12.58d0 12.72d0 12.83d0 15.46d0 16.75d0 12.83d0 12.67d0 12.45d0 12.19d0 11.89d0 11.6d0 11.35d0 11.12d0 10.95d0 10.76d0 10.42d0 10.11d0 10.04d0 10.02d0 10.11d0 9.87d0 8.65d0 7.27d0 6.44d0 5.83d0 5.41d0 5.04d0 4.57d0 4.12d0 3.77d0 3.46d0 3.08d0 2.73d0 2.47d0 2.25d0 2.06d0 1.9d0 1.75d0 1.62d0 1.54d0 1.45d0 1.32d0 1.17d0 0.99d0 0.81d0))) (defparameter +illum-f8-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.21d0 1.5d0 1.81d0 2.13d0 3.17d0 13.08d0 3.83d0 3.45d0 3.86d0 4.42d0 5.09d0 34.1d0 12.42d0 7.68d0 8.6d0 9.46d0 10.24d0 10.84d0 11.33d0 11.71d0 11.98d0 12.17d0 12.28d0 12.32d0 12.35d0 12.44d0 12.55d0 12.68d0 12.77d0 12.72d0 12.6d0 12.43d0 12.22d0 28.96d0 16.51d0 11.79d0 11.76d0 11.77d0 11.84d0 14.61d0 16.11d0 12.34d0 12.53d0 12.72d0 12.92d0 13.12d0 13.34d0 13.61d0 13.87d0 14.07d0 14.2d0 14.16d0 14.13d0 14.34d0 14.5d0 14.46d0 14d0 12.58d0 10.99d0 9.98d0 9.22d0 8.62d0 8.07d0 7.39d0 6.71d0 6.16d0 5.63d0 5.03d0 4.46d0 4.02d0 3.66d0 3.36d0 3.09d0 2.85d0 2.65d0 2.51d0 2.37d0 2.15d0 1.89d0 1.61d0 1.32d0))) (defparameter +illum-f9-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.9d0 1.12d0 1.36d0 1.6d0 2.59d0 12.8d0 3.05d0 2.56d0 2.86d0 3.3d0 3.82d0 32.62d0 10.77d0 5.84d0 6.57d0 7.25d0 7.86d0 8.35d0 8.75d0 9.06d0 9.31d0 9.48d0 9.61d0 9.68d0 9.74d0 9.88d0 10.04d0 10.26d0 10.48d0 10.63d0 10.78d0 10.96d0 11.18d0 27.71d0 16.29d0 12.28d0 12.74d0 13.21d0 13.65d0 16.57d0 18.14d0 14.55d0 14.65d0 14.66d0 14.61d0 14.5d0 14.39d0 14.4d0 14.47d0 14.62d0 14.72d0 14.55d0 14.4d0 14.58d0 14.88d0 15.51d0 15.47d0 13.2d0 10.57d0 9.18d0 8.25d0 7.57d0 7.03d0 6.35d0 5.72d0 5.25d0 4.8d0 4.29d0 3.8d0 3.43d0 3.12d0 2.86d0 2.64d0 2.43d0 2.26d0 2.14d0 2.02d0 1.83d0 1.61d0 1.38d0 1.12d0))) (defparameter +illum-f10-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.11d0 0.8d0 0.62d0 0.57d0 1.48d0 12.16d0 2.12d0 2.7d0 3.74d0 5.14d0 6.75d0 34.39d0 14.86d0 10.4d0 10.76d0 10.67d0 10.11d0 9.27d0 8.29d0 7.29d0 7.91d0 16.64d0 16.73d0 10.44d0 5.94d0 3.34d0 2.35d0 1.88d0 1.59d0 1.47d0 1.8d0 5.71d0 40.98d0 73.69d0 33.61d0 8.24d0 3.38d0 2.47d0 2.14d0 4.86d0 11.45d0 14.79d0 12.16d0 8.97d0 6.52d0 8.31d0 44.12d0 34.55d0 12.09d0 12.15d0 10.52d0 4.43d0 1.95d0 2.19d0 3.19d0 2.77d0 2.29d0 2d0 1.52d0 1.35d0 1.47d0 1.79d0 1.74d0 1.02d0 1.14d0 3.32d0 4.49d0 2.05d0 0.49d0 0.24d0 0.21d0 0.21d0 0.24d0 0.24d0 0.21d0 0.17d0 0.21d0 0.22d0 0.17d0 0.12d0 0.09d0))) (defparameter +illum-f11-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.91d0 0.63d0 0.46d0 0.37d0 1.29d0 12.68d0 1.59d0 1.79d0 2.46d0 3.33d0 4.49d0 33.94d0 12.13d0 6.95d0 7.19d0 7.12d0 6.72d0 6.13d0 5.46d0 4.79d0 5.66d0 14.29d0 14.96d0 8.97d0 4.72d0 2.33d0 1.47d0 1.1d0 0.89d0 0.83d0 1.18d0 4.9d0 39.59d0 72.84d0 32.61d0 7.52d0 2.83d0 1.96d0 1.67d0 4.43d0 11.28d0 14.76d0 12.73d0 9.74d0 7.33d0 9.72d0 55.27d0 42.58d0 13.18d0 13.16d0 12.26d0 5.11d0 2.07d0 2.34d0 3.58d0 3.01d0 2.48d0 2.14d0 1.54d0 1.33d0 1.46d0 1.94d0 2d0 1.2d0 1.35d0 4.1d0 5.58d0 2.51d0 0.57d0 0.27d0 0.23d0 0.21d0 0.24d0 0.24d0 0.2d0 0.24d0 0.32d0 0.26d0 0.16d0 0.12d0 0.09d0))) (defparameter +illum-f12-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.96d0 0.64d0 0.4d0 0.33d0 1.19d0 12.48d0 1.12d0 0.94d0 1.08d0 1.37d0 1.78d0 29.05d0 7.9d0 2.65d0 2.71d0 2.65d0 2.49d0 2.33d0 2.1d0 1.91d0 3.01d0 10.83d0 11.88d0 6.88d0 3.43d0 1.49d0 0.92d0 0.71d0 0.6d0 0.63d0 1.1d0 4.56d0 34.4d0 65.4d0 29.48d0 7.16d0 3.08d0 2.47d0 2.27d0 5.09d0 11.96d0 15.32d0 14.27d0 11.86d0 9.28d0 12.31d0 68.53d0 53.02d0 14.67d0 14.38d0 14.71d0 6.46d0 2.57d0 2.75d0 4.18d0 3.44d0 2.81d0 2.42d0 1.64d0 1.36d0 1.49d0 2.14d0 2.34d0 1.42d0 1.61d0 5.04d0 6.98d0 3.19d0 0.71d0 0.3d0 0.26d0 0.23d0 0.28d0 0.28d0 0.21d0 0.17d0 0.21d0 0.19d0 0.15d0 0.1d0 0.05d0)))) (defparameter +illum-f1+ (make-illuminant :spectrum (gen-spectrum +illum-f1-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f2+ (make-illuminant :spectrum (gen-spectrum +illum-f2-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f3+ (make-illuminant :spectrum (gen-spectrum +illum-f3-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f4+ (make-illuminant :spectrum (gen-spectrum +illum-f4-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f5+ (make-illuminant :spectrum (gen-spectrum +illum-f5-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f6+ (make-illuminant :spectrum (gen-spectrum +illum-f6-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f7+ (make-illuminant :spectrum (gen-spectrum +illum-f7-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f8+ (make-illuminant :spectrum (gen-spectrum +illum-f8-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f9+ (make-illuminant :spectrum (gen-spectrum +illum-f9-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f10+ (make-illuminant :spectrum (gen-spectrum +illum-f10-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f11+ (make-illuminant :spectrum (gen-spectrum +illum-f11-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f12+ (make-illuminant :spectrum (gen-spectrum +illum-f12-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t))
null
https://raw.githubusercontent.com/privet-kitty/dufy/c6ad03a9fca16a759c1c52449ac88420a536feca/src/extra-data/illuminants.lisp
lisp
Supplemental data of standard illuminants (originally contributed by wasserwerk) The white points of illuminants A, B, C, and D in dufy are illuminant B -data the same value as for F11 in next columns.
All the illuminants are defined under DUFY:+OBS - CIE1931 + ( 2 - degree observer ) (in-package :dufy/extra-data) calculated with 5 nm intervals . ( See the comment in the file with the same name in dufy / core package . ) (defparameter +illum-d55+ (make-illuminant :spectrum (gen-illum-d-spectrum 5500 :rectify t) :begin-wl 380 :end-wl 780 :band 5 :compile-time t)) (defparameter +illum-d75+ (make-illuminant :spectrum (gen-illum-d-spectrum 7500 :rectify t) :begin-wl 380 :end-wl 780 :band 5 :compile-time t)) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter +illum-b-table+ (make-array 97 :element-type 'double-float :initial-contents '(0.0d0 0.0d0 0.0d0 0.0d0 0.02d0 0.26d0 0.50d0 1.45d0 2.40d0 4.00d0 5.60d0 7.60d0 9.60d0 12.40d0 15.20d0 18.8d0 22.40d0 26.85d0 31.30d0 36.18d0 41.30d0 46.62d0 52.10d0 57.70d0 63.20d0 68.37d0 73.10d0 77.31d0 80.80d0 83.44d0 85.40d0 86.88d0 88.30d0 90.08d0 92.00d0 93.75d0 95.20d0 96.23d0 96.50d0 95.71d0 94.20d0 92.37d0 90.70d0 89.95d0 89.50d0 90.43d0 92.20d0 94.46d0 96.90d0 99.16d0 101.00d0 102.20d0 102.80d0 102.92d0 102.60d0 101.90d0 101.00d0 100.07d0 99.20d0 98.44d0 98.00d0 98.08d0 98.50d0 99.06d0 99.70d0 100.36d0 101.00d0 101.56d0 102.20d0 103.05d0 103.90d0 104.59d0 105.00d0 105.08d0 104.90d0 104.55d0 103.90d0 102.84d0 101.60d0 100.38d0 99.10d0 97.70d0 96.20d0 94.60d0 92.90d0 91.10d0 89.40d0 88.00d0 86.90d0 85.90d0 85.20d0 84.80d0 84.70d0 84.90d0 85.40d0 86.10d0 87.00d0)))) (defparameter +illum-b+ (make-illuminant :spectrum (gen-spectrum +illum-b-table+ 300 780) :begin-wl 380 :end-wl 780 :band 5 :compile-time t)) F series ( without 3.x ) Wavelength range for SPD is from 380 nm to 780 nm . Unfortunately , I could not find any sources with a range from 300 nm to 830 nm . Source for SPD : Source 1 : Source 2 : -mcsl.org/UsefulData/Fluorescents.xls Source 2 seems to have some typos . See the value for F10 for 385 nm - (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter +illum-f1-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.87d0 2.36d0 2.94d0 3.47d0 5.17d0 19.49d0 6.13d0 6.24d0 7.01d0 7.79d0 8.56d0 43.67d0 16.94d0 10.72d0 11.35d0 11.89d0 12.37d0 12.75d0 13d0 13.15d0 13.23d0 13.17d0 13.13d0 12.85d0 12.52d0 12.2d0 11.83d0 11.5d0 11.22d0 11.05d0 11.03d0 11.18d0 11.53d0 27.74d0 17.05d0 13.55d0 14.33d0 15.01d0 15.52d0 18.29d0 19.55d0 15.48d0 14.91d0 14.15d0 13.22d0 12.19d0 11.12d0 10.03d0 8.95d0 7.96d0 7.02d0 6.2d0 5.42d0 4.73d0 4.15d0 3.64d0 3.2d0 2.81d0 2.47d0 2.18d0 1.93d0 1.72d0 1.67d0 1.43d0 1.29d0 1.19d0 1.08d0 0.96d0 0.88d0 0.81d0 0.77d0 0.75d0 0.73d0 0.68d0 0.69d0 0.64d0 0.68d0 0.69d0 0.61d0 0.52d0 0.43d0))) (defparameter +illum-f2-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.18d0 1.48d0 1.84d0 2.15d0 3.44d0 15.69d0 3.85d0 3.74d0 4.19d0 4.62d0 5.06d0 34.98d0 11.81d0 6.27d0 6.63d0 6.93d0 7.19d0 7.4d0 7.54d0 7.62d0 7.65d0 7.62d0 7.62d0 7.45d0 7.28d0 7.15d0 7.05d0 7.04d0 7.16d0 7.47d0 8.04d0 8.88d0 10.01d0 24.88d0 16.64d0 14.59d0 16.16d0 17.56d0 18.62d0 21.47d0 22.79d0 19.29d0 18.66d0 17.73d0 16.54d0 15.21d0 13.8d0 12.36d0 10.95d0 9.65d0 8.4d0 7.32d0 6.31d0 5.43d0 4.68d0 4.02d0 3.45d0 2.96d0 2.55d0 2.19d0 1.89d0 1.64d0 1.53d0 1.27d0 1.1d0 0.99d0 0.88d0 0.76d0 0.68d0 0.61d0 0.56d0 0.54d0 0.51d0 0.47d0 0.47d0 0.43d0 0.46d0 0.47d0 0.4d0 0.33d0 0.27d0))) (defparameter +illum-f3-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.82d0 1.02d0 1.26d0 1.44d0 2.57d0 14.36d0 2.7d0 2.45d0 2.73d0 3d0 3.28d0 31.85d0 9.47d0 4.02d0 4.25d0 4.44d0 4.59d0 4.72d0 4.8d0 4.86d0 4.87d0 4.85d0 4.88d0 4.77d0 4.67d0 4.62d0 4.62d0 4.73d0 4.99d0 5.48d0 6.25d0 7.34d0 8.78d0 23.82d0 16.14d0 14.59d0 16.63d0 18.49d0 19.95d0 23.11d0 24.69d0 21.41d0 20.85d0 19.93d0 18.67d0 17.22d0 15.65d0 14.04d0 12.45d0 10.95d0 9.51d0 8.27d0 7.11d0 6.09d0 5.22d0 4.45d0 3.8d0 3.23d0 2.75d0 2.33d0 1.99d0 1.7d0 1.55d0 1.27d0 1.09d0 0.96d0 0.83d0 0.71d0 0.62d0 0.54d0 0.49d0 0.46d0 0.43d0 0.39d0 0.39d0 0.35d0 0.38d0 0.39d0 0.33d0 0.28d0 0.21d0))) (defparameter +illum-f4-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.57d0 0.7d0 0.87d0 0.98d0 2.01d0 13.75d0 1.95d0 1.59d0 1.76d0 1.93d0 2.1d0 30.28d0 8.03d0 2.55d0 2.7d0 2.82d0 2.91d0 2.99d0 3.04d0 3.08d0 3.09d0 3.09d0 3.14d0 3.06d0 3d0 2.98d0 3.01d0 3.14d0 3.41d0 3.9d0 4.69d0 5.81d0 7.32d0 22.59d0 15.11d0 13.88d0 16.33d0 18.68d0 20.64d0 24.28d0 26.26d0 23.28d0 22.94d0 22.14d0 20.91d0 19.43d0 17.74d0 16d0 14.42d0 12.56d0 10.93d0 9.52d0 8.18d0 7.01d0 6d0 5.11d0 4.36d0 3.69d0 3.13d0 2.64d0 2.24d0 1.91d0 1.7d0 1.39d0 1.18d0 1.03d0 0.88d0 0.74d0 0.64d0 0.54d0 0.49d0 0.46d0 0.42d0 0.37d0 0.37d0 0.33d0 0.35d0 0.36d0 0.31d0 0.26d0 0.19d0))) (defparameter +illum-f5-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.87d0 2.35d0 2.92d0 3.45d0 5.1d0 18.91d0 6d0 6.11d0 6.85d0 7.58d0 8.31d0 40.76d0 16.06d0 10.32d0 10.91d0 11.4d0 11.83d0 12.17d0 12.4d0 12.54d0 12.58d0 12.52d0 12.47d0 12.2d0 11.89d0 11.61d0 11.33d0 11.1d0 10.96d0 10.97d0 11.16d0 11.54d0 12.12d0 27.78d0 17.73d0 14.47d0 15.2d0 15.77d0 16.1d0 18.54d0 19.5d0 15.39d0 14.64d0 13.72d0 12.69d0 11.57d0 10.45d0 9.35d0 8.29d0 7.32d0 6.41d0 5.63d0 4.9d0 4.26d0 3.72d0 3.25d0 2.83d0 2.49d0 2.19d0 1.93d0 1.71d0 1.52d0 1.48d0 1.26d0 1.13d0 1.05d0 0.96d0 0.85d0 0.78d0 0.72d0 0.68d0 0.67d0 0.65d0 0.61d0 0.62d0 0.59d0 0.62d0 0.64d0 0.55d0 0.47d0 0.4d0))) (defparameter +illum-f6-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.05d0 1.31d0 1.63d0 1.9d0 3.11d0 14.8d0 3.43d0 3.3d0 3.68d0 4.07d0 4.45d0 32.61d0 10.74d0 5.48d0 5.78d0 6.03d0 6.25d0 6.41d0 6.52d0 6.58d0 6.59d0 6.56d0 6.56d0 6.42d0 6.28d0 6.2d0 6.19d0 6.3d0 6.6d0 7.12d0 7.94d0 9.07d0 10.49d0 25.22d0 17.46d0 15.63d0 17.22d0 18.53d0 19.43d0 21.97d0 23.01d0 19.41d0 18.56d0 17.42d0 16.09d0 14.64d0 13.15d0 11.68d0 10.25d0 8.95d0 7.74d0 6.69d0 5.71d0 4.87d0 4.16d0 3.55d0 3.02d0 2.57d0 2.2d0 1.87d0 1.6d0 1.37d0 1.29d0 1.05d0 0.91d0 0.81d0 0.71d0 0.61d0 0.54d0 0.48d0 0.44d0 0.43d0 0.4d0 0.37d0 0.38d0 0.35d0 0.39d0 0.41d0 0.33d0 0.26d0 0.21d0))) (defparameter +illum-f7-table+ (make-array 81 :element-type 'double-float :initial-contents '(2.56d0 3.18d0 3.84d0 4.53d0 6.15d0 19.37d0 7.37d0 7.05d0 7.71d0 8.41d0 9.15d0 44.14d0 17.52d0 11.35d0 12d0 12.58d0 13.08d0 13.45d0 13.71d0 13.88d0 13.95d0 13.93d0 13.82d0 13.64d0 13.43d0 13.25d0 13.08d0 12.93d0 12.78d0 12.6d0 12.44d0 12.33d0 12.26d0 29.52d0 17.05d0 12.44d0 12.58d0 12.72d0 12.83d0 15.46d0 16.75d0 12.83d0 12.67d0 12.45d0 12.19d0 11.89d0 11.6d0 11.35d0 11.12d0 10.95d0 10.76d0 10.42d0 10.11d0 10.04d0 10.02d0 10.11d0 9.87d0 8.65d0 7.27d0 6.44d0 5.83d0 5.41d0 5.04d0 4.57d0 4.12d0 3.77d0 3.46d0 3.08d0 2.73d0 2.47d0 2.25d0 2.06d0 1.9d0 1.75d0 1.62d0 1.54d0 1.45d0 1.32d0 1.17d0 0.99d0 0.81d0))) (defparameter +illum-f8-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.21d0 1.5d0 1.81d0 2.13d0 3.17d0 13.08d0 3.83d0 3.45d0 3.86d0 4.42d0 5.09d0 34.1d0 12.42d0 7.68d0 8.6d0 9.46d0 10.24d0 10.84d0 11.33d0 11.71d0 11.98d0 12.17d0 12.28d0 12.32d0 12.35d0 12.44d0 12.55d0 12.68d0 12.77d0 12.72d0 12.6d0 12.43d0 12.22d0 28.96d0 16.51d0 11.79d0 11.76d0 11.77d0 11.84d0 14.61d0 16.11d0 12.34d0 12.53d0 12.72d0 12.92d0 13.12d0 13.34d0 13.61d0 13.87d0 14.07d0 14.2d0 14.16d0 14.13d0 14.34d0 14.5d0 14.46d0 14d0 12.58d0 10.99d0 9.98d0 9.22d0 8.62d0 8.07d0 7.39d0 6.71d0 6.16d0 5.63d0 5.03d0 4.46d0 4.02d0 3.66d0 3.36d0 3.09d0 2.85d0 2.65d0 2.51d0 2.37d0 2.15d0 1.89d0 1.61d0 1.32d0))) (defparameter +illum-f9-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.9d0 1.12d0 1.36d0 1.6d0 2.59d0 12.8d0 3.05d0 2.56d0 2.86d0 3.3d0 3.82d0 32.62d0 10.77d0 5.84d0 6.57d0 7.25d0 7.86d0 8.35d0 8.75d0 9.06d0 9.31d0 9.48d0 9.61d0 9.68d0 9.74d0 9.88d0 10.04d0 10.26d0 10.48d0 10.63d0 10.78d0 10.96d0 11.18d0 27.71d0 16.29d0 12.28d0 12.74d0 13.21d0 13.65d0 16.57d0 18.14d0 14.55d0 14.65d0 14.66d0 14.61d0 14.5d0 14.39d0 14.4d0 14.47d0 14.62d0 14.72d0 14.55d0 14.4d0 14.58d0 14.88d0 15.51d0 15.47d0 13.2d0 10.57d0 9.18d0 8.25d0 7.57d0 7.03d0 6.35d0 5.72d0 5.25d0 4.8d0 4.29d0 3.8d0 3.43d0 3.12d0 2.86d0 2.64d0 2.43d0 2.26d0 2.14d0 2.02d0 1.83d0 1.61d0 1.38d0 1.12d0))) (defparameter +illum-f10-table+ (make-array 81 :element-type 'double-float :initial-contents '(1.11d0 0.8d0 0.62d0 0.57d0 1.48d0 12.16d0 2.12d0 2.7d0 3.74d0 5.14d0 6.75d0 34.39d0 14.86d0 10.4d0 10.76d0 10.67d0 10.11d0 9.27d0 8.29d0 7.29d0 7.91d0 16.64d0 16.73d0 10.44d0 5.94d0 3.34d0 2.35d0 1.88d0 1.59d0 1.47d0 1.8d0 5.71d0 40.98d0 73.69d0 33.61d0 8.24d0 3.38d0 2.47d0 2.14d0 4.86d0 11.45d0 14.79d0 12.16d0 8.97d0 6.52d0 8.31d0 44.12d0 34.55d0 12.09d0 12.15d0 10.52d0 4.43d0 1.95d0 2.19d0 3.19d0 2.77d0 2.29d0 2d0 1.52d0 1.35d0 1.47d0 1.79d0 1.74d0 1.02d0 1.14d0 3.32d0 4.49d0 2.05d0 0.49d0 0.24d0 0.21d0 0.21d0 0.24d0 0.24d0 0.21d0 0.17d0 0.21d0 0.22d0 0.17d0 0.12d0 0.09d0))) (defparameter +illum-f11-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.91d0 0.63d0 0.46d0 0.37d0 1.29d0 12.68d0 1.59d0 1.79d0 2.46d0 3.33d0 4.49d0 33.94d0 12.13d0 6.95d0 7.19d0 7.12d0 6.72d0 6.13d0 5.46d0 4.79d0 5.66d0 14.29d0 14.96d0 8.97d0 4.72d0 2.33d0 1.47d0 1.1d0 0.89d0 0.83d0 1.18d0 4.9d0 39.59d0 72.84d0 32.61d0 7.52d0 2.83d0 1.96d0 1.67d0 4.43d0 11.28d0 14.76d0 12.73d0 9.74d0 7.33d0 9.72d0 55.27d0 42.58d0 13.18d0 13.16d0 12.26d0 5.11d0 2.07d0 2.34d0 3.58d0 3.01d0 2.48d0 2.14d0 1.54d0 1.33d0 1.46d0 1.94d0 2d0 1.2d0 1.35d0 4.1d0 5.58d0 2.51d0 0.57d0 0.27d0 0.23d0 0.21d0 0.24d0 0.24d0 0.2d0 0.24d0 0.32d0 0.26d0 0.16d0 0.12d0 0.09d0))) (defparameter +illum-f12-table+ (make-array 81 :element-type 'double-float :initial-contents '(0.96d0 0.64d0 0.4d0 0.33d0 1.19d0 12.48d0 1.12d0 0.94d0 1.08d0 1.37d0 1.78d0 29.05d0 7.9d0 2.65d0 2.71d0 2.65d0 2.49d0 2.33d0 2.1d0 1.91d0 3.01d0 10.83d0 11.88d0 6.88d0 3.43d0 1.49d0 0.92d0 0.71d0 0.6d0 0.63d0 1.1d0 4.56d0 34.4d0 65.4d0 29.48d0 7.16d0 3.08d0 2.47d0 2.27d0 5.09d0 11.96d0 15.32d0 14.27d0 11.86d0 9.28d0 12.31d0 68.53d0 53.02d0 14.67d0 14.38d0 14.71d0 6.46d0 2.57d0 2.75d0 4.18d0 3.44d0 2.81d0 2.42d0 1.64d0 1.36d0 1.49d0 2.14d0 2.34d0 1.42d0 1.61d0 5.04d0 6.98d0 3.19d0 0.71d0 0.3d0 0.26d0 0.23d0 0.28d0 0.28d0 0.21d0 0.17d0 0.21d0 0.19d0 0.15d0 0.1d0 0.05d0)))) (defparameter +illum-f1+ (make-illuminant :spectrum (gen-spectrum +illum-f1-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f2+ (make-illuminant :spectrum (gen-spectrum +illum-f2-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f3+ (make-illuminant :spectrum (gen-spectrum +illum-f3-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f4+ (make-illuminant :spectrum (gen-spectrum +illum-f4-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f5+ (make-illuminant :spectrum (gen-spectrum +illum-f5-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f6+ (make-illuminant :spectrum (gen-spectrum +illum-f6-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f7+ (make-illuminant :spectrum (gen-spectrum +illum-f7-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f8+ (make-illuminant :spectrum (gen-spectrum +illum-f8-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f9+ (make-illuminant :spectrum (gen-spectrum +illum-f9-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f10+ (make-illuminant :spectrum (gen-spectrum +illum-f10-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f11+ (make-illuminant :spectrum (gen-spectrum +illum-f11-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t)) (defparameter +illum-f12+ (make-illuminant :spectrum (gen-spectrum +illum-f12-table+ 380 780) :begin-wl 380 :end-wl 780 :compile-time t))
cce05676969c93bbd8c63be050be7de4524c41fe6105956df59d482a5892286f
openmusic-project/openmusic
misc-types.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; misc-types.lisp --- Various tests on the type system. ;;; Copyright ( C ) 2005 - 2006 , loliveira(@)common - lisp.net > ;;; ;;; 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-tests) (defcfun ("my_strdup" strdup) :string+ptr (str :string)) (defcfun ("my_strfree" strfree) :void (str :pointer)) (deftest misc-types.string+ptr (destructuring-bind (string pointer) (strdup "foo") (strfree pointer) string) "foo") #-(and) (deftest misc-types.string+ptr.ub8 (destructuring-bind (string pointer) (strdup (make-array 3 :element-type '(unsigned-byte 8) :initial-contents (map 'list #'char-code "foo"))) (strfree pointer) string) "foo") #-(and) (deftest misc-types.string.ub8.1 (let ((array (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97)))) (with-foreign-string (foreign-string array) (foreign-string-to-lisp foreign-string))) "Turanga") #-(and) (deftest misc-types.string.ub8.2 (let ((str (foreign-string-alloc (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97))))) (prog1 (foreign-string-to-lisp str) (foreign-string-free str))) "Turanga") (defcfun "equalequal" :boolean (a (:boolean :int)) (b (:boolean :unsigned-int))) (defcfun "bool_and" (:boolean :char) (a (:boolean :unsigned-char)) (b (:boolean :char))) (defcfun "bool_xor" (:boolean :unsigned-long) (a (:boolean :long)) (b (:boolean :unsigned-long))) (deftest misc-types.boolean.1 (list (equalequal nil nil) (equalequal t t) (equalequal t 23) (bool-and 'a 'b) (bool-and "foo" nil) (bool-xor t nil) (bool-xor nil nil)) (t t t t nil t nil)) ;;; Regression test: boolean type only worked with canonicalized ;;; built-in integer types. Should work for any type that canonicalizes ;;; to a built-in integer type. (defctype int-for-bool :int) (defcfun ("equalequal" equalequal2) :boolean (a (:boolean int-for-bool)) (b (:boolean :uint))) (deftest misc-types.boolean.2 (equalequal2 nil t) nil) (defctype my-string :string+ptr) (defun funkify (str) (concatenate 'string "MORE " (string-upcase str))) (defun 3rd-person (value) (list (concatenate 'string "Strdup says: " (first value)) (second value))) ;; (defctype funky-string ;; (:wrapper my-string ;; :to-c #'funkify ;; :from-c (lambda (value) ;; (list ( concatenate ' string " says : " ( first value ) ) ( second value ) ) ) ) ;; "A useful type.") (defctype funky-string (:wrapper my-string :to-c funkify :from-c 3rd-person)) (defcfun ("my_strdup" funky-strdup) funky-string (str funky-string)) (deftest misc-types.wrapper (destructuring-bind (string ptr) (funky-strdup "code") (strfree ptr) string) "Strdup says: MORE CODE") (deftest misc-types.sized-ints (mapcar #'foreign-type-size '(:int8 :uint8 :int16 :uint16 :int32 :uint32 :int64 :uint64)) (1 1 2 2 4 4 8 8)) (define-foreign-type error-error () () (:actual-type :int) (:simple-parser error-error)) (defmethod translate-to-foreign (value (type error-error)) (declare (ignore value)) (error "translate-to-foreign invoked.")) (defmethod translate-from-foreign (value (type error-error)) (declare (ignore value)) (error "translate-from-foreign invoked.")) (eval-when (:load-toplevel :compile-toplevel :execute) (defmethod expand-to-foreign (value (type error-error)) value) (defmethod expand-from-foreign (value (type error-error)) value)) (defcfun ("abs" expand-abs) error-error (n error-error)) (defcvar ("var_int" *expand-var-int*) error-error) (defcfun ("expect_int_sum" expand-expect-int-sum) :boolean (cb :pointer)) (defcallback expand-int-sum error-error ((x error-error) (y error-error)) (+ x y)) ;;; Ensure that macroexpansion-time translators are called where this is guaranteed ( defcfun , defcvar , foreign - funcall and ) (deftest misc-types.expand.1 (expand-abs -1) 1) #-cffi-sys::no-foreign-funcall (deftest misc-types.expand.2 (foreign-funcall "abs" error-error -1 error-error) 1) (deftest misc-types.expand.3 (let ((old (mem-ref (get-var-pointer '*expand-var-int*) :int))) (unwind-protect (progn (setf *expand-var-int* 42) *expand-var-int*) (setf (mem-ref (get-var-pointer '*expand-var-int*) :int) old))) 42) (deftest misc-types.expand.4 (expand-expect-int-sum (callback expand-int-sum)) t) (define-foreign-type translate-tracker () () (:actual-type :int) (:simple-parser translate-tracker)) (declaim (special .fto-called.)) (defmethod free-translated-object (value (type translate-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (define-foreign-type expand-tracker () () (:actual-type :int) (:simple-parser expand-tracker)) (defmethod free-translated-object (value (type expand-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (eval-when (:compile-toplevel :load-toplevel :execute) (defmethod expand-to-foreign (value (type expand-tracker)) (declare (ignore value)) (call-next-method))) (defcfun ("abs" ttracker-abs) :int (n translate-tracker)) (defcfun ("abs" etracker-abs) :int (n expand-tracker)) ;; free-translated-object must be called when there is no etf (deftest misc-types.expand.5 (let ((.fto-called. nil)) (ttracker-abs -1) .fto-called.) t) ;; free-translated-object must be called when there is an etf, but ;; they answer *runtime-translator-form* (deftest misc-types.expand.6 (let ((.fto-called. nil)) (etracker-abs -1) .fto-called.) t) (define-foreign-type misc-type.expand.7 () () (:actual-type :int) (:simple-parser misc-type.expand.7)) (defmethod translate-to-foreign (value (type misc-type.expand.7)) (values value 'second-value)) ;; Auxiliary function to test CONVERT-TO-FOREIGN's compiler macro. (defun misc-type.expand.7-aux () (convert-to-foreign "foo" 'misc-type.expand.7)) Checking that expand - to - foreign does n't ignore the second value of ;; translate-to-foreign. (deftest misc-type.expand.7 (misc-type.expand.7-aux) "foo" second-value) Like MISC - TYPE.EXPAND.7 but does n't depend on compiler macros ;; kicking in. (deftest misc-type.expand.8 (eval (expand-to-foreign "foo" (cffi::parse-type 'misc-type.expand.7))) "foo" second-value)
null
https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/api/foreign-interface/ffi/CFFI/tests/misc-types.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- misc-types.lisp --- Various tests on the type system. 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. Regression test: boolean type only worked with canonicalized built-in integer types. Should work for any type that canonicalizes to a built-in integer type. (defctype funky-string (:wrapper my-string :to-c #'funkify :from-c (lambda (value) (list "A useful type.") Ensure that macroexpansion-time translators are called where this free-translated-object must be called when there is no etf free-translated-object must be called when there is an etf, but they answer *runtime-translator-form* Auxiliary function to test CONVERT-TO-FOREIGN's compiler macro. translate-to-foreign. kicking in.
Copyright ( C ) 2005 - 2006 , loliveira(@)common - lisp.net > 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-tests) (defcfun ("my_strdup" strdup) :string+ptr (str :string)) (defcfun ("my_strfree" strfree) :void (str :pointer)) (deftest misc-types.string+ptr (destructuring-bind (string pointer) (strdup "foo") (strfree pointer) string) "foo") #-(and) (deftest misc-types.string+ptr.ub8 (destructuring-bind (string pointer) (strdup (make-array 3 :element-type '(unsigned-byte 8) :initial-contents (map 'list #'char-code "foo"))) (strfree pointer) string) "foo") #-(and) (deftest misc-types.string.ub8.1 (let ((array (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97)))) (with-foreign-string (foreign-string array) (foreign-string-to-lisp foreign-string))) "Turanga") #-(and) (deftest misc-types.string.ub8.2 (let ((str (foreign-string-alloc (make-array 7 :element-type '(unsigned-byte 8) :initial-contents '(84 117 114 97 110 103 97))))) (prog1 (foreign-string-to-lisp str) (foreign-string-free str))) "Turanga") (defcfun "equalequal" :boolean (a (:boolean :int)) (b (:boolean :unsigned-int))) (defcfun "bool_and" (:boolean :char) (a (:boolean :unsigned-char)) (b (:boolean :char))) (defcfun "bool_xor" (:boolean :unsigned-long) (a (:boolean :long)) (b (:boolean :unsigned-long))) (deftest misc-types.boolean.1 (list (equalequal nil nil) (equalequal t t) (equalequal t 23) (bool-and 'a 'b) (bool-and "foo" nil) (bool-xor t nil) (bool-xor nil nil)) (t t t t nil t nil)) (defctype int-for-bool :int) (defcfun ("equalequal" equalequal2) :boolean (a (:boolean int-for-bool)) (b (:boolean :uint))) (deftest misc-types.boolean.2 (equalequal2 nil t) nil) (defctype my-string :string+ptr) (defun funkify (str) (concatenate 'string "MORE " (string-upcase str))) (defun 3rd-person (value) (list (concatenate 'string "Strdup says: " (first value)) (second value))) ( concatenate ' string " says : " ( first value ) ) ( second value ) ) ) ) (defctype funky-string (:wrapper my-string :to-c funkify :from-c 3rd-person)) (defcfun ("my_strdup" funky-strdup) funky-string (str funky-string)) (deftest misc-types.wrapper (destructuring-bind (string ptr) (funky-strdup "code") (strfree ptr) string) "Strdup says: MORE CODE") (deftest misc-types.sized-ints (mapcar #'foreign-type-size '(:int8 :uint8 :int16 :uint16 :int32 :uint32 :int64 :uint64)) (1 1 2 2 4 4 8 8)) (define-foreign-type error-error () () (:actual-type :int) (:simple-parser error-error)) (defmethod translate-to-foreign (value (type error-error)) (declare (ignore value)) (error "translate-to-foreign invoked.")) (defmethod translate-from-foreign (value (type error-error)) (declare (ignore value)) (error "translate-from-foreign invoked.")) (eval-when (:load-toplevel :compile-toplevel :execute) (defmethod expand-to-foreign (value (type error-error)) value) (defmethod expand-from-foreign (value (type error-error)) value)) (defcfun ("abs" expand-abs) error-error (n error-error)) (defcvar ("var_int" *expand-var-int*) error-error) (defcfun ("expect_int_sum" expand-expect-int-sum) :boolean (cb :pointer)) (defcallback expand-int-sum error-error ((x error-error) (y error-error)) (+ x y)) is guaranteed ( defcfun , defcvar , foreign - funcall and ) (deftest misc-types.expand.1 (expand-abs -1) 1) #-cffi-sys::no-foreign-funcall (deftest misc-types.expand.2 (foreign-funcall "abs" error-error -1 error-error) 1) (deftest misc-types.expand.3 (let ((old (mem-ref (get-var-pointer '*expand-var-int*) :int))) (unwind-protect (progn (setf *expand-var-int* 42) *expand-var-int*) (setf (mem-ref (get-var-pointer '*expand-var-int*) :int) old))) 42) (deftest misc-types.expand.4 (expand-expect-int-sum (callback expand-int-sum)) t) (define-foreign-type translate-tracker () () (:actual-type :int) (:simple-parser translate-tracker)) (declaim (special .fto-called.)) (defmethod free-translated-object (value (type translate-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (define-foreign-type expand-tracker () () (:actual-type :int) (:simple-parser expand-tracker)) (defmethod free-translated-object (value (type expand-tracker) param) (declare (ignore value param)) (setf .fto-called. t)) (eval-when (:compile-toplevel :load-toplevel :execute) (defmethod expand-to-foreign (value (type expand-tracker)) (declare (ignore value)) (call-next-method))) (defcfun ("abs" ttracker-abs) :int (n translate-tracker)) (defcfun ("abs" etracker-abs) :int (n expand-tracker)) (deftest misc-types.expand.5 (let ((.fto-called. nil)) (ttracker-abs -1) .fto-called.) t) (deftest misc-types.expand.6 (let ((.fto-called. nil)) (etracker-abs -1) .fto-called.) t) (define-foreign-type misc-type.expand.7 () () (:actual-type :int) (:simple-parser misc-type.expand.7)) (defmethod translate-to-foreign (value (type misc-type.expand.7)) (values value 'second-value)) (defun misc-type.expand.7-aux () (convert-to-foreign "foo" 'misc-type.expand.7)) Checking that expand - to - foreign does n't ignore the second value of (deftest misc-type.expand.7 (misc-type.expand.7-aux) "foo" second-value) Like MISC - TYPE.EXPAND.7 but does n't depend on compiler macros (deftest misc-type.expand.8 (eval (expand-to-foreign "foo" (cffi::parse-type 'misc-type.expand.7))) "foo" second-value)
3480b457b3ef9c9ae3a75dcdb03e4ea5d0e9b975ebfd88e50b82a12f445d9034
jedimahdi/soltan
Log.hs
module Hokm.Api.Network.Wai.Log ( logMiddleware ) where import Colog ( LogAction, usingLoggerT ) import Control.Lens ( (^.) ) import qualified Data.ByteString as W8 import qualified Data.List as List import qualified Data.Text as Text import qualified Hokm.Api.Data.Jwt as Jwt import Hokm.Api.Servant.Authentication import qualified Hokm.Data.ByteString as W8 import qualified Hokm.Logger as Logger import qualified Hokm.Logger.Message as Logger.Message import Network.HTTP.Types ( hAuthorization, hCookie ) import Network.HTTP.Types.Status ( Status (..) ) import Network.Wai ( Middleware, Request (..), responseStatus ) import Network.Wai.Logger import Web.Cookie ( parseCookies ) getClaims :: Request -> IO (Maybe Jwt.PrivateClaims) getClaims request = maybe (pure Nothing) ((fmap . fmap) Jwt.getPrivateClaims . Jwt.decode) token where cookies = request |> requestHeaders |> List.lookup hCookie |> fmap parseCookies tokenFromCookies = Jwt.reassociate <$> (cookies >>= List.lookup headerAndPayloadCookieName) <*> (cookies >>= List.lookup signatureCookieName) tokenFromAuthorization = (request |> requestHeaders |> List.lookup hAuthorization) >>= fmap W8.trim . W8.stripPrefix authorizationHeaderPrefix token = tokenFromCookies <|> tokenFromAuthorization apacheLog :: Request -> Int -> Maybe Jwt.PrivateClaims -> Text apacheLog req responseCode mclaims = ip <> " - " <> userId <> "\"" <> decodeUtf8 method <> " " <> decodeUtf8 path <> " " <> show (httpVersion req) <> "\" " <> show responseCode where ip = toText . showSockAddr . remoteHost <| req path = rawPathInfo req <> rawQueryString req method = requestMethod req userId = case mclaims of Nothing -> "- " Just claims -> show (claims ^. #userId) <> " " logMiddleware :: LogAction IO Logger.Message.Minimal -> Middleware logMiddleware logger app req respond = app req <| \response -> do let responseCode = statusCode . responseStatus <| response claims <- getClaims req usingLoggerT logger <| Logger.info (apacheLog req responseCode claims) respond response
null
https://raw.githubusercontent.com/jedimahdi/soltan/50a97213ec83c81f5ec79898e2855d0c5e78f06c/backend/hokm-api/src/Hokm/Api/Network/Wai/Log.hs
haskell
module Hokm.Api.Network.Wai.Log ( logMiddleware ) where import Colog ( LogAction, usingLoggerT ) import Control.Lens ( (^.) ) import qualified Data.ByteString as W8 import qualified Data.List as List import qualified Data.Text as Text import qualified Hokm.Api.Data.Jwt as Jwt import Hokm.Api.Servant.Authentication import qualified Hokm.Data.ByteString as W8 import qualified Hokm.Logger as Logger import qualified Hokm.Logger.Message as Logger.Message import Network.HTTP.Types ( hAuthorization, hCookie ) import Network.HTTP.Types.Status ( Status (..) ) import Network.Wai ( Middleware, Request (..), responseStatus ) import Network.Wai.Logger import Web.Cookie ( parseCookies ) getClaims :: Request -> IO (Maybe Jwt.PrivateClaims) getClaims request = maybe (pure Nothing) ((fmap . fmap) Jwt.getPrivateClaims . Jwt.decode) token where cookies = request |> requestHeaders |> List.lookup hCookie |> fmap parseCookies tokenFromCookies = Jwt.reassociate <$> (cookies >>= List.lookup headerAndPayloadCookieName) <*> (cookies >>= List.lookup signatureCookieName) tokenFromAuthorization = (request |> requestHeaders |> List.lookup hAuthorization) >>= fmap W8.trim . W8.stripPrefix authorizationHeaderPrefix token = tokenFromCookies <|> tokenFromAuthorization apacheLog :: Request -> Int -> Maybe Jwt.PrivateClaims -> Text apacheLog req responseCode mclaims = ip <> " - " <> userId <> "\"" <> decodeUtf8 method <> " " <> decodeUtf8 path <> " " <> show (httpVersion req) <> "\" " <> show responseCode where ip = toText . showSockAddr . remoteHost <| req path = rawPathInfo req <> rawQueryString req method = requestMethod req userId = case mclaims of Nothing -> "- " Just claims -> show (claims ^. #userId) <> " " logMiddleware :: LogAction IO Logger.Message.Minimal -> Middleware logMiddleware logger app req respond = app req <| \response -> do let responseCode = statusCode . responseStatus <| response claims <- getClaims req usingLoggerT logger <| Logger.info (apacheLog req responseCode claims) respond response
775b2f651f70e94bbcaf4fdf4ae27ec03fd893a9eba5a6a76a65895a7736da67
leo-zz-shuu/mfc
Utils.hs
module Macaf.Utils where import Control.Monad.State locally :: MonadState s m => m a -> m a locally computation = do oldState <- get result <- computation put oldState return result
null
https://raw.githubusercontent.com/leo-zz-shuu/mfc/4a9762727b87d079a914d2c5cd411a2e04a1982f/src/Macaf/Utils.hs
haskell
module Macaf.Utils where import Control.Monad.State locally :: MonadState s m => m a -> m a locally computation = do oldState <- get result <- computation put oldState return result
207bda6902b05e9d61ff98673898df0bd9fb6b6224d6ff3855772ad7dfd72062
reborg/clojure-essential-reference
4.clj
< 1 > Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. nil < 2 > 2
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/TheToolbox/clojure.core.server/4.clj
clojure
< 1 > Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. nil < 2 > 2
c78145b5a2327046e710369a5a0544e4278518b267a3c87945d496ef3d1610e6
slipstream/SlipStreamServer
javawrapper.clj
(ns sixsq.slipstream.prs.javawrapper " # Java interface to library for interaction with Placement and Ranking Service. " {:doc/format :markdown} (:require [clojure.data.json :as json] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.walk :as walk]) (:import [com.sixsq.slipstream.configuration Configuration] [com.sixsq.slipstream.persistence ImageModule Module ModuleCategory ModuleCategory] [java.util List Map Set] ) (:gen-class :name sixsq.slipstream.prs.core.JavaWrapper :methods [#^{:static true} [generatePrsRequest [java.util.Map] String]])) (defn keyword-name "Function that converts a keyword to a string taking into account the keyword namespace." [k] (if (keyword? k) (str/join "/" (remove nil? ((juxt namespace name) k))) (str k))) (defn java->clj "Transform java data structures into the equivalent clojure data structures. Elements that are not a Map, List, or Set are left unchanged." [data] (cond (instance? Map data) (into {} (map (fn [[k v]] [k (java->clj v)]) data)) (instance? List data) (into [] (map #(java->clj %) data)) (instance? Set data) (into #{} (map #(java->clj %) data)) :else data)) (defn- parameter-value [comp param-name] (if-let [param (.. comp (getParameter param-name))] (.getValue param))) (defn try-extract-digit [value] (re-find #"[\d.]+" (str value))) (defn get-orch-param [connector param-name] (-> (Configuration/getInstance) (.getProperty (format "%s.orchestrator.%s" connector param-name)))) (defn- connector-instance-types [comp user-connector] (let [connector-params {:instance.type (parameter-value comp (str user-connector ".instance.type")) :cpu (try-extract-digit (parameter-value comp (str user-connector ".cpu"))) :ram (try-extract-digit (parameter-value comp (str user-connector ".ram"))) :disk (try-extract-digit (parameter-value comp (str user-connector ".disk")))} connector-params (into {} (filter val connector-params))] {user-connector connector-params})) (defn- orchestrator-instance-types [user-connector] (let [connector-params {:instance.type (get-orch-param user-connector "instance.type") :cpu (or (try-extract-digit (or (get-orch-param user-connector "cpu.size") (get-orch-param user-connector "cpu"))) 0) :ram (or (try-extract-digit (or (get-orch-param user-connector "ram.size") (get-orch-param user-connector "ram"))) 0) :disk (or (try-extract-digit (or (get-orch-param user-connector "disk.size") (get-orch-param user-connector "disk"))) 0)}] {user-connector connector-params})) (defn- comp->map [comp user-connectors] {:module (.getResourceUri comp) :cpu.nb (parameter-value comp "cpu.nb") :ram.GB (parameter-value comp "ram.GB") :disk.GB (parameter-value comp "disk.GB") :operating-system (if (= "windows" (.getPlatform comp)) "windows" "linux") :placement-policy (.getPlacementPolicy comp) :connector-instance-types (apply merge (map (partial connector-instance-types comp) user-connectors))}) (defn- orch-node->map [user-connectors] {:module "module-orchestrator" :node "node-orchestrator" :cpu.nb nil :ram.GB nil :disk.GB nil :operating-system "linux" :placement-policy nil :connector-instance-types (apply merge (map orchestrator-instance-types user-connectors))}) (defn- node->map [user-connectors [node-name node]] (-> (.getImage node) (comp->map user-connectors) (assoc :node node-name))) (defn- app->map [app user-connectors] (map (partial node->map user-connectors) (.getNodes app))) (defn- component? [module] (= (.getCategory module) ModuleCategory/Image)) (defn- app? [module] (= (.getCategory module) ModuleCategory/Deployment)) (defn- throw-wrong-category [module] (throw (Exception. (format "Expected module of category %s or %s. Got %s" ModuleCategory/Image ModuleCategory/Deployment (.getCategory module))))) (defn- module->components [module user-connectors] (cond (component? module) [(comp->map module user-connectors)] (app? module) (app->map module user-connectors) :else (throw-wrong-category module))) (defn- add-orchestrator-component [m user-connectors] (update m :components #(conj % (orch-node->map user-connectors)))) (defn- explode-module [m] (-> m (assoc :components (module->components (:module m) (:user-connectors m))) (add-orchestrator-component (:user-connectors m)) (dissoc :module))) (defn placement->map "Converts java-placement (Java Map) to Clojure data structure. The module object is extracted as a list of components." [java-placement] (-> java-placement java->clj walk/keywordize-keys explode-module)) (defn -generatePrsRequest "Generate PRS request based on module and users connector information. Input { :module Module // java object - ImageModule or DeploymentModule :user-connectors ['c1' 'c2'] // list of strings } Output: valid JSON to contact PRS service. " [input] (log/debug "Generating PRS request for:" input) (-> input placement->map (json/write-str :key-fn keyword-name)))
null
https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/jar-prslib/src/clj/sixsq/slipstream/prs/javawrapper.clj
clojure
(ns sixsq.slipstream.prs.javawrapper " # Java interface to library for interaction with Placement and Ranking Service. " {:doc/format :markdown} (:require [clojure.data.json :as json] [clojure.string :as str] [clojure.tools.logging :as log] [clojure.walk :as walk]) (:import [com.sixsq.slipstream.configuration Configuration] [com.sixsq.slipstream.persistence ImageModule Module ModuleCategory ModuleCategory] [java.util List Map Set] ) (:gen-class :name sixsq.slipstream.prs.core.JavaWrapper :methods [#^{:static true} [generatePrsRequest [java.util.Map] String]])) (defn keyword-name "Function that converts a keyword to a string taking into account the keyword namespace." [k] (if (keyword? k) (str/join "/" (remove nil? ((juxt namespace name) k))) (str k))) (defn java->clj "Transform java data structures into the equivalent clojure data structures. Elements that are not a Map, List, or Set are left unchanged." [data] (cond (instance? Map data) (into {} (map (fn [[k v]] [k (java->clj v)]) data)) (instance? List data) (into [] (map #(java->clj %) data)) (instance? Set data) (into #{} (map #(java->clj %) data)) :else data)) (defn- parameter-value [comp param-name] (if-let [param (.. comp (getParameter param-name))] (.getValue param))) (defn try-extract-digit [value] (re-find #"[\d.]+" (str value))) (defn get-orch-param [connector param-name] (-> (Configuration/getInstance) (.getProperty (format "%s.orchestrator.%s" connector param-name)))) (defn- connector-instance-types [comp user-connector] (let [connector-params {:instance.type (parameter-value comp (str user-connector ".instance.type")) :cpu (try-extract-digit (parameter-value comp (str user-connector ".cpu"))) :ram (try-extract-digit (parameter-value comp (str user-connector ".ram"))) :disk (try-extract-digit (parameter-value comp (str user-connector ".disk")))} connector-params (into {} (filter val connector-params))] {user-connector connector-params})) (defn- orchestrator-instance-types [user-connector] (let [connector-params {:instance.type (get-orch-param user-connector "instance.type") :cpu (or (try-extract-digit (or (get-orch-param user-connector "cpu.size") (get-orch-param user-connector "cpu"))) 0) :ram (or (try-extract-digit (or (get-orch-param user-connector "ram.size") (get-orch-param user-connector "ram"))) 0) :disk (or (try-extract-digit (or (get-orch-param user-connector "disk.size") (get-orch-param user-connector "disk"))) 0)}] {user-connector connector-params})) (defn- comp->map [comp user-connectors] {:module (.getResourceUri comp) :cpu.nb (parameter-value comp "cpu.nb") :ram.GB (parameter-value comp "ram.GB") :disk.GB (parameter-value comp "disk.GB") :operating-system (if (= "windows" (.getPlatform comp)) "windows" "linux") :placement-policy (.getPlacementPolicy comp) :connector-instance-types (apply merge (map (partial connector-instance-types comp) user-connectors))}) (defn- orch-node->map [user-connectors] {:module "module-orchestrator" :node "node-orchestrator" :cpu.nb nil :ram.GB nil :disk.GB nil :operating-system "linux" :placement-policy nil :connector-instance-types (apply merge (map orchestrator-instance-types user-connectors))}) (defn- node->map [user-connectors [node-name node]] (-> (.getImage node) (comp->map user-connectors) (assoc :node node-name))) (defn- app->map [app user-connectors] (map (partial node->map user-connectors) (.getNodes app))) (defn- component? [module] (= (.getCategory module) ModuleCategory/Image)) (defn- app? [module] (= (.getCategory module) ModuleCategory/Deployment)) (defn- throw-wrong-category [module] (throw (Exception. (format "Expected module of category %s or %s. Got %s" ModuleCategory/Image ModuleCategory/Deployment (.getCategory module))))) (defn- module->components [module user-connectors] (cond (component? module) [(comp->map module user-connectors)] (app? module) (app->map module user-connectors) :else (throw-wrong-category module))) (defn- add-orchestrator-component [m user-connectors] (update m :components #(conj % (orch-node->map user-connectors)))) (defn- explode-module [m] (-> m (assoc :components (module->components (:module m) (:user-connectors m))) (add-orchestrator-component (:user-connectors m)) (dissoc :module))) (defn placement->map "Converts java-placement (Java Map) to Clojure data structure. The module object is extracted as a list of components." [java-placement] (-> java-placement java->clj walk/keywordize-keys explode-module)) (defn -generatePrsRequest "Generate PRS request based on module and users connector information. Input { :module Module // java object - ImageModule or DeploymentModule :user-connectors ['c1' 'c2'] // list of strings } Output: valid JSON to contact PRS service. " [input] (log/debug "Generating PRS request for:" input) (-> input placement->map (json/write-str :key-fn keyword-name)))
088bb9a42b6af6343558d9c550de8eed6662b13efb9874ef3c324da30db4fc0a
active-group/active-clojure
debug.clj
(ns active.clojure.debug) (defmacro pret [x] "Print and return the argument." `(let [x# ~x] (println x#) x#))
null
https://raw.githubusercontent.com/active-group/active-clojure/44050a1292fa610dde732d5fbfc42c37ad976d3a/src/active/clojure/debug.clj
clojure
(ns active.clojure.debug) (defmacro pret [x] "Print and return the argument." `(let [x# ~x] (println x#) x#))
b2ce9fd4a46348d94abc6bd502cb3df4406ae6a25aaf9bb20debe39a929f8009
inria-parkas/sundialsml
cvRoberts_dns_constraints.ml
* ----------------------------------------------------------------- * $ Revision : 1.2 $ * $ Date : 2008/12/29 22:21:29 $ * ----------------------------------------------------------------- * Programmer(s ): , and * @ LLNL * ----------------------------------------------------------------- * OCaml port : , , Feb 2019 . * ----------------------------------------------------------------- * Example problem : * * The following is a simple example problem , with the coding * needed for its solution by CVODE . The problem is from * chemical kinetics , and consists of the following three rate * equations : * dy1 / dt = -.04*y1 + 1.e4*y2*y3 * dy2 / dt = - 3.e7*(y2)^2 * dy3 / dt = 3.e7*(y2)^2 * on the interval from t = 0.0 to t = 4.e10 , with initial * conditions : y1 = 1.0 , y2 = y3 = 0 . The problem is stiff . * While integrating the system , we also use the rootfinding * feature to find the points at which y1 = 1e-4 or at which * y3 = 0.01 . This program solves the problem with the BDF method , * iteration with the CVDENSE dense linear solver , and a * user - supplied Jacobian routine . It uses a scalar relative tolerance * and a vector absolute tolerance . The constraint y_i > = 0 is * posed for all components . Output is printed in decades * from t = .4 to t = 4.e10 . Run statistics ( optional outputs ) * are printed at the end . * ----------------------------------------------------------------- * ----------------------------------------------------------------- * $Revision: 1.2 $ * $Date: 2008/12/29 22:21:29 $ * ----------------------------------------------------------------- * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and * Radu Serban @ LLNL * ----------------------------------------------------------------- * OCaml port: Timothy Bourke, Inria, Feb 2019. * ----------------------------------------------------------------- * Example problem: * * The following is a simple example problem, with the coding * needed for its solution by CVODE. The problem is from * chemical kinetics, and consists of the following three rate * equations: * dy1/dt = -.04*y1 + 1.e4*y2*y3 * dy2/dt = .04*y1 - 1.e4*y2*y3 - 3.e7*(y2)^2 * dy3/dt = 3.e7*(y2)^2 * on the interval from t = 0.0 to t = 4.e10, with initial * conditions: y1 = 1.0, y2 = y3 = 0. The problem is stiff. * While integrating the system, we also use the rootfinding * feature to find the points at which y1 = 1e-4 or at which * y3 = 0.01. This program solves the problem with the BDF method, * Newton iteration with the CVDENSE dense linear solver, and a * user-supplied Jacobian routine. It uses a scalar relative tolerance * and a vector absolute tolerance. The constraint y_i >= 0 is * posed for all components. Output is printed in decades * from t = .4 to t = 4.e10. Run statistics (optional outputs) * are printed at the end. * ----------------------------------------------------------------- *) open Sundials let unwrap = Nvector.unwrap let printf = Printf.printf let ith (v : RealArray.t) i = v.{i - 1} let set_ith (v : RealArray.t) i e = v.{i - 1} <- e (* Problem Constants *) let neq = 3 (* number of equations *) let y1 = 1.0 (* initial y components *) let y2 = 0.0 let y3 = 0.0 let rtol = 1.0e-4 (* scalar relative tolerance *) let atol1 = 1.0e-6 (* vector absolute tolerance components *) let atol2 = 1.0e-11 let atol3 = 1.0e-5 let t0 = 0.0 (* initial time *) let t1 = 0.4 (* first output time *) let tmult = 10.0 (* output time factor *) let nout = 12 (* number of output times *) let nroots = 2 (* number of root functions *) let f _ (y : RealArray.t) (yd : RealArray.t) = let yd1 = -0.04 *. y.{0} +. 1.0e4 *. y.{1} *. y.{2} and yd3 = 3.0e7 *. y.{1} *. y.{1} in yd.{0} <- yd1; yd.{1} <- (-. yd1 -. yd3); yd.{2} <- yd3 let g _ (y : RealArray.t) (gout : RealArray.t) = gout.{0} <- y.{0} -. 0.0001; gout.{1} <- y.{2} -. 0.01 let jac {Cvode.jac_y = (y : RealArray.t)} jmat = let set = Matrix.Dense.set jmat in set 0 0 (-0.04); set 0 1 (1.0e4 *. y.{2}); set 0 2 (1.0e4 *. y.{1}); set 1 0 (0.04); set 1 1 (-1.0e4 *. y.{2} -. 6.0e7 *. y.{1}); set 1 2 (-1.0e4 *. y.{1}); set 2 1 (6.0e7 *. y.{1}) let print_output = printf "At t = %0.4e y =%14.6e %14.6e %14.6e\n" let print_root_info r1 r2 = printf " rootsfound[] = %3d %3d\n" (Roots.int_of_root r1) (Roots.int_of_root r2) let print_final_stats s = let open Cvode in let nst = get_num_steps s and nfe = get_num_rhs_evals s and nsetups = get_num_lin_solv_setups s and netf = get_num_err_test_fails s and nni = get_num_nonlin_solv_iters s and ncfn = get_num_nonlin_solv_conv_fails s and nje = Dls.get_num_jac_evals s and nfeLS = Dls.get_num_lin_rhs_evals s and nge = get_num_g_evals s in printf "\nFinal Statistics:\n"; printf "nst = %-6d nfe = %-6d nsetups = %-6d nfeLS = %-6d nje = %d\n" nst nfe nsetups nfeLS nje; printf "nni = %-6d ncfn = %-6d netf = %-6d nge = %d\n \n" nni ncfn netf nge let main () = Create serial vector of length NEQ for I.C. and abstol , and constraints let y = Nvector_serial.make neq 0.0 and abstol = RealArray.create neq and constraints = Nvector_serial.make neq Constraint.geq_zero and roots = Roots.create nroots in let ydata = unwrap y in let r = Roots.get roots in Initialize y set_ith ydata 1 y1; set_ith ydata 2 y2; set_ith ydata 3 y3; (* Set the vector absolute tolerance *) set_ith abstol 1 atol1; set_ith abstol 2 atol2; set_ith abstol 3 atol3; printf " \n3-species kinetics problem\n\n"; Call CVodeCreate to create the solver memory and specify the * Backward Differentiation Formula and the use of a Newton iteration * Backward Differentiation Formula and the use of a Newton iteration *) (* Call CVodeInit to initialize the integrator memory and specify the * user's right hand side function in y'=f(t,y), the inital time T0, and * the initial dependent variable vector y. *) Call CVodeRootInit to specify the root function g with 2 components Call CVDense to specify the CVDENSE dense linear solver Set the Jacobian routine to ( user - supplied ) let m = Matrix.dense neq in let cvode_mem = Cvode.(init BDF ~lsolver:Dls.(solver ~jac:jac (dense y m)) (SVtolerances (rtol, (Nvector_serial.wrap abstol))) f ~roots:(nroots, g) t0 y) in Cvode.set_constraints cvode_mem constraints; In loop , call CVode , print results , and test for error . Break out of loop when NOUT preset output times have been reached . Break out of loop when NOUT preset output times have been reached. *) let tout = ref t1 and iout = ref 0 in while (!iout <> nout) do let (t, flag) = Cvode.solve_normal cvode_mem !tout y in print_output t (ith ydata 1) (ith ydata 2) (ith ydata 3); match flag with | Cvode.RootsFound -> Cvode.get_root_info cvode_mem roots; print_root_info (r 0) (r 1) | Cvode.Success -> iout := !iout + 1; tout := !tout *. tmult | Cvode.StopTimeReached -> iout := nout done; (* Print some final statistics *) print_final_stats cvode_mem (* Check environment variables for extra arguments. *) let reps = try int_of_string (Unix.getenv "NUM_REPS") with Not_found | Failure _ -> 1 let gc_at_end = try int_of_string (Unix.getenv "GC_AT_END") <> 0 with Not_found | Failure _ -> false let gc_each_rep = try int_of_string (Unix.getenv "GC_EACH_REP") <> 0 with Not_found | Failure _ -> false (* Entry point *) let _ = for _ = 1 to reps do main (); if gc_each_rep then Gc.compact () done; if gc_at_end then Gc.compact ()
null
https://raw.githubusercontent.com/inria-parkas/sundialsml/a1848318cac2e340c32ddfd42671bef07b1390db/examples/cvode/serial/cvRoberts_dns_constraints.ml
ocaml
Problem Constants number of equations initial y components scalar relative tolerance vector absolute tolerance components initial time first output time output time factor number of output times number of root functions Set the vector absolute tolerance Call CVodeInit to initialize the integrator memory and specify the * user's right hand side function in y'=f(t,y), the inital time T0, and * the initial dependent variable vector y. Print some final statistics Check environment variables for extra arguments. Entry point
* ----------------------------------------------------------------- * $ Revision : 1.2 $ * $ Date : 2008/12/29 22:21:29 $ * ----------------------------------------------------------------- * Programmer(s ): , and * @ LLNL * ----------------------------------------------------------------- * OCaml port : , , Feb 2019 . * ----------------------------------------------------------------- * Example problem : * * The following is a simple example problem , with the coding * needed for its solution by CVODE . The problem is from * chemical kinetics , and consists of the following three rate * equations : * dy1 / dt = -.04*y1 + 1.e4*y2*y3 * dy2 / dt = - 3.e7*(y2)^2 * dy3 / dt = 3.e7*(y2)^2 * on the interval from t = 0.0 to t = 4.e10 , with initial * conditions : y1 = 1.0 , y2 = y3 = 0 . The problem is stiff . * While integrating the system , we also use the rootfinding * feature to find the points at which y1 = 1e-4 or at which * y3 = 0.01 . This program solves the problem with the BDF method , * iteration with the CVDENSE dense linear solver , and a * user - supplied Jacobian routine . It uses a scalar relative tolerance * and a vector absolute tolerance . The constraint y_i > = 0 is * posed for all components . Output is printed in decades * from t = .4 to t = 4.e10 . Run statistics ( optional outputs ) * are printed at the end . * ----------------------------------------------------------------- * ----------------------------------------------------------------- * $Revision: 1.2 $ * $Date: 2008/12/29 22:21:29 $ * ----------------------------------------------------------------- * Programmer(s): Scott D. Cohen, Alan C. Hindmarsh and * Radu Serban @ LLNL * ----------------------------------------------------------------- * OCaml port: Timothy Bourke, Inria, Feb 2019. * ----------------------------------------------------------------- * Example problem: * * The following is a simple example problem, with the coding * needed for its solution by CVODE. The problem is from * chemical kinetics, and consists of the following three rate * equations: * dy1/dt = -.04*y1 + 1.e4*y2*y3 * dy2/dt = .04*y1 - 1.e4*y2*y3 - 3.e7*(y2)^2 * dy3/dt = 3.e7*(y2)^2 * on the interval from t = 0.0 to t = 4.e10, with initial * conditions: y1 = 1.0, y2 = y3 = 0. The problem is stiff. * While integrating the system, we also use the rootfinding * feature to find the points at which y1 = 1e-4 or at which * y3 = 0.01. This program solves the problem with the BDF method, * Newton iteration with the CVDENSE dense linear solver, and a * user-supplied Jacobian routine. It uses a scalar relative tolerance * and a vector absolute tolerance. The constraint y_i >= 0 is * posed for all components. Output is printed in decades * from t = .4 to t = 4.e10. Run statistics (optional outputs) * are printed at the end. * ----------------------------------------------------------------- *) open Sundials let unwrap = Nvector.unwrap let printf = Printf.printf let ith (v : RealArray.t) i = v.{i - 1} let set_ith (v : RealArray.t) i e = v.{i - 1} <- e let y2 = 0.0 let y3 = 0.0 let atol2 = 1.0e-11 let atol3 = 1.0e-5 let f _ (y : RealArray.t) (yd : RealArray.t) = let yd1 = -0.04 *. y.{0} +. 1.0e4 *. y.{1} *. y.{2} and yd3 = 3.0e7 *. y.{1} *. y.{1} in yd.{0} <- yd1; yd.{1} <- (-. yd1 -. yd3); yd.{2} <- yd3 let g _ (y : RealArray.t) (gout : RealArray.t) = gout.{0} <- y.{0} -. 0.0001; gout.{1} <- y.{2} -. 0.01 let jac {Cvode.jac_y = (y : RealArray.t)} jmat = let set = Matrix.Dense.set jmat in set 0 0 (-0.04); set 0 1 (1.0e4 *. y.{2}); set 0 2 (1.0e4 *. y.{1}); set 1 0 (0.04); set 1 1 (-1.0e4 *. y.{2} -. 6.0e7 *. y.{1}); set 1 2 (-1.0e4 *. y.{1}); set 2 1 (6.0e7 *. y.{1}) let print_output = printf "At t = %0.4e y =%14.6e %14.6e %14.6e\n" let print_root_info r1 r2 = printf " rootsfound[] = %3d %3d\n" (Roots.int_of_root r1) (Roots.int_of_root r2) let print_final_stats s = let open Cvode in let nst = get_num_steps s and nfe = get_num_rhs_evals s and nsetups = get_num_lin_solv_setups s and netf = get_num_err_test_fails s and nni = get_num_nonlin_solv_iters s and ncfn = get_num_nonlin_solv_conv_fails s and nje = Dls.get_num_jac_evals s and nfeLS = Dls.get_num_lin_rhs_evals s and nge = get_num_g_evals s in printf "\nFinal Statistics:\n"; printf "nst = %-6d nfe = %-6d nsetups = %-6d nfeLS = %-6d nje = %d\n" nst nfe nsetups nfeLS nje; printf "nni = %-6d ncfn = %-6d netf = %-6d nge = %d\n \n" nni ncfn netf nge let main () = Create serial vector of length NEQ for I.C. and abstol , and constraints let y = Nvector_serial.make neq 0.0 and abstol = RealArray.create neq and constraints = Nvector_serial.make neq Constraint.geq_zero and roots = Roots.create nroots in let ydata = unwrap y in let r = Roots.get roots in Initialize y set_ith ydata 1 y1; set_ith ydata 2 y2; set_ith ydata 3 y3; set_ith abstol 1 atol1; set_ith abstol 2 atol2; set_ith abstol 3 atol3; printf " \n3-species kinetics problem\n\n"; Call CVodeCreate to create the solver memory and specify the * Backward Differentiation Formula and the use of a Newton iteration * Backward Differentiation Formula and the use of a Newton iteration *) Call CVodeRootInit to specify the root function g with 2 components Call CVDense to specify the CVDENSE dense linear solver Set the Jacobian routine to ( user - supplied ) let m = Matrix.dense neq in let cvode_mem = Cvode.(init BDF ~lsolver:Dls.(solver ~jac:jac (dense y m)) (SVtolerances (rtol, (Nvector_serial.wrap abstol))) f ~roots:(nroots, g) t0 y) in Cvode.set_constraints cvode_mem constraints; In loop , call CVode , print results , and test for error . Break out of loop when NOUT preset output times have been reached . Break out of loop when NOUT preset output times have been reached. *) let tout = ref t1 and iout = ref 0 in while (!iout <> nout) do let (t, flag) = Cvode.solve_normal cvode_mem !tout y in print_output t (ith ydata 1) (ith ydata 2) (ith ydata 3); match flag with | Cvode.RootsFound -> Cvode.get_root_info cvode_mem roots; print_root_info (r 0) (r 1) | Cvode.Success -> iout := !iout + 1; tout := !tout *. tmult | Cvode.StopTimeReached -> iout := nout done; print_final_stats cvode_mem let reps = try int_of_string (Unix.getenv "NUM_REPS") with Not_found | Failure _ -> 1 let gc_at_end = try int_of_string (Unix.getenv "GC_AT_END") <> 0 with Not_found | Failure _ -> false let gc_each_rep = try int_of_string (Unix.getenv "GC_EACH_REP") <> 0 with Not_found | Failure _ -> false let _ = for _ = 1 to reps do main (); if gc_each_rep then Gc.compact () done; if gc_at_end then Gc.compact ()
5fe4821054098cce9fb6f8a7573c45fe4b7ed89a9dc8b5d5ebcfc87ef2b3b00c
kaznum/programming_in_ocaml_exercise
for.ml
let rec for_to (init : int ref) max body = if !init <= max then begin body (); init := !init + 1; for_to init max body end;; let rec for_downto (init : int ref) min body = if min <= !init then begin body (); init := !init - 1; for_downto init min body end;; let n = ref 1 in for_to n 10 (fun () -> print_string ("the number is " ^ string_of_int(!n) ^ "\n"); );; let m = ref 10 in for_downto m 1 (fun () -> print_string ("the number is " ^ string_of_int(!m) ^ "\n"); );;
null
https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ex8.6/for.ml
ocaml
let rec for_to (init : int ref) max body = if !init <= max then begin body (); init := !init + 1; for_to init max body end;; let rec for_downto (init : int ref) min body = if min <= !init then begin body (); init := !init - 1; for_downto init min body end;; let n = ref 1 in for_to n 10 (fun () -> print_string ("the number is " ^ string_of_int(!n) ^ "\n"); );; let m = ref 10 in for_downto m 1 (fun () -> print_string ("the number is " ^ string_of_int(!m) ^ "\n"); );;
b78f904af2a505e8d338fca404b147240ba80a77b0fe53e2a4bebed6b4e506b3
vivid-inc/ash-ra-template
ordering.clj
(ns com.acme.ordering) (def ^:const minimum-purchase-dollars 50) (defn minimum-order-qty "Absent-minded calculation of the minimum purchase price." [unit-price] (int (Math/ceil (/ (float minimum-purchase-dollars) (float unit-price)))))
null
https://raw.githubusercontent.com/vivid-inc/ash-ra-template/f64be7efd6f52ccd451cddb851f02511d1665b11/examples/custom-options/src/com/acme/ordering.clj
clojure
(ns com.acme.ordering) (def ^:const minimum-purchase-dollars 50) (defn minimum-order-qty "Absent-minded calculation of the minimum purchase price." [unit-price] (int (Math/ceil (/ (float minimum-purchase-dollars) (float unit-price)))))
e21afd567678ce8dacb3295c42430ac531dd515fdc6f5d47e74e77aff37ea2b8
ivankelly/gambit
web-server.scm
#!/usr/bin/env gsi-script File : " web-server.scm " , Time - stamp : < 2008 - 12 - 17 13:41:03 feeley > Copyright ( c ) 2004 - 2008 by , All Rights Reserved . ; A minimal web server which implements a web-site with a few ; interesting examples. ;============================================================================== (##include "~~lib/gambit#.scm") ;; import Gambit procedures and variables (##include "http#.scm") ;; import HTTP procedures and variables (##include "html#.scm") ;; import HTML procedures and variables (##include "base64#.scm") ;; import BASE64 procedures and variables (declare (block)) ;; required for serializing continuations ;; (for the web-continuation example) ;============================================================================== (define main (lambda (arg) (let ((port-number (string->number arg))) (http-server-start! (make-http-server port-number: port-number threaded?: #t GET: GET/POST POST: GET/POST))))) (define page-generators (make-table test: string=?)) (define show-exceptions (lambda (thunk) (with-exception-catcher (lambda (exc) (reply-html (<html> (<head> (<title> "Scheme exception")) (<body> (<p> "The following Scheme exception occurred while processing the request:") (<pre> (call-with-output-string "" (lambda (port) (##display-exception exc port)))))))) thunk))) (define GET/POST (lambda () (show-exceptions (lambda () (let* ((request (current-request)) (uri (request-uri request)) (path (uri-path uri)) (generator (table-ref page-generators path unknown-page))) (generator)))))) (define unknown-page (lambda () (let* ((request (current-request)) (uri (request-uri request)) (path (uri-path uri))) (get-filesys-path path)))) (define get-filesys-path (lambda (path) (let ((type (file-type path))) (case type ((directory) (reply-html (<html> (<head> (<title> "Files in directory " path)) (<body> (<h1> "Files in " path) (<ol> (map (lambda (fn) (<li> (<a> href: (object->string (path-expand fn path)) fn) " (" (object->string (with-exception-catcher (lambda (exc) 'other) (lambda () (file-type (path-expand fn path))))) ")")) (directory-files (list path: path ignore-hidden: #f)))))))) ((regular) (let* ((port (open-input-file path)) (file (read-line port #f))) (close-input-port port) (let ((ext (path-extension path))) (if (or (string-ci=? ext ".htm") (string-ci=? ext ".html")) (reply (lambda () (display file))) (reply-html (<html> (<head> (<title> "File " path)) (<body> (<pre> file)))))))) (else (reply-html (<html> (<head> (<title> "Error")) (<body> "Only directories and regular files can be displayed")))))))) ;============================================================================== Main web page . (define page-main (lambda () (reply-html (<html> (<head> (<title> "Main page")) (<body> (<center> (<b> "Welcome to the " (<i> "web-server") " example")) (<p> "Please choose one of these examples:") (<ul> (<li> (<a> href: (object->string (current-directory)) "Browse the web server's filesystem")) (<li> (<a> href: "/web-continuation" "Web-continuation based calculator")) (<li> (<a> href: "/terminate-server" "Terminate server")))))))) (table-set! page-generators "/" page-main) (table-set! page-generators "/index.html" page-main) (table-set! page-generators "/index.htm" page-main) ;============================================================================== ; Web pages for web-continuation example. (define page-web-continuation (lambda () (obtain-store-cont-on-server title-embed))) (table-set! page-generators "/web-continuation" page-web-continuation) (define page-calculator (lambda () ; check if we are resuming a continuation or starting the example (let* ((request (current-request)) (query (request-query request))) (cond ((and query (assoc "cont" query)) => (lambda (x) ; we're resuming a continuation (resume-continuation (cdr x) query))) ((and query (assoc "submit" query)) => (lambda (x) ; we're starting the calculator (let* ((x (assoc "store_cont_on_server" query)) (on-server? (and x (string=? (cdr x) "yes")))) (parameterize ((store-cont-on-server? on-server?)) (calculator-start))))) (else (reply-html (<html> (<head> (<title> "Error")) (<body> (<h1> "Something's wrong with the request..."))))))))) (table-set! page-generators "/calculator" page-calculator) ; BUG: parameters lose their identity when serialized/deserialized so ; we can't store this information in a parameter. (define store-cont-on-server? (make-parameter #f)) (define calculator-start (lambda () (let ((new-number (show-sum-and-obtain-number '() first-number-embed))) (calculator-loop (list new-number))))) (define calculator-loop (lambda (numbers-previously-entered) (let ((new-number (show-sum-and-obtain-number numbers-previously-entered plain-embed))) (calculator-loop (append numbers-previously-entered (list new-number)))))) (define show-sum-and-obtain-number (lambda (numbers-previously-entered embed) (let ((sum (apply + numbers-previously-entered))) (obtain-number (lambda (stuff) (embed (<table> (if (null? numbers-previously-entered) '() (list (map (lambda (x) (<tr> (<td>) (<td> align: 'right x))) numbers-previously-entered) (<tr> (<td>) (<td> align: 'right "---------------------")) (<tr> (<td> "TOTAL:") (<td> align: 'right bgcolor: "yellow" sum)))) (<tr> (<td>) (<td> stuff))))))))) (define title-embed (lambda (stuff) (<html> (<head> (<title> "Web-continuation example")) (<body> (<h1> "Web-continuation example") (<p> "This page implements a simple calculator that adds the " "numbers that are entered by the user.") (<p> "You can use the " (<strong> "back") " button to undo the " "additions. You can also clone the window and copy " "the URL to a different browser to start an independent " " branch of calculation.") (<p> "The web-server can be run interpreted or compiled. It is " "much more efficient to use a compiled web-server because " "the continuations in the HTML file sent back to the browser " "will be much more compact.") (<p> "Please indicate if you want the continuation to be stored " "on the web browser or on the web server. It is more " "efficient to store the continuation on the server but it " "introduces the problem of web-continuation garbage-collection " "(each continuation will be saved as a file on the server's file " "system; the issue is: when can these files be deleted?)") stuff)))) (define first-number-embed (lambda (stuff) (<html> (<head> (<title> "Web-continuation example")) (<body> (<h1> "Web-continuation example") (<p> "Enter the first number here: " stuff))))) (define plain-embed (lambda (stuff) (<html> (<head> (<title> "Web-continuation example")) (<body> (<h1> "Web-continuation example") stuff)))) (define form-method "GET") ; can be "GET" or "POST" (define obtain-number (lambda (embed) (let ((number-str (obtain "number" (lambda (cont) (embed (<form> action: "/calculator" method: form-method (<input> type: 'hidden name: "cont" value: cont) (<input> type: 'text name: "number") (<input> type: 'submit name: "submit" value: "ADD"))))))) (or (string->number number-str) (obtain-number embed))))) (define obtain-store-cont-on-server (lambda (embed) (obtain "store_cont_on_server" (lambda (cont) ; continuation is ignored (embed (<form> action: "/calculator" method: form-method (<input> type: 'checkbox name: "store_cont_on_server" value: "yes" "Store continuation on server") (<input> type: 'submit name: "submit" value: "\"START CALCULATOR\""))))))) (define obtain (lambda (name embed) (let ((query (capture-continuation (lambda (cont) (reply-html (embed cont)) (thread-terminate! (current-thread)))))) (cdr (assoc name query))))) (define capture-continuation (lambda (receiver) (call/cc (lambda (k) (let* ((k-str (u8vector->base64-string (object->u8vector k))) (cont (if (store-cont-on-server?) (let loop () ; find a unique filename (let* ((rn (random-integer (expt 2 64))) (fn (string-append "_cont" (number->string rn 16)))) (if (file-exists? fn) (loop) (begin (with-output-to-file fn (lambda () (display k-str))) fn)))) k-str))) (receiver cont)))))) (define resume-continuation (lambda (cont val) (let* ((k-str (if (and (> (string-length cont) 0) (char=? (string-ref cont 0) #\_)) (with-input-from-file cont read-line) cont)) (k (u8vector->object (base64-string->u8vector k-str)))) (k val)))) ;============================================================================== ; Web-IDE page. (define page-web-ide (lambda () (reply-html (<html> (<head> (<title> "Web-IDE page") (<style> web-ide-style) (<script> web-ide-script)) (<body> (<p> "This example is not complete")))))) (table-set! page-generators "/web-ide" page-web-ide) (define web-ide-style #<<EOF web ide style EOF ) (define web-ide-script #<<EOF web ide script EOF ) ;============================================================================== ; Web-server termination. (define page-terminate-server (lambda () (exit))) (table-set! page-generators "/terminate-server" page-terminate-server) ;==============================================================================
null
https://raw.githubusercontent.com/ivankelly/gambit/7377246988d0982ceeb10f4249e96badf3ff9a8f/examples/web-server/web-server.scm
scheme
A minimal web server which implements a web-site with a few interesting examples. ============================================================================== import Gambit procedures and variables import HTTP procedures and variables import HTML procedures and variables import BASE64 procedures and variables required for serializing continuations (for the web-continuation example) ============================================================================== ============================================================================== ============================================================================== Web pages for web-continuation example. check if we are resuming a continuation or starting the example we're resuming a continuation we're starting the calculator BUG: parameters lose their identity when serialized/deserialized so we can't store this information in a parameter. can be "GET" or "POST" continuation is ignored find a unique filename ============================================================================== Web-IDE page. ============================================================================== Web-server termination. ==============================================================================
#!/usr/bin/env gsi-script File : " web-server.scm " , Time - stamp : < 2008 - 12 - 17 13:41:03 feeley > Copyright ( c ) 2004 - 2008 by , All Rights Reserved . (define main (lambda (arg) (let ((port-number (string->number arg))) (http-server-start! (make-http-server port-number: port-number threaded?: #t GET: GET/POST POST: GET/POST))))) (define page-generators (make-table test: string=?)) (define show-exceptions (lambda (thunk) (with-exception-catcher (lambda (exc) (reply-html (<html> (<head> (<title> "Scheme exception")) (<body> (<p> "The following Scheme exception occurred while processing the request:") (<pre> (call-with-output-string "" (lambda (port) (##display-exception exc port)))))))) thunk))) (define GET/POST (lambda () (show-exceptions (lambda () (let* ((request (current-request)) (uri (request-uri request)) (path (uri-path uri)) (generator (table-ref page-generators path unknown-page))) (generator)))))) (define unknown-page (lambda () (let* ((request (current-request)) (uri (request-uri request)) (path (uri-path uri))) (get-filesys-path path)))) (define get-filesys-path (lambda (path) (let ((type (file-type path))) (case type ((directory) (reply-html (<html> (<head> (<title> "Files in directory " path)) (<body> (<h1> "Files in " path) (<ol> (map (lambda (fn) (<li> (<a> href: (object->string (path-expand fn path)) fn) " (" (object->string (with-exception-catcher (lambda (exc) 'other) (lambda () (file-type (path-expand fn path))))) ")")) (directory-files (list path: path ignore-hidden: #f)))))))) ((regular) (let* ((port (open-input-file path)) (file (read-line port #f))) (close-input-port port) (let ((ext (path-extension path))) (if (or (string-ci=? ext ".htm") (string-ci=? ext ".html")) (reply (lambda () (display file))) (reply-html (<html> (<head> (<title> "File " path)) (<body> (<pre> file)))))))) (else (reply-html (<html> (<head> (<title> "Error")) (<body> "Only directories and regular files can be displayed")))))))) Main web page . (define page-main (lambda () (reply-html (<html> (<head> (<title> "Main page")) (<body> (<center> (<b> "Welcome to the " (<i> "web-server") " example")) (<p> "Please choose one of these examples:") (<ul> (<li> (<a> href: (object->string (current-directory)) "Browse the web server's filesystem")) (<li> (<a> href: "/web-continuation" "Web-continuation based calculator")) (<li> (<a> href: "/terminate-server" "Terminate server")))))))) (table-set! page-generators "/" page-main) (table-set! page-generators "/index.html" page-main) (table-set! page-generators "/index.htm" page-main) (define page-web-continuation (lambda () (obtain-store-cont-on-server title-embed))) (table-set! page-generators "/web-continuation" page-web-continuation) (define page-calculator (lambda () (let* ((request (current-request)) (query (request-query request))) (cond ((and query (assoc "cont" query)) => (lambda (x) (resume-continuation (cdr x) query))) ((and query (assoc "submit" query)) => (lambda (x) (let* ((x (assoc "store_cont_on_server" query)) (on-server? (and x (string=? (cdr x) "yes")))) (parameterize ((store-cont-on-server? on-server?)) (calculator-start))))) (else (reply-html (<html> (<head> (<title> "Error")) (<body> (<h1> "Something's wrong with the request..."))))))))) (table-set! page-generators "/calculator" page-calculator) (define store-cont-on-server? (make-parameter #f)) (define calculator-start (lambda () (let ((new-number (show-sum-and-obtain-number '() first-number-embed))) (calculator-loop (list new-number))))) (define calculator-loop (lambda (numbers-previously-entered) (let ((new-number (show-sum-and-obtain-number numbers-previously-entered plain-embed))) (calculator-loop (append numbers-previously-entered (list new-number)))))) (define show-sum-and-obtain-number (lambda (numbers-previously-entered embed) (let ((sum (apply + numbers-previously-entered))) (obtain-number (lambda (stuff) (embed (<table> (if (null? numbers-previously-entered) '() (list (map (lambda (x) (<tr> (<td>) (<td> align: 'right x))) numbers-previously-entered) (<tr> (<td>) (<td> align: 'right "---------------------")) (<tr> (<td> "TOTAL:") (<td> align: 'right bgcolor: "yellow" sum)))) (<tr> (<td>) (<td> stuff))))))))) (define title-embed (lambda (stuff) (<html> (<head> (<title> "Web-continuation example")) (<body> (<h1> "Web-continuation example") (<p> "This page implements a simple calculator that adds the " "numbers that are entered by the user.") (<p> "You can use the " (<strong> "back") " button to undo the " "additions. You can also clone the window and copy " "the URL to a different browser to start an independent " " branch of calculation.") (<p> "The web-server can be run interpreted or compiled. It is " "much more efficient to use a compiled web-server because " "the continuations in the HTML file sent back to the browser " "will be much more compact.") (<p> "Please indicate if you want the continuation to be stored " "on the web browser or on the web server. It is more " "efficient to store the continuation on the server but it " "introduces the problem of web-continuation garbage-collection " "(each continuation will be saved as a file on the server's file " "system; the issue is: when can these files be deleted?)") stuff)))) (define first-number-embed (lambda (stuff) (<html> (<head> (<title> "Web-continuation example")) (<body> (<h1> "Web-continuation example") (<p> "Enter the first number here: " stuff))))) (define plain-embed (lambda (stuff) (<html> (<head> (<title> "Web-continuation example")) (<body> (<h1> "Web-continuation example") stuff)))) (define obtain-number (lambda (embed) (let ((number-str (obtain "number" (lambda (cont) (embed (<form> action: "/calculator" method: form-method (<input> type: 'hidden name: "cont" value: cont) (<input> type: 'text name: "number") (<input> type: 'submit name: "submit" value: "ADD"))))))) (or (string->number number-str) (obtain-number embed))))) (define obtain-store-cont-on-server (lambda (embed) (obtain "store_cont_on_server" (embed (<form> action: "/calculator" method: form-method (<input> type: 'checkbox name: "store_cont_on_server" value: "yes" "Store continuation on server") (<input> type: 'submit name: "submit" value: "\"START CALCULATOR\""))))))) (define obtain (lambda (name embed) (let ((query (capture-continuation (lambda (cont) (reply-html (embed cont)) (thread-terminate! (current-thread)))))) (cdr (assoc name query))))) (define capture-continuation (lambda (receiver) (call/cc (lambda (k) (let* ((k-str (u8vector->base64-string (object->u8vector k))) (cont (if (store-cont-on-server?) (let* ((rn (random-integer (expt 2 64))) (fn (string-append "_cont" (number->string rn 16)))) (if (file-exists? fn) (loop) (begin (with-output-to-file fn (lambda () (display k-str))) fn)))) k-str))) (receiver cont)))))) (define resume-continuation (lambda (cont val) (let* ((k-str (if (and (> (string-length cont) 0) (char=? (string-ref cont 0) #\_)) (with-input-from-file cont read-line) cont)) (k (u8vector->object (base64-string->u8vector k-str)))) (k val)))) (define page-web-ide (lambda () (reply-html (<html> (<head> (<title> "Web-IDE page") (<style> web-ide-style) (<script> web-ide-script)) (<body> (<p> "This example is not complete")))))) (table-set! page-generators "/web-ide" page-web-ide) (define web-ide-style #<<EOF web ide style EOF ) (define web-ide-script #<<EOF web ide script EOF ) (define page-terminate-server (lambda () (exit))) (table-set! page-generators "/terminate-server" page-terminate-server)
5582d96aad343c1d64359ca84b55c582e019dd4a7918f78ebe09e2090188f918
adamdoupe/find_ear_rails
print_cfg.ml
open Parse_helper open Printf open Cfg open Cfg_printer let _ = if (Array.length Sys.argv) != 2 then begin eprintf "Usage: print_cfg <ruby_file> \n"; exit 1 end; let fname = Sys.argv.(1) in let ast = try Parse_helper.parse_file fname with Invalid_argument(_) -> parse_file fname in let loader = File_loader.create File_loader . EmptyCfg " .. /std - lib " in let stmt = Cfg_refactor.refactor_ast ast in let stmt = Cfg_scope.resolve_scopes loader stmt in let oc = open_out "output.rb" in let () = CodePrinter.print_stmt oc stmt in let () = CodePrinter.print_stmt stdout stmt in let () = close_out oc in () let ( ) = compute_cfg stmt in let _ , _ = Dataflow.DataTypeFlowDF.fixpoint stmt in let _ , out_tbl = Dataflow.EarlyCastDF.fixpoint stmt in Hashtbl.iter ( fun stmt t - > let s1 = Cfg_printer.string_of_cfg stmt in let s2 = Dataflow . EarlyCast.to_string t in printf " [ % s ] : % s\n\n " s1 s2 ) out_tbl let () = compute_cfg stmt in let _,_ = Dataflow.DataTypeFlowDF.fixpoint stmt in let _, out_tbl = Dataflow.EarlyCastDF.fixpoint stmt in Hashtbl.iter (fun stmt t -> let s1 = Cfg_printer.string_of_cfg stmt in let s2 = Dataflow.EarlyCast.to_string t in printf "[%s]: %s\n\n" s1 s2 ) out_tbl *)
null
https://raw.githubusercontent.com/adamdoupe/find_ear_rails/38f892f9962ad415a583973caf24fbab1a011be1/diamondback-ruby-0.20090726/src/print_cfg.ml
ocaml
open Parse_helper open Printf open Cfg open Cfg_printer let _ = if (Array.length Sys.argv) != 2 then begin eprintf "Usage: print_cfg <ruby_file> \n"; exit 1 end; let fname = Sys.argv.(1) in let ast = try Parse_helper.parse_file fname with Invalid_argument(_) -> parse_file fname in let loader = File_loader.create File_loader . EmptyCfg " .. /std - lib " in let stmt = Cfg_refactor.refactor_ast ast in let stmt = Cfg_scope.resolve_scopes loader stmt in let oc = open_out "output.rb" in let () = CodePrinter.print_stmt oc stmt in let () = CodePrinter.print_stmt stdout stmt in let () = close_out oc in () let ( ) = compute_cfg stmt in let _ , _ = Dataflow.DataTypeFlowDF.fixpoint stmt in let _ , out_tbl = Dataflow.EarlyCastDF.fixpoint stmt in Hashtbl.iter ( fun stmt t - > let s1 = Cfg_printer.string_of_cfg stmt in let s2 = Dataflow . EarlyCast.to_string t in printf " [ % s ] : % s\n\n " s1 s2 ) out_tbl let () = compute_cfg stmt in let _,_ = Dataflow.DataTypeFlowDF.fixpoint stmt in let _, out_tbl = Dataflow.EarlyCastDF.fixpoint stmt in Hashtbl.iter (fun stmt t -> let s1 = Cfg_printer.string_of_cfg stmt in let s2 = Dataflow.EarlyCast.to_string t in printf "[%s]: %s\n\n" s1 s2 ) out_tbl *)
7becaf3a783a1bf3e6cd4ceddc1e5cda1c2f14336a70985b85ede3aac8ade1b0
racket/typed-racket
rational-literal.rkt
#;#; #<<END TR opt: rational-literal.rkt 2:0 (+ 3/4 1.2) -- binary float END #<<END 1.95 END #lang typed/racket #:optimize #reader typed-racket-test/optimizer/reset-port ;; rational literals should be promoted to floats at compile time (+ 3/4 1.2)
null
https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/optimizer/tests/rational-literal.rkt
racket
#; rational literals should be promoted to floats at compile time
#<<END TR opt: rational-literal.rkt 2:0 (+ 3/4 1.2) -- binary float END #<<END 1.95 END #lang typed/racket #:optimize #reader typed-racket-test/optimizer/reset-port (+ 3/4 1.2)
90aa393d23ce5b742e0cca76fab68042cd276fc1daa1a494d00957d0dc62c7c0
helium/miner
miner.erl
-module(miner). -behavior(gen_server). -include_lib("blockchain/include/blockchain_vars.hrl"). -include_lib("blockchain/include/blockchain.hrl"). %% API -export([ start_link/0, p2p_status/0, block_age/0, relcast_info/1, relcast_queue/1, hbbft_artifact/0, hbbft_status/0, hbbft_skip/0, create_block/3, signed_block/2, keys/0, reset_late_block_timer/0, start_chain/2, install_consensus/1, remove_consensus/0, version/0 ]). -export_type([ create_block_ok/0, create_block_error/0, create_block_result/0 ]). %% gen_server -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2 ]). -type metadata_v1() :: {integer(), blockchain_block:hash()}. -type metadata_v2() :: #{ timestamp => integer(), seen => binary(), bba_completion => binary(), head_hash => blockchain_block:hash(), snapshot_hash => binary() }. -type metadata() :: [{J :: pos_integer(), M :: metadata_v2() | metadata_v1()}]. -type swarm_keys() :: {libp2p_crypto:pubkey(), libp2p_crypto:sig_fun()}. -type create_block_error() :: stale_hash | multiple_hashes. -type create_block_ok() :: #{ address => libp2p_crypto:pubkey_bin(), unsigned_binary_block => binary(), signature => binary(), pending_txns => blockchain_txn:txns(), invalid_txns => blockchain_txn:txns() }. -type create_block_result() :: {ok, create_block_ok()} | {error, create_block_error()}. -record(state, { %% NOTE: a miner may or may not participate in consensus consensus_group :: undefined | pid(), blockchain :: undefined | blockchain:blockchain(), %% but every miner keeps a timer reference? block_timer = make_ref() :: reference(), late_block_timer = make_ref() :: reference(), current_height = -1 :: integer(), blockchain_ref = make_ref() :: reference(), swarm_tid :: ets:tid() | atom(), swarm_keys :: swarm_keys() }). -define(H3_MINIMUM_RESOLUTION, 9). -ifdef(TEST). -define(tv, '$test_version'). -export([test_version/0, inc_tv/1]). test_version() -> case ets:info(?tv) of undefined -> ets:new(?tv, [named_table, public]), ets:insert(?tv, {?tv, 1}), 1; _ -> [{_, V}] = ets:lookup(?tv, ?tv), lager:info("tv got ~p", [V]), V end. inc_tv(Incr) -> lager:info("increment: ~p", [Incr]), case ets:info(?tv) of undefined -> ets:new(?tv, [named_table, public]), ets:insert(?tv, {?tv, 1 + Incr}), 1 + Incr; _ -> ets:update_counter(?tv, ?tv, Incr) end. -endif. %% ---------------------------------------------------------------------------- %% API %% ---------------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], [{hibernate_after, 5000}]). block_age() -> Chain = blockchain_worker:blockchain(), {ok, #block_info_v2{time=BlockTime}} = blockchain:head_block_info(Chain), erlang:system_time(seconds) - BlockTime. -spec p2p_status() -> [{Check::string(), Result::string()}]. p2p_status() -> SwarmTID = blockchain_swarm:tid(), CheckSessions = fun() -> case (catch length(libp2p_swarm:sessions(SwarmTID)) > 5) of true -> "yes"; _ -> "no" end end, CheckPublicAddr = fun() -> case (catch lists:any(fun(Addr) -> libp2p_relay:is_p2p_circuit(Addr) orelse libp2p_transport_tcp:is_public(Addr) end, libp2p_swarm:listen_addrs(SwarmTID))) of true -> "yes"; _ -> "no" end end, CheckNatType = fun() -> try case libp2p_peerbook:get(libp2p_swarm:peerbook(SwarmTID), libp2p_swarm:pubkey_bin(SwarmTID)) of {ok, Peer} -> atom_to_list(libp2p_peer:nat_type(Peer)); {error, _} -> "unknown" end catch _:_ -> "unknown" end end, CheckHeight = fun() -> Chain = blockchain_worker:blockchain(), {ok, Height} = blockchain:height(Chain), integer_to_list(Height) end, lists:foldr(fun({Fun, Name}, Acc) -> [{Name, Fun()} | Acc] end, [], [{CheckSessions, "connected"}, {CheckPublicAddr, "dialable"}, {CheckNatType, "nat_type"}, {CheckHeight, "height"}]). %% TODO: spec relcast_info(Group) -> Mod = case Group of dkg_group -> miner_consensus_mgr; _ -> ?MODULE end, case gen_server:call(Mod, Group, 60000) of undefined -> #{}; Pid -> libp2p_group_relcast:info(Pid) end. %% TODO: spec relcast_queue(Group) -> Mod = case Group of dkg_group -> miner_consensus_mgr; _ -> ?MODULE end, case gen_server:call(Mod, Group, 60000) of undefined -> #{}; Pid -> try libp2p_group_relcast:queues(Pid) of {_ModState, Inbound, Outbound} -> O = maps:map( fun(_, V) -> [erlang:binary_to_term(Value) || Value <- V] end, Outbound ), I = [{Index,binary_to_term(B)} || {Index, B} <- Inbound], #{ inbound => I, outbound => O } catch What:Why -> {error, {What, Why}} end end. -spec create_block(metadata(), blockchain_txn:txns(), non_neg_integer()) -> create_block_result(). create_block(Metadata, Txns, HBBFTRound) -> try gen_server:call(?MODULE, {create_block, Metadata, Txns, HBBFTRound}, infinity) catch exit:{noproc, _} -> %% if the miner noprocs, we're likely shutting down {error, no_miner} end. -spec hbbft_status() -> map() | {error, timeout}. hbbft_status() -> case gen_server:call(?MODULE, consensus_group, 60000) of undefined -> ok; Pid -> Ref = make_ref(), ok = libp2p_group_relcast:handle_input(Pid, {status, Ref, self()}), receive {Ref, Result} -> Result after timer:seconds(60) -> {error, timeout} end end. -spec hbbft_artifact() -> {ok, undefined} | {ok, binary()} | not_running | {error, timeout}. hbbft_artifact() -> case gen_server:call(?MODULE, consensus_group, 60000) of undefined -> not_running; Pid -> Ref = make_ref(), ok = libp2p_group_relcast:handle_input(Pid, {get_artifact, Ref, self()}), receive {Ref, Result} -> {ok, Result} after timer:seconds(60) -> {error, timeout} end end. -spec hbbft_skip() -> ok | {error, timeout}. hbbft_skip() -> case gen_server:call(?MODULE, consensus_group, 60000) of undefined -> ok; Pid -> ok = libp2p_group_relcast:handle_input(Pid, maybe_skip) end. -spec signed_block([binary()], binary()) -> ok. signed_block(Signatures, BinBlock) -> %% Once a miner gets a sign_block message (only happens if the miner is in %% consensus group): %% * cancel the block timer %% * sign the block * tell to go to next round %% * add the block to blockchain Chain = blockchain_worker:blockchain(), Block = blockchain_block:set_signatures(blockchain_block:deserialize(BinBlock), Signatures), case blockchain:add_block(Block, Chain) of ok -> lager:info("sending the gossiped block to other workers"), Swarm = blockchain_swarm:swarm(), SwarmTID = blockchain_swarm:tid(), Data = case application:get_env(blockchain, gossip_version, 1) of 1 -> blockchain_gossip_handler:gossip_data_v1(SwarmTID, Block); 2 -> Height = blockchain_block:height(Block), {ok, #block_info_v2{hash = Hash}} = blockchain:get_block_info(Height, Chain), blockchain_gossip_handler:gossip_data_v2(SwarmTID, Hash, Height) end, libp2p_group_gossip:send( SwarmTID, ?GOSSIP_PROTOCOL_V1, Data ), {Signatories, _} = lists:unzip(blockchain_block:signatures(Block)), {ok, ConsensusAddrs} = blockchain_ledger_v1:consensus_members(blockchain:ledger(Chain)), FF non signatory consensus members lists:foreach( fun(Member) -> spawn(fun() -> blockchain_fastforward_handler:dial( Swarm, Chain, libp2p_crypto:pubkey_bin_to_p2p(Member)) end) end, ConsensusAddrs -- Signatories); Error -> lager:error("signed_block, error: ~p", [Error]) end, ok. -spec keys() -> {ok, {libp2p_crypto:pubkey(), libp2p_crypto:sig_fun()}}. keys() -> gen_server:call(?MODULE, keys). -spec reset_late_block_timer() -> ok. reset_late_block_timer() -> gen_server:call(?MODULE, reset_late_block_timer). start_chain(ConsensusGroup, Chain) -> gen_server:call(?MODULE, {start_chain, ConsensusGroup, Chain}, infinity). install_consensus(ConsensusGroup) -> gen_server:cast(?MODULE, {install_consensus, ConsensusGroup}). remove_consensus() -> gen_server:cast(?MODULE, remove_consensus). -spec version() -> integer(). version() -> %% format: MMMmmmPPPP 0010170002. %% ------------------------------------------------------------------ %% gen_server %% ------------------------------------------------------------------ init(_Args) -> Mode = application:get_env(miner, mode), lager:info("STARTING UP MINER with mode ~p", [Mode]), ok = blockchain_event:add_handler(self()), %% TODO: Maybe put this somewhere else? ok = miner_discovery_handler:add_stream_handler(blockchain_swarm:tid()), BlockchainRef = erlang:monitor(process, blockchain_worker), {ok, MyPubKey, SignFun, _ECDHFun} = blockchain_swarm:keys(), SwarmTID = blockchain_swarm:tid(), % We don't actually use this for % anything at this time, but we should % use this if we need it. case blockchain_worker:blockchain() of undefined -> {ok, #state{swarm_keys = {MyPubKey, SignFun}, swarm_tid = SwarmTID}}; Chain -> {ok, #state{swarm_keys = {MyPubKey, SignFun}, swarm_tid = SwarmTID, blockchain = Chain, blockchain_ref = BlockchainRef}} end. handle_call(consensus_group, _From, State) -> {reply, State#state.consensus_group, State}; handle_call({start_chain, ConsensusGroup, Chain}, _From, State) -> lager:info("registering first consensus group"), {reply, ok, set_next_block_timer(State#state{consensus_group = ConsensusGroup, blockchain = Chain})}; handle_call({create_block, Metadata, Txns, HBBFTRound}, _From, #state{blockchain = Chain, swarm_keys = SK} = State) -> Result = try_create_block(Metadata, Txns, HBBFTRound, Chain, SK), {reply, Result, State}; handle_call(keys, _From, State) -> {reply, {ok, State#state.swarm_keys}, State}; handle_call(reset_late_block_timer, _From, State) -> erlang:cancel_timer(State#state.late_block_timer), LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120), LateTimer = erlang:send_after(LateBlockTimeout * 1000, self(), late_block_timeout), {reply, ok, State#state{late_block_timer = LateTimer}}; handle_call(_Msg, _From, State) -> lager:warning("unhandled call ~p", [_Msg]), {noreply, State}. handle_cast(remove_consensus, State) -> erlang:cancel_timer(State#state.block_timer), {noreply, State#state{consensus_group = undefined, block_timer = make_ref()}}; handle_cast({install_consensus, NewConsensusGroup}, #state{consensus_group = Group} = State) when Group == NewConsensusGroup -> {noreply, State}; handle_cast({install_consensus, NewConsensusGroup}, State) -> lager:info("installing consensus ~p after ~p", [NewConsensusGroup, State#state.consensus_group]), {noreply, set_next_block_timer(State#state{consensus_group = NewConsensusGroup})}; handle_cast(_Msg, State) -> lager:warning("unhandled cast ~p", [_Msg]), {noreply, State}. handle_info({'DOWN', Ref, process, _, Reason}, State = #state{blockchain_ref=Ref}) -> lager:warning("Blockchain worker exited with reason ~p", [Reason]), {stop, Reason, State}; handle_info(block_timeout, State) when State#state.consensus_group == undefined -> {noreply, State}; handle_info(block_timeout, State) -> lager:info("block timeout"), libp2p_group_relcast:handle_input(State#state.consensus_group, start_acs), {noreply, State}; handle_info(late_block_timeout, State) -> LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120) * 1000, lager:info("late block timeout"), libp2p_group_relcast:handle_input(State#state.consensus_group, maybe_skip), LateTimer = erlang:send_after(LateBlockTimeout, self(), late_block_timeout), {noreply, State#state{late_block_timer = LateTimer}}; handle_info({blockchain_event, {add_block, Hash, Sync, Ledger}}, State=#state{consensus_group = ConsensusGroup, current_height = CurrHeight, swarm_keys = {PubKey, _SigFun}, blockchain = Chain}) when ConsensusGroup /= undefined andalso Chain /= undefined -> %% NOTE: only the consensus group member must do this If this miner is in consensus group and lagging on a previous %% round, make it forcefully go to next round NewState = case blockchain:get_block_height(Hash, Chain) of {ok, Height} when Height > CurrHeight -> case blockchain:get_block(Hash, Chain) of {ok, Block} -> erlang:cancel_timer(State#state.block_timer), lager:info("processing block for ~p", [Height]), Round = blockchain_block:hbbft_round(Block), Txns = blockchain_block:transactions(Block), case blockchain_election:has_new_group(Txns) of false -> lager:debug("reg round c ~p", [Height]), NextRound = Round + 1, libp2p_group_relcast:handle_input( ConsensusGroup, {next_round, NextRound, Txns, Sync}), {ok, ConsensusAddrs} = blockchain_ledger_v1:consensus_members(Ledger), F = (length(ConsensusAddrs) - 1) div 3, BBAs = blockchain_utils:bitvector_to_map(length(ConsensusAddrs), blockchain_block_v1:bba_completion(Block)), BBAAddrs = maps:fold(fun(K, true, Acc) -> [lists:nth(K, ConsensusAddrs) | Acc]; (_, _, Acc) -> Acc end, [], BBAs), case lists:member(libp2p_crypto:pubkey_to_bin(PubKey), BBAAddrs) orelse length(BBAAddrs) < (2 * F)+1 of true -> we got our proposal in last round , or we did n't see enough BBA votes %% to know if we did set_next_block_timer(State#state{current_height = Height}); false -> lager:info("jumping to next hbbft round ~p early", [Round+1]), %% didn't get included last round, try to get a jump on things Timer = erlang:send_after(0, self(), block_timeout), %% now figure out the late block timer erlang:cancel_timer(State#state.late_block_timer), LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120), LateTimer = erlang:send_after(LateBlockTimeout * 1000, self(), late_block_timeout), State#state{block_timer=Timer, late_block_timer=LateTimer} end; {true, _, _, _} -> State#state{block_timer = make_ref(), current_height = Height} end; {error, Reason} -> lager:error("Error, Reason: ~p", [Reason]), State end; {ok, _Height} -> lager:debug("skipped re-processing block for ~p", [_Height]), State end, {noreply, NewState}; handle_info({blockchain_event, {add_block, Hash, _Sync, _Ledger}}, #state{consensus_group = ConsensusGroup, current_height = CurrHeight, blockchain = Chain} = State) when ConsensusGroup == undefined andalso Chain /= undefined -> case blockchain:get_block_height(Hash, Chain) of {ok, Height} -> lager:info("non-consensus block ~p", [Height]), case Height of H when H > CurrHeight -> {noreply, State#state{current_height = Height}}; _ -> {noreply, State} end; {error, Reason} -> lager:error("Error, Reason: ~p", [Reason]), {noreply, State} end; handle_info({blockchain_event, {add_block, _Hash, _Sync, _Ledger}}, State) when State#state.blockchain == undefined -> Chain = blockchain_worker:blockchain(), {noreply, State#state{blockchain = Chain}}; handle_info({blockchain_event, {new_chain, NC}}, #state{blockchain_ref = Ref, swarm_keys=SK, swarm_tid=STid}) -> State1 = #state{blockchain = NC, blockchain_ref = Ref, swarm_keys=SK, swarm_tid=STid}, {noreply, State1}; handle_info(_Msg, State) -> lager:warning("unhandled info message ~p", [_Msg]), {noreply, State}. terminate(Reason, _State) -> lager:info("stopping: ~p", [Reason]), ok. %% ============================================================================ %% Private %% ============================================================================ -spec try_create_block( metadata(), blockchain_txn:txns(), non_neg_integer(), blockchain:blockchain(), swarm_keys() ) -> create_block_result(). try_create_block(Metadata, Txns, HBBFTRound, Chain, SwarmKeys) -> %% This can actually be a stale message, in which case we'd produce a block %% with a garbage timestamp. This is not actually that big of a deal, since %% it won't be accepted, but we can short circuit some effort by checking %% for a stale hash. {ok, HashCurr} = blockchain:head_hash(Chain), lager:debug("Metadata ~p, current hash ~p", [Metadata, HashCurr]), N = count_consensus_members(Chain), VotesNeeded = N - ((N - 1) div 3), {_, Hashes} = meta_to_stamp_hashes(Metadata), case hash_check_if_stale(HashCurr, Hashes, VotesNeeded) of {ok, {}} -> {ok, create_block(Metadata, Txns, HBBFTRound, Chain, VotesNeeded, SwarmKeys)}; {error, {stale, HashStale, Votes}} -> lager:warning("Stale hash: ~p, picked by ~b nodes.", [HashStale, Votes]), {error, stale_hash}; {error, {unexpected_counts, Counts}} -> lager:warning( "got unexpected block hashes in stamp information ~p", [Counts] ), XXX May also be [ ] , so not just multiple ! {error, multiple_hashes} end. -spec count_consensus_members(blockchain:blockchain()) -> non_neg_integer(). count_consensus_members(Chain) -> {ok, ConsensusMembers} = blockchain_ledger_v1:consensus_members(blockchain:ledger(Chain)), length(ConsensusMembers). -spec hash_check_if_stale(H, [H], C) -> {ok, {}} | {error, E} when E :: {stale, H, C} | {unexpected_counts, [{H, C}]}, H :: blockchain_block:hash(), C :: non_neg_integer(). hash_check_if_stale(HashCurr, Hashes, VotesNeeded) -> case lists:filter( fun ({_, Votes}) -> Votes >= VotesNeeded end, maps:to_list(miner_util:list_count(Hashes)) ) of %% We expect every stamp to contain the same block hash: [{HashCurr, _}] -> {ok, {}}; [{HashStale, Votes}] -> {error, {stale, HashStale, Votes}}; Counts -> {error, {unexpected_counts, Counts}} end. -spec create_block( metadata(), blockchain_txn:txns(), non_neg_integer(), blockchain:blockchain(), non_neg_integer(), swarm_keys() ) -> create_block_ok(). create_block(Metadata, Txns, HBBFTRound, Chain, VotesNeeded, {MyPubKey, SignFun}) -> {ok, #block_info_v2{height=HeightCurr, time=CurrentBlockTime, hash=CurrentBlockHash, election_info=ElectionInfo}} = blockchain:head_block_info(Chain), HeightNext = HeightCurr + 1, Ledger = blockchain:ledger(Chain), SnapshotHash = snapshot_hash(Ledger, HeightNext, Metadata, VotesNeeded), SeenBBAs = [{{J, S}, B} || {J, #{seen := S, bba_completion := B}} <- metadata_only_v2(Metadata)], {SeenVectors, BBAs} = lists:unzip(SeenBBAs), if we can not agree on the BBA results , default to flagging everyone as having completed VoteDefault = case blockchain:config(?election_version, Ledger) of {ok, N} when N >= 5 -> blockchain_utils:map_to_bitvector( maps:from_list([ {I, true} || I <- lists:seq(1, count_consensus_members(Chain))])); _ -> <<>> end, BBA = common_enough_or_default(VotesNeeded, BBAs, VoteDefault), {ElectionEpoch, EpochStart, TxnsToInsert, InvalidTransactions} = select_transactions(Chain, Txns, ElectionInfo, HeightCurr, HeightNext), NewBlock = blockchain_block_v1:new(#{ prev_hash => CurrentBlockHash, height => HeightNext, transactions => TxnsToInsert, signatures => [], hbbft_round => HBBFTRound, time => block_time(CurrentBlockTime, Metadata), election_epoch => ElectionEpoch, epoch_start => EpochStart, seen_votes => SeenVectors, bba_completion => BBA, snapshot_hash => SnapshotHash }), BinNewBlock = blockchain_block:serialize(NewBlock), Signature = SignFun(BinNewBlock), lager:debug("Worker:~p, Created Block: ~p, Txns: ~p", [self(), NewBlock, TxnsToInsert]), #{ address => libp2p_crypto:pubkey_to_bin(MyPubKey), unsigned_binary_block => BinNewBlock, signature => Signature, %% Both pending and invalid are to be removed from the buffer: pending_txns => TxnsToInsert, invalid_txns => InvalidTransactions }. -spec block_time(non_neg_integer(), metadata()) -> pos_integer(). block_time(LastBlockTime, Metadata) -> %% Try to rule out invalid values by not allowing timestamps to go %% backwards and take the median proposed value. {Stamps, _} = meta_to_stamp_hashes(Metadata), case miner_util:median([S || S <- Stamps, S >= LastBlockTime]) of 0 -> LastBlockTime + 1; LastBlockTime -> LastBlockTime + 1; NewTime -> NewTime end. -spec select_transactions( blockchain:blockchain(), blockchain_txn:txns(), {non_neg_integer(), non_neg_integer()}, non_neg_integer(), non_neg_integer() ) -> { ElectionEpoch :: non_neg_integer(), EpochStart :: non_neg_integer(), TxsValid :: blockchain_txn:txns(), TxsInvalid :: blockchain_txn:txns() }. select_transactions(Chain, Txns, {ElectionEpoch0, EpochStart0}, BlockHeightCurr, BlockHeightNext) -> SortedTransactions = lists:sort(fun blockchain_txn:sort/2, [T || T <- Txns, not txn_is_rewards(T)]), {ValidTransactions0, InvalidTransactions0} = blockchain_txn:validate(SortedTransactions, Chain), InvalidTransactions0 is a list of tuples in the format { Txn , InvalidReason } %% we dont need the invalid reason here so need to remove the tuple format and have a regular list of txn items in prep for returning to . InvalidTransactions1 = [InvTxn || {InvTxn, _InvalidReason} <- InvalidTransactions0], Ledger = blockchain:ledger(Chain), SizeLimit = case blockchain:config(?block_size_limit, Ledger) of {ok, Limit} -> Limit; 50 mb default end, {_, ValidTransactions1} = lists:foldl(fun(_Txn, {done, Acc}) -> %% already full, don't want to skip because %% of possible txn ordering issues so just drop everything {done, Acc}; (Txn, {Count, Acc}) -> case Count - byte_size(blockchain_txn:serialize(Txn)) of Remainder when Remainder < 0 -> {done, Acc}; Remainder -> {Remainder, [Txn|Acc]} end end, {SizeLimit, []}, ValidTransactions0), ValidTransactions = lists:reverse(ValidTransactions1), %% any that overflowed go back into the buffer InvalidTransactions = InvalidTransactions1 ++ (ValidTransactions0 -- ValidTransactions), case blockchain_election:has_new_group(ValidTransactions) of {true, _, ConsensusGroupTxn, _} -> Epoch = ElectionEpoch0 + 1, Start = EpochStart0 + 1, End = BlockHeightCurr, RewardsMod = case blockchain:config(?rewards_txn_version, Ledger) of {ok, 2} -> blockchain_txn_rewards_v2; _ -> blockchain_txn_rewards_v1 end, {ok, Rewards} = RewardsMod:calculate_rewards(Start, End, Chain), blockchain_hex:destroy_memoization(), lager:debug("RewardsMod: ~p, Rewards: ~p~n", [RewardsMod, Rewards]), RewardsTxn = RewardsMod:new(Start, End, Rewards), %% To cut down on the size of group txn blocks, which we'll %% need to fetch and store all of to validate snapshots, we %% discard all other txns for this block. Transactions = lists:sort( %% TODO Rename blockchain_txn:sort to blockchain_txn:(compare|cmp) fun blockchain_txn:sort/2, [RewardsTxn, ConsensusGroupTxn] ), {Epoch, BlockHeightNext, Transactions, InvalidTransactions}; _ -> %% try to isolate the var txn in its own block case {blockchain:config(?isolate_var_txns, Ledger), lists:filter(fun(T) -> blockchain_txn:type(T) == blockchain_txn_vars_v1 end, ValidTransactions)} of {{ok, true}, [VarTxn|_]} -> take the first var txn found as the only txn in a block {ElectionEpoch0, EpochStart0, [VarTxn], InvalidTransactions}; _ -> {ElectionEpoch0, EpochStart0, ValidTransactions, InvalidTransactions} end end. -spec txn_is_rewards(blockchain_txn:txn()) -> boolean(). txn_is_rewards(Txn) -> Rewards = [blockchain_txn_rewards_v1, blockchain_txn_rewards_v2], lists:member(blockchain_txn:type(Txn), Rewards). -spec metadata_only_v2(metadata()) -> [{non_neg_integer(), metadata_v2()}]. metadata_only_v2(Metadata) -> lists:filter(fun ({_, M}) -> is_map(M) end, Metadata). -spec meta_to_stamp_hashes(metadata()) -> { Stamps :: [integer()], Hashes :: [blockchain_block:hash()] }. meta_to_stamp_hashes(Metadata) -> lists:unzip([metadata_as_v1(M) || {_, M} <- Metadata]). -spec metadata_as_v1(metadata_v1() | metadata_v2()) -> metadata_v1(). metadata_as_v1(#{head_hash := H, timestamp := S}) -> {S, H}; % v2 -> v1 metadata_as_v1({S, H}) -> {S, H}. % v1 -> v1 -spec snapshot_hash(L, H, M, V) -> binary() when L :: blockchain_ledger_v1:ledger(), H :: non_neg_integer(), M :: metadata(), V :: non_neg_integer(). snapshot_hash(Ledger, BlockHeightNext, Metadata, VotesNeeded) -> %% Find a snapshot hash. If not enabled or we're unable to determine or %% agree on one, just leave it blank, so other nodes can absorb it. case blockchain:config(?snapshot_interval, Ledger) of {ok, Interval} when (BlockHeightNext - 1) rem Interval == 0 -> Hashes = [H || {_, #{snapshot_hash := H}} <- metadata_only_v2(Metadata)], common_enough_or_default(VotesNeeded, Hashes, <<>>); _ -> <<>> end. -spec common_enough_or_default(non_neg_integer(), [X], X) -> X. common_enough_or_default(_, [], Default) -> Default; common_enough_or_default(Threshold, Xs, Default) -> %% Looking for highest count AND sufficient agreement: case miner_util:list_count_and_sort(Xs) of [{X, C}|_] when C >= Threshold -> X; [{_, _}|_] -> Default % Not common-enough. end. set_next_block_timer(State=#state{blockchain=Chain}) -> Now = erlang:system_time(seconds), {ok, BlockTime0} = blockchain:config(?block_time, blockchain:ledger(Chain)), {ok, #block_info_v2{time=LastBlockTime, height=Height}} = blockchain:head_block_info(Chain), BlockTime = BlockTime0 div 1000, LastBlockTimestamp = case Height of 1 -> %% make up a plausible time for the genesis block Now; _ -> LastBlockTime end, StartHeight0 = application:get_env(miner, stabilization_period, 0), StartHeight = max(1, Height - StartHeight0), {ActualStartHeight0, StartBlockTime0} = case Height > StartHeight of true -> case blockchain:find_first_block_after(StartHeight, Chain) of {ok, Actual, StartBlock} -> {Actual, blockchain_block:time(StartBlock)}; _ -> {0, undefined} end; false -> {0, undefined} end, {ActualStartHeight, StartBlockTime} = case ActualStartHeight0 =< (StartHeight + 1) of true -> % enough history {ActualStartHeight0, StartBlockTime0}; false -> % not enough history, try to augment with other sources case miner_blockhistory:get_history() of {ok, {AugmentedHeight, AugmentedTime}} -> case AugmentedTime > StartBlockTime0 of true -> % Historical blocktime is newer than our own, this can't be right {ActualStartHeight0, StartBlockTime0}; false -> % Historical blocktime is older than our own, probably right {AugmentedHeight, AugmentedTime} end; _ -> % we don't have an augmented source, use our own history anyway {ActualStartHeight0, StartBlockTime0} end end, AvgBlockTime = case StartBlockTime of undefined -> BlockTime; _ -> (LastBlockTimestamp - StartBlockTime) / max(Height - ActualStartHeight, 1) end, BlockTimeDeviation0 = BlockTime - AvgBlockTime, lager:info("average ~p block times ~p difference ~p", [Height, AvgBlockTime, BlockTime - AvgBlockTime]), BlockTimeDeviation = case BlockTimeDeviation0 of N when N > 0 -> min(1, catchup_time(abs(N))); N -> -1 * catchup_time(abs(N)) end, NextBlockTime = max(0, (LastBlockTimestamp + BlockTime + BlockTimeDeviation) - Now), lager:info("Next block after ~p is in ~p seconds", [LastBlockTimestamp, NextBlockTime]), Timer = erlang:send_after(NextBlockTime * 1000, self(), block_timeout), %% now figure out the late block timer erlang:cancel_timer(State#state.late_block_timer), LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120), LateTimer = erlang:send_after((LateBlockTimeout + NextBlockTime) * 1000, self(), late_block_timeout), State#state{block_timer=Timer, late_block_timer = LateTimer}. input in fractional seconds , the number of seconds between the %% target block time and the average total time over the target period output in seconds of adjustment to apply to the block time target the constants here are by feel : currently at 100k target and 5sec adjustment it takes roughly a day of blocks to make up a tenth of a second . with the new 50k target we can expect double the adjustment leverage , so 1s adjustments will take roughly a day to make up the final 0.04 ( twice as much leverage , but 20 % of the rate ) . %% when drift is small or 0, let it accumulate for a bit catchup_time(N) when N < 0.001 -> 0; %% when it's still relatively small, apply gentle adjustments catchup_time(N) when N < 0.01 -> 1; %% if it's large, jam on the gas catchup_time(_) -> 10.
null
https://raw.githubusercontent.com/helium/miner/5d9f6132d87d06ac5a0f02ea5da7dbe9f730755d/src/miner.erl
erlang
API gen_server NOTE: a miner may or may not participate in consensus but every miner keeps a timer reference? ---------------------------------------------------------------------------- API ---------------------------------------------------------------------------- TODO: spec TODO: spec if the miner noprocs, we're likely shutting down Once a miner gets a sign_block message (only happens if the miner is in consensus group): * cancel the block timer * sign the block * add the block to blockchain format: ------------------------------------------------------------------ gen_server ------------------------------------------------------------------ TODO: Maybe put this somewhere else? We don't actually use this for anything at this time, but we should use this if we need it. NOTE: only the consensus group member must do this round, make it forcefully go to next round to know if we did didn't get included last round, try to get a jump on things now figure out the late block timer ============================================================================ Private ============================================================================ This can actually be a stale message, in which case we'd produce a block with a garbage timestamp. This is not actually that big of a deal, since it won't be accepted, but we can short circuit some effort by checking for a stale hash. We expect every stamp to contain the same block hash: Both pending and invalid are to be removed from the buffer: Try to rule out invalid values by not allowing timestamps to go backwards and take the median proposed value. we dont need the invalid reason here so need to remove the tuple format already full, don't want to skip because of possible txn ordering issues so just drop everything any that overflowed go back into the buffer To cut down on the size of group txn blocks, which we'll need to fetch and store all of to validate snapshots, we discard all other txns for this block. TODO Rename blockchain_txn:sort to blockchain_txn:(compare|cmp) try to isolate the var txn in its own block v2 -> v1 v1 -> v1 Find a snapshot hash. If not enabled or we're unable to determine or agree on one, just leave it blank, so other nodes can absorb it. Looking for highest count AND sufficient agreement: Not common-enough. make up a plausible time for the genesis block enough history not enough history, try to augment with other sources Historical blocktime is newer than our own, this can't be right Historical blocktime is older than our own, probably right we don't have an augmented source, use our own history anyway now figure out the late block timer target block time and the average total time over the target period of the rate ) . when drift is small or 0, let it accumulate for a bit when it's still relatively small, apply gentle adjustments if it's large, jam on the gas
-module(miner). -behavior(gen_server). -include_lib("blockchain/include/blockchain_vars.hrl"). -include_lib("blockchain/include/blockchain.hrl"). -export([ start_link/0, p2p_status/0, block_age/0, relcast_info/1, relcast_queue/1, hbbft_artifact/0, hbbft_status/0, hbbft_skip/0, create_block/3, signed_block/2, keys/0, reset_late_block_timer/0, start_chain/2, install_consensus/1, remove_consensus/0, version/0 ]). -export_type([ create_block_ok/0, create_block_error/0, create_block_result/0 ]). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2 ]). -type metadata_v1() :: {integer(), blockchain_block:hash()}. -type metadata_v2() :: #{ timestamp => integer(), seen => binary(), bba_completion => binary(), head_hash => blockchain_block:hash(), snapshot_hash => binary() }. -type metadata() :: [{J :: pos_integer(), M :: metadata_v2() | metadata_v1()}]. -type swarm_keys() :: {libp2p_crypto:pubkey(), libp2p_crypto:sig_fun()}. -type create_block_error() :: stale_hash | multiple_hashes. -type create_block_ok() :: #{ address => libp2p_crypto:pubkey_bin(), unsigned_binary_block => binary(), signature => binary(), pending_txns => blockchain_txn:txns(), invalid_txns => blockchain_txn:txns() }. -type create_block_result() :: {ok, create_block_ok()} | {error, create_block_error()}. -record(state, { consensus_group :: undefined | pid(), blockchain :: undefined | blockchain:blockchain(), block_timer = make_ref() :: reference(), late_block_timer = make_ref() :: reference(), current_height = -1 :: integer(), blockchain_ref = make_ref() :: reference(), swarm_tid :: ets:tid() | atom(), swarm_keys :: swarm_keys() }). -define(H3_MINIMUM_RESOLUTION, 9). -ifdef(TEST). -define(tv, '$test_version'). -export([test_version/0, inc_tv/1]). test_version() -> case ets:info(?tv) of undefined -> ets:new(?tv, [named_table, public]), ets:insert(?tv, {?tv, 1}), 1; _ -> [{_, V}] = ets:lookup(?tv, ?tv), lager:info("tv got ~p", [V]), V end. inc_tv(Incr) -> lager:info("increment: ~p", [Incr]), case ets:info(?tv) of undefined -> ets:new(?tv, [named_table, public]), ets:insert(?tv, {?tv, 1 + Incr}), 1 + Incr; _ -> ets:update_counter(?tv, ?tv, Incr) end. -endif. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], [{hibernate_after, 5000}]). block_age() -> Chain = blockchain_worker:blockchain(), {ok, #block_info_v2{time=BlockTime}} = blockchain:head_block_info(Chain), erlang:system_time(seconds) - BlockTime. -spec p2p_status() -> [{Check::string(), Result::string()}]. p2p_status() -> SwarmTID = blockchain_swarm:tid(), CheckSessions = fun() -> case (catch length(libp2p_swarm:sessions(SwarmTID)) > 5) of true -> "yes"; _ -> "no" end end, CheckPublicAddr = fun() -> case (catch lists:any(fun(Addr) -> libp2p_relay:is_p2p_circuit(Addr) orelse libp2p_transport_tcp:is_public(Addr) end, libp2p_swarm:listen_addrs(SwarmTID))) of true -> "yes"; _ -> "no" end end, CheckNatType = fun() -> try case libp2p_peerbook:get(libp2p_swarm:peerbook(SwarmTID), libp2p_swarm:pubkey_bin(SwarmTID)) of {ok, Peer} -> atom_to_list(libp2p_peer:nat_type(Peer)); {error, _} -> "unknown" end catch _:_ -> "unknown" end end, CheckHeight = fun() -> Chain = blockchain_worker:blockchain(), {ok, Height} = blockchain:height(Chain), integer_to_list(Height) end, lists:foldr(fun({Fun, Name}, Acc) -> [{Name, Fun()} | Acc] end, [], [{CheckSessions, "connected"}, {CheckPublicAddr, "dialable"}, {CheckNatType, "nat_type"}, {CheckHeight, "height"}]). relcast_info(Group) -> Mod = case Group of dkg_group -> miner_consensus_mgr; _ -> ?MODULE end, case gen_server:call(Mod, Group, 60000) of undefined -> #{}; Pid -> libp2p_group_relcast:info(Pid) end. relcast_queue(Group) -> Mod = case Group of dkg_group -> miner_consensus_mgr; _ -> ?MODULE end, case gen_server:call(Mod, Group, 60000) of undefined -> #{}; Pid -> try libp2p_group_relcast:queues(Pid) of {_ModState, Inbound, Outbound} -> O = maps:map( fun(_, V) -> [erlang:binary_to_term(Value) || Value <- V] end, Outbound ), I = [{Index,binary_to_term(B)} || {Index, B} <- Inbound], #{ inbound => I, outbound => O } catch What:Why -> {error, {What, Why}} end end. -spec create_block(metadata(), blockchain_txn:txns(), non_neg_integer()) -> create_block_result(). create_block(Metadata, Txns, HBBFTRound) -> try gen_server:call(?MODULE, {create_block, Metadata, Txns, HBBFTRound}, infinity) catch exit:{noproc, _} -> {error, no_miner} end. -spec hbbft_status() -> map() | {error, timeout}. hbbft_status() -> case gen_server:call(?MODULE, consensus_group, 60000) of undefined -> ok; Pid -> Ref = make_ref(), ok = libp2p_group_relcast:handle_input(Pid, {status, Ref, self()}), receive {Ref, Result} -> Result after timer:seconds(60) -> {error, timeout} end end. -spec hbbft_artifact() -> {ok, undefined} | {ok, binary()} | not_running | {error, timeout}. hbbft_artifact() -> case gen_server:call(?MODULE, consensus_group, 60000) of undefined -> not_running; Pid -> Ref = make_ref(), ok = libp2p_group_relcast:handle_input(Pid, {get_artifact, Ref, self()}), receive {Ref, Result} -> {ok, Result} after timer:seconds(60) -> {error, timeout} end end. -spec hbbft_skip() -> ok | {error, timeout}. hbbft_skip() -> case gen_server:call(?MODULE, consensus_group, 60000) of undefined -> ok; Pid -> ok = libp2p_group_relcast:handle_input(Pid, maybe_skip) end. -spec signed_block([binary()], binary()) -> ok. signed_block(Signatures, BinBlock) -> * tell to go to next round Chain = blockchain_worker:blockchain(), Block = blockchain_block:set_signatures(blockchain_block:deserialize(BinBlock), Signatures), case blockchain:add_block(Block, Chain) of ok -> lager:info("sending the gossiped block to other workers"), Swarm = blockchain_swarm:swarm(), SwarmTID = blockchain_swarm:tid(), Data = case application:get_env(blockchain, gossip_version, 1) of 1 -> blockchain_gossip_handler:gossip_data_v1(SwarmTID, Block); 2 -> Height = blockchain_block:height(Block), {ok, #block_info_v2{hash = Hash}} = blockchain:get_block_info(Height, Chain), blockchain_gossip_handler:gossip_data_v2(SwarmTID, Hash, Height) end, libp2p_group_gossip:send( SwarmTID, ?GOSSIP_PROTOCOL_V1, Data ), {Signatories, _} = lists:unzip(blockchain_block:signatures(Block)), {ok, ConsensusAddrs} = blockchain_ledger_v1:consensus_members(blockchain:ledger(Chain)), FF non signatory consensus members lists:foreach( fun(Member) -> spawn(fun() -> blockchain_fastforward_handler:dial( Swarm, Chain, libp2p_crypto:pubkey_bin_to_p2p(Member)) end) end, ConsensusAddrs -- Signatories); Error -> lager:error("signed_block, error: ~p", [Error]) end, ok. -spec keys() -> {ok, {libp2p_crypto:pubkey(), libp2p_crypto:sig_fun()}}. keys() -> gen_server:call(?MODULE, keys). -spec reset_late_block_timer() -> ok. reset_late_block_timer() -> gen_server:call(?MODULE, reset_late_block_timer). start_chain(ConsensusGroup, Chain) -> gen_server:call(?MODULE, {start_chain, ConsensusGroup, Chain}, infinity). install_consensus(ConsensusGroup) -> gen_server:cast(?MODULE, {install_consensus, ConsensusGroup}). remove_consensus() -> gen_server:cast(?MODULE, remove_consensus). -spec version() -> integer(). version() -> MMMmmmPPPP 0010170002. init(_Args) -> Mode = application:get_env(miner, mode), lager:info("STARTING UP MINER with mode ~p", [Mode]), ok = blockchain_event:add_handler(self()), ok = miner_discovery_handler:add_stream_handler(blockchain_swarm:tid()), BlockchainRef = erlang:monitor(process, blockchain_worker), {ok, MyPubKey, SignFun, _ECDHFun} = blockchain_swarm:keys(), case blockchain_worker:blockchain() of undefined -> {ok, #state{swarm_keys = {MyPubKey, SignFun}, swarm_tid = SwarmTID}}; Chain -> {ok, #state{swarm_keys = {MyPubKey, SignFun}, swarm_tid = SwarmTID, blockchain = Chain, blockchain_ref = BlockchainRef}} end. handle_call(consensus_group, _From, State) -> {reply, State#state.consensus_group, State}; handle_call({start_chain, ConsensusGroup, Chain}, _From, State) -> lager:info("registering first consensus group"), {reply, ok, set_next_block_timer(State#state{consensus_group = ConsensusGroup, blockchain = Chain})}; handle_call({create_block, Metadata, Txns, HBBFTRound}, _From, #state{blockchain = Chain, swarm_keys = SK} = State) -> Result = try_create_block(Metadata, Txns, HBBFTRound, Chain, SK), {reply, Result, State}; handle_call(keys, _From, State) -> {reply, {ok, State#state.swarm_keys}, State}; handle_call(reset_late_block_timer, _From, State) -> erlang:cancel_timer(State#state.late_block_timer), LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120), LateTimer = erlang:send_after(LateBlockTimeout * 1000, self(), late_block_timeout), {reply, ok, State#state{late_block_timer = LateTimer}}; handle_call(_Msg, _From, State) -> lager:warning("unhandled call ~p", [_Msg]), {noreply, State}. handle_cast(remove_consensus, State) -> erlang:cancel_timer(State#state.block_timer), {noreply, State#state{consensus_group = undefined, block_timer = make_ref()}}; handle_cast({install_consensus, NewConsensusGroup}, #state{consensus_group = Group} = State) when Group == NewConsensusGroup -> {noreply, State}; handle_cast({install_consensus, NewConsensusGroup}, State) -> lager:info("installing consensus ~p after ~p", [NewConsensusGroup, State#state.consensus_group]), {noreply, set_next_block_timer(State#state{consensus_group = NewConsensusGroup})}; handle_cast(_Msg, State) -> lager:warning("unhandled cast ~p", [_Msg]), {noreply, State}. handle_info({'DOWN', Ref, process, _, Reason}, State = #state{blockchain_ref=Ref}) -> lager:warning("Blockchain worker exited with reason ~p", [Reason]), {stop, Reason, State}; handle_info(block_timeout, State) when State#state.consensus_group == undefined -> {noreply, State}; handle_info(block_timeout, State) -> lager:info("block timeout"), libp2p_group_relcast:handle_input(State#state.consensus_group, start_acs), {noreply, State}; handle_info(late_block_timeout, State) -> LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120) * 1000, lager:info("late block timeout"), libp2p_group_relcast:handle_input(State#state.consensus_group, maybe_skip), LateTimer = erlang:send_after(LateBlockTimeout, self(), late_block_timeout), {noreply, State#state{late_block_timer = LateTimer}}; handle_info({blockchain_event, {add_block, Hash, Sync, Ledger}}, State=#state{consensus_group = ConsensusGroup, current_height = CurrHeight, swarm_keys = {PubKey, _SigFun}, blockchain = Chain}) when ConsensusGroup /= undefined andalso Chain /= undefined -> If this miner is in consensus group and lagging on a previous NewState = case blockchain:get_block_height(Hash, Chain) of {ok, Height} when Height > CurrHeight -> case blockchain:get_block(Hash, Chain) of {ok, Block} -> erlang:cancel_timer(State#state.block_timer), lager:info("processing block for ~p", [Height]), Round = blockchain_block:hbbft_round(Block), Txns = blockchain_block:transactions(Block), case blockchain_election:has_new_group(Txns) of false -> lager:debug("reg round c ~p", [Height]), NextRound = Round + 1, libp2p_group_relcast:handle_input( ConsensusGroup, {next_round, NextRound, Txns, Sync}), {ok, ConsensusAddrs} = blockchain_ledger_v1:consensus_members(Ledger), F = (length(ConsensusAddrs) - 1) div 3, BBAs = blockchain_utils:bitvector_to_map(length(ConsensusAddrs), blockchain_block_v1:bba_completion(Block)), BBAAddrs = maps:fold(fun(K, true, Acc) -> [lists:nth(K, ConsensusAddrs) | Acc]; (_, _, Acc) -> Acc end, [], BBAs), case lists:member(libp2p_crypto:pubkey_to_bin(PubKey), BBAAddrs) orelse length(BBAAddrs) < (2 * F)+1 of true -> we got our proposal in last round , or we did n't see enough BBA votes set_next_block_timer(State#state{current_height = Height}); false -> lager:info("jumping to next hbbft round ~p early", [Round+1]), Timer = erlang:send_after(0, self(), block_timeout), erlang:cancel_timer(State#state.late_block_timer), LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120), LateTimer = erlang:send_after(LateBlockTimeout * 1000, self(), late_block_timeout), State#state{block_timer=Timer, late_block_timer=LateTimer} end; {true, _, _, _} -> State#state{block_timer = make_ref(), current_height = Height} end; {error, Reason} -> lager:error("Error, Reason: ~p", [Reason]), State end; {ok, _Height} -> lager:debug("skipped re-processing block for ~p", [_Height]), State end, {noreply, NewState}; handle_info({blockchain_event, {add_block, Hash, _Sync, _Ledger}}, #state{consensus_group = ConsensusGroup, current_height = CurrHeight, blockchain = Chain} = State) when ConsensusGroup == undefined andalso Chain /= undefined -> case blockchain:get_block_height(Hash, Chain) of {ok, Height} -> lager:info("non-consensus block ~p", [Height]), case Height of H when H > CurrHeight -> {noreply, State#state{current_height = Height}}; _ -> {noreply, State} end; {error, Reason} -> lager:error("Error, Reason: ~p", [Reason]), {noreply, State} end; handle_info({blockchain_event, {add_block, _Hash, _Sync, _Ledger}}, State) when State#state.blockchain == undefined -> Chain = blockchain_worker:blockchain(), {noreply, State#state{blockchain = Chain}}; handle_info({blockchain_event, {new_chain, NC}}, #state{blockchain_ref = Ref, swarm_keys=SK, swarm_tid=STid}) -> State1 = #state{blockchain = NC, blockchain_ref = Ref, swarm_keys=SK, swarm_tid=STid}, {noreply, State1}; handle_info(_Msg, State) -> lager:warning("unhandled info message ~p", [_Msg]), {noreply, State}. terminate(Reason, _State) -> lager:info("stopping: ~p", [Reason]), ok. -spec try_create_block( metadata(), blockchain_txn:txns(), non_neg_integer(), blockchain:blockchain(), swarm_keys() ) -> create_block_result(). try_create_block(Metadata, Txns, HBBFTRound, Chain, SwarmKeys) -> {ok, HashCurr} = blockchain:head_hash(Chain), lager:debug("Metadata ~p, current hash ~p", [Metadata, HashCurr]), N = count_consensus_members(Chain), VotesNeeded = N - ((N - 1) div 3), {_, Hashes} = meta_to_stamp_hashes(Metadata), case hash_check_if_stale(HashCurr, Hashes, VotesNeeded) of {ok, {}} -> {ok, create_block(Metadata, Txns, HBBFTRound, Chain, VotesNeeded, SwarmKeys)}; {error, {stale, HashStale, Votes}} -> lager:warning("Stale hash: ~p, picked by ~b nodes.", [HashStale, Votes]), {error, stale_hash}; {error, {unexpected_counts, Counts}} -> lager:warning( "got unexpected block hashes in stamp information ~p", [Counts] ), XXX May also be [ ] , so not just multiple ! {error, multiple_hashes} end. -spec count_consensus_members(blockchain:blockchain()) -> non_neg_integer(). count_consensus_members(Chain) -> {ok, ConsensusMembers} = blockchain_ledger_v1:consensus_members(blockchain:ledger(Chain)), length(ConsensusMembers). -spec hash_check_if_stale(H, [H], C) -> {ok, {}} | {error, E} when E :: {stale, H, C} | {unexpected_counts, [{H, C}]}, H :: blockchain_block:hash(), C :: non_neg_integer(). hash_check_if_stale(HashCurr, Hashes, VotesNeeded) -> case lists:filter( fun ({_, Votes}) -> Votes >= VotesNeeded end, maps:to_list(miner_util:list_count(Hashes)) ) of [{HashCurr, _}] -> {ok, {}}; [{HashStale, Votes}] -> {error, {stale, HashStale, Votes}}; Counts -> {error, {unexpected_counts, Counts}} end. -spec create_block( metadata(), blockchain_txn:txns(), non_neg_integer(), blockchain:blockchain(), non_neg_integer(), swarm_keys() ) -> create_block_ok(). create_block(Metadata, Txns, HBBFTRound, Chain, VotesNeeded, {MyPubKey, SignFun}) -> {ok, #block_info_v2{height=HeightCurr, time=CurrentBlockTime, hash=CurrentBlockHash, election_info=ElectionInfo}} = blockchain:head_block_info(Chain), HeightNext = HeightCurr + 1, Ledger = blockchain:ledger(Chain), SnapshotHash = snapshot_hash(Ledger, HeightNext, Metadata, VotesNeeded), SeenBBAs = [{{J, S}, B} || {J, #{seen := S, bba_completion := B}} <- metadata_only_v2(Metadata)], {SeenVectors, BBAs} = lists:unzip(SeenBBAs), if we can not agree on the BBA results , default to flagging everyone as having completed VoteDefault = case blockchain:config(?election_version, Ledger) of {ok, N} when N >= 5 -> blockchain_utils:map_to_bitvector( maps:from_list([ {I, true} || I <- lists:seq(1, count_consensus_members(Chain))])); _ -> <<>> end, BBA = common_enough_or_default(VotesNeeded, BBAs, VoteDefault), {ElectionEpoch, EpochStart, TxnsToInsert, InvalidTransactions} = select_transactions(Chain, Txns, ElectionInfo, HeightCurr, HeightNext), NewBlock = blockchain_block_v1:new(#{ prev_hash => CurrentBlockHash, height => HeightNext, transactions => TxnsToInsert, signatures => [], hbbft_round => HBBFTRound, time => block_time(CurrentBlockTime, Metadata), election_epoch => ElectionEpoch, epoch_start => EpochStart, seen_votes => SeenVectors, bba_completion => BBA, snapshot_hash => SnapshotHash }), BinNewBlock = blockchain_block:serialize(NewBlock), Signature = SignFun(BinNewBlock), lager:debug("Worker:~p, Created Block: ~p, Txns: ~p", [self(), NewBlock, TxnsToInsert]), #{ address => libp2p_crypto:pubkey_to_bin(MyPubKey), unsigned_binary_block => BinNewBlock, signature => Signature, pending_txns => TxnsToInsert, invalid_txns => InvalidTransactions }. -spec block_time(non_neg_integer(), metadata()) -> pos_integer(). block_time(LastBlockTime, Metadata) -> {Stamps, _} = meta_to_stamp_hashes(Metadata), case miner_util:median([S || S <- Stamps, S >= LastBlockTime]) of 0 -> LastBlockTime + 1; LastBlockTime -> LastBlockTime + 1; NewTime -> NewTime end. -spec select_transactions( blockchain:blockchain(), blockchain_txn:txns(), {non_neg_integer(), non_neg_integer()}, non_neg_integer(), non_neg_integer() ) -> { ElectionEpoch :: non_neg_integer(), EpochStart :: non_neg_integer(), TxsValid :: blockchain_txn:txns(), TxsInvalid :: blockchain_txn:txns() }. select_transactions(Chain, Txns, {ElectionEpoch0, EpochStart0}, BlockHeightCurr, BlockHeightNext) -> SortedTransactions = lists:sort(fun blockchain_txn:sort/2, [T || T <- Txns, not txn_is_rewards(T)]), {ValidTransactions0, InvalidTransactions0} = blockchain_txn:validate(SortedTransactions, Chain), InvalidTransactions0 is a list of tuples in the format { Txn , InvalidReason } and have a regular list of txn items in prep for returning to . InvalidTransactions1 = [InvTxn || {InvTxn, _InvalidReason} <- InvalidTransactions0], Ledger = blockchain:ledger(Chain), SizeLimit = case blockchain:config(?block_size_limit, Ledger) of {ok, Limit} -> Limit; 50 mb default end, {_, ValidTransactions1} = lists:foldl(fun(_Txn, {done, Acc}) -> {done, Acc}; (Txn, {Count, Acc}) -> case Count - byte_size(blockchain_txn:serialize(Txn)) of Remainder when Remainder < 0 -> {done, Acc}; Remainder -> {Remainder, [Txn|Acc]} end end, {SizeLimit, []}, ValidTransactions0), ValidTransactions = lists:reverse(ValidTransactions1), InvalidTransactions = InvalidTransactions1 ++ (ValidTransactions0 -- ValidTransactions), case blockchain_election:has_new_group(ValidTransactions) of {true, _, ConsensusGroupTxn, _} -> Epoch = ElectionEpoch0 + 1, Start = EpochStart0 + 1, End = BlockHeightCurr, RewardsMod = case blockchain:config(?rewards_txn_version, Ledger) of {ok, 2} -> blockchain_txn_rewards_v2; _ -> blockchain_txn_rewards_v1 end, {ok, Rewards} = RewardsMod:calculate_rewards(Start, End, Chain), blockchain_hex:destroy_memoization(), lager:debug("RewardsMod: ~p, Rewards: ~p~n", [RewardsMod, Rewards]), RewardsTxn = RewardsMod:new(Start, End, Rewards), Transactions = lists:sort( fun blockchain_txn:sort/2, [RewardsTxn, ConsensusGroupTxn] ), {Epoch, BlockHeightNext, Transactions, InvalidTransactions}; _ -> case {blockchain:config(?isolate_var_txns, Ledger), lists:filter(fun(T) -> blockchain_txn:type(T) == blockchain_txn_vars_v1 end, ValidTransactions)} of {{ok, true}, [VarTxn|_]} -> take the first var txn found as the only txn in a block {ElectionEpoch0, EpochStart0, [VarTxn], InvalidTransactions}; _ -> {ElectionEpoch0, EpochStart0, ValidTransactions, InvalidTransactions} end end. -spec txn_is_rewards(blockchain_txn:txn()) -> boolean(). txn_is_rewards(Txn) -> Rewards = [blockchain_txn_rewards_v1, blockchain_txn_rewards_v2], lists:member(blockchain_txn:type(Txn), Rewards). -spec metadata_only_v2(metadata()) -> [{non_neg_integer(), metadata_v2()}]. metadata_only_v2(Metadata) -> lists:filter(fun ({_, M}) -> is_map(M) end, Metadata). -spec meta_to_stamp_hashes(metadata()) -> { Stamps :: [integer()], Hashes :: [blockchain_block:hash()] }. meta_to_stamp_hashes(Metadata) -> lists:unzip([metadata_as_v1(M) || {_, M} <- Metadata]). -spec metadata_as_v1(metadata_v1() | metadata_v2()) -> metadata_v1(). -spec snapshot_hash(L, H, M, V) -> binary() when L :: blockchain_ledger_v1:ledger(), H :: non_neg_integer(), M :: metadata(), V :: non_neg_integer(). snapshot_hash(Ledger, BlockHeightNext, Metadata, VotesNeeded) -> case blockchain:config(?snapshot_interval, Ledger) of {ok, Interval} when (BlockHeightNext - 1) rem Interval == 0 -> Hashes = [H || {_, #{snapshot_hash := H}} <- metadata_only_v2(Metadata)], common_enough_or_default(VotesNeeded, Hashes, <<>>); _ -> <<>> end. -spec common_enough_or_default(non_neg_integer(), [X], X) -> X. common_enough_or_default(_, [], Default) -> Default; common_enough_or_default(Threshold, Xs, Default) -> case miner_util:list_count_and_sort(Xs) of [{X, C}|_] when C >= Threshold -> X; end. set_next_block_timer(State=#state{blockchain=Chain}) -> Now = erlang:system_time(seconds), {ok, BlockTime0} = blockchain:config(?block_time, blockchain:ledger(Chain)), {ok, #block_info_v2{time=LastBlockTime, height=Height}} = blockchain:head_block_info(Chain), BlockTime = BlockTime0 div 1000, LastBlockTimestamp = case Height of 1 -> Now; _ -> LastBlockTime end, StartHeight0 = application:get_env(miner, stabilization_period, 0), StartHeight = max(1, Height - StartHeight0), {ActualStartHeight0, StartBlockTime0} = case Height > StartHeight of true -> case blockchain:find_first_block_after(StartHeight, Chain) of {ok, Actual, StartBlock} -> {Actual, blockchain_block:time(StartBlock)}; _ -> {0, undefined} end; false -> {0, undefined} end, {ActualStartHeight, StartBlockTime} = case ActualStartHeight0 =< (StartHeight + 1) of true -> {ActualStartHeight0, StartBlockTime0}; false -> case miner_blockhistory:get_history() of {ok, {AugmentedHeight, AugmentedTime}} -> case AugmentedTime > StartBlockTime0 of true -> {ActualStartHeight0, StartBlockTime0}; false -> {AugmentedHeight, AugmentedTime} end; _ -> {ActualStartHeight0, StartBlockTime0} end end, AvgBlockTime = case StartBlockTime of undefined -> BlockTime; _ -> (LastBlockTimestamp - StartBlockTime) / max(Height - ActualStartHeight, 1) end, BlockTimeDeviation0 = BlockTime - AvgBlockTime, lager:info("average ~p block times ~p difference ~p", [Height, AvgBlockTime, BlockTime - AvgBlockTime]), BlockTimeDeviation = case BlockTimeDeviation0 of N when N > 0 -> min(1, catchup_time(abs(N))); N -> -1 * catchup_time(abs(N)) end, NextBlockTime = max(0, (LastBlockTimestamp + BlockTime + BlockTimeDeviation) - Now), lager:info("Next block after ~p is in ~p seconds", [LastBlockTimestamp, NextBlockTime]), Timer = erlang:send_after(NextBlockTime * 1000, self(), block_timeout), erlang:cancel_timer(State#state.late_block_timer), LateBlockTimeout = application:get_env(miner, late_block_timeout_seconds, 120), LateTimer = erlang:send_after((LateBlockTimeout + NextBlockTime) * 1000, self(), late_block_timeout), State#state{block_timer=Timer, late_block_timer = LateTimer}. input in fractional seconds , the number of seconds between the output in seconds of adjustment to apply to the block time target the constants here are by feel : currently at 100k target and 5sec adjustment it takes roughly a day of blocks to make up a tenth of a second . with the new 50k target we can expect double the adjustment leverage , so 1s adjustments will take roughly a day to make up the catchup_time(N) when N < 0.001 -> 0; catchup_time(N) when N < 0.01 -> 1; catchup_time(_) -> 10.
259b332a3c9f19ee5329a88fb5a232177a4341d0bb077d1d953e099ac6358b7b
lambdacube3d/lambdacube-edsl
ObjParser.hs
{-# LANGUAGE OverloadedStrings #-} module ObjParser where import System.Environment import Control.Applicative import Control.Monad import Control.Monad.State.Strict import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.ByteString.Lazy.Char8 as B import LambdaCube.GL -- {- data ObjMesh = ObjMesh { points :: [Int] , lines :: [Int] , triangles :: [Int] -- , name } -} data ObjState = ObjState { position :: [V3F] , normal :: [V3F] , uvw :: [V3F] , positionSize :: Int , normalSize :: Int , uvwSize :: Int , points :: [Int] , lines' :: [Int] , triangles :: [Int] } deriving Show readV3F [x] = V3 (read $ B.unpack x) 0 0 readV3F [x,y] = V3 (read $ B.unpack x) (read $ B.unpack y) 0 readV3F [x,y,z] = V3 (read $ B.unpack x) (read $ B.unpack y) (read $ B.unpack z) readV3F l = error $ show l incPosition = modify (\s -> s {positionSize = positionSize s + 1}) incNormal = modify (\s -> s {normalSize = normalSize s + 1}) incUVW = modify (\s -> s {uvwSize = uvwSize s + 1}) tokenize :: Bool -> ByteString -> [(Int, [ByteString])] tokenize filterComments str = zip [1..] . map B.words . joinLines . (if filterComments then map filterComment else id) . B.lines $ str where filterComment = B.takeWhile (/= '#') joinLines (a:b:xs) | B.length a > 0 && B.last a == '\\' = joinLines (B.init a `B.append` b : xs) | otherwise = a : joinLines (b:xs) joinLines a = a TODO : support position parsing first parse lines parse tirangles parse quads add normal parsing add texture coord parsing TODO: support position parsing first parse lines parse tirangles parse quads add normal parsing add texture coord parsing -} readObj str = execState (mapM_ parseLine $ tokenize False str) $ ObjState [] [] [] 0 0 0 [] [] [] where addV xs = modify (\s -> s {position = readV3F xs : position s}) >> incPosition addVT xs = modify (\s -> s {uvw = readV3F xs : uvw s}) >> incUVW addVN xs = modify (\s -> s {normal = readV3F xs : normal s}) >> incNormal addP xs = modify (\s -> s {points = xs ++ points s}) addL xs = modify (\s -> s {lines' = xs ++ lines' s}) addT xs = modify (\s -> s {triangles = xs ++ triangles s}) chop "" = [] chop xs = a : if b == "/" then [""] else chop (B.drop 1 b) where (a,b) = B.break (=='/') xs parseLine (lineNumber,l) = case l of -- [] -> return () -- * Supported statements Vertex data "v":xs -> case xs of [_,_,_] -> addV xs [_,_,_,_] -> notSupported _ -> err ["vn",x,y,z] -> addVN [x,y,z] "vt":xs -> case xs of [_] -> addVT xs [_,_] -> addVT xs [_,_,_] -> addVT xs _ -> err -- Elements "p":xs -> do pIndex <- gets positionSize let f x = if x < 0 then x + pIndex else x - 1 addP $ map (f . read . B.unpack) xs "l":xs -> do pIndex <- gets positionSize let f x = if x < 0 then x + pIndex else x - 1 ps = map (f . read . B.unpack . head . chop) xs segments (a:xs@(b:_)) = a : b : segments xs segments a = a addL $ segments ps "f":xs -> do pIndex <- gets positionSize let f x = if x < 0 then x + pIndex else x - 1 ps = map (f . read . B.unpack . head . chop) xs case xs of [_,_,_] -> addT ps [_,_,_,_] -> let [a,b,c,d] = ps in addT [a,b,c,c,d,a] _ -> notSupported Grouping TODO TODO TODO -- Display/render attributes TODO TODO TODO _ -> return () -- * Unsupported statements ( for future work ) -- Vertex data " vp":xs - > case xs of [ _ ] - > notSupported [ _ , _ ] - > notSupported [ _ , _ , _ ] - > notSupported _ - > err " cstype":xs - > case xs of [ " rat",a ] | a ` elem ` [ " bmatrix","bezier","bspline","cardinal","taylor " ] - > notSupported [ a ] | a ` elem ` [ " bmatrix","bezier","bspline","cardinal","taylor " ] - > notSupported _ - > err " deg":xs - > case xs of [ _ ] - > notSupported [ _ , _ ] - > notSupported _ - > err " bmat":xs - > case xs of " u " : _ - > notSupported " v " : _ - > notSupported _ - > err " step":xs - > case xs of [ _ ] - > notSupported [ _ , _ ] - > notSupported _ - > err -- Elements " curv " : _ - > notSupported " " : _ - > notSupported " surf " : _ - > notSupported -- Free - fvorm curve / surface body statements " parm " : _ - > notSupported " trim " : _ - > notSupported " hole " : _ - > notSupported " scrv " : _ - > notSupported " sp " : _ - > notSupported [ " end " ] - > notSupported -- Connectivity between free - form surfaces [ " con " , _ , _ , _ , _ , _ , _ , _ , _ ] - > notSupported -- Grouping [ " mg " , _ , _ ] - > notSupported -- Display / render attributes " bevel":xs - > case xs of [ " on " ] - > notSupported [ " off " ] - > notSupported _ - > err " c_interp":xs - > case xs of [ " on " ] - > notSupported [ " off " ] - > notSupported _ - > err " d_interp":xs - > case xs of [ " on " ] - > notSupported [ " off " ] - > notSupported _ - > err [ " lod " , _ ] - > notSupported [ " shadow_obj " , _ ] - > notSupported [ " trace_obj " , _ ] - > notSupported " ctech":xs - > case xs of [ " cparm " , _ ] - > notSupported [ " cspace " , _ ] - > notSupported [ " curv " , _ , _ ] - > notSupported _ - > err " stech":xs - > case xs of [ " " , _ , _ ] - > notSupported [ " " , _ ] - > notSupported [ " cspace " , _ ] - > notSupported [ " curv " , _ , _ ] - > notSupported _ - > err ( a : _ ) | B.head a = = ' # ' - > return ( ) | otherwise - > err -- * Unsupported statements (for future work) -- Vertex data "vp":xs -> case xs of [_] -> notSupported [_,_] -> notSupported [_,_,_] -> notSupported _ -> err "cstype":xs -> case xs of ["rat",a] | a `elem` ["bmatrix","bezier","bspline","cardinal","taylor"] -> notSupported [a] | a `elem` ["bmatrix","bezier","bspline","cardinal","taylor"] -> notSupported _ -> err "deg":xs -> case xs of [_] -> notSupported [_,_] -> notSupported _ -> err "bmat":xs -> case xs of "u":_ -> notSupported "v":_ -> notSupported _ -> err "step":xs -> case xs of [_] -> notSupported [_,_] -> notSupported _ -> err -- Elements "curv":_ -> notSupported "curv2":_ -> notSupported "surf":_ -> notSupported -- Free-fvorm curve/surface body statements "parm":_ -> notSupported "trim":_ -> notSupported "hole":_ -> notSupported "scrv":_ -> notSupported "sp":_ -> notSupported ["end"] -> notSupported -- Connectivity between free-form surfaces ["con",_,_,_,_,_,_,_,_] -> notSupported -- Grouping ["mg",_,_] -> notSupported -- Display/render attributes "bevel":xs -> case xs of ["on"] -> notSupported ["off"] -> notSupported _ -> err "c_interp":xs -> case xs of ["on"] -> notSupported ["off"] -> notSupported _ -> err "d_interp":xs -> case xs of ["on"] -> notSupported ["off"] -> notSupported _ -> err ["lod",_] -> notSupported ["shadow_obj",_] -> notSupported ["trace_obj",_] -> notSupported "ctech":xs -> case xs of ["cparm",_] -> notSupported ["cspace",_] -> notSupported ["curv",_,_] -> notSupported _ -> err "stech":xs -> case xs of ["cparma",_,_] -> notSupported ["cparmb",_] -> notSupported ["cspace",_] -> notSupported ["curv",_,_] -> notSupported _ -> err (a : _) | B.head a == '#' -> return () | otherwise -> err -} where err = error $ "line " ++ show lineNumber ++ " syntax error: " ++ show l notSupported = error $ "line " ++ show lineNumber ++ " unsupported statement: " ++ show l newmtl my_mtl Ka 0.0435 0.0435 0.0435 Kd 0.1086 0.1086 0.1086 Ks 0.0000 0.0000 0.0000 Tf 0.9885 0.9885 0.9885 illum 6 d -halo 0.6600 Ns 10.0000 sharpness 60 Ni 1.19713 map_Ka -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Kd -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ks -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ns -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps map_d -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps disp -s 1 1 .5 wisp.mps decal -s 1 1 1 -o 0 0 0 -mm 0 1 bump -s 1 1 1 -o 0 0 0 -bm 1 sand.mpb refl -type sphere -mm 0 1 clouds.mpc newmtl name b Ka spectral file.rfl factor y z Kd r g b Kd spectral file.rfl factor Kd xyz x y z Ks r g b Ks spectral file.rfl factor y z Tf r g b Tf spectral file.rfl factor Tf xyz x y z d factor d -halo factor Ns exponent sharpness value -options args filename map_Kd -options args filename map_Ks -options args filename map_Ns -options args filename map_d -options args filename map_aat on decal -options args filename disp -options args filename bump -options args filename newmtl my_mtl Ka 0.0435 0.0435 0.0435 Kd 0.1086 0.1086 0.1086 Ks 0.0000 0.0000 0.0000 Tf 0.9885 0.9885 0.9885 illum 6 d -halo 0.6600 Ns 10.0000 sharpness 60 Ni 1.19713 map_Ka -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Kd -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ks -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ns -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps map_d -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps disp -s 1 1 .5 wisp.mps decal -s 1 1 1 -o 0 0 0 -mm 0 1 sand.mps bump -s 1 1 1 -o 0 0 0 -bm 1 sand.mpb refl -type sphere -mm 0 1 clouds.mpc newmtl name Ka r g b Ka spectral file.rfl factor Ka xyz x y z Kd r g b Kd spectral file.rfl factor Kd xyz x y z Ks r g b Ks spectral file.rfl factor Ks xyz x y z Tf r g b Tf spectral file.rfl factor Tf xyz x y z d factor d -halo factor Ns exponent sharpness value Ni optical_density map_Ka -options args filename map_Kd -options args filename map_Ks -options args filename map_Ns -options args filename map_d -options args filename map_aat on decal -options args filename disp -options args filename bump -options args filename -} pragmatic : Wavefront OBJ material file # this is a comment Ka 0.00941176 0.0745098 0.0156863 Ka 0.14 0.45 0.091 # Green Kd 0.000000 0.000000 0.501961 Ke 0.3 0.05 0.01 Ke 17 12 4 # The empty water Cornell Box as seen in Ks .0001 .0001 .0001 Ks 0 0 0 Ks 0.427451 0.427451 0.427451 Ni 1.0000 Ns 0 Tf 0.066667 0.631373 0.074510 Tr 0 Tr 0 0 bump kamen-bump.png bump textures\vase_round_bump.png d 0.100000 illum 2 illum 4 illum 5 illum 5 illum 7 map_Ka KAMEN-stup.png map_Ka textures\background.tga map_Kd KAMEN-stup.png map_Kd textures\sponza_floor_a_diff.tga map_bump -bm 0.001 bump-lowRes.png map_bump kamen-bump.png map_bump textures\vase_round_bump.png map_d house-Alpha.png map_d textures\vase_plant_mask.tga newmtl Brick pragmatic: Wavefront OBJ material file #this is a comment Ka 0.00941176 0.0745098 0.0156863 Ka 0.14 0.45 0.091 # Green Kd 0.000000 0.000000 0.501961 Ke 0.3 0.05 0.01 Ke 17 12 4# The empty water Cornell Box as seen in Henrik Jensen's Ks .0001 .0001 .0001 Ks 0 0 0 Ks 0.427451 0.427451 0.427451 Ni 1.0000 Ns 0 Tf 0.066667 0.631373 0.074510 Tr 0 Tr 0 0 bump kamen-bump.png bump textures\vase_round_bump.png d 0.100000 illum 2 illum 4 illum 5 illum 5 illum 7 map_Ka KAMEN-stup.png map_Ka textures\background.tga map_Kd KAMEN-stup.png map_Kd textures\sponza_floor_a_diff.tga map_bump -bm 0.001 bump-lowRes.png map_bump kamen-bump.png map_bump textures\vase_round_bump.png map_d house-Alpha.png map_d textures\vase_plant_mask.tga newmtl Brick -} data Mtl = Mtl { mtlName :: String , mtlKa :: V3F , mtlKd :: V3F , mtlKe :: V3F , mtlKs :: V3F , mtlNi :: Float , mtlTf :: V3F , mtlBump :: String , mtlD :: Float , mtlIllum :: Int , mtlMapKa :: String , mtlMapKd :: String , mtlMapBump :: String , mtlMapBumpMultiplier :: Float , mtlMapD :: String } readMtl str = execState (mapM_ parseLine $ tokenize True str) () -- $ ObjState [] [] [] 0 0 0 where parseLine (1,["Wavefront","OBJ","material","file"]) = return () parseLine (lineNumber,l) = case l of [] -> return () ["newmtl",a] -> return () ["Ka",r,g,b] -> return () ["Kd",r,g,b] -> return () ["Ke",r,g,b] -> return () ["Ks",r,g,b] -> return () ["Ni",a] -> return () ["Ns",a] -> return () ["Tf",r,g,b] -> return () -- ["Tr",a] -> return () -- ["Tr",a,b] -> return () ["bump",a] -> return () ["d",a] -> return () ["illum",a] -> return () ["map_Ka",a] -> return () ["map_Kd",a] -> return () ["map_bump","-bm",a,b] -> return () ["map_bump",a] -> return () ["map_d",a] -> return () _ -> return () where err = error $ "line " ++ show lineNumber ++ " syntax error: " ++ show l notSupported = error $ "line " ++ show lineNumber ++ " unsupported statement: " ++ show l main = do l <- getArgs forM_ l $ \n -> do print n c <- B.readFile n print $ length $ triangles $ readObj c
null
https://raw.githubusercontent.com/lambdacube3d/lambdacube-edsl/4347bb0ed344e71c0333136cf2e162aec5941df7/lambdacube-gl/src/lib/LambdaCube/GL/ObjParser.hs
haskell
# LANGUAGE OverloadedStrings # data ObjMesh = ObjMesh { points :: [Int] , lines :: [Int] , triangles :: [Int] -- , name } [] -> return () * Supported statements Elements Display/render attributes * Unsupported statements ( for future work ) Vertex data Elements Free - fvorm curve / surface body statements Connectivity between free - form surfaces Grouping Display / render attributes * Unsupported statements (for future work) Vertex data Elements Free-fvorm curve/surface body statements Connectivity between free-form surfaces Grouping Display/render attributes $ ObjState [] [] [] 0 0 0 ["Tr",a] -> return () ["Tr",a,b] -> return ()
module ObjParser where import System.Environment import Control.Applicative import Control.Monad import Control.Monad.State.Strict import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.ByteString.Lazy.Char8 as B import LambdaCube.GL data ObjState = ObjState { position :: [V3F] , normal :: [V3F] , uvw :: [V3F] , positionSize :: Int , normalSize :: Int , uvwSize :: Int , points :: [Int] , lines' :: [Int] , triangles :: [Int] } deriving Show readV3F [x] = V3 (read $ B.unpack x) 0 0 readV3F [x,y] = V3 (read $ B.unpack x) (read $ B.unpack y) 0 readV3F [x,y,z] = V3 (read $ B.unpack x) (read $ B.unpack y) (read $ B.unpack z) readV3F l = error $ show l incPosition = modify (\s -> s {positionSize = positionSize s + 1}) incNormal = modify (\s -> s {normalSize = normalSize s + 1}) incUVW = modify (\s -> s {uvwSize = uvwSize s + 1}) tokenize :: Bool -> ByteString -> [(Int, [ByteString])] tokenize filterComments str = zip [1..] . map B.words . joinLines . (if filterComments then map filterComment else id) . B.lines $ str where filterComment = B.takeWhile (/= '#') joinLines (a:b:xs) | B.length a > 0 && B.last a == '\\' = joinLines (B.init a `B.append` b : xs) | otherwise = a : joinLines (b:xs) joinLines a = a TODO : support position parsing first parse lines parse tirangles parse quads add normal parsing add texture coord parsing TODO: support position parsing first parse lines parse tirangles parse quads add normal parsing add texture coord parsing -} readObj str = execState (mapM_ parseLine $ tokenize False str) $ ObjState [] [] [] 0 0 0 [] [] [] where addV xs = modify (\s -> s {position = readV3F xs : position s}) >> incPosition addVT xs = modify (\s -> s {uvw = readV3F xs : uvw s}) >> incUVW addVN xs = modify (\s -> s {normal = readV3F xs : normal s}) >> incNormal addP xs = modify (\s -> s {points = xs ++ points s}) addL xs = modify (\s -> s {lines' = xs ++ lines' s}) addT xs = modify (\s -> s {triangles = xs ++ triangles s}) chop "" = [] chop xs = a : if b == "/" then [""] else chop (B.drop 1 b) where (a,b) = B.break (=='/') xs parseLine (lineNumber,l) = case l of Vertex data "v":xs -> case xs of [_,_,_] -> addV xs [_,_,_,_] -> notSupported _ -> err ["vn",x,y,z] -> addVN [x,y,z] "vt":xs -> case xs of [_] -> addVT xs [_,_] -> addVT xs [_,_,_] -> addVT xs _ -> err "p":xs -> do pIndex <- gets positionSize let f x = if x < 0 then x + pIndex else x - 1 addP $ map (f . read . B.unpack) xs "l":xs -> do pIndex <- gets positionSize let f x = if x < 0 then x + pIndex else x - 1 ps = map (f . read . B.unpack . head . chop) xs segments (a:xs@(b:_)) = a : b : segments xs segments a = a addL $ segments ps "f":xs -> do pIndex <- gets positionSize let f x = if x < 0 then x + pIndex else x - 1 ps = map (f . read . B.unpack . head . chop) xs case xs of [_,_,_] -> addT ps [_,_,_,_] -> let [a,b,c,d] = ps in addT [a,b,c,c,d,a] _ -> notSupported Grouping TODO TODO TODO TODO TODO TODO _ -> return () " vp":xs - > case xs of [ _ ] - > notSupported [ _ , _ ] - > notSupported [ _ , _ , _ ] - > notSupported _ - > err " cstype":xs - > case xs of [ " rat",a ] | a ` elem ` [ " bmatrix","bezier","bspline","cardinal","taylor " ] - > notSupported [ a ] | a ` elem ` [ " bmatrix","bezier","bspline","cardinal","taylor " ] - > notSupported _ - > err " deg":xs - > case xs of [ _ ] - > notSupported [ _ , _ ] - > notSupported _ - > err " bmat":xs - > case xs of " u " : _ - > notSupported " v " : _ - > notSupported _ - > err " step":xs - > case xs of [ _ ] - > notSupported [ _ , _ ] - > notSupported _ - > err " curv " : _ - > notSupported " " : _ - > notSupported " surf " : _ - > notSupported " parm " : _ - > notSupported " trim " : _ - > notSupported " hole " : _ - > notSupported " scrv " : _ - > notSupported " sp " : _ - > notSupported [ " end " ] - > notSupported [ " con " , _ , _ , _ , _ , _ , _ , _ , _ ] - > notSupported [ " mg " , _ , _ ] - > notSupported " bevel":xs - > case xs of [ " on " ] - > notSupported [ " off " ] - > notSupported _ - > err " c_interp":xs - > case xs of [ " on " ] - > notSupported [ " off " ] - > notSupported _ - > err " d_interp":xs - > case xs of [ " on " ] - > notSupported [ " off " ] - > notSupported _ - > err [ " lod " , _ ] - > notSupported [ " shadow_obj " , _ ] - > notSupported [ " trace_obj " , _ ] - > notSupported " ctech":xs - > case xs of [ " cparm " , _ ] - > notSupported [ " cspace " , _ ] - > notSupported [ " curv " , _ , _ ] - > notSupported _ - > err " stech":xs - > case xs of [ " " , _ , _ ] - > notSupported [ " " , _ ] - > notSupported [ " cspace " , _ ] - > notSupported [ " curv " , _ , _ ] - > notSupported _ - > err ( a : _ ) | B.head a = = ' # ' - > return ( ) | otherwise - > err "vp":xs -> case xs of [_] -> notSupported [_,_] -> notSupported [_,_,_] -> notSupported _ -> err "cstype":xs -> case xs of ["rat",a] | a `elem` ["bmatrix","bezier","bspline","cardinal","taylor"] -> notSupported [a] | a `elem` ["bmatrix","bezier","bspline","cardinal","taylor"] -> notSupported _ -> err "deg":xs -> case xs of [_] -> notSupported [_,_] -> notSupported _ -> err "bmat":xs -> case xs of "u":_ -> notSupported "v":_ -> notSupported _ -> err "step":xs -> case xs of [_] -> notSupported [_,_] -> notSupported _ -> err "curv":_ -> notSupported "curv2":_ -> notSupported "surf":_ -> notSupported "parm":_ -> notSupported "trim":_ -> notSupported "hole":_ -> notSupported "scrv":_ -> notSupported "sp":_ -> notSupported ["end"] -> notSupported ["con",_,_,_,_,_,_,_,_] -> notSupported ["mg",_,_] -> notSupported "bevel":xs -> case xs of ["on"] -> notSupported ["off"] -> notSupported _ -> err "c_interp":xs -> case xs of ["on"] -> notSupported ["off"] -> notSupported _ -> err "d_interp":xs -> case xs of ["on"] -> notSupported ["off"] -> notSupported _ -> err ["lod",_] -> notSupported ["shadow_obj",_] -> notSupported ["trace_obj",_] -> notSupported "ctech":xs -> case xs of ["cparm",_] -> notSupported ["cspace",_] -> notSupported ["curv",_,_] -> notSupported _ -> err "stech":xs -> case xs of ["cparma",_,_] -> notSupported ["cparmb",_] -> notSupported ["cspace",_] -> notSupported ["curv",_,_] -> notSupported _ -> err (a : _) | B.head a == '#' -> return () | otherwise -> err -} where err = error $ "line " ++ show lineNumber ++ " syntax error: " ++ show l notSupported = error $ "line " ++ show lineNumber ++ " unsupported statement: " ++ show l newmtl my_mtl Ka 0.0435 0.0435 0.0435 Kd 0.1086 0.1086 0.1086 Ks 0.0000 0.0000 0.0000 Tf 0.9885 0.9885 0.9885 illum 6 d -halo 0.6600 Ns 10.0000 sharpness 60 Ni 1.19713 map_Ka -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Kd -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ks -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ns -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps map_d -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps disp -s 1 1 .5 wisp.mps decal -s 1 1 1 -o 0 0 0 -mm 0 1 bump -s 1 1 1 -o 0 0 0 -bm 1 sand.mpb refl -type sphere -mm 0 1 clouds.mpc newmtl name b Ka spectral file.rfl factor y z Kd r g b Kd spectral file.rfl factor Kd xyz x y z Ks r g b Ks spectral file.rfl factor y z Tf r g b Tf spectral file.rfl factor Tf xyz x y z d factor d -halo factor Ns exponent sharpness value -options args filename map_Kd -options args filename map_Ks -options args filename map_Ns -options args filename map_d -options args filename map_aat on decal -options args filename disp -options args filename bump -options args filename newmtl my_mtl Ka 0.0435 0.0435 0.0435 Kd 0.1086 0.1086 0.1086 Ks 0.0000 0.0000 0.0000 Tf 0.9885 0.9885 0.9885 illum 6 d -halo 0.6600 Ns 10.0000 sharpness 60 Ni 1.19713 map_Ka -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Kd -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ks -s 1 1 1 -o 0 0 0 -mm 0 1 chrome.mpc map_Ns -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps map_d -s 1 1 1 -o 0 0 0 -mm 0 1 wisp.mps disp -s 1 1 .5 wisp.mps decal -s 1 1 1 -o 0 0 0 -mm 0 1 sand.mps bump -s 1 1 1 -o 0 0 0 -bm 1 sand.mpb refl -type sphere -mm 0 1 clouds.mpc newmtl name Ka r g b Ka spectral file.rfl factor Ka xyz x y z Kd r g b Kd spectral file.rfl factor Kd xyz x y z Ks r g b Ks spectral file.rfl factor Ks xyz x y z Tf r g b Tf spectral file.rfl factor Tf xyz x y z d factor d -halo factor Ns exponent sharpness value Ni optical_density map_Ka -options args filename map_Kd -options args filename map_Ks -options args filename map_Ns -options args filename map_d -options args filename map_aat on decal -options args filename disp -options args filename bump -options args filename -} pragmatic : Wavefront OBJ material file # this is a comment Ka 0.00941176 0.0745098 0.0156863 Ka 0.14 0.45 0.091 # Green Kd 0.000000 0.000000 0.501961 Ke 0.3 0.05 0.01 Ke 17 12 4 # The empty water Cornell Box as seen in Ks .0001 .0001 .0001 Ks 0 0 0 Ks 0.427451 0.427451 0.427451 Ni 1.0000 Ns 0 Tf 0.066667 0.631373 0.074510 Tr 0 Tr 0 0 bump kamen-bump.png bump textures\vase_round_bump.png d 0.100000 illum 2 illum 4 illum 5 illum 5 illum 7 map_Ka KAMEN-stup.png map_Ka textures\background.tga map_Kd KAMEN-stup.png map_Kd textures\sponza_floor_a_diff.tga map_bump -bm 0.001 bump-lowRes.png map_bump kamen-bump.png map_bump textures\vase_round_bump.png map_d house-Alpha.png map_d textures\vase_plant_mask.tga newmtl Brick pragmatic: Wavefront OBJ material file #this is a comment Ka 0.00941176 0.0745098 0.0156863 Ka 0.14 0.45 0.091 # Green Kd 0.000000 0.000000 0.501961 Ke 0.3 0.05 0.01 Ke 17 12 4# The empty water Cornell Box as seen in Henrik Jensen's Ks .0001 .0001 .0001 Ks 0 0 0 Ks 0.427451 0.427451 0.427451 Ni 1.0000 Ns 0 Tf 0.066667 0.631373 0.074510 Tr 0 Tr 0 0 bump kamen-bump.png bump textures\vase_round_bump.png d 0.100000 illum 2 illum 4 illum 5 illum 5 illum 7 map_Ka KAMEN-stup.png map_Ka textures\background.tga map_Kd KAMEN-stup.png map_Kd textures\sponza_floor_a_diff.tga map_bump -bm 0.001 bump-lowRes.png map_bump kamen-bump.png map_bump textures\vase_round_bump.png map_d house-Alpha.png map_d textures\vase_plant_mask.tga newmtl Brick -} data Mtl = Mtl { mtlName :: String , mtlKa :: V3F , mtlKd :: V3F , mtlKe :: V3F , mtlKs :: V3F , mtlNi :: Float , mtlTf :: V3F , mtlBump :: String , mtlD :: Float , mtlIllum :: Int , mtlMapKa :: String , mtlMapKd :: String , mtlMapBump :: String , mtlMapBumpMultiplier :: Float , mtlMapD :: String } where parseLine (1,["Wavefront","OBJ","material","file"]) = return () parseLine (lineNumber,l) = case l of [] -> return () ["newmtl",a] -> return () ["Ka",r,g,b] -> return () ["Kd",r,g,b] -> return () ["Ke",r,g,b] -> return () ["Ks",r,g,b] -> return () ["Ni",a] -> return () ["Ns",a] -> return () ["Tf",r,g,b] -> return () ["bump",a] -> return () ["d",a] -> return () ["illum",a] -> return () ["map_Ka",a] -> return () ["map_Kd",a] -> return () ["map_bump","-bm",a,b] -> return () ["map_bump",a] -> return () ["map_d",a] -> return () _ -> return () where err = error $ "line " ++ show lineNumber ++ " syntax error: " ++ show l notSupported = error $ "line " ++ show lineNumber ++ " unsupported statement: " ++ show l main = do l <- getArgs forM_ l $ \n -> do print n c <- B.readFile n print $ length $ triangles $ readObj c
f22e27f6c6bc69353073e564033773503f1d7bd743618b60f39e173cce4847ae
clojang/jiface
object.clj
(ns jiface.erlang.object (:import (com.ericsson.otp.erlang OtpErlangObject OtpErlangExternalFun OtpErlangFun OtpInputStream OtpOutputStream)) (:refer-clojure :exclude [hash])) (defprotocol ErlangObject (bind [this binds] "Make new Erlang term replacing variables with the respective values from bindings argument(s).") (clone [this] "Clone the Erlang object.") (decode [this buff] "Read binary data in the Erlang external format, and produce a corresponding Erlang data type object.") (encode [this buff] "Convert the object according to the rules of the Erlang external format.") (equal? [this other-erl-obj] "Determine if two Erlang objects are equal.") (hash [this] "Get the object hash code.") (match [this term binds] "Perform match operation against given term.") (->str [this] "Convert to a string.")) (def behaviour {:bind (fn [this binds] (.bind this binds)) :clone (fn [this] (.clone this)) :decode (fn [this ^OtpInputStream buff] (.decode this buff)) :encode (fn [this ^OtpOutputStream buff] (.encode this buff)) :equal? (fn [this ^java.lang.Object other] (.equals this other)) :hash (fn [this] (.hashCode this)) :match (fn [this ^OtpErlangObject term binds] (.match this term binds)) :->str (fn [this] (.toString this))}) (extend OtpErlangObject ErlangObject behaviour) (extend OtpErlangExternalFun ErlangObject behaviour) (extend OtpErlangFun ErlangObject behaviour)
null
https://raw.githubusercontent.com/clojang/jiface/dcc9e9463eec143b99ce5cf104b5201f7847a1dd/src/jiface/erlang/object.clj
clojure
(ns jiface.erlang.object (:import (com.ericsson.otp.erlang OtpErlangObject OtpErlangExternalFun OtpErlangFun OtpInputStream OtpOutputStream)) (:refer-clojure :exclude [hash])) (defprotocol ErlangObject (bind [this binds] "Make new Erlang term replacing variables with the respective values from bindings argument(s).") (clone [this] "Clone the Erlang object.") (decode [this buff] "Read binary data in the Erlang external format, and produce a corresponding Erlang data type object.") (encode [this buff] "Convert the object according to the rules of the Erlang external format.") (equal? [this other-erl-obj] "Determine if two Erlang objects are equal.") (hash [this] "Get the object hash code.") (match [this term binds] "Perform match operation against given term.") (->str [this] "Convert to a string.")) (def behaviour {:bind (fn [this binds] (.bind this binds)) :clone (fn [this] (.clone this)) :decode (fn [this ^OtpInputStream buff] (.decode this buff)) :encode (fn [this ^OtpOutputStream buff] (.encode this buff)) :equal? (fn [this ^java.lang.Object other] (.equals this other)) :hash (fn [this] (.hashCode this)) :match (fn [this ^OtpErlangObject term binds] (.match this term binds)) :->str (fn [this] (.toString this))}) (extend OtpErlangObject ErlangObject behaviour) (extend OtpErlangExternalFun ErlangObject behaviour) (extend OtpErlangFun ErlangObject behaviour)
b0d13f28dcdf971b27fa3e81b5222cf60c31aa0cdbb51ac97f1f363d07a2767c
threatgrid/ctia
data_table.clj
(ns ctia.entity.data-table (:require [ctia.domain.entities :refer [default-realize-fn]] [ctia.http.routes.common :as routes.common] [ctia.http.routes.crud :refer [services->entity-crud-routes]] [ctia.schemas.core :refer [APIHandlerServices def-acl-schema def-stored-schema]] [ctia.schemas.sorting :refer [default-entity-sort-fields]] [ctia.stores.es.mapping :as em] [ctia.stores.es.store :refer [def-es-store]] [ctim.schemas.data-table :as ds] [flanders.utils :as fu] [schema-tools.core :as st] [schema.core :as s])) (def-acl-schema DataTable (fu/replace-either-with-any ds/DataTable) "data-table") (def-acl-schema PartialDataTable (fu/optionalize-all (fu/replace-either-with-any ds/DataTable)) "partial-data-table") (s/defschema PartialDataTableList [PartialDataTable]) (def-acl-schema NewDataTable (fu/replace-either-with-any ds/NewDataTable) "new-data-table") (def-stored-schema StoredDataTable DataTable) (s/defschema PartialStoredDataTable (st/optional-keys-schema StoredDataTable)) (def realize-data-table (default-realize-fn "data-table" NewDataTable StoredDataTable)) (def datatable-sort-fields (apply s/enum default-entity-sort-fields)) (s/defschema DataTableFieldsParam {(s/optional-key :fields) [datatable-sort-fields]}) (s/defschema DataTableSearchParams (st/merge routes.common/PagingParams routes.common/BaseEntityFilterParams routes.common/SourcableEntityFilterParams DataTableFieldsParam (st/optional-keys {:sort_by datatable-sort-fields}))) (def DataTableGetParams DataTableFieldsParam) (s/defschema DataTableByExternalIdQueryParams (st/merge routes.common/PagingParams DataTableFieldsParam)) (def data-table-mapping {"data-table" {:dynamic false :properties (merge em/base-entity-mapping em/describable-entity-mapping em/sourcable-entity-mapping em/stored-entity-mapping {:valid_time em/valid-time :row_count em/long-type :columns {:enabled false} :rows {:enabled false}})}}) (def-es-store DataTableStore :data-table StoredDataTable PartialStoredDataTable) (def capabilities #{:create-data-table :read-data-table :delete-data-table :search-data-table}) (s/defn data-table-routes [services :- APIHandlerServices] (services->entity-crud-routes services {:entity :data-table :new-spec :new-data-table/map :new-schema NewDataTable :entity-schema DataTable :get-schema PartialDataTable :get-params DataTableGetParams :list-schema PartialDataTableList :external-id-q-params DataTableByExternalIdQueryParams :search-q-params DataTableSearchParams :realize-fn realize-data-table :get-capabilities :read-data-table :post-capabilities :create-data-table :delete-capabilities :delete-data-table :external-id-capabilities :read-data-table :can-update? false :can-search? false})) (def data-table-entity {:route-context "/data-table" :tags ["DataTable"] :entity :data-table :plural :data-tables :new-spec :new-data-table/map :schema DataTable :partial-schema PartialDataTable :partial-list-schema PartialDataTableList :new-schema NewDataTable :stored-schema StoredDataTable :partial-stored-schema PartialStoredDataTable :realize-fn realize-data-table :es-store ->DataTableStore :es-mapping data-table-mapping :services->routes (routes.common/reloadable-function data-table-routes) :capabilities capabilities})
null
https://raw.githubusercontent.com/threatgrid/ctia/9e6cd48ffb7d3fd6ca4eac9eba9a19970eef7413/src/ctia/entity/data_table.clj
clojure
(ns ctia.entity.data-table (:require [ctia.domain.entities :refer [default-realize-fn]] [ctia.http.routes.common :as routes.common] [ctia.http.routes.crud :refer [services->entity-crud-routes]] [ctia.schemas.core :refer [APIHandlerServices def-acl-schema def-stored-schema]] [ctia.schemas.sorting :refer [default-entity-sort-fields]] [ctia.stores.es.mapping :as em] [ctia.stores.es.store :refer [def-es-store]] [ctim.schemas.data-table :as ds] [flanders.utils :as fu] [schema-tools.core :as st] [schema.core :as s])) (def-acl-schema DataTable (fu/replace-either-with-any ds/DataTable) "data-table") (def-acl-schema PartialDataTable (fu/optionalize-all (fu/replace-either-with-any ds/DataTable)) "partial-data-table") (s/defschema PartialDataTableList [PartialDataTable]) (def-acl-schema NewDataTable (fu/replace-either-with-any ds/NewDataTable) "new-data-table") (def-stored-schema StoredDataTable DataTable) (s/defschema PartialStoredDataTable (st/optional-keys-schema StoredDataTable)) (def realize-data-table (default-realize-fn "data-table" NewDataTable StoredDataTable)) (def datatable-sort-fields (apply s/enum default-entity-sort-fields)) (s/defschema DataTableFieldsParam {(s/optional-key :fields) [datatable-sort-fields]}) (s/defschema DataTableSearchParams (st/merge routes.common/PagingParams routes.common/BaseEntityFilterParams routes.common/SourcableEntityFilterParams DataTableFieldsParam (st/optional-keys {:sort_by datatable-sort-fields}))) (def DataTableGetParams DataTableFieldsParam) (s/defschema DataTableByExternalIdQueryParams (st/merge routes.common/PagingParams DataTableFieldsParam)) (def data-table-mapping {"data-table" {:dynamic false :properties (merge em/base-entity-mapping em/describable-entity-mapping em/sourcable-entity-mapping em/stored-entity-mapping {:valid_time em/valid-time :row_count em/long-type :columns {:enabled false} :rows {:enabled false}})}}) (def-es-store DataTableStore :data-table StoredDataTable PartialStoredDataTable) (def capabilities #{:create-data-table :read-data-table :delete-data-table :search-data-table}) (s/defn data-table-routes [services :- APIHandlerServices] (services->entity-crud-routes services {:entity :data-table :new-spec :new-data-table/map :new-schema NewDataTable :entity-schema DataTable :get-schema PartialDataTable :get-params DataTableGetParams :list-schema PartialDataTableList :external-id-q-params DataTableByExternalIdQueryParams :search-q-params DataTableSearchParams :realize-fn realize-data-table :get-capabilities :read-data-table :post-capabilities :create-data-table :delete-capabilities :delete-data-table :external-id-capabilities :read-data-table :can-update? false :can-search? false})) (def data-table-entity {:route-context "/data-table" :tags ["DataTable"] :entity :data-table :plural :data-tables :new-spec :new-data-table/map :schema DataTable :partial-schema PartialDataTable :partial-list-schema PartialDataTableList :new-schema NewDataTable :stored-schema StoredDataTable :partial-stored-schema PartialStoredDataTable :realize-fn realize-data-table :es-store ->DataTableStore :es-mapping data-table-mapping :services->routes (routes.common/reloadable-function data-table-routes) :capabilities capabilities})
6cad0577442d41eb177812bafc928f4b40a4de6f95c3b011cdca833c635b4b92
metaocaml/ber-metaocaml
includeclass.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1997 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. *) (* *) (**************************************************************************) (* Inclusion checks for the class language *) open Types let class_types env cty1 cty2 = Ctype.match_class_types env cty1 cty2 let class_type_declarations ~loc env cty1 cty2 = Builtin_attributes.check_alerts_inclusion ~def:cty1.clty_loc ~use:cty2.clty_loc loc cty1.clty_attributes cty2.clty_attributes (Path.last cty1.clty_path); Ctype.match_class_declarations env cty1.clty_params cty1.clty_type cty2.clty_params cty2.clty_type let class_declarations env cty1 cty2 = match cty1.cty_new, cty2.cty_new with None, Some _ -> [Ctype.CM_Virtual_class] | _ -> Ctype.match_class_declarations env cty1.cty_params cty1.cty_type cty2.cty_params cty2.cty_type open Format open Ctype let rec hide_params = function ( " * " , _ , cty ) - > hide_params cty | cty - > cty let rec hide_params = function Tcty_arrow ("*", _, cty) -> hide_params cty | cty -> cty *) let include_err ppf = function | CM_Virtual_class -> fprintf ppf "A class cannot be changed from virtual to concrete" | CM_Parameter_arity_mismatch _ -> fprintf ppf "The classes do not have the same number of type parameters" | CM_Type_parameter_mismatch (env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "A type parameter has type") (function ppf -> fprintf ppf "but is expected to have type") | CM_Class_type_mismatch (env, cty1, cty2) -> Printtyp.wrap_printing_env ~error:true env (fun () -> fprintf ppf "@[The class type@;<1 2>%a@ %s@;<1 2>%a@]" Printtyp.class_type cty1 "is not matched by the class type" Printtyp.class_type cty2) | CM_Parameter_mismatch (env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "A parameter has type") (function ppf -> fprintf ppf "but is expected to have type") | CM_Val_type_mismatch (lab, env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "The instance variable %s@ has type" lab) (function ppf -> fprintf ppf "but is expected to have type") | CM_Meth_type_mismatch (lab, env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "The method %s@ has type" lab) (function ppf -> fprintf ppf "but is expected to have type") | CM_Non_mutable_value lab -> fprintf ppf "@[The non-mutable instance variable %s cannot become mutable@]" lab | CM_Non_concrete_value lab -> fprintf ppf "@[The virtual instance variable %s cannot become concrete@]" lab | CM_Missing_value lab -> fprintf ppf "@[The first class type has no instance variable %s@]" lab | CM_Missing_method lab -> fprintf ppf "@[The first class type has no method %s@]" lab | CM_Hide_public lab -> fprintf ppf "@[The public method %s cannot be hidden@]" lab | CM_Hide_virtual (k, lab) -> fprintf ppf "@[The virtual %s %s cannot be hidden@]" k lab | CM_Public_method lab -> fprintf ppf "@[The public method %s cannot become private@]" lab | CM_Virtual_method lab -> fprintf ppf "@[The virtual method %s cannot become concrete@]" lab | CM_Private_method lab -> fprintf ppf "@[The private method %s cannot become public@]" lab let report_error ppf = function | [] -> () | err :: errs -> let print_errs ppf errs = List.iter (fun err -> fprintf ppf "@ %a" include_err err) errs in fprintf ppf "@[<v>%a%a@]" include_err err print_errs errs
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/typing/includeclass.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. ************************************************************************ Inclusion checks for the class language
, projet Cristal , INRIA Rocquencourt Copyright 1997 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Types let class_types env cty1 cty2 = Ctype.match_class_types env cty1 cty2 let class_type_declarations ~loc env cty1 cty2 = Builtin_attributes.check_alerts_inclusion ~def:cty1.clty_loc ~use:cty2.clty_loc loc cty1.clty_attributes cty2.clty_attributes (Path.last cty1.clty_path); Ctype.match_class_declarations env cty1.clty_params cty1.clty_type cty2.clty_params cty2.clty_type let class_declarations env cty1 cty2 = match cty1.cty_new, cty2.cty_new with None, Some _ -> [Ctype.CM_Virtual_class] | _ -> Ctype.match_class_declarations env cty1.cty_params cty1.cty_type cty2.cty_params cty2.cty_type open Format open Ctype let rec hide_params = function ( " * " , _ , cty ) - > hide_params cty | cty - > cty let rec hide_params = function Tcty_arrow ("*", _, cty) -> hide_params cty | cty -> cty *) let include_err ppf = function | CM_Virtual_class -> fprintf ppf "A class cannot be changed from virtual to concrete" | CM_Parameter_arity_mismatch _ -> fprintf ppf "The classes do not have the same number of type parameters" | CM_Type_parameter_mismatch (env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "A type parameter has type") (function ppf -> fprintf ppf "but is expected to have type") | CM_Class_type_mismatch (env, cty1, cty2) -> Printtyp.wrap_printing_env ~error:true env (fun () -> fprintf ppf "@[The class type@;<1 2>%a@ %s@;<1 2>%a@]" Printtyp.class_type cty1 "is not matched by the class type" Printtyp.class_type cty2) | CM_Parameter_mismatch (env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "A parameter has type") (function ppf -> fprintf ppf "but is expected to have type") | CM_Val_type_mismatch (lab, env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "The instance variable %s@ has type" lab) (function ppf -> fprintf ppf "but is expected to have type") | CM_Meth_type_mismatch (lab, env, trace) -> Printtyp.report_unification_error ppf env trace (function ppf -> fprintf ppf "The method %s@ has type" lab) (function ppf -> fprintf ppf "but is expected to have type") | CM_Non_mutable_value lab -> fprintf ppf "@[The non-mutable instance variable %s cannot become mutable@]" lab | CM_Non_concrete_value lab -> fprintf ppf "@[The virtual instance variable %s cannot become concrete@]" lab | CM_Missing_value lab -> fprintf ppf "@[The first class type has no instance variable %s@]" lab | CM_Missing_method lab -> fprintf ppf "@[The first class type has no method %s@]" lab | CM_Hide_public lab -> fprintf ppf "@[The public method %s cannot be hidden@]" lab | CM_Hide_virtual (k, lab) -> fprintf ppf "@[The virtual %s %s cannot be hidden@]" k lab | CM_Public_method lab -> fprintf ppf "@[The public method %s cannot become private@]" lab | CM_Virtual_method lab -> fprintf ppf "@[The virtual method %s cannot become concrete@]" lab | CM_Private_method lab -> fprintf ppf "@[The private method %s cannot become public@]" lab let report_error ppf = function | [] -> () | err :: errs -> let print_errs ppf errs = List.iter (fun err -> fprintf ppf "@ %a" include_err err) errs in fprintf ppf "@[<v>%a%a@]" include_err err print_errs errs
6aa7308fdd27ee49c6bdb7001cf2ed51cb5ca241de4f564743e2fc3fa8721bfd
c4-project/c4f
global.ml
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) open Base open Stdio open struct module Src = C4f_config end module Data = struct let fuzz : C4f_fuzz_run.Config.t Lazy.t = Lazy.from_fun C4f_fuzz_run.Config.make let global : Src.Global.t Lazy.t = Lazy.Let_syntax.( let%map fuzz = fuzz in Src.Global.make ~fuzz ()) end let%test_module "accessors" = ( module struct let global = Lazy.force Data.global let%expect_test "fuzz" = print_s [%sexp (Src.Global.fuzz global : C4f_fuzz_run.Config.t)] ; [%expect {| ((weights ()) (params ()) (flags ())) |}] end )
null
https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/config/test/global.ml
ocaml
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) open Base open Stdio open struct module Src = C4f_config end module Data = struct let fuzz : C4f_fuzz_run.Config.t Lazy.t = Lazy.from_fun C4f_fuzz_run.Config.make let global : Src.Global.t Lazy.t = Lazy.Let_syntax.( let%map fuzz = fuzz in Src.Global.make ~fuzz ()) end let%test_module "accessors" = ( module struct let global = Lazy.force Data.global let%expect_test "fuzz" = print_s [%sexp (Src.Global.fuzz global : C4f_fuzz_run.Config.t)] ; [%expect {| ((weights ()) (params ()) (flags ())) |}] end )
e6bc5c6b7ab20c7bcc774f31ce3c0d990c30dc7bc88e42c8909b03b672feb46b
emmabastas/elm-embed
Kernel.hs
# OPTIONS_GHC -Wall # # LANGUAGE BangPatterns , EmptyDataDecls , OverloadedStrings , UnboxedTuples # module Elm.Kernel ( Content(..) , Chunk(..) , fromByteString , countFields ) where import Control.Monad (liftM, liftM2) import Data.Binary (Binary, get, put, getWord8, putWord8) import qualified Data.ByteString.Internal as B import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Name as Name import Data.Word (Word8) import Foreign.Ptr (Ptr, plusPtr, minusPtr) import Foreign.ForeignPtr (ForeignPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import qualified AST.Source as Src import qualified Elm.ModuleName as ModuleName import qualified Elm.Package as Pkg import qualified Parse.Module as Module import qualified Parse.Space as Space import qualified Parse.Variable as Var import Parse.Primitives hiding (fromByteString) import qualified Parse.Primitives as P import qualified Reporting.Annotation as A CHUNK data Chunk = JS B.ByteString | ElmVar ModuleName.Canonical Name.Name | JsVar Name.Name Name.Name | ElmField Name.Name | JsField Int | JsEnum Int | Debug | Prod -- COUNT FIELDS countFields :: [Chunk] -> Map.Map Name.Name Int countFields chunks = foldr addField Map.empty chunks addField :: Chunk -> Map.Map Name.Name Int -> Map.Map Name.Name Int addField chunk fields = case chunk of JS _ -> fields ElmVar _ _ -> fields JsVar _ _ -> fields ElmField f -> Map.insertWith (+) f 1 fields JsField _ -> fields JsEnum _ -> fields Debug -> fields Prod -> fields -- FROM FILE data Content = Content [Src.Import] [Chunk] type Foreigns = Map.Map ModuleName.Raw Pkg.Name fromByteString :: Pkg.Name -> Foreigns -> B.ByteString -> Maybe Content fromByteString pkg foreigns bytes = case P.fromByteString (parser pkg foreigns) toError bytes of Right content -> Just content Left () -> Nothing parser :: Pkg.Name -> Foreigns -> Parser () Content parser pkg foreigns = do word2 0x2F 0x2A {-/*-} toError Space.chomp ignoreError Space.checkFreshLine toError imports <- specialize ignoreError (Module.chompImports []) word2 0x2A 0x2F {-*/-} toError chunks <- parseChunks (toVarTable pkg foreigns imports) Map.empty Map.empty return (Content imports chunks) toError :: Row -> Col -> () toError _ _ = () ignoreError :: a -> Row -> Col -> () ignoreError _ _ _ = () PARSE CHUNKS parseChunks :: VarTable -> Enums -> Fields -> Parser () [Chunk] parseChunks vtable enums fields = P.Parser $ \(P.State src pos end indent row col state) cok _ cerr _ -> let (# chunks, newPos, newRow, newCol #) = chompChunks vtable enums fields src pos end row col pos [] in if newPos == end then cok chunks (P.State src newPos end indent newRow newCol state) else cerr row col toError chompChunks :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #) chompChunks vs es fs src pos end row col lastPos revChunks = if pos >= end then let !js = toByteString src lastPos end in (# reverse (JS js : revChunks), pos, row, col #) else let !word = unsafeIndex pos in if word == 0x5F {-_-} then let !pos1 = plusPtr pos 1 !pos3 = plusPtr pos 3 in if pos3 <= end && unsafeIndex pos1 == 0x5F {-_-} then let !js = toByteString src lastPos pos in chompTag vs es fs src pos3 end row (col + 3) (JS js : revChunks) else chompChunks vs es fs src pos1 end row (col + 1) lastPos revChunks else if word == 0x0A {-\n-} then chompChunks vs es fs src (plusPtr pos 1) end (row + 1) 1 lastPos revChunks else let !newPos = plusPtr pos (getCharWidth word) in chompChunks vs es fs src newPos end row (col + 1) lastPos revChunks toByteString :: ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> B.ByteString toByteString src pos end = let !off = minusPtr pos (unsafeForeignPtrToPtr src) !len = minusPtr end pos in B.PS src off len -- relies on external checks in chompChunks chompTag :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #) chompTag vs es fs src pos end row col revChunks = let (# newPos, newCol #) = Var.chompInnerChars pos end col !tagPos = plusPtr pos (-1) !word = unsafeIndex tagPos in if word == 0x24 {-$-} then let !name = Name.fromPtr pos newPos in chompChunks vs es fs src newPos end row newCol newPos $ ElmField name : revChunks else let !name = Name.fromPtr tagPos newPos in 9 let (enum, newEnums) = lookupEnum (word - 0x30) name es in chompChunks vs newEnums fs src newPos end row newCol newPos $ JsEnum enum : revChunks else if 0x61 {-a-} <= word && word <= 0x7A {-z-} then let (field, newFields) = lookupField name fs in chompChunks vs es newFields src newPos end row newCol newPos $ JsField field : revChunks else if name == "DEBUG" then chompChunks vs es fs src newPos end row newCol newPos (Debug : revChunks) else if name == "PROD" then chompChunks vs es fs src newPos end row newCol newPos (Prod : revChunks) else case Map.lookup name vs of Just chunk -> chompChunks vs es fs src newPos end row newCol newPos (chunk : revChunks) Nothing -> (# revChunks, pos, row, col #) -- FIELDS type Fields = Map.Map Name.Name Int lookupField :: Name.Name -> Fields -> (Int, Fields) lookupField name fields = case Map.lookup name fields of Just n -> ( n, fields ) Nothing -> let n = Map.size fields in ( n, Map.insert name n fields ) ENUMS type Enums = Map.Map Word8 (Map.Map Name.Name Int) lookupEnum :: Word8 -> Name.Name -> Enums -> (Int, Enums) lookupEnum word var allEnums = let enums = Map.findWithDefault Map.empty word allEnums in case Map.lookup var enums of Just n -> ( n, allEnums ) Nothing -> let n = Map.size enums in ( n, Map.insert word (Map.insert var n enums) allEnums ) -- PROCESS IMPORTS type VarTable = Map.Map Name.Name Chunk toVarTable :: Pkg.Name -> Foreigns -> [Src.Import] -> VarTable toVarTable pkg foreigns imports = List.foldl' (addImport pkg foreigns) Map.empty imports addImport :: Pkg.Name -> Foreigns -> VarTable -> Src.Import -> VarTable addImport pkg foreigns vtable (Src.Import (A.At _ importName) maybeAlias exposing) = if Name.isKernel importName then case maybeAlias of Just _ -> error ("cannot use `as` with kernel import of: " ++ Name.toChars importName) Nothing -> let home = Name.getKernel importName add table name = Map.insert (Name.sepBy 0x5F {-_-} home name) (JsVar home name) table in List.foldl' add vtable (toNames exposing) else let home = ModuleName.Canonical (Map.findWithDefault pkg importName foreigns) importName prefix = toPrefix importName maybeAlias add table name = Map.insert (Name.sepBy 0x5F {-_-} prefix name) (ElmVar home name) table in List.foldl' add vtable (toNames exposing) toPrefix :: Name.Name -> Maybe Name.Name -> Name.Name toPrefix home maybeAlias = case maybeAlias of Just alias -> alias Nothing -> if Name.hasDot home then error ("kernel imports with dots need an alias: " ++ show (Name.toChars home)) else home toNames :: Src.Exposing -> [Name.Name] toNames exposing = case exposing of Src.Open -> error "cannot have `exposing (..)` in kernel code." Src.Explicit exposedList -> map toName exposedList toName :: Src.Exposed -> Name.Name toName exposed = case exposed of Src.Lower (A.At _ name) -> name Src.Upper (A.At _ name) Src.Private -> name Src.Upper _ (Src.Public _) -> error "cannot have Maybe(..) syntax in kernel code header" Src.Operator _ _ -> error "cannot use binops in kernel code" -- BINARY instance Binary Chunk where put chunk = case chunk of JS a -> putWord8 0 >> put a ElmVar a b -> putWord8 1 >> put a >> put b JsVar a b -> putWord8 2 >> put a >> put b ElmField a -> putWord8 3 >> put a JsField a -> putWord8 4 >> put a JsEnum a -> putWord8 5 >> put a Debug -> putWord8 6 Prod -> putWord8 7 get = do word <- getWord8 case word of 0 -> liftM JS get 1 -> liftM2 ElmVar get get 2 -> liftM2 JsVar get get 3 -> liftM ElmField get 4 -> liftM JsField get 5 -> liftM JsEnum get 6 -> return Debug 7 -> return Prod _ -> error "problem deserializing Elm.Kernel.Chunk"
null
https://raw.githubusercontent.com/emmabastas/elm-embed/c2c4f9dcc5c4f47480f728247ff7b4d0700d7476/compiler/src/Elm/Kernel.hs
haskell
COUNT FIELDS FROM FILE /* */ _ _ \n relies on external checks in chompChunks $ a z FIELDS PROCESS IMPORTS _ _ BINARY
# OPTIONS_GHC -Wall # # LANGUAGE BangPatterns , EmptyDataDecls , OverloadedStrings , UnboxedTuples # module Elm.Kernel ( Content(..) , Chunk(..) , fromByteString , countFields ) where import Control.Monad (liftM, liftM2) import Data.Binary (Binary, get, put, getWord8, putWord8) import qualified Data.ByteString.Internal as B import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Name as Name import Data.Word (Word8) import Foreign.Ptr (Ptr, plusPtr, minusPtr) import Foreign.ForeignPtr (ForeignPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import qualified AST.Source as Src import qualified Elm.ModuleName as ModuleName import qualified Elm.Package as Pkg import qualified Parse.Module as Module import qualified Parse.Space as Space import qualified Parse.Variable as Var import Parse.Primitives hiding (fromByteString) import qualified Parse.Primitives as P import qualified Reporting.Annotation as A CHUNK data Chunk = JS B.ByteString | ElmVar ModuleName.Canonical Name.Name | JsVar Name.Name Name.Name | ElmField Name.Name | JsField Int | JsEnum Int | Debug | Prod countFields :: [Chunk] -> Map.Map Name.Name Int countFields chunks = foldr addField Map.empty chunks addField :: Chunk -> Map.Map Name.Name Int -> Map.Map Name.Name Int addField chunk fields = case chunk of JS _ -> fields ElmVar _ _ -> fields JsVar _ _ -> fields ElmField f -> Map.insertWith (+) f 1 fields JsField _ -> fields JsEnum _ -> fields Debug -> fields Prod -> fields data Content = Content [Src.Import] [Chunk] type Foreigns = Map.Map ModuleName.Raw Pkg.Name fromByteString :: Pkg.Name -> Foreigns -> B.ByteString -> Maybe Content fromByteString pkg foreigns bytes = case P.fromByteString (parser pkg foreigns) toError bytes of Right content -> Just content Left () -> Nothing parser :: Pkg.Name -> Foreigns -> Parser () Content parser pkg foreigns = Space.chomp ignoreError Space.checkFreshLine toError imports <- specialize ignoreError (Module.chompImports []) chunks <- parseChunks (toVarTable pkg foreigns imports) Map.empty Map.empty return (Content imports chunks) toError :: Row -> Col -> () toError _ _ = () ignoreError :: a -> Row -> Col -> () ignoreError _ _ _ = () PARSE CHUNKS parseChunks :: VarTable -> Enums -> Fields -> Parser () [Chunk] parseChunks vtable enums fields = P.Parser $ \(P.State src pos end indent row col state) cok _ cerr _ -> let (# chunks, newPos, newRow, newCol #) = chompChunks vtable enums fields src pos end row col pos [] in if newPos == end then cok chunks (P.State src newPos end indent newRow newCol state) else cerr row col toError chompChunks :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> Ptr Word8 -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #) chompChunks vs es fs src pos end row col lastPos revChunks = if pos >= end then let !js = toByteString src lastPos end in (# reverse (JS js : revChunks), pos, row, col #) else let !word = unsafeIndex pos in let !pos1 = plusPtr pos 1 !pos3 = plusPtr pos 3 in let !js = toByteString src lastPos pos in chompTag vs es fs src pos3 end row (col + 3) (JS js : revChunks) else chompChunks vs es fs src pos1 end row (col + 1) lastPos revChunks chompChunks vs es fs src (plusPtr pos 1) end (row + 1) 1 lastPos revChunks else let !newPos = plusPtr pos (getCharWidth word) in chompChunks vs es fs src newPos end row (col + 1) lastPos revChunks toByteString :: ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> B.ByteString toByteString src pos end = let !off = minusPtr pos (unsafeForeignPtrToPtr src) !len = minusPtr end pos in B.PS src off len chompTag :: VarTable -> Enums -> Fields -> ForeignPtr Word8 -> Ptr Word8 -> Ptr Word8 -> Row -> Col -> [Chunk] -> (# [Chunk], Ptr Word8, Row, Col #) chompTag vs es fs src pos end row col revChunks = let (# newPos, newCol #) = Var.chompInnerChars pos end col !tagPos = plusPtr pos (-1) !word = unsafeIndex tagPos in let !name = Name.fromPtr pos newPos in chompChunks vs es fs src newPos end row newCol newPos $ ElmField name : revChunks else let !name = Name.fromPtr tagPos newPos in 9 let (enum, newEnums) = lookupEnum (word - 0x30) name es in chompChunks vs newEnums fs src newPos end row newCol newPos $ JsEnum enum : revChunks let (field, newFields) = lookupField name fs in chompChunks vs es newFields src newPos end row newCol newPos $ JsField field : revChunks else if name == "DEBUG" then chompChunks vs es fs src newPos end row newCol newPos (Debug : revChunks) else if name == "PROD" then chompChunks vs es fs src newPos end row newCol newPos (Prod : revChunks) else case Map.lookup name vs of Just chunk -> chompChunks vs es fs src newPos end row newCol newPos (chunk : revChunks) Nothing -> (# revChunks, pos, row, col #) type Fields = Map.Map Name.Name Int lookupField :: Name.Name -> Fields -> (Int, Fields) lookupField name fields = case Map.lookup name fields of Just n -> ( n, fields ) Nothing -> let n = Map.size fields in ( n, Map.insert name n fields ) ENUMS type Enums = Map.Map Word8 (Map.Map Name.Name Int) lookupEnum :: Word8 -> Name.Name -> Enums -> (Int, Enums) lookupEnum word var allEnums = let enums = Map.findWithDefault Map.empty word allEnums in case Map.lookup var enums of Just n -> ( n, allEnums ) Nothing -> let n = Map.size enums in ( n, Map.insert word (Map.insert var n enums) allEnums ) type VarTable = Map.Map Name.Name Chunk toVarTable :: Pkg.Name -> Foreigns -> [Src.Import] -> VarTable toVarTable pkg foreigns imports = List.foldl' (addImport pkg foreigns) Map.empty imports addImport :: Pkg.Name -> Foreigns -> VarTable -> Src.Import -> VarTable addImport pkg foreigns vtable (Src.Import (A.At _ importName) maybeAlias exposing) = if Name.isKernel importName then case maybeAlias of Just _ -> error ("cannot use `as` with kernel import of: " ++ Name.toChars importName) Nothing -> let home = Name.getKernel importName add table name = in List.foldl' add vtable (toNames exposing) else let home = ModuleName.Canonical (Map.findWithDefault pkg importName foreigns) importName prefix = toPrefix importName maybeAlias add table name = in List.foldl' add vtable (toNames exposing) toPrefix :: Name.Name -> Maybe Name.Name -> Name.Name toPrefix home maybeAlias = case maybeAlias of Just alias -> alias Nothing -> if Name.hasDot home then error ("kernel imports with dots need an alias: " ++ show (Name.toChars home)) else home toNames :: Src.Exposing -> [Name.Name] toNames exposing = case exposing of Src.Open -> error "cannot have `exposing (..)` in kernel code." Src.Explicit exposedList -> map toName exposedList toName :: Src.Exposed -> Name.Name toName exposed = case exposed of Src.Lower (A.At _ name) -> name Src.Upper (A.At _ name) Src.Private -> name Src.Upper _ (Src.Public _) -> error "cannot have Maybe(..) syntax in kernel code header" Src.Operator _ _ -> error "cannot use binops in kernel code" instance Binary Chunk where put chunk = case chunk of JS a -> putWord8 0 >> put a ElmVar a b -> putWord8 1 >> put a >> put b JsVar a b -> putWord8 2 >> put a >> put b ElmField a -> putWord8 3 >> put a JsField a -> putWord8 4 >> put a JsEnum a -> putWord8 5 >> put a Debug -> putWord8 6 Prod -> putWord8 7 get = do word <- getWord8 case word of 0 -> liftM JS get 1 -> liftM2 ElmVar get get 2 -> liftM2 JsVar get get 3 -> liftM ElmField get 4 -> liftM JsField get 5 -> liftM JsEnum get 6 -> return Debug 7 -> return Prod _ -> error "problem deserializing Elm.Kernel.Chunk"
5d6e8cc1477a5a824fe5c695d17914c9037061f995f5e698f88ff6b01bcff056
haskus/haskus-system
Error.hs
# LANGUAGE DataKinds # # LANGUAGE TypeApplications # {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE TemplateHaskell # # LANGUAGE LambdaCase # -- | System calls error codes module Haskus.System.Linux.Internals.Error ( ErrorCode (..) ) where import Data.Data import System.IO.Unsafe import Haskus.Binary.Storable import Haskus.Number.Word import GHC.Ptr import Haskus.Binary.Enum import Haskus.Utils.Embed import Haskus.System.Linux.Internals.Tables -- ============================================================= -- From linux/include/uapi/asm-generic/errno-base.h -- and linux/include/uapi/asm-generic/errno.h -- ============================================================= -- DO NOT CHANGE THE CONSTRUCTOR ORDER WITHOUT CHANGING THE ERROR TABLE -- | Linux error codes data ErrorCode = EPERM -- ^ Operation not permitted | ENOENT -- ^ No such file or directory | ESRCH -- ^ No such process | EINTR -- ^ Interrupted system call | EIO -- ^ I/O error | ENXIO -- ^ No such device or address | E2BIG -- ^ Argument list too long | ENOEXEC -- ^ Exec format error | EBADF -- ^ Bad file number | ECHILD -- ^ No child processes | EAGAIN -- ^ Try again | ENOMEM -- ^ Out of memory | EACCES -- ^ Permission denied | EFAULT -- ^ Bad address | ENOTBLK -- ^ Block device required | EBUSY -- ^ Device or resource busy | EEXIST -- ^ File exists | EXDEV -- ^ Cross-device link | ENODEV -- ^ No such device | ENOTDIR -- ^ Not a directory | EISDIR -- ^ Is a directory | EINVAL -- ^ Invalid argument | ENFILE -- ^ File table overflow | EMFILE -- ^ Too many open files | ENOTTY -- ^ Not a typewriter | ETXTBSY -- ^ Text file busy | EFBIG -- ^ File too large | ENOSPC -- ^ No space left on device | ESPIPE -- ^ Illegal seek | EROFS -- ^ Read-only file system | EMLINK -- ^ Too many links | EPIPE -- ^ Broken pipe | EDOM -- ^ Math argument out of domain of func | ERANGE -- ^ Math result not representable | EDEADLK -- ^ Resource deadlock would occur | ENAMETOOLONG -- ^ File name too long | ENOLCK -- ^ No record locks available | ENOSYS -- ^ Function not implemented | ENOTEMPTY -- ^ Directory not empty | ELOOP -- ^ Too many symbolic links encountered | ENOMSG -- ^ No message of desired type | EIDRM -- ^ Identifier removed | ECHRNG -- ^ Channel number out of range ^ Level 2 not synchronized ^ Level 3 halted ^ Level 3 reset | ELNRNG -- ^ Link number out of range | EUNATCH -- ^ Protocol driver not attached | ENOCSI -- ^ No CSI structure available ^ Level 2 halted | EBADE -- ^ Invalid exchange | EBADR -- ^ Invalid request descriptor | EXFULL -- ^ Exchange full | ENOANO -- ^ No anode ^ Invalid request code | EBADSLT -- ^ Invalid slot | EBFONT -- ^ Bad font file format | ENOSTR -- ^ Device not a stream | ENODATA -- ^ No data available | ETIME -- ^ Timer expired | ENOSR -- ^ Out of streams resources | ENONET -- ^ Machine is not on the network | ENOPKG -- ^ Package not installed | EREMOTE -- ^ Object is remote | ENOLINK -- ^ Link has been severed | EADV -- ^ Advertise error | ESRMNT -- ^ Srmount error | ECOMM -- ^ Communication error on send ^ Protocol error ^ attempted | EDOTDOT -- ^ RFS specific error | EBADMSG -- ^ Not a data message | EOVERFLOW -- ^ Value too large for defined data type | ENOTUNIQ -- ^ Name not unique on network | EBADFD -- ^ File descriptor in bad state | EREMCHG -- ^ Remote address changed | ELIBACC -- ^ Can not access a needed shared library | ELIBBAD -- ^ Accessing a corrupted shared library | ELIBSCN -- ^ .lib section in a.out corrupted | ELIBMAX -- ^ Attempting to link in too many shared libraries | ELIBEXEC -- ^ Cannot exec a shared library directly | EILSEQ -- ^ Illegal byte sequence | ERESTART -- ^ Interrupted system call should be restarted | ESTRPIPE -- ^ Streams pipe error | EUSERS -- ^ Too many users | ENOTSOCK -- ^ Socket operation on non-socket | EDESTADDRREQ -- ^ Destination address required | EMSGSIZE -- ^ Message too long | EPROTOTYPE -- ^ Protocol wrong type for socket | ENOPROTOOPT -- ^ Protocol not available | EPROTONOSUPPORT -- ^ Protocol not supported | ESOCKTNOSUPPORT -- ^ Socket type not supported | EOPNOTSUPP -- ^ Operation not supported on transport endpoint | EPFNOSUPPORT -- ^ Protocol family not supported | EAFNOSUPPORT -- ^ Address family not supported by protocol | EADDRINUSE -- ^ Address already in use | EADDRNOTAVAIL -- ^ Cannot assign requested address | ENETDOWN -- ^ Network is down | ENETUNREACH -- ^ Network is unreachable | ENETRESET -- ^ Network dropped connection because of reset | ECONNABORTED -- ^ Software caused connection abort | ECONNRESET -- ^ Connection reset by peer | ENOBUFS -- ^ No buffer space available | EISCONN -- ^ Transport endpoint is already connected | ENOTCONN -- ^ Transport endpoint is not connected | ESHUTDOWN -- ^ Cannot send after transport endpoint shutdown | ETOOMANYREFS -- ^ Too many references: cannot splice | ETIMEDOUT -- ^ Connection timed out | ECONNREFUSED -- ^ Connection refused | EHOSTDOWN -- ^ Host is down | EHOSTUNREACH -- ^ No route to host | EALREADY -- ^ Operation already in progress | EINPROGRESS -- ^ Operation now in progress ^ Stale file handle | EUCLEAN -- ^ Structure needs cleaning ^ Not a named type file | ENAVAIL -- ^ No XENIX semaphores available | EISNAM -- ^ Is a named type file | EREMOTEIO -- ^ Remote I/O error | EDQUOT -- ^ Quota exceeded | ENOMEDIUM -- ^ No medium found | EMEDIUMTYPE -- ^ Wrong medium type | ECANCELED -- ^ Operation Canceled | ENOKEY -- ^ Required key not available | EKEYEXPIRED -- ^ Key has expired | EKEYREVOKED -- ^ Key has been revoked | EKEYREJECTED -- ^ Key was rejected by service | EOWNERDEAD -- ^ Owner died | ENOTRECOVERABLE -- ^ State not recoverable | ERFKILL -- ^ Operation not possible due to RF-kill | EHWPOISON -- ^ Memory page has hardware error | EOTHER Word64 -- ^ Other error code deriving (Eq,Show,Data) errorTablePtr :: Ptr Word8 errorTablePtr = Ptr $(embedBytes errorTable) peekErrorTable :: Integral a => a -> Word8 peekErrorTable = unsafePerformIO . peekElemOff errorTablePtr . fromIntegral instance CEnum ErrorCode where toCEnum x | x <= fromIntegral errorTableMax , Just r <- makeEnumMaybe @ErrorCode (peekErrorTable x) = r | otherwise = EOTHER (fromIntegral x) where fromCEnum = \case EOTHER x -> fromIntegral x TODO
null
https://raw.githubusercontent.com/haskus/haskus-system/38b3a363c26bc4d82e3493d8638d46bc35678616/haskus-system/src/lib/Haskus/System/Linux/Internals/Error.hs
haskell
# LANGUAGE DeriveDataTypeable # | System calls error codes ============================================================= From linux/include/uapi/asm-generic/errno-base.h and linux/include/uapi/asm-generic/errno.h ============================================================= DO NOT CHANGE THE CONSTRUCTOR ORDER WITHOUT CHANGING THE ERROR TABLE | Linux error codes ^ Operation not permitted ^ No such file or directory ^ No such process ^ Interrupted system call ^ I/O error ^ No such device or address ^ Argument list too long ^ Exec format error ^ Bad file number ^ No child processes ^ Try again ^ Out of memory ^ Permission denied ^ Bad address ^ Block device required ^ Device or resource busy ^ File exists ^ Cross-device link ^ No such device ^ Not a directory ^ Is a directory ^ Invalid argument ^ File table overflow ^ Too many open files ^ Not a typewriter ^ Text file busy ^ File too large ^ No space left on device ^ Illegal seek ^ Read-only file system ^ Too many links ^ Broken pipe ^ Math argument out of domain of func ^ Math result not representable ^ Resource deadlock would occur ^ File name too long ^ No record locks available ^ Function not implemented ^ Directory not empty ^ Too many symbolic links encountered ^ No message of desired type ^ Identifier removed ^ Channel number out of range ^ Link number out of range ^ Protocol driver not attached ^ No CSI structure available ^ Invalid exchange ^ Invalid request descriptor ^ Exchange full ^ No anode ^ Invalid slot ^ Bad font file format ^ Device not a stream ^ No data available ^ Timer expired ^ Out of streams resources ^ Machine is not on the network ^ Package not installed ^ Object is remote ^ Link has been severed ^ Advertise error ^ Srmount error ^ Communication error on send ^ RFS specific error ^ Not a data message ^ Value too large for defined data type ^ Name not unique on network ^ File descriptor in bad state ^ Remote address changed ^ Can not access a needed shared library ^ Accessing a corrupted shared library ^ .lib section in a.out corrupted ^ Attempting to link in too many shared libraries ^ Cannot exec a shared library directly ^ Illegal byte sequence ^ Interrupted system call should be restarted ^ Streams pipe error ^ Too many users ^ Socket operation on non-socket ^ Destination address required ^ Message too long ^ Protocol wrong type for socket ^ Protocol not available ^ Protocol not supported ^ Socket type not supported ^ Operation not supported on transport endpoint ^ Protocol family not supported ^ Address family not supported by protocol ^ Address already in use ^ Cannot assign requested address ^ Network is down ^ Network is unreachable ^ Network dropped connection because of reset ^ Software caused connection abort ^ Connection reset by peer ^ No buffer space available ^ Transport endpoint is already connected ^ Transport endpoint is not connected ^ Cannot send after transport endpoint shutdown ^ Too many references: cannot splice ^ Connection timed out ^ Connection refused ^ Host is down ^ No route to host ^ Operation already in progress ^ Operation now in progress ^ Structure needs cleaning ^ No XENIX semaphores available ^ Is a named type file ^ Remote I/O error ^ Quota exceeded ^ No medium found ^ Wrong medium type ^ Operation Canceled ^ Required key not available ^ Key has expired ^ Key has been revoked ^ Key was rejected by service ^ Owner died ^ State not recoverable ^ Operation not possible due to RF-kill ^ Memory page has hardware error ^ Other error code
# LANGUAGE DataKinds # # LANGUAGE TypeApplications # # LANGUAGE TemplateHaskell # # LANGUAGE LambdaCase # module Haskus.System.Linux.Internals.Error ( ErrorCode (..) ) where import Data.Data import System.IO.Unsafe import Haskus.Binary.Storable import Haskus.Number.Word import GHC.Ptr import Haskus.Binary.Enum import Haskus.Utils.Embed import Haskus.System.Linux.Internals.Tables data ErrorCode ^ Level 2 not synchronized ^ Level 3 halted ^ Level 3 reset ^ Level 2 halted ^ Invalid request code ^ Protocol error ^ attempted ^ Stale file handle ^ Not a named type file deriving (Eq,Show,Data) errorTablePtr :: Ptr Word8 errorTablePtr = Ptr $(embedBytes errorTable) peekErrorTable :: Integral a => a -> Word8 peekErrorTable = unsafePerformIO . peekElemOff errorTablePtr . fromIntegral instance CEnum ErrorCode where toCEnum x | x <= fromIntegral errorTableMax , Just r <- makeEnumMaybe @ErrorCode (peekErrorTable x) = r | otherwise = EOTHER (fromIntegral x) where fromCEnum = \case EOTHER x -> fromIntegral x TODO
bfcbd1f0058896c1fa258c9c2456575a46203ba28c999519455188f5d4abca50
AccelerateHS/accelerate-fft
FFT.hs
# LANGUAGE CPP # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE GADTs # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # LANGUAGE ViewPatterns # -- | -- Module : Data.Array.Accelerate.Math.FFT Copyright : [ 2012 .. 2020 ] The Accelerate Team -- License : BSD3 -- Maintainer : < > -- Stability : experimental Portability : non - portable ( GHC extensions ) -- -- For performance, compile against the foreign library bindings (using any -- number of '-fllvm-ptx', and '-fllvm-cpu' for the accelerate-llvm-ptx, and -- accelerate-llvm-native backends, respectively). -- module Data.Array.Accelerate.Math.FFT ( Mode(..), Numeric, fft, fft1D, fft2D, fft3D, ) where import Data.Array.Accelerate as A import Data.Array.Accelerate.Data.Complex import Data.Array.Accelerate.Math.FFT.Type import Data.Array.Accelerate.Math.FFT.Mode import qualified Data.Array.Accelerate.Sugar.Shape as A ( rank, shapeR ) import qualified Data.Array.Accelerate.Math.FFT.Adhoc as Adhoc #ifdef ACCELERATE_LLVM_NATIVE_BACKEND import qualified Data.Array.Accelerate.Math.FFT.LLVM.Native as Native #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND import qualified Data.Array.Accelerate.Math.FFT.LLVM.PTX as PTX #endif import Prelude as P -- | Discrete Fourier Transform along the innermost dimension of an array. -- Notes for FFI implementations : -- * fftw supports arrays of dimension 1 - 5 * cuFFT supports arrays of dimension 1 - 3 -- -- The pure implementation will be used otherwise. -- fft :: forall sh e. (Shape sh, Slice sh, Numeric e) => Mode -> Acc (Array (sh:.Int) (Complex e)) -> Acc (Array (sh:.Int) (Complex e)) fft mode arr = let scale = A.fromIntegral (indexHead (shape arr)) rank = A.rank @(sh:.Int) shR = A.shapeR @(sh:.Int) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND (if rank P.<= 5 then foreignAcc (Native.fft mode shR eR) else id) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND (if rank P.<= 3 then foreignAcc (PTX.fft mode shR eR) else id) $ #endif Adhoc.fft mode in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr Vector Transform -- ---------------- -- | Discrete Fourier Transform of a vector. -- fft1D :: forall e. Numeric e => Mode -> Acc (Array DIM1 (Complex e)) -> Acc (Array DIM1 (Complex e)) fft1D mode arr = let scale = A.fromIntegral (A.length arr) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND foreignAcc (Native.fft1D mode eR) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND foreignAcc (PTX.fft1D mode eR) $ #endif Adhoc.fft mode in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr Matrix Transform -- ---------------- -- | Discrete Fourier Transform of a matrix. -- fft2D :: forall e. Numeric e => Mode -> Acc (Array DIM2 (Complex e)) -> Acc (Array DIM2 (Complex e)) fft2D mode arr = let scale = A.fromIntegral (A.size arr) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND foreignAcc (Native.fft2D mode eR) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND foreignAcc (PTX.fft2D mode eR) $ #endif fft' fft' a = A.transpose . Adhoc.fft mode >-> A.transpose . Adhoc.fft mode $ a in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr -- Cube Transform -- -------------- -- | Discrete Fourier Transform of a 3D array. -- fft3D :: forall e. Numeric e => Mode -> Acc (Array DIM3 (Complex e)) -> Acc (Array DIM3 (Complex e)) fft3D mode arr = let scale = A.fromIntegral (A.size arr) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND foreignAcc (Native.fft3D mode eR) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND foreignAcc (PTX.fft3D mode eR) $ #endif fft' fft' a = rotate3D . Adhoc.fft mode >-> rotate3D . Adhoc.fft mode >-> rotate3D . Adhoc.fft mode $ a in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr rotate3D :: Elt e => Acc (Array DIM3 e) -> Acc (Array DIM3 e) rotate3D arr = backpermute sh rot arr where sh :: Exp DIM3 sh = let Z :. z :. y :. x = unlift (shape arr) :: Z :. Exp Int :. Exp Int :. Exp Int in index3 y x z -- rot :: Exp DIM3 -> Exp DIM3 rot ix = let Z :. z :. y :. x = unlift ix :: Z :. Exp Int :. Exp Int :. Exp Int in index3 x z y - -- Rank - generalised Cooley - Tuckey DFT -- -- We require the innermost dimension be passed as a value because we -- ca n't do divide - and - conquer recursion directly in the meta - language . -- fft : : forall sh e. ( Slice sh , Shape sh , A.RealFloat e , A.FromIntegral Int e ) = > e - > sh - > Int - > Acc ( Array ( sh:.Int ) ( Complex e ) ) - > Acc ( Array ( sh:.Int ) ( Complex e ) ) fft sign sh sz arr | P.any ( P.not . isPow2 ) ( shapeToList ( sh:.sz ) ) = error $ printf " fft : array dimensions must be powers - of - two , but are : % s " ( ( sh:.sz ) ) -- | otherwise = go sz 0 1 where go : : Int - > Int - > Int - > Acc ( Array ( sh:.Int ) ( Complex e ) ) go len offset stride | len P.== 2 = A.generate ( constant ( sh : . len ) ) swivel | otherwise = combine ( go ( len ` div ` 2 ) offset ( stride * 2 ) ) ( go ( len ` div ` 2 ) ( offset + stride ) ( stride * 2 ) ) where len ' = the ( unit ( constant len ) ) offset ' = the ( unit ( constant offset ) ) stride ' = the ( unit ( constant stride ) ) swivel ix = let sh ' : . sz ' = unlift ix : : Exp sh : . Exp Int in sz ' A.== 0 ? ( ( arr ! lift ( sh ' : . offset ' ) ) + ( arr ! lift ( sh ' : . offset ' + stride ' ) ) { - A.== 1 -- Rank-generalised Cooley-Tuckey DFT -- -- We require the innermost dimension be passed as a Haskell value because we -- can't do divide-and-conquer recursion directly in the meta-language. -- fft :: forall sh e. (Slice sh, Shape sh, A.RealFloat e, A.FromIntegral Int e) => e -> sh -> Int -> Acc (Array (sh:.Int) (Complex e)) -> Acc (Array (sh:.Int) (Complex e)) fft sign sh sz arr | P.any (P.not . isPow2) (shapeToList (sh:.sz)) = error $ printf "fft: array dimensions must be powers-of-two, but are: %s" (showShape (sh:.sz)) -- | otherwise = go sz 0 1 where go :: Int -> Int -> Int -> Acc (Array (sh:.Int) (Complex e)) go len offset stride | len P.== 2 = A.generate (constant (sh :. len)) swivel | otherwise = combine (go (len `div` 2) offset (stride * 2)) (go (len `div` 2) (offset + stride) (stride * 2)) where len' = the (unit (constant len)) offset' = the (unit (constant offset)) stride' = the (unit (constant stride)) swivel ix = let sh' :. sz' = unlift ix :: Exp sh :. Exp Int in sz' A.== 0 ? ( (arr ! lift (sh' :. offset')) + (arr ! lift (sh' :. offset' + stride')) {- A.== 1-} , (arr ! lift (sh' :. offset')) - (arr ! lift (sh' :. offset' + stride')) ) combine evens odds = let odds' = A.generate (A.shape odds) (\ix -> twiddle len' (indexHead ix) * odds!ix) in append (A.zipWith (+) evens odds') (A.zipWith (-) evens odds') twiddle n' i' = let n = A.fromIntegral n' i = A.fromIntegral i' k = 2*pi*i/n in lift ( cos k :+ A.constant sign * sin k ) Append two arrays . This is a specialised version of ( A.++ ) which does not do -- bounds checking or intersection. -- append :: forall sh e. (Slice sh, Shape sh, Elt e) => Acc (Array (sh:.Int) e) -> Acc (Array (sh:.Int) e) -> Acc (Array (sh:.Int) e) append xs ys = let sh :. n = unlift (A.shape xs) :: Exp sh :. Exp Int _ :. m = unlift (A.shape ys) :: Exp sh :. Exp Int in generate (lift (sh :. n+m)) (\ix -> let sz :. i = unlift ix :: Exp sh :. Exp Int in i A.< n ? (xs ! lift (sz:.i), ys ! lift (sz:.i-n) )) isPow2 :: Int -> Bool isPow2 0 = True isPow2 1 = False isPow2 x = x .&. (x-1) P.== 0 --}
null
https://raw.githubusercontent.com/AccelerateHS/accelerate-fft/3c195de6a4528071388d817f55b0a7adf0547cc6/src/Data/Array/Accelerate/Math/FFT.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE EmptyDataDecls # # LANGUAGE FlexibleContexts # # LANGUAGE TypeOperators # | Module : Data.Array.Accelerate.Math.FFT License : BSD3 Stability : experimental For performance, compile against the foreign library bindings (using any number of '-fllvm-ptx', and '-fllvm-cpu' for the accelerate-llvm-ptx, and accelerate-llvm-native backends, respectively). | Discrete Fourier Transform along the innermost dimension of an array. The pure implementation will be used otherwise. ---------------- | Discrete Fourier Transform of a vector. ---------------- | Discrete Fourier Transform of a matrix. Cube Transform -------------- | Discrete Fourier Transform of a 3D array. Rank - generalised Cooley - Tuckey DFT We require the innermost dimension be passed as a value because we ca n't do divide - and - conquer recursion directly in the meta - language . Rank-generalised Cooley-Tuckey DFT We require the innermost dimension be passed as a Haskell value because we can't do divide-and-conquer recursion directly in the meta-language. A.== 1 bounds checking or intersection. }
# LANGUAGE CPP # # LANGUAGE GADTs # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE ViewPatterns # Copyright : [ 2012 .. 2020 ] The Accelerate Team Maintainer : < > Portability : non - portable ( GHC extensions ) module Data.Array.Accelerate.Math.FFT ( Mode(..), Numeric, fft, fft1D, fft2D, fft3D, ) where import Data.Array.Accelerate as A import Data.Array.Accelerate.Data.Complex import Data.Array.Accelerate.Math.FFT.Type import Data.Array.Accelerate.Math.FFT.Mode import qualified Data.Array.Accelerate.Sugar.Shape as A ( rank, shapeR ) import qualified Data.Array.Accelerate.Math.FFT.Adhoc as Adhoc #ifdef ACCELERATE_LLVM_NATIVE_BACKEND import qualified Data.Array.Accelerate.Math.FFT.LLVM.Native as Native #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND import qualified Data.Array.Accelerate.Math.FFT.LLVM.PTX as PTX #endif import Prelude as P Notes for FFI implementations : * fftw supports arrays of dimension 1 - 5 * cuFFT supports arrays of dimension 1 - 3 fft :: forall sh e. (Shape sh, Slice sh, Numeric e) => Mode -> Acc (Array (sh:.Int) (Complex e)) -> Acc (Array (sh:.Int) (Complex e)) fft mode arr = let scale = A.fromIntegral (indexHead (shape arr)) rank = A.rank @(sh:.Int) shR = A.shapeR @(sh:.Int) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND (if rank P.<= 5 then foreignAcc (Native.fft mode shR eR) else id) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND (if rank P.<= 3 then foreignAcc (PTX.fft mode shR eR) else id) $ #endif Adhoc.fft mode in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr Vector Transform fft1D :: forall e. Numeric e => Mode -> Acc (Array DIM1 (Complex e)) -> Acc (Array DIM1 (Complex e)) fft1D mode arr = let scale = A.fromIntegral (A.length arr) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND foreignAcc (Native.fft1D mode eR) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND foreignAcc (PTX.fft1D mode eR) $ #endif Adhoc.fft mode in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr Matrix Transform fft2D :: forall e. Numeric e => Mode -> Acc (Array DIM2 (Complex e)) -> Acc (Array DIM2 (Complex e)) fft2D mode arr = let scale = A.fromIntegral (A.size arr) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND foreignAcc (Native.fft2D mode eR) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND foreignAcc (PTX.fft2D mode eR) $ #endif fft' fft' a = A.transpose . Adhoc.fft mode >-> A.transpose . Adhoc.fft mode $ a in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr fft3D :: forall e. Numeric e => Mode -> Acc (Array DIM3 (Complex e)) -> Acc (Array DIM3 (Complex e)) fft3D mode arr = let scale = A.fromIntegral (A.size arr) eR = numericR @e go = #ifdef ACCELERATE_LLVM_NATIVE_BACKEND foreignAcc (Native.fft3D mode eR) $ #endif #ifdef ACCELERATE_LLVM_PTX_BACKEND foreignAcc (PTX.fft3D mode eR) $ #endif fft' fft' a = rotate3D . Adhoc.fft mode >-> rotate3D . Adhoc.fft mode >-> rotate3D . Adhoc.fft mode $ a in case mode of Inverse -> A.map (/scale) (go arr) _ -> go arr rotate3D :: Elt e => Acc (Array DIM3 e) -> Acc (Array DIM3 e) rotate3D arr = backpermute sh rot arr where sh :: Exp DIM3 sh = let Z :. z :. y :. x = unlift (shape arr) :: Z :. Exp Int :. Exp Int :. Exp Int in index3 y x z rot :: Exp DIM3 -> Exp DIM3 rot ix = let Z :. z :. y :. x = unlift ix :: Z :. Exp Int :. Exp Int :. Exp Int in index3 x z y - fft : : forall sh e. ( Slice sh , Shape sh , A.RealFloat e , A.FromIntegral Int e ) = > e - > sh - > Int - > Acc ( Array ( sh:.Int ) ( Complex e ) ) - > Acc ( Array ( sh:.Int ) ( Complex e ) ) fft sign sh sz arr | P.any ( P.not . isPow2 ) ( shapeToList ( sh:.sz ) ) = error $ printf " fft : array dimensions must be powers - of - two , but are : % s " ( ( sh:.sz ) ) | otherwise = go sz 0 1 where go : : Int - > Int - > Int - > Acc ( Array ( sh:.Int ) ( Complex e ) ) go len offset stride | len P.== 2 = A.generate ( constant ( sh : . len ) ) swivel | otherwise = combine ( go ( len ` div ` 2 ) offset ( stride * 2 ) ) ( go ( len ` div ` 2 ) ( offset + stride ) ( stride * 2 ) ) where len ' = the ( unit ( constant len ) ) offset ' = the ( unit ( constant offset ) ) stride ' = the ( unit ( constant stride ) ) swivel ix = let sh ' : . sz ' = unlift ix : : Exp sh : . Exp Int in sz ' A.== 0 ? ( ( arr ! lift ( sh ' : . offset ' ) ) + ( arr ! lift ( sh ' : . offset ' + stride ' ) ) { - A.== 1 fft :: forall sh e. (Slice sh, Shape sh, A.RealFloat e, A.FromIntegral Int e) => e -> sh -> Int -> Acc (Array (sh:.Int) (Complex e)) -> Acc (Array (sh:.Int) (Complex e)) fft sign sh sz arr | P.any (P.not . isPow2) (shapeToList (sh:.sz)) = error $ printf "fft: array dimensions must be powers-of-two, but are: %s" (showShape (sh:.sz)) | otherwise = go sz 0 1 where go :: Int -> Int -> Int -> Acc (Array (sh:.Int) (Complex e)) go len offset stride | len P.== 2 = A.generate (constant (sh :. len)) swivel | otherwise = combine (go (len `div` 2) offset (stride * 2)) (go (len `div` 2) (offset + stride) (stride * 2)) where len' = the (unit (constant len)) offset' = the (unit (constant offset)) stride' = the (unit (constant stride)) swivel ix = let sh' :. sz' = unlift ix :: Exp sh :. Exp Int in sz' A.== 0 ? ( (arr ! lift (sh' :. offset')) + (arr ! lift (sh' :. offset' + stride')) combine evens odds = let odds' = A.generate (A.shape odds) (\ix -> twiddle len' (indexHead ix) * odds!ix) in append (A.zipWith (+) evens odds') (A.zipWith (-) evens odds') twiddle n' i' = let n = A.fromIntegral n' i = A.fromIntegral i' k = 2*pi*i/n in lift ( cos k :+ A.constant sign * sin k ) Append two arrays . This is a specialised version of ( A.++ ) which does not do append :: forall sh e. (Slice sh, Shape sh, Elt e) => Acc (Array (sh:.Int) e) -> Acc (Array (sh:.Int) e) -> Acc (Array (sh:.Int) e) append xs ys = let sh :. n = unlift (A.shape xs) :: Exp sh :. Exp Int _ :. m = unlift (A.shape ys) :: Exp sh :. Exp Int in generate (lift (sh :. n+m)) (\ix -> let sz :. i = unlift ix :: Exp sh :. Exp Int in i A.< n ? (xs ! lift (sz:.i), ys ! lift (sz:.i-n) )) isPow2 :: Int -> Bool isPow2 0 = True isPow2 1 = False isPow2 x = x .&. (x-1) P.== 0
41cecb95544571f7a5edb94e3ded4810aafbbf99becd54bfc76df0d5698cf2f0
diku-dk/futhark
Traversals.hs
-- | -- Functions for generic traversals across syntax trees . The -- motivation for this module came from dissatisfaction with rewriting -- the same trivial tree recursions for every module. A possible -- alternative would be to use normal \"Scrap your boilerplate\"-techniques , but these are rejected for two reasons : -- -- * They are too slow. -- -- * More importantly, they do not tell you whether you have missed -- some cases. -- Instead , this module defines various traversals of the syntax -- tree. The implementation is rather tedious, but the interface is -- easy to use. -- A traversal of the syntax tree is expressed as a record of -- functions expressing the operations to be performed on the various -- types of nodes. module Language.Futhark.Traversals ( ASTMapper (..), ASTMappable (..), identityMapper, bareExp, ) where import Data.List.NonEmpty qualified as NE import Data.Set qualified as S import Language.Futhark.Syntax -- | Express a monad mapping operation on a syntax node. Each element -- of this structure expresses the operation to be performed on a -- given child. data ASTMapper m = ASTMapper { mapOnExp :: ExpBase Info VName -> m (ExpBase Info VName), mapOnName :: VName -> m VName, mapOnStructType :: StructType -> m StructType, mapOnPatType :: PatType -> m PatType, mapOnStructRetType :: StructRetType -> m StructRetType, mapOnPatRetType :: PatRetType -> m PatRetType } -- | An 'ASTMapper' that just leaves its input unchanged. identityMapper :: Monad m => ASTMapper m identityMapper = ASTMapper { mapOnExp = pure, mapOnName = pure, mapOnStructType = pure, mapOnPatType = pure, mapOnStructRetType = pure, mapOnPatRetType = pure } -- | The class of things that we can map an 'ASTMapper' across. class ASTMappable x where -- | Map a monadic action across the immediate children of an -- object. Importantly, the 'astMap' action is not invoked for -- the object itself, and the mapping does not descend recursively -- into subexpressions. The mapping is done left-to-right. astMap :: Monad m => ASTMapper m -> x -> m x instance ASTMappable (QualName VName) where astMap tv = traverse (mapOnName tv) instance ASTMappable (AppExpBase Info VName) where astMap tv (Range start next end loc) = Range <$> mapOnExp tv start <*> traverse (mapOnExp tv) next <*> traverse (mapOnExp tv) end <*> pure loc astMap tv (If c texp fexp loc) = If <$> mapOnExp tv c <*> mapOnExp tv texp <*> mapOnExp tv fexp <*> pure loc astMap tv (Match e cases loc) = Match <$> mapOnExp tv e <*> astMap tv cases <*> pure loc astMap tv (Apply f args loc) = do f' <- mapOnExp tv f args' <- traverse (traverse $ mapOnExp tv) args -- Safe to disregard return type because existentials cannot be -- instantiated here, as the return is necessarily a function. pure $ case f' of AppExp (Apply f_inner args_inner _) _ -> Apply f_inner (args_inner <> args') loc _ -> Apply f' args' loc astMap tv (LetPat sizes pat e body loc) = LetPat <$> astMap tv sizes <*> astMap tv pat <*> mapOnExp tv e <*> mapOnExp tv body <*> pure loc astMap tv (LetFun name (fparams, params, ret, t, e) body loc) = LetFun <$> mapOnName tv name <*> ( (,,,,) <$> mapM (astMap tv) fparams <*> mapM (astMap tv) params <*> traverse (astMap tv) ret <*> traverse (mapOnStructRetType tv) t <*> mapOnExp tv e ) <*> mapOnExp tv body <*> pure loc astMap tv (LetWith dest src idxexps vexp body loc) = LetWith <$> astMap tv dest <*> astMap tv src <*> mapM (astMap tv) idxexps <*> mapOnExp tv vexp <*> mapOnExp tv body <*> pure loc astMap tv (Coerce e tdecl loc) = Coerce <$> mapOnExp tv e <*> astMap tv tdecl <*> pure loc astMap tv (BinOp (fname, fname_loc) t (x, Info (xt, xext)) (y, Info (yt, yext)) loc) = BinOp <$> ((,) <$> astMap tv fname <*> pure fname_loc) <*> traverse (mapOnPatType tv) t <*> ( (,) <$> mapOnExp tv x <*> (Info <$> ((,) <$> mapOnStructType tv xt <*> pure xext)) ) <*> ( (,) <$> mapOnExp tv y <*> (Info <$> ((,) <$> mapOnStructType tv yt <*> pure yext)) ) <*> pure loc astMap tv (DoLoop sparams mergepat mergeexp form loopbody loc) = DoLoop <$> mapM (mapOnName tv) sparams <*> astMap tv mergepat <*> mapOnExp tv mergeexp <*> astMap tv form <*> mapOnExp tv loopbody <*> pure loc astMap tv (Index arr idxexps loc) = Index <$> mapOnExp tv arr <*> mapM (astMap tv) idxexps <*> pure loc instance ASTMappable (ExpBase Info VName) where astMap tv (Var name t loc) = Var <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Hole t loc) = Hole <$> traverse (mapOnPatType tv) t <*> pure loc astMap _ (Literal val loc) = pure $ Literal val loc astMap _ (StringLit vs loc) = pure $ StringLit vs loc astMap tv (IntLit val t loc) = IntLit val <$> traverse (mapOnPatType tv) t <*> pure loc astMap tv (FloatLit val t loc) = FloatLit val <$> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Parens e loc) = Parens <$> mapOnExp tv e <*> pure loc astMap tv (QualParens (name, nameloc) e loc) = QualParens <$> ((,) <$> astMap tv name <*> pure nameloc) <*> mapOnExp tv e <*> pure loc astMap tv (TupLit els loc) = TupLit <$> mapM (mapOnExp tv) els <*> pure loc astMap tv (RecordLit fields loc) = RecordLit <$> astMap tv fields <*> pure loc astMap tv (ArrayLit els t loc) = ArrayLit <$> mapM (mapOnExp tv) els <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Ascript e tdecl loc) = Ascript <$> mapOnExp tv e <*> astMap tv tdecl <*> pure loc astMap tv (Negate x loc) = Negate <$> mapOnExp tv x <*> pure loc astMap tv (Not x loc) = Not <$> mapOnExp tv x <*> pure loc astMap tv (Update src slice v loc) = Update <$> mapOnExp tv src <*> mapM (astMap tv) slice <*> mapOnExp tv v <*> pure loc astMap tv (RecordUpdate src fs v (Info t) loc) = RecordUpdate <$> mapOnExp tv src <*> pure fs <*> mapOnExp tv v <*> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (Project field e t loc) = Project field <$> mapOnExp tv e <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Assert e1 e2 desc loc) = Assert <$> mapOnExp tv e1 <*> mapOnExp tv e2 <*> pure desc <*> pure loc astMap tv (Lambda params body ret t loc) = Lambda <$> mapM (astMap tv) params <*> mapOnExp tv body <*> traverse (astMap tv) ret <*> traverse (traverse $ mapOnStructRetType tv) t <*> pure loc astMap tv (OpSection name t loc) = OpSection <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (OpSectionLeft name t arg (Info (pa, t1a, argext), Info (pb, t1b)) (ret, retext) loc) = OpSectionLeft <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> mapOnExp tv arg <*> ( (,) <$> (Info <$> ((pa,,) <$> mapOnStructType tv t1a <*> pure argext)) <*> (Info <$> ((pb,) <$> mapOnStructType tv t1b)) ) <*> ((,) <$> traverse (mapOnPatRetType tv) ret <*> traverse (mapM (mapOnName tv)) retext) <*> pure loc astMap tv (OpSectionRight name t arg (Info (pa, t1a), Info (pb, t1b, argext)) t2 loc) = OpSectionRight <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> mapOnExp tv arg <*> ( (,) <$> (Info <$> ((pa,) <$> mapOnStructType tv t1a)) <*> (Info <$> ((pb,,) <$> mapOnStructType tv t1b <*> pure argext)) ) <*> traverse (mapOnPatRetType tv) t2 <*> pure loc astMap tv (ProjectSection fields t loc) = ProjectSection fields <$> traverse (mapOnPatType tv) t <*> pure loc astMap tv (IndexSection idxs t loc) = IndexSection <$> mapM (astMap tv) idxs <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Constr name es t loc) = Constr name <$> traverse (mapOnExp tv) es <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Attr attr e loc) = Attr attr <$> mapOnExp tv e <*> pure loc astMap tv (AppExp e res) = AppExp <$> astMap tv e <*> astMap tv res instance ASTMappable (LoopFormBase Info VName) where astMap tv (For i bound) = For <$> astMap tv i <*> mapOnExp tv bound astMap tv (ForIn pat e) = ForIn <$> astMap tv pat <*> mapOnExp tv e astMap tv (While e) = While <$> mapOnExp tv e instance ASTMappable (TypeExp Info VName) where astMap tv (TEVar qn loc) = TEVar <$> astMap tv qn <*> pure loc astMap tv (TETuple ts loc) = TETuple <$> traverse (astMap tv) ts <*> pure loc astMap tv (TERecord ts loc) = TERecord <$> traverse (traverse $ astMap tv) ts <*> pure loc astMap tv (TEArray te dim loc) = TEArray <$> astMap tv te <*> astMap tv dim <*> pure loc astMap tv (TEUnique t loc) = TEUnique <$> astMap tv t <*> pure loc astMap tv (TEApply t1 t2 loc) = TEApply <$> astMap tv t1 <*> astMap tv t2 <*> pure loc astMap tv (TEArrow v t1 t2 loc) = TEArrow v <$> astMap tv t1 <*> astMap tv t2 <*> pure loc astMap tv (TESum cs loc) = TESum <$> traverse (traverse $ astMap tv) cs <*> pure loc astMap tv (TEDim dims t loc) = TEDim dims <$> astMap tv t <*> pure loc instance ASTMappable (TypeArgExp Info VName) where astMap tv (TypeArgExpSize dim) = TypeArgExpSize <$> astMap tv dim astMap tv (TypeArgExpType te) = TypeArgExpType <$> astMap tv te instance ASTMappable (SizeExp Info VName) where astMap tv (SizeExp e loc) = SizeExp <$> mapOnExp tv e <*> pure loc astMap _ (SizeExpAny loc) = pure $ SizeExpAny loc instance ASTMappable Size where astMap tv (NamedSize vn) = NamedSize <$> astMap tv vn astMap _ (ConstSize k) = pure $ ConstSize k astMap tv (AnySize vn) = AnySize <$> traverse (mapOnName tv) vn instance ASTMappable (TypeParamBase VName) where astMap = traverse . mapOnName instance ASTMappable (DimIndexBase Info VName) where astMap tv (DimFix j) = DimFix <$> mapOnExp tv j astMap tv (DimSlice i j stride) = DimSlice <$> maybe (pure Nothing) (fmap Just . mapOnExp tv) i <*> maybe (pure Nothing) (fmap Just . mapOnExp tv) j <*> maybe (pure Nothing) (fmap Just . mapOnExp tv) stride instance ASTMappable Alias where astMap tv (AliasBound v) = AliasBound <$> mapOnName tv v astMap tv (AliasFree v) = AliasFree <$> mapOnName tv v instance ASTMappable Aliasing where astMap tv = fmap S.fromList . traverse (astMap tv) . S.toList instance ASTMappable AppRes where astMap tv (AppRes t ext) = AppRes <$> mapOnPatType tv t <*> pure ext type TypeTraverser f t dim1 als1 dim2 als2 = (QualName VName -> f (QualName VName)) -> (dim1 -> f dim2) -> (als1 -> f als2) -> t dim1 als1 -> f (t dim2 als2) traverseScalarType :: Applicative f => TypeTraverser f ScalarTypeBase dim1 als1 dims als2 traverseScalarType _ _ _ (Prim t) = pure $ Prim t traverseScalarType f g h (Record fs) = Record <$> traverse (traverseType f g h) fs traverseScalarType f g h (TypeVar als u t args) = TypeVar <$> h als <*> pure u <*> f t <*> traverse (traverseTypeArg f g) args traverseScalarType f g h (Arrow als v u t1 (RetType dims t2)) = Arrow <$> h als <*> pure v <*> pure u <*> traverseType f g pure t1 <*> (RetType dims <$> traverseType f g h t2) traverseScalarType f g h (Sum cs) = Sum <$> (traverse . traverse) (traverseType f g h) cs traverseType :: Applicative f => TypeTraverser f TypeBase dim1 als1 dims als2 traverseType f g h (Array als u shape et) = Array <$> h als <*> pure u <*> traverse g shape <*> traverseScalarType f g pure et traverseType f g h (Scalar t) = Scalar <$> traverseScalarType f g h t traverseTypeArg :: Applicative f => (QualName VName -> f (QualName VName)) -> (dim1 -> f dim2) -> TypeArg dim1 -> f (TypeArg dim2) traverseTypeArg _ g (TypeArgDim d loc) = TypeArgDim <$> g d <*> pure loc traverseTypeArg f g (TypeArgType t loc) = TypeArgType <$> traverseType f g pure t <*> pure loc instance ASTMappable StructType where astMap tv = traverseType (astMap tv) (astMap tv) pure instance ASTMappable PatType where astMap tv = traverseType (astMap tv) (astMap tv) (astMap tv) instance ASTMappable StructRetType where astMap tv (RetType ext t) = RetType ext <$> astMap tv t instance ASTMappable PatRetType where astMap tv (RetType ext t) = RetType ext <$> astMap tv t instance ASTMappable (IdentBase Info VName) where astMap tv (Ident name (Info t) loc) = Ident <$> mapOnName tv name <*> (Info <$> mapOnPatType tv t) <*> pure loc instance ASTMappable (SizeBinder VName) where astMap tv (SizeBinder name loc) = SizeBinder <$> mapOnName tv name <*> pure loc instance ASTMappable (PatBase Info VName) where astMap tv (Id name (Info t) loc) = Id <$> mapOnName tv name <*> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (TuplePat pats loc) = TuplePat <$> mapM (astMap tv) pats <*> pure loc astMap tv (RecordPat fields loc) = RecordPat <$> mapM (traverse $ astMap tv) fields <*> pure loc astMap tv (PatParens pat loc) = PatParens <$> astMap tv pat <*> pure loc astMap tv (PatAscription pat t loc) = PatAscription <$> astMap tv pat <*> astMap tv t <*> pure loc astMap tv (Wildcard (Info t) loc) = Wildcard <$> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (PatLit v (Info t) loc) = PatLit v <$> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (PatConstr n (Info t) ps loc) = PatConstr n <$> (Info <$> mapOnPatType tv t) <*> mapM (astMap tv) ps <*> pure loc astMap tv (PatAttr attr p loc) = PatAttr attr <$> astMap tv p <*> pure loc instance ASTMappable (FieldBase Info VName) where astMap tv (RecordFieldExplicit name e loc) = RecordFieldExplicit name <$> mapOnExp tv e <*> pure loc astMap tv (RecordFieldImplicit name t loc) = RecordFieldImplicit <$> mapOnName tv name <*> traverse (mapOnPatType tv) t <*> pure loc instance ASTMappable (CaseBase Info VName) where astMap tv (CasePat pat e loc) = CasePat <$> astMap tv pat <*> mapOnExp tv e <*> pure loc instance ASTMappable a => ASTMappable (Info a) where astMap tv = traverse $ astMap tv instance ASTMappable a => ASTMappable [a] where astMap tv = traverse $ astMap tv instance ASTMappable a => ASTMappable (NE.NonEmpty a) where astMap tv = traverse $ astMap tv instance (ASTMappable a, ASTMappable b) => ASTMappable (a, b) where astMap tv (x, y) = (,) <$> astMap tv x <*> astMap tv y instance (ASTMappable a, ASTMappable b, ASTMappable c) => ASTMappable (a, b, c) where astMap tv (x, y, z) = (,,) <$> astMap tv x <*> astMap tv y <*> astMap tv z -- It would be lovely if the following code would be written in terms of ASTMappable , but unfortunately it involves changing the Info -- functor. For simplicity, the general traversals do not support -- that. Sometimes a little duplication is better than an overly -- complex abstraction. The types ensure that this will be correct -- anyway, so it's just tedious, and not actually fragile. bareField :: FieldBase Info VName -> FieldBase NoInfo VName bareField (RecordFieldExplicit name e loc) = RecordFieldExplicit name (bareExp e) loc bareField (RecordFieldImplicit name _ loc) = RecordFieldImplicit name NoInfo loc barePat :: PatBase Info VName -> PatBase NoInfo VName barePat (TuplePat ps loc) = TuplePat (map barePat ps) loc barePat (RecordPat fs loc) = RecordPat (map (fmap barePat) fs) loc barePat (PatParens p loc) = PatParens (barePat p) loc barePat (Id v _ loc) = Id v NoInfo loc barePat (Wildcard _ loc) = Wildcard NoInfo loc barePat (PatAscription pat t loc) = PatAscription (barePat pat) (bareTypeExp t) loc barePat (PatLit v _ loc) = PatLit v NoInfo loc barePat (PatConstr c _ ps loc) = PatConstr c NoInfo (map barePat ps) loc barePat (PatAttr attr p loc) = PatAttr attr (barePat p) loc bareDimIndex :: DimIndexBase Info VName -> DimIndexBase NoInfo VName bareDimIndex (DimFix e) = DimFix $ bareExp e bareDimIndex (DimSlice x y z) = DimSlice (bareExp <$> x) (bareExp <$> y) (bareExp <$> z) bareLoopForm :: LoopFormBase Info VName -> LoopFormBase NoInfo VName bareLoopForm (For (Ident i _ loc) e) = For (Ident i NoInfo loc) (bareExp e) bareLoopForm (ForIn pat e) = ForIn (barePat pat) (bareExp e) bareLoopForm (While e) = While (bareExp e) bareCase :: CaseBase Info VName -> CaseBase NoInfo VName bareCase (CasePat pat e loc) = CasePat (barePat pat) (bareExp e) loc bareTypeExp :: TypeExp Info VName -> TypeExp NoInfo VName bareTypeExp = undefined -- | Remove all annotations from an expression, but retain the -- name/scope information. bareExp :: ExpBase Info VName -> ExpBase NoInfo VName bareExp (Var name _ loc) = Var name NoInfo loc bareExp (Hole _ loc) = Hole NoInfo loc bareExp (Literal v loc) = Literal v loc bareExp (IntLit val _ loc) = IntLit val NoInfo loc bareExp (FloatLit val _ loc) = FloatLit val NoInfo loc bareExp (Parens e loc) = Parens (bareExp e) loc bareExp (QualParens name e loc) = QualParens name (bareExp e) loc bareExp (TupLit els loc) = TupLit (map bareExp els) loc bareExp (StringLit vs loc) = StringLit vs loc bareExp (RecordLit fields loc) = RecordLit (map bareField fields) loc bareExp (ArrayLit els _ loc) = ArrayLit (map bareExp els) NoInfo loc bareExp (Ascript e te loc) = Ascript (bareExp e) (bareTypeExp te) loc bareExp (Negate x loc) = Negate (bareExp x) loc bareExp (Not x loc) = Not (bareExp x) loc bareExp (Update src slice v loc) = Update (bareExp src) (map bareDimIndex slice) (bareExp v) loc bareExp (RecordUpdate src fs v _ loc) = RecordUpdate (bareExp src) fs (bareExp v) NoInfo loc bareExp (Project field e _ loc) = Project field (bareExp e) NoInfo loc bareExp (Assert e1 e2 _ loc) = Assert (bareExp e1) (bareExp e2) NoInfo loc bareExp (Lambda params body ret _ loc) = Lambda (map barePat params) (bareExp body) (fmap bareTypeExp ret) NoInfo loc bareExp (OpSection name _ loc) = OpSection name NoInfo loc bareExp (OpSectionLeft name _ arg _ _ loc) = OpSectionLeft name NoInfo (bareExp arg) (NoInfo, NoInfo) (NoInfo, NoInfo) loc bareExp (OpSectionRight name _ arg _ _ loc) = OpSectionRight name NoInfo (bareExp arg) (NoInfo, NoInfo) NoInfo loc bareExp (ProjectSection fields _ loc) = ProjectSection fields NoInfo loc bareExp (IndexSection slice _ loc) = IndexSection (map bareDimIndex slice) NoInfo loc bareExp (Constr name es _ loc) = Constr name (map bareExp es) NoInfo loc bareExp (AppExp appexp _) = AppExp appexp' NoInfo where appexp' = case appexp of Match e cases loc -> Match (bareExp e) (fmap bareCase cases) loc DoLoop _ mergepat mergeexp form loopbody loc -> DoLoop [] (barePat mergepat) (bareExp mergeexp) (bareLoopForm form) (bareExp loopbody) loc LetWith (Ident dest _ destloc) (Ident src _ srcloc) idxexps vexp body loc -> LetWith (Ident dest NoInfo destloc) (Ident src NoInfo srcloc) (map bareDimIndex idxexps) (bareExp vexp) (bareExp body) loc BinOp fname _ (x, _) (y, _) loc -> BinOp fname NoInfo (bareExp x, NoInfo) (bareExp y, NoInfo) loc If c texp fexp loc -> If (bareExp c) (bareExp texp) (bareExp fexp) loc Apply f args loc -> Apply (bareExp f) (fmap ((NoInfo,) . bareExp . snd) args) loc LetPat sizes pat e body loc -> LetPat sizes (barePat pat) (bareExp e) (bareExp body) loc LetFun name (fparams, params, ret, _, e) body loc -> LetFun name (fparams, map barePat params, fmap bareTypeExp ret, NoInfo, bareExp e) (bareExp body) loc Range start next end loc -> Range (bareExp start) (fmap bareExp next) (fmap bareExp end) loc Coerce e te loc -> Coerce (bareExp e) (bareTypeExp te) loc Index arr slice loc -> Index (bareExp arr) (map bareDimIndex slice) loc bareExp (Attr attr e loc) = Attr attr (bareExp e) loc
null
https://raw.githubusercontent.com/diku-dk/futhark/b562f0c340748cfbd200ee823201bf727fc76270/src/Language/Futhark/Traversals.hs
haskell
| motivation for this module came from dissatisfaction with rewriting the same trivial tree recursions for every module. A possible alternative would be to use normal \"Scrap your * They are too slow. * More importantly, they do not tell you whether you have missed some cases. tree. The implementation is rather tedious, but the interface is easy to use. functions expressing the operations to be performed on the various types of nodes. | Express a monad mapping operation on a syntax node. Each element of this structure expresses the operation to be performed on a given child. | An 'ASTMapper' that just leaves its input unchanged. | The class of things that we can map an 'ASTMapper' across. | Map a monadic action across the immediate children of an object. Importantly, the 'astMap' action is not invoked for the object itself, and the mapping does not descend recursively into subexpressions. The mapping is done left-to-right. Safe to disregard return type because existentials cannot be instantiated here, as the return is necessarily a function. It would be lovely if the following code would be written in terms functor. For simplicity, the general traversals do not support that. Sometimes a little duplication is better than an overly complex abstraction. The types ensure that this will be correct anyway, so it's just tedious, and not actually fragile. | Remove all annotations from an expression, but retain the name/scope information.
Functions for generic traversals across syntax trees . The boilerplate\"-techniques , but these are rejected for two reasons : Instead , this module defines various traversals of the syntax A traversal of the syntax tree is expressed as a record of module Language.Futhark.Traversals ( ASTMapper (..), ASTMappable (..), identityMapper, bareExp, ) where import Data.List.NonEmpty qualified as NE import Data.Set qualified as S import Language.Futhark.Syntax data ASTMapper m = ASTMapper { mapOnExp :: ExpBase Info VName -> m (ExpBase Info VName), mapOnName :: VName -> m VName, mapOnStructType :: StructType -> m StructType, mapOnPatType :: PatType -> m PatType, mapOnStructRetType :: StructRetType -> m StructRetType, mapOnPatRetType :: PatRetType -> m PatRetType } identityMapper :: Monad m => ASTMapper m identityMapper = ASTMapper { mapOnExp = pure, mapOnName = pure, mapOnStructType = pure, mapOnPatType = pure, mapOnStructRetType = pure, mapOnPatRetType = pure } class ASTMappable x where astMap :: Monad m => ASTMapper m -> x -> m x instance ASTMappable (QualName VName) where astMap tv = traverse (mapOnName tv) instance ASTMappable (AppExpBase Info VName) where astMap tv (Range start next end loc) = Range <$> mapOnExp tv start <*> traverse (mapOnExp tv) next <*> traverse (mapOnExp tv) end <*> pure loc astMap tv (If c texp fexp loc) = If <$> mapOnExp tv c <*> mapOnExp tv texp <*> mapOnExp tv fexp <*> pure loc astMap tv (Match e cases loc) = Match <$> mapOnExp tv e <*> astMap tv cases <*> pure loc astMap tv (Apply f args loc) = do f' <- mapOnExp tv f args' <- traverse (traverse $ mapOnExp tv) args pure $ case f' of AppExp (Apply f_inner args_inner _) _ -> Apply f_inner (args_inner <> args') loc _ -> Apply f' args' loc astMap tv (LetPat sizes pat e body loc) = LetPat <$> astMap tv sizes <*> astMap tv pat <*> mapOnExp tv e <*> mapOnExp tv body <*> pure loc astMap tv (LetFun name (fparams, params, ret, t, e) body loc) = LetFun <$> mapOnName tv name <*> ( (,,,,) <$> mapM (astMap tv) fparams <*> mapM (astMap tv) params <*> traverse (astMap tv) ret <*> traverse (mapOnStructRetType tv) t <*> mapOnExp tv e ) <*> mapOnExp tv body <*> pure loc astMap tv (LetWith dest src idxexps vexp body loc) = LetWith <$> astMap tv dest <*> astMap tv src <*> mapM (astMap tv) idxexps <*> mapOnExp tv vexp <*> mapOnExp tv body <*> pure loc astMap tv (Coerce e tdecl loc) = Coerce <$> mapOnExp tv e <*> astMap tv tdecl <*> pure loc astMap tv (BinOp (fname, fname_loc) t (x, Info (xt, xext)) (y, Info (yt, yext)) loc) = BinOp <$> ((,) <$> astMap tv fname <*> pure fname_loc) <*> traverse (mapOnPatType tv) t <*> ( (,) <$> mapOnExp tv x <*> (Info <$> ((,) <$> mapOnStructType tv xt <*> pure xext)) ) <*> ( (,) <$> mapOnExp tv y <*> (Info <$> ((,) <$> mapOnStructType tv yt <*> pure yext)) ) <*> pure loc astMap tv (DoLoop sparams mergepat mergeexp form loopbody loc) = DoLoop <$> mapM (mapOnName tv) sparams <*> astMap tv mergepat <*> mapOnExp tv mergeexp <*> astMap tv form <*> mapOnExp tv loopbody <*> pure loc astMap tv (Index arr idxexps loc) = Index <$> mapOnExp tv arr <*> mapM (astMap tv) idxexps <*> pure loc instance ASTMappable (ExpBase Info VName) where astMap tv (Var name t loc) = Var <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Hole t loc) = Hole <$> traverse (mapOnPatType tv) t <*> pure loc astMap _ (Literal val loc) = pure $ Literal val loc astMap _ (StringLit vs loc) = pure $ StringLit vs loc astMap tv (IntLit val t loc) = IntLit val <$> traverse (mapOnPatType tv) t <*> pure loc astMap tv (FloatLit val t loc) = FloatLit val <$> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Parens e loc) = Parens <$> mapOnExp tv e <*> pure loc astMap tv (QualParens (name, nameloc) e loc) = QualParens <$> ((,) <$> astMap tv name <*> pure nameloc) <*> mapOnExp tv e <*> pure loc astMap tv (TupLit els loc) = TupLit <$> mapM (mapOnExp tv) els <*> pure loc astMap tv (RecordLit fields loc) = RecordLit <$> astMap tv fields <*> pure loc astMap tv (ArrayLit els t loc) = ArrayLit <$> mapM (mapOnExp tv) els <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Ascript e tdecl loc) = Ascript <$> mapOnExp tv e <*> astMap tv tdecl <*> pure loc astMap tv (Negate x loc) = Negate <$> mapOnExp tv x <*> pure loc astMap tv (Not x loc) = Not <$> mapOnExp tv x <*> pure loc astMap tv (Update src slice v loc) = Update <$> mapOnExp tv src <*> mapM (astMap tv) slice <*> mapOnExp tv v <*> pure loc astMap tv (RecordUpdate src fs v (Info t) loc) = RecordUpdate <$> mapOnExp tv src <*> pure fs <*> mapOnExp tv v <*> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (Project field e t loc) = Project field <$> mapOnExp tv e <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Assert e1 e2 desc loc) = Assert <$> mapOnExp tv e1 <*> mapOnExp tv e2 <*> pure desc <*> pure loc astMap tv (Lambda params body ret t loc) = Lambda <$> mapM (astMap tv) params <*> mapOnExp tv body <*> traverse (astMap tv) ret <*> traverse (traverse $ mapOnStructRetType tv) t <*> pure loc astMap tv (OpSection name t loc) = OpSection <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (OpSectionLeft name t arg (Info (pa, t1a, argext), Info (pb, t1b)) (ret, retext) loc) = OpSectionLeft <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> mapOnExp tv arg <*> ( (,) <$> (Info <$> ((pa,,) <$> mapOnStructType tv t1a <*> pure argext)) <*> (Info <$> ((pb,) <$> mapOnStructType tv t1b)) ) <*> ((,) <$> traverse (mapOnPatRetType tv) ret <*> traverse (mapM (mapOnName tv)) retext) <*> pure loc astMap tv (OpSectionRight name t arg (Info (pa, t1a), Info (pb, t1b, argext)) t2 loc) = OpSectionRight <$> astMap tv name <*> traverse (mapOnPatType tv) t <*> mapOnExp tv arg <*> ( (,) <$> (Info <$> ((pa,) <$> mapOnStructType tv t1a)) <*> (Info <$> ((pb,,) <$> mapOnStructType tv t1b <*> pure argext)) ) <*> traverse (mapOnPatRetType tv) t2 <*> pure loc astMap tv (ProjectSection fields t loc) = ProjectSection fields <$> traverse (mapOnPatType tv) t <*> pure loc astMap tv (IndexSection idxs t loc) = IndexSection <$> mapM (astMap tv) idxs <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Constr name es t loc) = Constr name <$> traverse (mapOnExp tv) es <*> traverse (mapOnPatType tv) t <*> pure loc astMap tv (Attr attr e loc) = Attr attr <$> mapOnExp tv e <*> pure loc astMap tv (AppExp e res) = AppExp <$> astMap tv e <*> astMap tv res instance ASTMappable (LoopFormBase Info VName) where astMap tv (For i bound) = For <$> astMap tv i <*> mapOnExp tv bound astMap tv (ForIn pat e) = ForIn <$> astMap tv pat <*> mapOnExp tv e astMap tv (While e) = While <$> mapOnExp tv e instance ASTMappable (TypeExp Info VName) where astMap tv (TEVar qn loc) = TEVar <$> astMap tv qn <*> pure loc astMap tv (TETuple ts loc) = TETuple <$> traverse (astMap tv) ts <*> pure loc astMap tv (TERecord ts loc) = TERecord <$> traverse (traverse $ astMap tv) ts <*> pure loc astMap tv (TEArray te dim loc) = TEArray <$> astMap tv te <*> astMap tv dim <*> pure loc astMap tv (TEUnique t loc) = TEUnique <$> astMap tv t <*> pure loc astMap tv (TEApply t1 t2 loc) = TEApply <$> astMap tv t1 <*> astMap tv t2 <*> pure loc astMap tv (TEArrow v t1 t2 loc) = TEArrow v <$> astMap tv t1 <*> astMap tv t2 <*> pure loc astMap tv (TESum cs loc) = TESum <$> traverse (traverse $ astMap tv) cs <*> pure loc astMap tv (TEDim dims t loc) = TEDim dims <$> astMap tv t <*> pure loc instance ASTMappable (TypeArgExp Info VName) where astMap tv (TypeArgExpSize dim) = TypeArgExpSize <$> astMap tv dim astMap tv (TypeArgExpType te) = TypeArgExpType <$> astMap tv te instance ASTMappable (SizeExp Info VName) where astMap tv (SizeExp e loc) = SizeExp <$> mapOnExp tv e <*> pure loc astMap _ (SizeExpAny loc) = pure $ SizeExpAny loc instance ASTMappable Size where astMap tv (NamedSize vn) = NamedSize <$> astMap tv vn astMap _ (ConstSize k) = pure $ ConstSize k astMap tv (AnySize vn) = AnySize <$> traverse (mapOnName tv) vn instance ASTMappable (TypeParamBase VName) where astMap = traverse . mapOnName instance ASTMappable (DimIndexBase Info VName) where astMap tv (DimFix j) = DimFix <$> mapOnExp tv j astMap tv (DimSlice i j stride) = DimSlice <$> maybe (pure Nothing) (fmap Just . mapOnExp tv) i <*> maybe (pure Nothing) (fmap Just . mapOnExp tv) j <*> maybe (pure Nothing) (fmap Just . mapOnExp tv) stride instance ASTMappable Alias where astMap tv (AliasBound v) = AliasBound <$> mapOnName tv v astMap tv (AliasFree v) = AliasFree <$> mapOnName tv v instance ASTMappable Aliasing where astMap tv = fmap S.fromList . traverse (astMap tv) . S.toList instance ASTMappable AppRes where astMap tv (AppRes t ext) = AppRes <$> mapOnPatType tv t <*> pure ext type TypeTraverser f t dim1 als1 dim2 als2 = (QualName VName -> f (QualName VName)) -> (dim1 -> f dim2) -> (als1 -> f als2) -> t dim1 als1 -> f (t dim2 als2) traverseScalarType :: Applicative f => TypeTraverser f ScalarTypeBase dim1 als1 dims als2 traverseScalarType _ _ _ (Prim t) = pure $ Prim t traverseScalarType f g h (Record fs) = Record <$> traverse (traverseType f g h) fs traverseScalarType f g h (TypeVar als u t args) = TypeVar <$> h als <*> pure u <*> f t <*> traverse (traverseTypeArg f g) args traverseScalarType f g h (Arrow als v u t1 (RetType dims t2)) = Arrow <$> h als <*> pure v <*> pure u <*> traverseType f g pure t1 <*> (RetType dims <$> traverseType f g h t2) traverseScalarType f g h (Sum cs) = Sum <$> (traverse . traverse) (traverseType f g h) cs traverseType :: Applicative f => TypeTraverser f TypeBase dim1 als1 dims als2 traverseType f g h (Array als u shape et) = Array <$> h als <*> pure u <*> traverse g shape <*> traverseScalarType f g pure et traverseType f g h (Scalar t) = Scalar <$> traverseScalarType f g h t traverseTypeArg :: Applicative f => (QualName VName -> f (QualName VName)) -> (dim1 -> f dim2) -> TypeArg dim1 -> f (TypeArg dim2) traverseTypeArg _ g (TypeArgDim d loc) = TypeArgDim <$> g d <*> pure loc traverseTypeArg f g (TypeArgType t loc) = TypeArgType <$> traverseType f g pure t <*> pure loc instance ASTMappable StructType where astMap tv = traverseType (astMap tv) (astMap tv) pure instance ASTMappable PatType where astMap tv = traverseType (astMap tv) (astMap tv) (astMap tv) instance ASTMappable StructRetType where astMap tv (RetType ext t) = RetType ext <$> astMap tv t instance ASTMappable PatRetType where astMap tv (RetType ext t) = RetType ext <$> astMap tv t instance ASTMappable (IdentBase Info VName) where astMap tv (Ident name (Info t) loc) = Ident <$> mapOnName tv name <*> (Info <$> mapOnPatType tv t) <*> pure loc instance ASTMappable (SizeBinder VName) where astMap tv (SizeBinder name loc) = SizeBinder <$> mapOnName tv name <*> pure loc instance ASTMappable (PatBase Info VName) where astMap tv (Id name (Info t) loc) = Id <$> mapOnName tv name <*> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (TuplePat pats loc) = TuplePat <$> mapM (astMap tv) pats <*> pure loc astMap tv (RecordPat fields loc) = RecordPat <$> mapM (traverse $ astMap tv) fields <*> pure loc astMap tv (PatParens pat loc) = PatParens <$> astMap tv pat <*> pure loc astMap tv (PatAscription pat t loc) = PatAscription <$> astMap tv pat <*> astMap tv t <*> pure loc astMap tv (Wildcard (Info t) loc) = Wildcard <$> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (PatLit v (Info t) loc) = PatLit v <$> (Info <$> mapOnPatType tv t) <*> pure loc astMap tv (PatConstr n (Info t) ps loc) = PatConstr n <$> (Info <$> mapOnPatType tv t) <*> mapM (astMap tv) ps <*> pure loc astMap tv (PatAttr attr p loc) = PatAttr attr <$> astMap tv p <*> pure loc instance ASTMappable (FieldBase Info VName) where astMap tv (RecordFieldExplicit name e loc) = RecordFieldExplicit name <$> mapOnExp tv e <*> pure loc astMap tv (RecordFieldImplicit name t loc) = RecordFieldImplicit <$> mapOnName tv name <*> traverse (mapOnPatType tv) t <*> pure loc instance ASTMappable (CaseBase Info VName) where astMap tv (CasePat pat e loc) = CasePat <$> astMap tv pat <*> mapOnExp tv e <*> pure loc instance ASTMappable a => ASTMappable (Info a) where astMap tv = traverse $ astMap tv instance ASTMappable a => ASTMappable [a] where astMap tv = traverse $ astMap tv instance ASTMappable a => ASTMappable (NE.NonEmpty a) where astMap tv = traverse $ astMap tv instance (ASTMappable a, ASTMappable b) => ASTMappable (a, b) where astMap tv (x, y) = (,) <$> astMap tv x <*> astMap tv y instance (ASTMappable a, ASTMappable b, ASTMappable c) => ASTMappable (a, b, c) where astMap tv (x, y, z) = (,,) <$> astMap tv x <*> astMap tv y <*> astMap tv z of ASTMappable , but unfortunately it involves changing the Info bareField :: FieldBase Info VName -> FieldBase NoInfo VName bareField (RecordFieldExplicit name e loc) = RecordFieldExplicit name (bareExp e) loc bareField (RecordFieldImplicit name _ loc) = RecordFieldImplicit name NoInfo loc barePat :: PatBase Info VName -> PatBase NoInfo VName barePat (TuplePat ps loc) = TuplePat (map barePat ps) loc barePat (RecordPat fs loc) = RecordPat (map (fmap barePat) fs) loc barePat (PatParens p loc) = PatParens (barePat p) loc barePat (Id v _ loc) = Id v NoInfo loc barePat (Wildcard _ loc) = Wildcard NoInfo loc barePat (PatAscription pat t loc) = PatAscription (barePat pat) (bareTypeExp t) loc barePat (PatLit v _ loc) = PatLit v NoInfo loc barePat (PatConstr c _ ps loc) = PatConstr c NoInfo (map barePat ps) loc barePat (PatAttr attr p loc) = PatAttr attr (barePat p) loc bareDimIndex :: DimIndexBase Info VName -> DimIndexBase NoInfo VName bareDimIndex (DimFix e) = DimFix $ bareExp e bareDimIndex (DimSlice x y z) = DimSlice (bareExp <$> x) (bareExp <$> y) (bareExp <$> z) bareLoopForm :: LoopFormBase Info VName -> LoopFormBase NoInfo VName bareLoopForm (For (Ident i _ loc) e) = For (Ident i NoInfo loc) (bareExp e) bareLoopForm (ForIn pat e) = ForIn (barePat pat) (bareExp e) bareLoopForm (While e) = While (bareExp e) bareCase :: CaseBase Info VName -> CaseBase NoInfo VName bareCase (CasePat pat e loc) = CasePat (barePat pat) (bareExp e) loc bareTypeExp :: TypeExp Info VName -> TypeExp NoInfo VName bareTypeExp = undefined bareExp :: ExpBase Info VName -> ExpBase NoInfo VName bareExp (Var name _ loc) = Var name NoInfo loc bareExp (Hole _ loc) = Hole NoInfo loc bareExp (Literal v loc) = Literal v loc bareExp (IntLit val _ loc) = IntLit val NoInfo loc bareExp (FloatLit val _ loc) = FloatLit val NoInfo loc bareExp (Parens e loc) = Parens (bareExp e) loc bareExp (QualParens name e loc) = QualParens name (bareExp e) loc bareExp (TupLit els loc) = TupLit (map bareExp els) loc bareExp (StringLit vs loc) = StringLit vs loc bareExp (RecordLit fields loc) = RecordLit (map bareField fields) loc bareExp (ArrayLit els _ loc) = ArrayLit (map bareExp els) NoInfo loc bareExp (Ascript e te loc) = Ascript (bareExp e) (bareTypeExp te) loc bareExp (Negate x loc) = Negate (bareExp x) loc bareExp (Not x loc) = Not (bareExp x) loc bareExp (Update src slice v loc) = Update (bareExp src) (map bareDimIndex slice) (bareExp v) loc bareExp (RecordUpdate src fs v _ loc) = RecordUpdate (bareExp src) fs (bareExp v) NoInfo loc bareExp (Project field e _ loc) = Project field (bareExp e) NoInfo loc bareExp (Assert e1 e2 _ loc) = Assert (bareExp e1) (bareExp e2) NoInfo loc bareExp (Lambda params body ret _ loc) = Lambda (map barePat params) (bareExp body) (fmap bareTypeExp ret) NoInfo loc bareExp (OpSection name _ loc) = OpSection name NoInfo loc bareExp (OpSectionLeft name _ arg _ _ loc) = OpSectionLeft name NoInfo (bareExp arg) (NoInfo, NoInfo) (NoInfo, NoInfo) loc bareExp (OpSectionRight name _ arg _ _ loc) = OpSectionRight name NoInfo (bareExp arg) (NoInfo, NoInfo) NoInfo loc bareExp (ProjectSection fields _ loc) = ProjectSection fields NoInfo loc bareExp (IndexSection slice _ loc) = IndexSection (map bareDimIndex slice) NoInfo loc bareExp (Constr name es _ loc) = Constr name (map bareExp es) NoInfo loc bareExp (AppExp appexp _) = AppExp appexp' NoInfo where appexp' = case appexp of Match e cases loc -> Match (bareExp e) (fmap bareCase cases) loc DoLoop _ mergepat mergeexp form loopbody loc -> DoLoop [] (barePat mergepat) (bareExp mergeexp) (bareLoopForm form) (bareExp loopbody) loc LetWith (Ident dest _ destloc) (Ident src _ srcloc) idxexps vexp body loc -> LetWith (Ident dest NoInfo destloc) (Ident src NoInfo srcloc) (map bareDimIndex idxexps) (bareExp vexp) (bareExp body) loc BinOp fname _ (x, _) (y, _) loc -> BinOp fname NoInfo (bareExp x, NoInfo) (bareExp y, NoInfo) loc If c texp fexp loc -> If (bareExp c) (bareExp texp) (bareExp fexp) loc Apply f args loc -> Apply (bareExp f) (fmap ((NoInfo,) . bareExp . snd) args) loc LetPat sizes pat e body loc -> LetPat sizes (barePat pat) (bareExp e) (bareExp body) loc LetFun name (fparams, params, ret, _, e) body loc -> LetFun name (fparams, map barePat params, fmap bareTypeExp ret, NoInfo, bareExp e) (bareExp body) loc Range start next end loc -> Range (bareExp start) (fmap bareExp next) (fmap bareExp end) loc Coerce e te loc -> Coerce (bareExp e) (bareTypeExp te) loc Index arr slice loc -> Index (bareExp arr) (map bareDimIndex slice) loc bareExp (Attr attr e loc) = Attr attr (bareExp e) loc
fe8e4b40c7d28c4b1648b71bc6bfd99c170e4f1dfc36eff0801da7fa06ade862
dimitri/pgloader
ixf-connection.lisp
;;; Tools to handle IBM PC version of IXF file format ;;; (in-package :pgloader.source.ixf) (defclass ixf-connection (fd-connection) () (:documentation "pgloader connection parameters for IXF files.")) (defmethod initialize-instance :after ((ixfconn ixf-connection) &key) "Assign the type slot to dbf." (setf (slot-value ixfconn 'type) "ixf")) (defmethod open-connection ((ixfconn ixf-connection) &key) (setf (conn-handle ixfconn) (open (fd-path ixfconn) :direction :input :element-type '(unsigned-byte 8))) ixfconn) (defmethod close-connection ((ixfconn ixf-connection)) (close (conn-handle ixfconn)) (setf (conn-handle ixfconn) nil) ixfconn) (defmethod clone-connection ((c ixf-connection)) (change-class (call-next-method c) 'ixf-connection))
null
https://raw.githubusercontent.com/dimitri/pgloader/3047c9afe141763e9e7ec05b7f2a6aa97cf06801/src/sources/ixf/ixf-connection.lisp
lisp
Tools to handle IBM PC version of IXF file format (in-package :pgloader.source.ixf) (defclass ixf-connection (fd-connection) () (:documentation "pgloader connection parameters for IXF files.")) (defmethod initialize-instance :after ((ixfconn ixf-connection) &key) "Assign the type slot to dbf." (setf (slot-value ixfconn 'type) "ixf")) (defmethod open-connection ((ixfconn ixf-connection) &key) (setf (conn-handle ixfconn) (open (fd-path ixfconn) :direction :input :element-type '(unsigned-byte 8))) ixfconn) (defmethod close-connection ((ixfconn ixf-connection)) (close (conn-handle ixfconn)) (setf (conn-handle ixfconn) nil) ixfconn) (defmethod clone-connection ((c ixf-connection)) (change-class (call-next-method c) 'ixf-connection))
cf9745eb686c0a3926688b7ea802ea9a439799cd0da52e0aee2c000b81843079
byorgey/diagrams-play
SquareSide.hs
# LANGUAGE NoMonomorphismRestriction # import Diagrams.Prelude import Diagrams.Backend.Cairo.CmdLine import Control.Lens dia = mconcat . (element 2 %~ lc blue) . concat . explodePath $ square 1 main = defaultMain (dia # pad 1.1)
null
https://raw.githubusercontent.com/byorgey/diagrams-play/5362c715db394be6848ff5de1bbe71178e5f173f/SquareSide.hs
haskell
# LANGUAGE NoMonomorphismRestriction # import Diagrams.Prelude import Diagrams.Backend.Cairo.CmdLine import Control.Lens dia = mconcat . (element 2 %~ lc blue) . concat . explodePath $ square 1 main = defaultMain (dia # pad 1.1)
8644f7149ad44bf6b1c87e39b50f7bd272c1fd32ea23660e5276d38d44de19b5
thelema/ocaml-community
debugger_config.mli
(***********************************************************************) (* *) (* 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 Q Public License version 1.0 . (* *) (***********************************************************************) (********************** Configuration file *****************************) exception Toplevel (*** Miscellaneous parameters. ***) val debugger_prompt : string val event_mark_before : string val event_mark_after : string val shell : string val runtime_program : string val history_size : int ref val load_path_for : (string, string list) Hashtbl.t (*** Time travel paramaters. ***) val checkpoint_big_step : int64 ref val checkpoint_small_step : int64 ref val checkpoint_max_count : int ref val make_checkpoints : bool ref * * Environment variables for debugee . * * val environment : string list ref
null
https://raw.githubusercontent.com/thelema/ocaml-community/ed0a2424bbf13d1b33292725e089f0d7ba94b540/debugger/debugger_config.mli
ocaml
********************************************************************* OCaml ********************************************************************* ********************* Configuration file **************************** ** Miscellaneous parameters. ** ** Time travel paramaters. **
, 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 Q Public License version 1.0 . exception Toplevel val debugger_prompt : string val event_mark_before : string val event_mark_after : string val shell : string val runtime_program : string val history_size : int ref val load_path_for : (string, string list) Hashtbl.t val checkpoint_big_step : int64 ref val checkpoint_small_step : int64 ref val checkpoint_max_count : int ref val make_checkpoints : bool ref * * Environment variables for debugee . * * val environment : string list ref
959d074e9ae8b5321639951628b4b937b46c4c8cfbe64a73e8af82c6e086cf9a
terezka/cherry-core
Result.hs
| Module : Result Description : A ` Result ` is the result of a computation that may fail . This is a great way to manage errors . License : BSD 3 Maintainer : Stability : experimental Portability : POSIX A ` Result ` is the result of a computation that may fail . This is a great way to manage errors . Module : Result Description : A `Result` is the result of a computation that may fail. This is a great way to manage errors. License : BSD 3 Maintainer : Stability : experimental Portability : POSIX A `Result` is the result of a computation that may fail. This is a great way to manage errors. -} module Result ( Result(..) -- * Mapping , map, map2, map3, map4, map5 -- * Chaining , andThen -- * Handling Errors , withDefault, toMaybe, fromMaybe, mapError -- * Conversions from Haskell Types , fromEither ) where import Prelude (Applicative, Char, Eq, Functor, Monad, Num, Ord, Show, flip, fromIntegral, mappend, mconcat, otherwise, pure, (<*>), (>>=), fmap) import Maybe (Maybe(Just, Nothing)) import qualified Data.Either import qualified Internal.Shortcut as Shortcut {-| A `Result` is either `Ok` meaning the computation succeeded, or it is an `Err` meaning that there was some failure. -} data Result error success = Ok success | Err error deriving (Prelude.Show, Prelude.Eq) instance Functor (Result error) where fmap func result = case result of Ok success -> Ok (func success) Err error -> Err error instance Applicative (Result error) where pure = Ok (<*>) r1 r2 = case (r1, r2) of (Ok func, Ok a) -> Ok (func a) (Err err, _) -> Err err (Ok _, Err err) -> Err err instance Monad (Result error) where (>>=) result func = case result of Ok success -> func success Err error -> Err error | If the result is ` Ok ` return the value , but if the result is an ` Err ` then return a given default value . The following examples try to parse integers . > Result.withDefault 0 ( Ok 123 ) = = 123 > Result.withDefault 0 ( Err " no " ) = = 0 return a given default value. The following examples try to parse integers. > Result.withDefault 0 (Ok 123) == 123 > Result.withDefault 0 (Err "no") == 0 -} withDefault :: a -> Result b a -> a withDefault fallback result = case result of Ok success -> success Err _ -> fallback {-| Apply a function to a result. If the result is `Ok`, it will be converted. If the result is an `Err`, the same error value will propagate through. map sqrt (Ok 4.0) == Ok 2.0 map sqrt (Err "bad input") == Err "bad input" -} map :: (a -> b) -> Result c a -> Result c b map = Shortcut.map | Apply a function if both results are ` Ok ` . If not , the first ` Err ` will propagate through . > map2 max ( Ok 42 ) ( Ok 13 ) = = Ok 42 > map2 max ( Err " x " ) ( Ok 13 ) = = " > map2 max ( Ok 42 ) ( " ) = = y " > map2 max ( Err " x " ) ( " ) = = " This can be useful if you have two computations that may fail , and you want to put them together quickly . propagate through. > map2 max (Ok 42) (Ok 13) == Ok 42 > map2 max (Err "x") (Ok 13) == Err "x" > map2 max (Ok 42) (Err "y") == Err "y" > map2 max (Err "x") (Err "y") == Err "x" This can be useful if you have two computations that may fail, and you want to put them together quickly. -} map2 :: (a -> b -> c) -> Result err a -> Result err b -> Result err c map2 = Shortcut.map2 {-|-} map3 :: (a -> b -> c -> d) -> Result err a -> Result err b -> Result err c -> Result err d map3 = Shortcut.map3 {-|-} map4 :: (a -> b -> c -> d -> e) -> Result err a -> Result err b -> Result err c -> Result err d -> Result err e map4 = Shortcut.map4 {-|-} map5 :: (a -> b -> c -> d -> e -> f) -> Result err a -> Result err b -> Result err c -> Result err d -> Result err e -> Result err f map5 = Shortcut.map5 | Chain together a sequence of computations that may fail . It is helpful to see its definition : > andThen : : ( a - > Result e b ) - > Result e a - > Result e b > andThen callback result = > case result of > Ok value - > callback value > Err msg - > Err msg This means we only continue with the callback if things are going well . For example , say you need to use ( ` toInt : : String - > Result String Int ` ) to parse a month and make sure it is between 1 and 12 : > toValidMonth : : Int - > Result String Int > toValidMonth month = > if month > = 1 & & month < = 12 > then Ok month > else " months must be between 1 and 12 " > toMonth : : String - > Result String Int > toMonth = > toInt > | > > -- toMonth " 4 " = = Ok 4 > -- toMonth " 9 " = = Ok 9 > -- toMonth " a " = = Err " can not parse to an Int " > -- toMonth " 0 " = = Err " months must be between 1 and 12 " This allows us to come out of a chain of operations with quite a specific error message . It is often best to create a custom type that explicitly represents the exact ways your computation may fail . This way it is easy to handle in your code . to see its definition: > andThen :: (a -> Result e b) -> Result e a -> Result e b > andThen callback result = > case result of > Ok value -> callback value > Err msg -> Err msg This means we only continue with the callback if things are going well. For example, say you need to use (`toInt :: String -> Result String Int`) to parse a month and make sure it is between 1 and 12: > toValidMonth :: Int -> Result String Int > toValidMonth month = > if month >= 1 && month <= 12 > then Ok month > else Err "months must be between 1 and 12" > toMonth :: String -> Result String Int > toMonth rawString = > toInt rawString > |> andThen toValidMonth > -- toMonth "4" == Ok 4 > -- toMonth "9" == Ok 9 > -- toMonth "a" == Err "cannot parse to an Int" > -- toMonth "0" == Err "months must be between 1 and 12" This allows us to come out of a chain of operations with quite a specific error message. It is often best to create a custom type that explicitly represents the exact ways your computation may fail. This way it is easy to handle in your code. -} andThen :: (a -> Result c b) -> Result c a -> Result c b andThen = Shortcut.andThen | Transform an ` Err ` value . For example , say the errors we get have too much information : > parseInt : : String - > Result ParseError Int > > data ParseError = ParseError > { message : : String > , code : : Int > , position : : ( Int , Int ) > } > > mapError message ( parseInt " 123 " ) = = Ok 123 > mapError message ( parseInt " abc " ) = = Err " char ' a ' is not a number " information: > parseInt :: String -> Result ParseError Int > > data ParseError = ParseError > { message :: String > , code :: Int > , position :: (Int,Int) > } > > mapError message (parseInt "123") == Ok 123 > mapError message (parseInt "abc") == Err "char 'a' is not a number" -} mapError :: (a -> b) -> Result a c -> Result b c mapError func result = case result of Ok success -> Ok success Err error -> Err (func error) | Convert to a simpler ` Maybe ` if the actual error message is not needed or you need to interact with some code that primarily uses maybes . > parseInt : : String - > Result ParseError Int > > maybeParseInt : : String - > Maybe > maybeParseInt string = > toMaybe ( parseInt string ) you need to interact with some code that primarily uses maybes. > parseInt :: String -> Result ParseError Int > > maybeParseInt :: String -> Maybe Int > maybeParseInt string = > toMaybe (parseInt string) -} toMaybe :: Result a b -> Maybe b toMaybe result = case result of Ok success -> Just success Err _ -> Nothing {-| Convert from a simple `Maybe` to interact with some code that primarily uses `Results`. > parseInt :: String -> Maybe Int > > resultParseInt :: String -> Result String Int > resultParseInt string = > fromMaybe ("error parsing string: " ++ toString string) (parseInt string) -} fromMaybe :: a -> Maybe b -> Result a b fromMaybe error maybe = case maybe of Just something -> Ok something Nothing -> Err error {-| -} fromEither :: Data.Either.Either x a -> Result x a fromEither either = case either of Data.Either.Right a -> Ok a Data.Either.Left x -> Err x
null
https://raw.githubusercontent.com/terezka/cherry-core/d9bd446e226fc9b04783532969fa670211a150c6/src/Result.hs
haskell
* Mapping * Chaining * Handling Errors * Conversions from Haskell Types | A `Result` is either `Ok` meaning the computation succeeded, or it is an `Err` meaning that there was some failure. | Apply a function to a result. If the result is `Ok`, it will be converted. If the result is an `Err`, the same error value will propagate through. map sqrt (Ok 4.0) == Ok 2.0 map sqrt (Err "bad input") == Err "bad input" | | | toMonth " 4 " = = Ok 4 toMonth " 9 " = = Ok 9 toMonth " a " = = Err " can not parse to an Int " toMonth " 0 " = = Err " months must be between 1 and 12 " toMonth "4" == Ok 4 toMonth "9" == Ok 9 toMonth "a" == Err "cannot parse to an Int" toMonth "0" == Err "months must be between 1 and 12" | Convert from a simple `Maybe` to interact with some code that primarily uses `Results`. > parseInt :: String -> Maybe Int > > resultParseInt :: String -> Result String Int > resultParseInt string = > fromMaybe ("error parsing string: " ++ toString string) (parseInt string) |
| Module : Result Description : A ` Result ` is the result of a computation that may fail . This is a great way to manage errors . License : BSD 3 Maintainer : Stability : experimental Portability : POSIX A ` Result ` is the result of a computation that may fail . This is a great way to manage errors . Module : Result Description : A `Result` is the result of a computation that may fail. This is a great way to manage errors. License : BSD 3 Maintainer : Stability : experimental Portability : POSIX A `Result` is the result of a computation that may fail. This is a great way to manage errors. -} module Result ( Result(..) , map, map2, map3, map4, map5 , andThen , withDefault, toMaybe, fromMaybe, mapError , fromEither ) where import Prelude (Applicative, Char, Eq, Functor, Monad, Num, Ord, Show, flip, fromIntegral, mappend, mconcat, otherwise, pure, (<*>), (>>=), fmap) import Maybe (Maybe(Just, Nothing)) import qualified Data.Either import qualified Internal.Shortcut as Shortcut data Result error success = Ok success | Err error deriving (Prelude.Show, Prelude.Eq) instance Functor (Result error) where fmap func result = case result of Ok success -> Ok (func success) Err error -> Err error instance Applicative (Result error) where pure = Ok (<*>) r1 r2 = case (r1, r2) of (Ok func, Ok a) -> Ok (func a) (Err err, _) -> Err err (Ok _, Err err) -> Err err instance Monad (Result error) where (>>=) result func = case result of Ok success -> func success Err error -> Err error | If the result is ` Ok ` return the value , but if the result is an ` Err ` then return a given default value . The following examples try to parse integers . > Result.withDefault 0 ( Ok 123 ) = = 123 > Result.withDefault 0 ( Err " no " ) = = 0 return a given default value. The following examples try to parse integers. > Result.withDefault 0 (Ok 123) == 123 > Result.withDefault 0 (Err "no") == 0 -} withDefault :: a -> Result b a -> a withDefault fallback result = case result of Ok success -> success Err _ -> fallback map :: (a -> b) -> Result c a -> Result c b map = Shortcut.map | Apply a function if both results are ` Ok ` . If not , the first ` Err ` will propagate through . > map2 max ( Ok 42 ) ( Ok 13 ) = = Ok 42 > map2 max ( Err " x " ) ( Ok 13 ) = = " > map2 max ( Ok 42 ) ( " ) = = y " > map2 max ( Err " x " ) ( " ) = = " This can be useful if you have two computations that may fail , and you want to put them together quickly . propagate through. > map2 max (Ok 42) (Ok 13) == Ok 42 > map2 max (Err "x") (Ok 13) == Err "x" > map2 max (Ok 42) (Err "y") == Err "y" > map2 max (Err "x") (Err "y") == Err "x" This can be useful if you have two computations that may fail, and you want to put them together quickly. -} map2 :: (a -> b -> c) -> Result err a -> Result err b -> Result err c map2 = Shortcut.map2 map3 :: (a -> b -> c -> d) -> Result err a -> Result err b -> Result err c -> Result err d map3 = Shortcut.map3 map4 :: (a -> b -> c -> d -> e) -> Result err a -> Result err b -> Result err c -> Result err d -> Result err e map4 = Shortcut.map4 map5 :: (a -> b -> c -> d -> e -> f) -> Result err a -> Result err b -> Result err c -> Result err d -> Result err e -> Result err f map5 = Shortcut.map5 | Chain together a sequence of computations that may fail . It is helpful to see its definition : > andThen : : ( a - > Result e b ) - > Result e a - > Result e b > andThen callback result = > case result of > Ok value - > callback value > Err msg - > Err msg This means we only continue with the callback if things are going well . For example , say you need to use ( ` toInt : : String - > Result String Int ` ) to parse a month and make sure it is between 1 and 12 : > toValidMonth : : Int - > Result String Int > toValidMonth month = > if month > = 1 & & month < = 12 > then Ok month > else " months must be between 1 and 12 " > toMonth : : String - > Result String Int > toMonth = > toInt > | > This allows us to come out of a chain of operations with quite a specific error message . It is often best to create a custom type that explicitly represents the exact ways your computation may fail . This way it is easy to handle in your code . to see its definition: > andThen :: (a -> Result e b) -> Result e a -> Result e b > andThen callback result = > case result of > Ok value -> callback value > Err msg -> Err msg This means we only continue with the callback if things are going well. For example, say you need to use (`toInt :: String -> Result String Int`) to parse a month and make sure it is between 1 and 12: > toValidMonth :: Int -> Result String Int > toValidMonth month = > if month >= 1 && month <= 12 > then Ok month > else Err "months must be between 1 and 12" > toMonth :: String -> Result String Int > toMonth rawString = > toInt rawString > |> andThen toValidMonth This allows us to come out of a chain of operations with quite a specific error message. It is often best to create a custom type that explicitly represents the exact ways your computation may fail. This way it is easy to handle in your code. -} andThen :: (a -> Result c b) -> Result c a -> Result c b andThen = Shortcut.andThen | Transform an ` Err ` value . For example , say the errors we get have too much information : > parseInt : : String - > Result ParseError Int > > data ParseError = ParseError > { message : : String > , code : : Int > , position : : ( Int , Int ) > } > > mapError message ( parseInt " 123 " ) = = Ok 123 > mapError message ( parseInt " abc " ) = = Err " char ' a ' is not a number " information: > parseInt :: String -> Result ParseError Int > > data ParseError = ParseError > { message :: String > , code :: Int > , position :: (Int,Int) > } > > mapError message (parseInt "123") == Ok 123 > mapError message (parseInt "abc") == Err "char 'a' is not a number" -} mapError :: (a -> b) -> Result a c -> Result b c mapError func result = case result of Ok success -> Ok success Err error -> Err (func error) | Convert to a simpler ` Maybe ` if the actual error message is not needed or you need to interact with some code that primarily uses maybes . > parseInt : : String - > Result ParseError Int > > maybeParseInt : : String - > Maybe > maybeParseInt string = > toMaybe ( parseInt string ) you need to interact with some code that primarily uses maybes. > parseInt :: String -> Result ParseError Int > > maybeParseInt :: String -> Maybe Int > maybeParseInt string = > toMaybe (parseInt string) -} toMaybe :: Result a b -> Maybe b toMaybe result = case result of Ok success -> Just success Err _ -> Nothing fromMaybe :: a -> Maybe b -> Result a b fromMaybe error maybe = case maybe of Just something -> Ok something Nothing -> Err error fromEither :: Data.Either.Either x a -> Result x a fromEither either = case either of Data.Either.Right a -> Ok a Data.Either.Left x -> Err x
0cc50fa7ceb657a0ff6f0d9e008c6dc59e088e66743c7f2c8e0f5a42ce1d6481
janestreet/delimited_parsing
read.ml
open Core open Async include Delimited_kernel.Read open Deferred.Let_syntax the maximum read / write I managed to get off of a socket or disk was 65k let buffer_size = 10 * 65 * 1024 module Streaming = struct include Delimited_kernel.Read.Streaming let input_reader t r = let buffer = Bytes.create buffer_size in Deferred.repeat_until_finished t (fun t -> match%map Reader.read r buffer ~len:buffer_size with | `Eof -> `Finished t | `Ok len -> let t = Streaming.input t buffer ~len in `Repeat t) ;; let read_file ?strip ?sep ?quote ?start_line_number ?on_invalid_row ?header builder ~init ~f ~filename = let t = create ?strip ?sep ?quote ?start_line_number ?on_invalid_row ?header builder ~init ~f in let%map t = Reader.with_file filename ~f:(input_reader t) in let t = finish t in t ;; end let fold_reader_internal ?strip ?(skip_lines = 0) ?sep ?quote ?header ?on_invalid_row builder ~init ~f ~what_to_enqueue r = let%bind () = Shared.drop_lines r skip_lines in let buffer = Bytes.create buffer_size in let queue = Queue.create () in let state = Streaming.create_indexed ?strip ?sep ?quote ~start_line_number:(skip_lines + 1) ?header ?on_invalid_row builder ~init:() ~f:(fun line_number () elt -> Queue.enqueue queue (what_to_enqueue elt ~line_number)) in Deferred.repeat_until_finished (state, init) (fun (state, acc) -> match%bind Reader.read r buffer ~len:buffer_size with | `Eof -> let (_ : unit Streaming.t) = Streaming.finish state in let%bind acc = if Queue.is_empty queue then return acc else f acc queue in Queue.clear queue; let%map () = Reader.close r in `Finished acc | `Ok len -> let state = Streaming.input state buffer ~len in let%map acc = if Queue.is_empty queue then return acc else f acc queue in Queue.clear queue; `Repeat (state, acc)) ;; let fold_readeri' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader_internal ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f ~what_to_enqueue:(fun line ~line_number -> line_number, line) r ;; let fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader_internal ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f ~what_to_enqueue:(fun line ~line_number:_ -> line) r ;; let fold_queue acc queue ~f = Queue.fold queue ~init:(return acc) ~f:(fun deferred_acc elt -> let bind_without_unnecessary_yielding x ~f = match Deferred.peek x with | Some x -> f x | None -> Deferred.bind x ~f in bind_without_unnecessary_yielding deferred_acc ~f:(fun acc -> f acc elt)) ;; let fold_readeri ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_readeri' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fold_queue ~f:(fun acc (line_number, elt) -> f line_number acc elt)) ;; let fold_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fold_queue ~f) ;; let fold_reader_without_pushback ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fun acc queue -> return (Queue.fold queue ~init:acc ~f)) ;; let fold_reader_without_pushbacki ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_readeri' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fun acc queue -> return (Queue.fold queue ~init:acc ~f:(fun acc (line_number, elt) -> f line_number acc elt))) ;; let pipe_of_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder reader = let r, w = Pipe.create () in let write_to_pipe : unit Deferred.t = let%bind () = fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init:() reader ~f:(fun () queue -> if Pipe.is_closed w then ( let%bind () = Reader.close reader in Deferred.never ()) else Pipe.transfer_in w ~from:queue) in return (Pipe.close w) in don't_wait_for write_to_pipe; r ;; let create_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder filename = let%bind reader = Reader.open_file filename in Monitor.handle_errors (fun () -> return (pipe_of_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder reader)) (fun exn -> don't_wait_for (Reader.close reader); raise (Monitor.extract_exn exn)) ;; let rec do_line_skip ~newlines_between_reads ~skip_lines ~skipped_so_far ~stream ~input_pipe = if skipped_so_far >= skip_lines then return stream else ( match%bind Pipe.read input_pipe with | `Eof -> raise_s [%message "Delimited.Read.pipe_of_chunks: Reached EOF while skipping lines" (skip_lines : int) (skipped_so_far : int)] | `Ok input -> let rec skip_lines_in_chunk ~pos ~skipped_so_far = match String.index_from input pos '\n' with | None -> let skipped_so_far = skipped_so_far + if newlines_between_reads then 1 else 0 in do_line_skip ~newlines_between_reads ~skip_lines ~skipped_so_far ~stream ~input_pipe | Some end_pos -> let skipped_so_far = skipped_so_far + 1 in if skipped_so_far >= skip_lines then ( let stream = Streaming.input_string stream ~pos:(end_pos + 1) input in return stream) else skip_lines_in_chunk ~pos:(end_pos + 1) ~skipped_so_far in skip_lines_in_chunk ~pos:0 ~skipped_so_far) ;; let parse_pipe ~newlines_between_reads ?strip ?(start_line_number = 1) ?(skip_lines = 0) ?sep ?quote ?header ?on_invalid_row builder input_pipe = Pipe.create_reader ~close_on_exception:false (fun writer -> let init = Streaming.create ?header ?strip ?sep ?quote ~start_line_number:(start_line_number + skip_lines) ?on_invalid_row builder (* The accumulator is a deferred that waits for all the outstanding row outputs to be consumed. Then you can get good pushback behaviour by waiting for the accumulator before feeding any more input in (which indeed is what the [Pipe.fold] below does). *) ~init:(return ()) ~f:(fun _ row -> (* Waiting for the accumulator is not necessary, since [Pipe.write] should not become determined until all previous writes have become determined anyway. *) Pipe.write writer row) in let%bind init = do_line_skip ~newlines_between_reads ~skip_lines ~skipped_so_far:0 ~stream:init ~input_pipe in let%bind stream = Pipe.fold input_pipe ~init ~f:(fun stream input -> let stream = Streaming.input_string stream input in let stream = if newlines_between_reads then Streaming.input_string stream "\n" else stream in let%map () = Streaming.acc stream in stream) in let stream = Streaming.finish stream in (* I think this last wait for the accumulator before closing the pipe is probably unnecessary. The [Streaming.finish] call should already have written everything to the pipe. But it's easy to write [f] in the streaming fold such that that's not true, or at least not obviously true, e.g. by waiting for the accumulator before doing the pipe write. So this seems safer against possible future refactors. *) Streaming.acc stream) ;; let pipe_of_chunks ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe = parse_pipe ~newlines_between_reads:false ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe ;; let pipe_of_lines ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe = parse_pipe ~newlines_between_reads:true ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe ;;
null
https://raw.githubusercontent.com/janestreet/delimited_parsing/da781604207173f54a16042910a3605e6176e479/src/read.ml
ocaml
The accumulator is a deferred that waits for all the outstanding row outputs to be consumed. Then you can get good pushback behaviour by waiting for the accumulator before feeding any more input in (which indeed is what the [Pipe.fold] below does). Waiting for the accumulator is not necessary, since [Pipe.write] should not become determined until all previous writes have become determined anyway. I think this last wait for the accumulator before closing the pipe is probably unnecessary. The [Streaming.finish] call should already have written everything to the pipe. But it's easy to write [f] in the streaming fold such that that's not true, or at least not obviously true, e.g. by waiting for the accumulator before doing the pipe write. So this seems safer against possible future refactors.
open Core open Async include Delimited_kernel.Read open Deferred.Let_syntax the maximum read / write I managed to get off of a socket or disk was 65k let buffer_size = 10 * 65 * 1024 module Streaming = struct include Delimited_kernel.Read.Streaming let input_reader t r = let buffer = Bytes.create buffer_size in Deferred.repeat_until_finished t (fun t -> match%map Reader.read r buffer ~len:buffer_size with | `Eof -> `Finished t | `Ok len -> let t = Streaming.input t buffer ~len in `Repeat t) ;; let read_file ?strip ?sep ?quote ?start_line_number ?on_invalid_row ?header builder ~init ~f ~filename = let t = create ?strip ?sep ?quote ?start_line_number ?on_invalid_row ?header builder ~init ~f in let%map t = Reader.with_file filename ~f:(input_reader t) in let t = finish t in t ;; end let fold_reader_internal ?strip ?(skip_lines = 0) ?sep ?quote ?header ?on_invalid_row builder ~init ~f ~what_to_enqueue r = let%bind () = Shared.drop_lines r skip_lines in let buffer = Bytes.create buffer_size in let queue = Queue.create () in let state = Streaming.create_indexed ?strip ?sep ?quote ~start_line_number:(skip_lines + 1) ?header ?on_invalid_row builder ~init:() ~f:(fun line_number () elt -> Queue.enqueue queue (what_to_enqueue elt ~line_number)) in Deferred.repeat_until_finished (state, init) (fun (state, acc) -> match%bind Reader.read r buffer ~len:buffer_size with | `Eof -> let (_ : unit Streaming.t) = Streaming.finish state in let%bind acc = if Queue.is_empty queue then return acc else f acc queue in Queue.clear queue; let%map () = Reader.close r in `Finished acc | `Ok len -> let state = Streaming.input state buffer ~len in let%map acc = if Queue.is_empty queue then return acc else f acc queue in Queue.clear queue; `Repeat (state, acc)) ;; let fold_readeri' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader_internal ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f ~what_to_enqueue:(fun line ~line_number -> line_number, line) r ;; let fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader_internal ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f ~what_to_enqueue:(fun line ~line_number:_ -> line) r ;; let fold_queue acc queue ~f = Queue.fold queue ~init:(return acc) ~f:(fun deferred_acc elt -> let bind_without_unnecessary_yielding x ~f = match Deferred.peek x with | Some x -> f x | None -> Deferred.bind x ~f in bind_without_unnecessary_yielding deferred_acc ~f:(fun acc -> f acc elt)) ;; let fold_readeri ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_readeri' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fold_queue ~f:(fun acc (line_number, elt) -> f line_number acc elt)) ;; let fold_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fold_queue ~f) ;; let fold_reader_without_pushback ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fun acc queue -> return (Queue.fold queue ~init:acc ~f)) ;; let fold_reader_without_pushbacki ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init ~f r = fold_readeri' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init r ~f:(fun acc queue -> return (Queue.fold queue ~init:acc ~f:(fun acc (line_number, elt) -> f line_number acc elt))) ;; let pipe_of_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder reader = let r, w = Pipe.create () in let write_to_pipe : unit Deferred.t = let%bind () = fold_reader' ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder ~init:() reader ~f:(fun () queue -> if Pipe.is_closed w then ( let%bind () = Reader.close reader in Deferred.never ()) else Pipe.transfer_in w ~from:queue) in return (Pipe.close w) in don't_wait_for write_to_pipe; r ;; let create_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder filename = let%bind reader = Reader.open_file filename in Monitor.handle_errors (fun () -> return (pipe_of_reader ?strip ?skip_lines ?sep ?quote ?header ?on_invalid_row builder reader)) (fun exn -> don't_wait_for (Reader.close reader); raise (Monitor.extract_exn exn)) ;; let rec do_line_skip ~newlines_between_reads ~skip_lines ~skipped_so_far ~stream ~input_pipe = if skipped_so_far >= skip_lines then return stream else ( match%bind Pipe.read input_pipe with | `Eof -> raise_s [%message "Delimited.Read.pipe_of_chunks: Reached EOF while skipping lines" (skip_lines : int) (skipped_so_far : int)] | `Ok input -> let rec skip_lines_in_chunk ~pos ~skipped_so_far = match String.index_from input pos '\n' with | None -> let skipped_so_far = skipped_so_far + if newlines_between_reads then 1 else 0 in do_line_skip ~newlines_between_reads ~skip_lines ~skipped_so_far ~stream ~input_pipe | Some end_pos -> let skipped_so_far = skipped_so_far + 1 in if skipped_so_far >= skip_lines then ( let stream = Streaming.input_string stream ~pos:(end_pos + 1) input in return stream) else skip_lines_in_chunk ~pos:(end_pos + 1) ~skipped_so_far in skip_lines_in_chunk ~pos:0 ~skipped_so_far) ;; let parse_pipe ~newlines_between_reads ?strip ?(start_line_number = 1) ?(skip_lines = 0) ?sep ?quote ?header ?on_invalid_row builder input_pipe = Pipe.create_reader ~close_on_exception:false (fun writer -> let init = Streaming.create ?header ?strip ?sep ?quote ~start_line_number:(start_line_number + skip_lines) ?on_invalid_row builder ~init:(return ()) ~f:(fun _ row -> Pipe.write writer row) in let%bind init = do_line_skip ~newlines_between_reads ~skip_lines ~skipped_so_far:0 ~stream:init ~input_pipe in let%bind stream = Pipe.fold input_pipe ~init ~f:(fun stream input -> let stream = Streaming.input_string stream input in let stream = if newlines_between_reads then Streaming.input_string stream "\n" else stream in let%map () = Streaming.acc stream in stream) in let stream = Streaming.finish stream in Streaming.acc stream) ;; let pipe_of_chunks ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe = parse_pipe ~newlines_between_reads:false ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe ;; let pipe_of_lines ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe = parse_pipe ~newlines_between_reads:true ?strip ?start_line_number ?skip_lines ?sep ?quote ?header ?on_invalid_row builder input_pipe ;;
dbbf7fd8b19f3dad99a461de6649dd86cf9848073d7af0ec27bf6e3566f3db53
pepe/two-in-shadows
material.cljs
(ns two-in-shadows.client.material (:require [rum.core :as rum] ["@material/ripple" :as ripple] ["@material/textfield" :as text-field])) (def fixed-toolbar :header.mdc-toolbar.mdc-toolbar--fixed) (def toolbar-row :div.mdc-toolbar__row) (def toolbar-section-start :section.mdc-toolbar__section.mdc-toolbar__section--align-start) (def toolbar-section-end :section.mdc-toolbar__section.mdc-toolbar__section--align-end) (def toolbar-title :span.mdc-toolbar__title) (def adjust-fixed-toolbar [:div.mdc-toolbar-fixed-adjust]) (def card-media :div.mdc-card__media) (def title :div.mdc-typography--title) (def subheading :div.mdc-typography--subheading1) (def elevation-z2 :div.mdc-elevation--z2) (def ^:private attach-ripple {:did-mount (fn [state] (-> state rum/dom-node ripple/MDCRipple.attachTo) state)}) (def card-style {:width "30rem" :margin "1rem"}) (def card-primary {:width "30rem" :padding "1rem"}) (defn card-action-buttons "Scaffold for card action buttons" [& buttons] [:div.mdc-card__actions {:style {:display :flex :justify-content :flex-end}} [:div.mdc-card__action-buttons buttons]]) (defn card ([opts primary] (card opts primary nil)) ([opts primary actions] [:div.mdc-card (merge {:style card-style} opts) [:div {:style card-primary} primary] (when actions (card-action-buttons actions))])) (rum/defc Button < attach-ripple rum/static [opts label] [:button.mdc-button opts label]) (defn card-button [opts label] (Button (assoc opts :class "mdc-card__action mdc-card__action--button") label)) (def attach-text-field {:did-mount (fn [state] (-> state rum/dom-node text-field/MDCTextField.attachTo) state)}) (rum/defc TextField < attach-text-field rum/static [opts label] (let [id (str (:name opts) "-input") value (:value opts)] [:div.mdc-text-field [:input.mdc-text-field__input (merge {:id id} opts)] [:label.mdc-floating-label {:for (:name opts)} label] [:div.mdc-line-ripple]]))
null
https://raw.githubusercontent.com/pepe/two-in-shadows/b49a484cf1cc1a9a2e0a5ffb358acfe0f56d895c/src/two_in_shadows/client/material.cljs
clojure
(ns two-in-shadows.client.material (:require [rum.core :as rum] ["@material/ripple" :as ripple] ["@material/textfield" :as text-field])) (def fixed-toolbar :header.mdc-toolbar.mdc-toolbar--fixed) (def toolbar-row :div.mdc-toolbar__row) (def toolbar-section-start :section.mdc-toolbar__section.mdc-toolbar__section--align-start) (def toolbar-section-end :section.mdc-toolbar__section.mdc-toolbar__section--align-end) (def toolbar-title :span.mdc-toolbar__title) (def adjust-fixed-toolbar [:div.mdc-toolbar-fixed-adjust]) (def card-media :div.mdc-card__media) (def title :div.mdc-typography--title) (def subheading :div.mdc-typography--subheading1) (def elevation-z2 :div.mdc-elevation--z2) (def ^:private attach-ripple {:did-mount (fn [state] (-> state rum/dom-node ripple/MDCRipple.attachTo) state)}) (def card-style {:width "30rem" :margin "1rem"}) (def card-primary {:width "30rem" :padding "1rem"}) (defn card-action-buttons "Scaffold for card action buttons" [& buttons] [:div.mdc-card__actions {:style {:display :flex :justify-content :flex-end}} [:div.mdc-card__action-buttons buttons]]) (defn card ([opts primary] (card opts primary nil)) ([opts primary actions] [:div.mdc-card (merge {:style card-style} opts) [:div {:style card-primary} primary] (when actions (card-action-buttons actions))])) (rum/defc Button < attach-ripple rum/static [opts label] [:button.mdc-button opts label]) (defn card-button [opts label] (Button (assoc opts :class "mdc-card__action mdc-card__action--button") label)) (def attach-text-field {:did-mount (fn [state] (-> state rum/dom-node text-field/MDCTextField.attachTo) state)}) (rum/defc TextField < attach-text-field rum/static [opts label] (let [id (str (:name opts) "-input") value (:value opts)] [:div.mdc-text-field [:input.mdc-text-field__input (merge {:id id} opts)] [:label.mdc-floating-label {:for (:name opts)} label] [:div.mdc-line-ripple]]))
579fd21f0f11e79b5285e112ad23b060effd8bb737a99090afc67c9ff2e466c6
valis/hoq
Definitions.hs
module TypeChecking.Definitions ( typeCheckDefs ) where import Data.Void import Syntax import Syntax.ErrorDoc import TypeChecking.Expressions import TypeChecking.Expressions.Utils import TypeChecking.Definitions.Records import TypeChecking.Definitions.DataTypes import TypeChecking.Definitions.Functions import TypeChecking.Monad typeCheckDefs :: Monad m => [Def] -> TCM m () typeCheckDefs [] = return () typeCheckDefs (DefImport{} : defs) = typeCheckDefs defs typeCheckDefs (DefFixity{} : defs) = typeCheckDefs defs typeCheckDefs (DefType p@(pos, name) ty : defs) = case span (theSameAs name) defs of ([],_) -> do warn [Error Other $ emsgLC pos ("Missing a realization of function " ++ show (nameToString name)) enull] typeCheckDefs defs (defs1,defs2) -> do typeCheckFunction p ty (map (\d -> case d of DefFun (pos, _) pats expr -> (pos, pats, expr) _ -> error "typeCheckDefs") defs1) `catchError` \errs -> warn errs >> return () typeCheckDefs defs2 typeCheckDefs (DefFun p@(pos, name) [] (Just expr) : defs) = do (term, ty) <- typeCheck expr Nothing addFunctionCheck p ([([], closed term)]) $ Closed (vacuous ty) typeCheckDefs defs typeCheckDefs (DefFun (pos, name) [] Nothing : defs) = do warn [Error Other $ emsgLC pos "Expected right hand side" enull] typeCheckDefs $ dropWhile (theSameAs name) defs typeCheckDefs (DefFun (pos, name) _ _ : defs) = do warn [inferErrorMsg pos "the argument"] typeCheckDefs $ dropWhile (theSameAs name) defs typeCheckDefs (DefData dt ty cons conds : defs) = do typeCheckDataType dt ty cons conds typeCheckDefs defs typeCheckDefs (DefRecord name params mcon fields conds : defs) = do typeCheckRecord name params mcon fields conds typeCheckDefs defs theSameAs :: Name -> Def -> Bool theSameAs name (DefFun (_, name') _ _) = name == name' theSameAs _ _ = False
null
https://raw.githubusercontent.com/valis/hoq/9d2d2f5dee367ca5a609199856ca5964499bf33a/src/TypeChecking/Definitions.hs
haskell
module TypeChecking.Definitions ( typeCheckDefs ) where import Data.Void import Syntax import Syntax.ErrorDoc import TypeChecking.Expressions import TypeChecking.Expressions.Utils import TypeChecking.Definitions.Records import TypeChecking.Definitions.DataTypes import TypeChecking.Definitions.Functions import TypeChecking.Monad typeCheckDefs :: Monad m => [Def] -> TCM m () typeCheckDefs [] = return () typeCheckDefs (DefImport{} : defs) = typeCheckDefs defs typeCheckDefs (DefFixity{} : defs) = typeCheckDefs defs typeCheckDefs (DefType p@(pos, name) ty : defs) = case span (theSameAs name) defs of ([],_) -> do warn [Error Other $ emsgLC pos ("Missing a realization of function " ++ show (nameToString name)) enull] typeCheckDefs defs (defs1,defs2) -> do typeCheckFunction p ty (map (\d -> case d of DefFun (pos, _) pats expr -> (pos, pats, expr) _ -> error "typeCheckDefs") defs1) `catchError` \errs -> warn errs >> return () typeCheckDefs defs2 typeCheckDefs (DefFun p@(pos, name) [] (Just expr) : defs) = do (term, ty) <- typeCheck expr Nothing addFunctionCheck p ([([], closed term)]) $ Closed (vacuous ty) typeCheckDefs defs typeCheckDefs (DefFun (pos, name) [] Nothing : defs) = do warn [Error Other $ emsgLC pos "Expected right hand side" enull] typeCheckDefs $ dropWhile (theSameAs name) defs typeCheckDefs (DefFun (pos, name) _ _ : defs) = do warn [inferErrorMsg pos "the argument"] typeCheckDefs $ dropWhile (theSameAs name) defs typeCheckDefs (DefData dt ty cons conds : defs) = do typeCheckDataType dt ty cons conds typeCheckDefs defs typeCheckDefs (DefRecord name params mcon fields conds : defs) = do typeCheckRecord name params mcon fields conds typeCheckDefs defs theSameAs :: Name -> Def -> Bool theSameAs name (DefFun (_, name') _ _) = name == name' theSameAs _ _ = False
0e7ea3030cd1599fd62dc4a8becf3ff45eba3ccd27795ec5b027dbb414c8a3eb
pink-gorilla/demo-goldly
quil.cljs
(ns qil-demo (:require [reagent.core :as reagent :refer [atom]] [quil.core :as q :include-macros true] [quil.middleware :as m])) (def w 400) (def h 400) (defn setup [] {:t 1}) (defn update [state] (update-in state [:t] inc)) (defn draw [state] (q/background 255) (q/fill 0) (q/ellipse (rem (:t state) w) 46 55 55)) (q/defsketch foo :setup setup :update update :draw draw :host "foo" :no-start true :middleware [m/fun-mode] :size [w h]) (defn hello-world [] (reagent/create-class {:reagent-render (fn [] [:canvas#foo {:width w :height h}]) :component-did-mount foo})) (reagent/render-component [hello-world] (. js/document (getElementById "app"))) ;;; - -project/reagent-cookbook/tree/master/recipes/canvas-fills-div ;;; - -03-30-Interactive-Sierpinski-Triangle/ ;;; - ;;; - -sketch-on-a-reagent-canvas ;;; - -project/reagent-cookbook/tree/master/recipes/canvas-fills-div ;;; - ;;; - -02-16-Random-Polygons/ ;; **
null
https://raw.githubusercontent.com/pink-gorilla/demo-goldly/a3edeefc2a164fa38beb877b60bfa76b9b1faad6/src/notebook/bad/quil.cljs
clojure
- -project/reagent-cookbook/tree/master/recipes/canvas-fills-div - -03-30-Interactive-Sierpinski-Triangle/ - - -sketch-on-a-reagent-canvas - -project/reagent-cookbook/tree/master/recipes/canvas-fills-div - - -02-16-Random-Polygons/ **
(ns qil-demo (:require [reagent.core :as reagent :refer [atom]] [quil.core :as q :include-macros true] [quil.middleware :as m])) (def w 400) (def h 400) (defn setup [] {:t 1}) (defn update [state] (update-in state [:t] inc)) (defn draw [state] (q/background 255) (q/fill 0) (q/ellipse (rem (:t state) w) 46 55 55)) (q/defsketch foo :setup setup :update update :draw draw :host "foo" :no-start true :middleware [m/fun-mode] :size [w h]) (defn hello-world [] (reagent/create-class {:reagent-render (fn [] [:canvas#foo {:width w :height h}]) :component-did-mount foo})) (reagent/render-component [hello-world] (. js/document (getElementById "app")))
bcc4533074c0d605403179f7c5a47dad4f63566cda2b0b887f1bfa046e7cce99
luksamuk/sonic-lisp-engine
globals.lisp
;;;; globals.lisp Copyright ( c ) 2018 - 2020 < > This file is distributed under the MIT License . ;;;; See LICENSE for details. (in-package :sonic-lisp) (defvar +black+ (gamekit:vec4 0 0 0 1)) (defvar +black-transp+ (gamekit:vec4 0 0 0 0.5)) (defvar +white+ (gamekit:vec4 1 1 1 1)) (defvar +cornflower-blue+ (gamekit:vec4 (/ 100 255) (/ 149 255) (/ 237 255))) (defvar +origin+ (gamekit:vec2 0 0)) (defvar *dt* 0) (defvar *fps* 60) (defvar *last-check* (get-internal-real-time)) (defparameter *basic-rendering-ok* nil) (defparameter *game-start* nil) (defvar *game-properties* `(:title "Sonic Engine" :window-width 640 :window-height 360 :background ,+cornflower-blue+)) (defmacro gameprop (property) `(getf *game-properties* ,property)) (gamekit:defgame sonic-game () () (:viewport-title (gameprop :title)) (:viewport-width 960) (:viewport-height 540) (:prepare-resources nil)) (gamekit:register-resource-package :keyword (merge-pathnames "resources/" (asdf:system-relative-pathname :sonic-lisp ""))) (gamekit:define-image :sonic-sprites "sprites/sonic.png") ;; Level BGM Missing levels : 2 , 3 , 4 , 7 , 9 (gamekit:define-sound :bgm-level0 "bgm/level0.ogg") (gamekit:define-sound :bgm-level1 "bgm/level1.ogg") (gamekit:define-sound :bgm-level3 "bgm/level3.ogg") (gamekit:define-sound :bgm-level5 "bgm/level5.ogg") (gamekit:define-sound :bgm-level6 "bgm/level6.ogg") (gamekit:define-sound :bgm-level8 "bgm/level8.ogg") (gamekit:define-sound :bgm-levelA "bgm/levelA.ogg") (gamekit:define-sound :bgm-levelB "bgm/levelB.ogg") (gamekit:define-sound :bgm-levelC "bgm/levelC.ogg") ;; Engine test BGM (gamekit:define-sound :bgm-test0 "bgm/test0.ogg") (gamekit:define-sound :bgm-test1 "bgm/test1.ogg") (gamekit:define-sound :bgm-test2 "bgm/test2.ogg") ;; Miscellaneous BGM (gamekit:define-sound :bgm-menu "bgm/menu_select.ogg") (gamekit:define-sound :bgm-power "bgm/powerup.ogg") (defparameter *level-bgm* :bgm-level3) ; YOU SAY! (gamekit:define-sound :sfx-skidding "sfx/00_skidding.ogg") (gamekit:define-sound :sfx-jump "sfx/02_jump.ogg") (gamekit:define-sound :sfx-spindash "sfx/03_spindash.ogg") (gamekit:define-sound :sfx-release "sfx/04_release.ogg") (gamekit:define-font :gohufont "fonts/gohufont-uni-11.ttf") (defparameter *font-gohu-11* nil) (gamekit:define-image :bg-layer0 "bg/level6/parallax/layer0.png") (gamekit:define-image :bg-layer1 "bg/level6/parallax/layer1.png") (gamekit:define-image :bg-layer2 "bg/level6/parallax/layer2.png") (gamekit:define-image :bg-layer3 "bg/level6/parallax/layer3.png") (gamekit:define-image :bg-layer4 "bg/level6/parallax/layer4.png") (gamekit:define-image :bg-layer5 "bg/level6/parallax/layer5.png")
null
https://raw.githubusercontent.com/luksamuk/sonic-lisp-engine/28987769a8c60411862a415010e44c495c4ea875/globals.lisp
lisp
globals.lisp See LICENSE for details. Level BGM Engine test BGM Miscellaneous BGM YOU SAY!
Copyright ( c ) 2018 - 2020 < > This file is distributed under the MIT License . (in-package :sonic-lisp) (defvar +black+ (gamekit:vec4 0 0 0 1)) (defvar +black-transp+ (gamekit:vec4 0 0 0 0.5)) (defvar +white+ (gamekit:vec4 1 1 1 1)) (defvar +cornflower-blue+ (gamekit:vec4 (/ 100 255) (/ 149 255) (/ 237 255))) (defvar +origin+ (gamekit:vec2 0 0)) (defvar *dt* 0) (defvar *fps* 60) (defvar *last-check* (get-internal-real-time)) (defparameter *basic-rendering-ok* nil) (defparameter *game-start* nil) (defvar *game-properties* `(:title "Sonic Engine" :window-width 640 :window-height 360 :background ,+cornflower-blue+)) (defmacro gameprop (property) `(getf *game-properties* ,property)) (gamekit:defgame sonic-game () () (:viewport-title (gameprop :title)) (:viewport-width 960) (:viewport-height 540) (:prepare-resources nil)) (gamekit:register-resource-package :keyword (merge-pathnames "resources/" (asdf:system-relative-pathname :sonic-lisp ""))) (gamekit:define-image :sonic-sprites "sprites/sonic.png") Missing levels : 2 , 3 , 4 , 7 , 9 (gamekit:define-sound :bgm-level0 "bgm/level0.ogg") (gamekit:define-sound :bgm-level1 "bgm/level1.ogg") (gamekit:define-sound :bgm-level3 "bgm/level3.ogg") (gamekit:define-sound :bgm-level5 "bgm/level5.ogg") (gamekit:define-sound :bgm-level6 "bgm/level6.ogg") (gamekit:define-sound :bgm-level8 "bgm/level8.ogg") (gamekit:define-sound :bgm-levelA "bgm/levelA.ogg") (gamekit:define-sound :bgm-levelB "bgm/levelB.ogg") (gamekit:define-sound :bgm-levelC "bgm/levelC.ogg") (gamekit:define-sound :bgm-test0 "bgm/test0.ogg") (gamekit:define-sound :bgm-test1 "bgm/test1.ogg") (gamekit:define-sound :bgm-test2 "bgm/test2.ogg") (gamekit:define-sound :bgm-menu "bgm/menu_select.ogg") (gamekit:define-sound :bgm-power "bgm/powerup.ogg") (gamekit:define-sound :sfx-skidding "sfx/00_skidding.ogg") (gamekit:define-sound :sfx-jump "sfx/02_jump.ogg") (gamekit:define-sound :sfx-spindash "sfx/03_spindash.ogg") (gamekit:define-sound :sfx-release "sfx/04_release.ogg") (gamekit:define-font :gohufont "fonts/gohufont-uni-11.ttf") (defparameter *font-gohu-11* nil) (gamekit:define-image :bg-layer0 "bg/level6/parallax/layer0.png") (gamekit:define-image :bg-layer1 "bg/level6/parallax/layer1.png") (gamekit:define-image :bg-layer2 "bg/level6/parallax/layer2.png") (gamekit:define-image :bg-layer3 "bg/level6/parallax/layer3.png") (gamekit:define-image :bg-layer4 "bg/level6/parallax/layer4.png") (gamekit:define-image :bg-layer5 "bg/level6/parallax/layer5.png")
e6a99e89f798fdc8fe824d18eb59b84932a4f82dc1eb7cf718851db08a2a5e84
nyu-acsys/drift
app-nonrec.ml
let apply (ab:int) (af: int->unit) ax = af ax let check (cx:int) (cy:int) = assert (cx = cy) let main_p (n:int) = apply n (check n) n let main (w:unit) = let _ = main_p 2 in let _ = for i = 1 to 1000000 do main ( Random.int 1000 ) done for i = 1 to 1000000 do main (Random.int 1000) done *) () let _ = main ()
null
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/DOrder/high/app-nonrec.ml
ocaml
let apply (ab:int) (af: int->unit) ax = af ax let check (cx:int) (cy:int) = assert (cx = cy) let main_p (n:int) = apply n (check n) n let main (w:unit) = let _ = main_p 2 in let _ = for i = 1 to 1000000 do main ( Random.int 1000 ) done for i = 1 to 1000000 do main (Random.int 1000) done *) () let _ = main ()
86793292d355ba6b41e489c97b5b7a43dbaee9dbaae9d67314cfa1f2f334328d
mpickering/apply-refact
Default54.hs
yes = id 1
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Default54.hs
haskell
yes = id 1
c1c0424b33fd9c83f7f640e0fe936702a215138ac151ff5a8ff4858b2d2c8620
artyom-poptsov/guile-smc
guix.scm
guix.scm --- GNU Guix package recipe -*- coding : utf-8 -*- ;; Copyright ( C ) 2021 - 2022 Artyom V. Poptsov < > ;; This file is part of Guile - SMC . ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; The program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with the program. If not, see </>. ;;; Commentary: ;; ;; GNU Guix development package. To use as the basis for a development ;; environment, run: ;; ;; guix environment --pure --container -l guix.scm ;; ;; In the new shell, run: ;; ;; autoreconf -vif && ./configure && make check ;; ;;; Code: (use-modules (guix gexp) (guix packages) (guix licenses) (guix git-download) (guix build-system gnu) (gnu packages autotools) (gnu packages guile) (gnu packages base) (gnu packages bash) (gnu packages admin) (gnu packages guile-xyz) (gnu packages pkg-config) (gnu packages texinfo) (gnu packages tex) (gnu packages man)) (define %source-dir (dirname (current-filename))) (define-public guile-smc (package (name "guile-smc") (version "git") (source (local-file %source-dir #:recursive? #t #:select? (git-predicate %source-dir))) (build-system gnu-build-system) (arguments `(#:make-flags '("GUILE_AUTO_COMPILE=0") ;to prevent guild warnings #:modules (((guix build guile-build-system) #:select (target-guile-effective-version)) ,@%gnu-build-system-modules) #:imported-modules ((guix build guile-build-system) ,@%gnu-build-system-modules) #:phases (modify-phases %standard-phases (delete 'strip) (add-after 'install 'wrap-program (lambda* (#:key inputs outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin")) (guile-lib (assoc-ref inputs "guile-lib")) (version (target-guile-effective-version)) (scm (string-append "/share/guile/site/" version)) (go (string-append "/lib/guile/" version "/site-ccache"))) (wrap-program (string-append bin "/smc") `("GUILE_LOAD_PATH" prefix (,(string-append out scm) ,(string-append guile-lib scm))) `("GUILE_LOAD_COMPILED_PATH" prefix (,(string-append out go) ,(string-append guile-lib go))))) #t))))) (native-inputs (list autoconf automake pkg-config help2man texinfo which texlive)) (inputs (list bash-minimal guile-3.0 guile-lib inetutils)) (home-page "-poptsov/guile-smc") (synopsis "GNU Guile state machine compiler") (description "Guile-SMC is a state machine compiler that allows users to describe finite state machines (FSMs) in Scheme in terms of transition tables. It is capable to generate such transition tables from a @url{/, PlantUML} state diagrams. A transition table can be verified and checked for dead-ends and infinite loops. Also Guile-SMC FSMs gather statistics when they run. Guile-SMC comes with a Scheme program called @command{smc} -- a state machine compiler itself. It produces a Scheme code for an FSM from the PlantUML format. This tool is meant to be called on a PlantUML file when a program with a FSM is being built (for example, from a Makefile.)") (license gpl3))) guile-smc
null
https://raw.githubusercontent.com/artyom-poptsov/guile-smc/f997f138642c77afd430af0b52dea8b2b7a6875f/guix.scm
scheme
This program is free software: you can redistribute it and/or modify (at your option) any later version. The program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with the program. If not, see </>. Commentary: GNU Guix development package. To use as the basis for a development environment, run: guix environment --pure --container -l guix.scm In the new shell, run: autoreconf -vif && ./configure && make check Code: to prevent guild warnings
guix.scm --- GNU Guix package recipe -*- coding : utf-8 -*- Copyright ( C ) 2021 - 2022 Artyom V. Poptsov < > This file is part of Guile - SMC . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License (use-modules (guix gexp) (guix packages) (guix licenses) (guix git-download) (guix build-system gnu) (gnu packages autotools) (gnu packages guile) (gnu packages base) (gnu packages bash) (gnu packages admin) (gnu packages guile-xyz) (gnu packages pkg-config) (gnu packages texinfo) (gnu packages tex) (gnu packages man)) (define %source-dir (dirname (current-filename))) (define-public guile-smc (package (name "guile-smc") (version "git") (source (local-file %source-dir #:recursive? #t #:select? (git-predicate %source-dir))) (build-system gnu-build-system) (arguments #:modules (((guix build guile-build-system) #:select (target-guile-effective-version)) ,@%gnu-build-system-modules) #:imported-modules ((guix build guile-build-system) ,@%gnu-build-system-modules) #:phases (modify-phases %standard-phases (delete 'strip) (add-after 'install 'wrap-program (lambda* (#:key inputs outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin")) (guile-lib (assoc-ref inputs "guile-lib")) (version (target-guile-effective-version)) (scm (string-append "/share/guile/site/" version)) (go (string-append "/lib/guile/" version "/site-ccache"))) (wrap-program (string-append bin "/smc") `("GUILE_LOAD_PATH" prefix (,(string-append out scm) ,(string-append guile-lib scm))) `("GUILE_LOAD_COMPILED_PATH" prefix (,(string-append out go) ,(string-append guile-lib go))))) #t))))) (native-inputs (list autoconf automake pkg-config help2man texinfo which texlive)) (inputs (list bash-minimal guile-3.0 guile-lib inetutils)) (home-page "-poptsov/guile-smc") (synopsis "GNU Guile state machine compiler") (description "Guile-SMC is a state machine compiler that allows users to describe finite state machines (FSMs) in Scheme in terms of transition tables. It is capable to generate such transition tables from a @url{/, PlantUML} state diagrams. A transition table can be verified and checked for dead-ends and infinite loops. Also Guile-SMC FSMs gather statistics when they run. Guile-SMC comes with a Scheme program called @command{smc} -- a state machine compiler itself. It produces a Scheme code for an FSM from the PlantUML format. This tool is meant to be called on a PlantUML file when a program with a FSM is being built (for example, from a Makefile.)") (license gpl3))) guile-smc
7a8b91378d6fe7d16fff401f62936b41bb582f0774bea97de7bd70685db70d31
sky-big/RabbitMQ
rabbit_connection_sup.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_connection_sup). -behaviour(supervisor2). -export([start_link/0, reader/1]). -export([init/1]). -include("rabbit.hrl"). %%---------------------------------------------------------------------------- -ifdef(use_specs). -spec(start_link/0 :: () -> {'ok', pid(), pid()}). -spec(reader/1 :: (pid()) -> pid()). -endif. %%-------------------------------------------------------------------------- %% 单个客户端进程监控树中的最上层监督进程 start_link() -> 启动rabbit_connection_sup监督进程 {ok, SupPid} = supervisor2:start_link(?MODULE, []), %% We need to get channels in the hierarchy(阶层) here so they get shut %% down after the reader, so the reader gets a chance to terminate them cleanly . But for 1.0 readers we ca n't start the real ch_sup_sup ( because we do n't know if we will be 0 - 9 - 1 or 1.0 ) - %% so we add another supervisor into the hierarchy. %% %% This supervisor also acts as an intermediary(中介) for heartbeaters and %% the queue collector process, since these must not be siblings(兄弟姐妹) of the %% reader due to the potential(潜在的) for deadlock if they are added/restarted %% whilst the supervision tree is shutting down. 在rabbit_connection_sup监督进程下启动rabbit_connection_helper_sup监督进程 intrinsic如果child非正常退出(normal , { shutdown , _ } ( { shutdown , restart})这些都是正常退出,其他的都是异常退出,异常退出intrinsic会重启该子进程,否则会将该监督进程下的其他子进程删除掉 ) %% supervisor也会退出并删除其他所有children。 {ok, HelperSup} = supervisor2:start_child( SupPid, {helper_sup, {rabbit_connection_helper_sup, start_link, []}, intrinsic, infinity, supervisor, [rabbit_connection_helper_sup]}), %% 在rabbit_connection_sup监督进程下启动rabbit_reader进程 intrinsic如果child非正常退出(normal , { shutdown , _ } ( { shutdown , restart})这些都是正常退出,其他的都是异常退出,异常退出intrinsic会重启该子进程,否则会将该监督进程下的其他子进程删除掉 ) %% supervisor也会退出并删除其他所有children。 {ok, ReaderPid} = supervisor2:start_child( SupPid, {reader, {rabbit_reader, start_link, [HelperSup]}, intrinsic, ?MAX_WAIT, worker, [rabbit_reader]}), {ok, SupPid, ReaderPid}. reader(Pid) -> hd(supervisor2:find_child(Pid, reader)). %%-------------------------------------------------------------------------- init([]) -> {ok, {{one_for_all, 0, 1}, []}}.
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/src/rabbit_connection_sup.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. ---------------------------------------------------------------------------- -------------------------------------------------------------------------- 单个客户端进程监控树中的最上层监督进程 We need to get channels in the hierarchy(阶层) here so they get shut down after the reader, so the reader gets a chance to terminate so we add another supervisor into the hierarchy. This supervisor also acts as an intermediary(中介) for heartbeaters and the queue collector process, since these must not be siblings(兄弟姐妹) of the reader due to the potential(潜在的) for deadlock if they are added/restarted whilst the supervision tree is shutting down. supervisor也会退出并删除其他所有children。 在rabbit_connection_sup监督进程下启动rabbit_reader进程 supervisor也会退出并删除其他所有children。 --------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_connection_sup). -behaviour(supervisor2). -export([start_link/0, reader/1]). -export([init/1]). -include("rabbit.hrl"). -ifdef(use_specs). -spec(start_link/0 :: () -> {'ok', pid(), pid()}). -spec(reader/1 :: (pid()) -> pid()). -endif. start_link() -> 启动rabbit_connection_sup监督进程 {ok, SupPid} = supervisor2:start_link(?MODULE, []), them cleanly . But for 1.0 readers we ca n't start the real ch_sup_sup ( because we do n't know if we will be 0 - 9 - 1 or 1.0 ) - 在rabbit_connection_sup监督进程下启动rabbit_connection_helper_sup监督进程 intrinsic如果child非正常退出(normal , { shutdown , _ } ( { shutdown , restart})这些都是正常退出,其他的都是异常退出,异常退出intrinsic会重启该子进程,否则会将该监督进程下的其他子进程删除掉 ) {ok, HelperSup} = supervisor2:start_child( SupPid, {helper_sup, {rabbit_connection_helper_sup, start_link, []}, intrinsic, infinity, supervisor, [rabbit_connection_helper_sup]}), intrinsic如果child非正常退出(normal , { shutdown , _ } ( { shutdown , restart})这些都是正常退出,其他的都是异常退出,异常退出intrinsic会重启该子进程,否则会将该监督进程下的其他子进程删除掉 ) {ok, ReaderPid} = supervisor2:start_child( SupPid, {reader, {rabbit_reader, start_link, [HelperSup]}, intrinsic, ?MAX_WAIT, worker, [rabbit_reader]}), {ok, SupPid, ReaderPid}. reader(Pid) -> hd(supervisor2:find_child(Pid, reader)). init([]) -> {ok, {{one_for_all, 0, 1}, []}}.
9edfbd488aac245607bd9d7ca40b29f830e1b64370d7ca1a373feaa77c248f35
ds-wizard/engine-backend
DocumentDTO.hs
module Wizard.Api.Resource.Document.DocumentDTO where import Data.Time import qualified Data.UUID as U import GHC.Generics import GHC.Int import Wizard.Api.Resource.DocumentTemplate.DocumentTemplateSimpleDTO import Wizard.Api.Resource.DocumentTemplate.DocumentTemplateSimpleJM () import Wizard.Api.Resource.Submission.SubmissionDTO import Wizard.Api.Resource.Submission.SubmissionJM () import Wizard.Model.Document.Document import Wizard.Model.Questionnaire.QuestionnaireSimple data DocumentDTO = DocumentDTO { uuid :: U.UUID , name :: String , state :: DocumentState , questionnaire :: Maybe QuestionnaireSimple , questionnaireEventUuid :: Maybe U.UUID , documentTemplate :: DocumentTemplateSimpleDTO , formatUuid :: U.UUID , fileName :: Maybe String , contentType :: Maybe String , fileSize :: Maybe Int64 , workerLog :: Maybe String , submissions :: [SubmissionDTO] , creatorUuid :: Maybe U.UUID , createdAt :: UTCTime } deriving (Show, Eq, Generic)
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/src/Wizard/Api/Resource/Document/DocumentDTO.hs
haskell
module Wizard.Api.Resource.Document.DocumentDTO where import Data.Time import qualified Data.UUID as U import GHC.Generics import GHC.Int import Wizard.Api.Resource.DocumentTemplate.DocumentTemplateSimpleDTO import Wizard.Api.Resource.DocumentTemplate.DocumentTemplateSimpleJM () import Wizard.Api.Resource.Submission.SubmissionDTO import Wizard.Api.Resource.Submission.SubmissionJM () import Wizard.Model.Document.Document import Wizard.Model.Questionnaire.QuestionnaireSimple data DocumentDTO = DocumentDTO { uuid :: U.UUID , name :: String , state :: DocumentState , questionnaire :: Maybe QuestionnaireSimple , questionnaireEventUuid :: Maybe U.UUID , documentTemplate :: DocumentTemplateSimpleDTO , formatUuid :: U.UUID , fileName :: Maybe String , contentType :: Maybe String , fileSize :: Maybe Int64 , workerLog :: Maybe String , submissions :: [SubmissionDTO] , creatorUuid :: Maybe U.UUID , createdAt :: UTCTime } deriving (Show, Eq, Generic)
36b999c4946e4b7609cec309091249005dff03d086cf570efe08b2fcb06bda27
ghcjs/ghcjs
carryOverflow.hs
# LANGUAGE MagicHash , UnboxedTuples # import GHC.Prim import GHC.Word import GHC.Exts import Control.Monad import Data.Bits import Data.List import System.Exit allEqual :: Eq a => [a] -> Bool allEqual [] = error "allEqual: nothing to compare" allEqual (x:xs) = all (== x) xs testWords :: [Word] testWords = map head . group . sort $ concatMap (\w -> [w - 1, w, w + 1]) $ concatMap (\w -> [w, maxBound - w]) $ trailingOnes ++ randoms where trailingOnes = takeWhile (/= 0) $ iterate (`div` 2) $ maxBound What would a program be without some Fibonacci numbers ? randoms = take 40 $ drop 100 fibs fibs = 0 : 1 : zipWith (+) fibs (tail fibs) wordSizeInBits :: Int wordSizeInBits = length $ takeWhile (/= 0) $ iterate (`div` 2) (maxBound :: Word) -- plusWord2# (Word# carry) ways_plusWord2# :: [Word -> Word -> Bool] ways_plusWord2# = [ltTest, integerTest, primopTest] where ltTest x y = let r = x + y in r < x integerTest x y = let r = fromIntegral x + fromIntegral y :: Integer in r > fromIntegral (maxBound :: Word) primopTest (W# x) (W# y) = case plusWord2# x y of (# 0##, _ #) -> False (# 1##, _ #) -> True _ -> error "unexpected result from plusWord2#" -- addIntC# (Int# addition overflow) ways_addIntC# :: [Int -> Int -> Bool] ways_addIntC# = [ltTest, integerTest, highBitTest, primopTest] where ltTest x y = let r = x + y in (y > 0 && r < x) || (y < 0 && r > x) integerTest x y = let r = fromIntegral x + fromIntegral y :: Integer in r < fromIntegral (minBound :: Int) || r > fromIntegral (maxBound :: Int) highBitTest x y = let r = x + y in testBit ((x `xor` r) .&. (y `xor` r)) (wordSizeInBits - 1) primopTest (I# x) (I# y) = case addIntC# x y of (# _, 0# #) -> False _ -> True -- subIntC# (Int# subtraction overflow) ways_subIntC# :: [Int -> Int -> Bool] ways_subIntC# = [ltTest, integerTest, highBitTest, primopTest] where ltTest x y = let r = x - y in (y > 0 && r > x) || (y < 0 && r < x) integerTest x y = let r = fromIntegral x - fromIntegral y :: Integer in r < fromIntegral (minBound :: Int) || r > fromIntegral (maxBound :: Int) highBitTest x y = let r = x - y in testBit ((x `xor` r) .&. complement (y `xor` r)) (wordSizeInBits - 1) primopTest (I# x) (I# y) = case subIntC# x y of (# _, 0# #) -> False _ -> True runTest :: Show a => String -> [a -> a -> Bool] -> a -> a -> IO () runTest label ways x y = do let results = map (\f -> f x y) ways unless (allEqual results) $ do putStrLn $ "Failed (" ++ label ++ "): " ++ show (x,y) ++ " " ++ show results exitWith (ExitFailure 1) main :: IO () main = do forM_ testWords $ \x -> forM_ testWords $ \y -> do runTest "ways_plusWord2#" ways_plusWord2# x y runTest "ways_addIntC#" ways_addIntC# (fromIntegral x) (fromIntegral y) runTest "ways_subIntC#" ways_subIntC# (fromIntegral x) (fromIntegral y) putStrLn "Passed"
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/numeric/carryOverflow.hs
haskell
plusWord2# (Word# carry) addIntC# (Int# addition overflow) subIntC# (Int# subtraction overflow)
# LANGUAGE MagicHash , UnboxedTuples # import GHC.Prim import GHC.Word import GHC.Exts import Control.Monad import Data.Bits import Data.List import System.Exit allEqual :: Eq a => [a] -> Bool allEqual [] = error "allEqual: nothing to compare" allEqual (x:xs) = all (== x) xs testWords :: [Word] testWords = map head . group . sort $ concatMap (\w -> [w - 1, w, w + 1]) $ concatMap (\w -> [w, maxBound - w]) $ trailingOnes ++ randoms where trailingOnes = takeWhile (/= 0) $ iterate (`div` 2) $ maxBound What would a program be without some Fibonacci numbers ? randoms = take 40 $ drop 100 fibs fibs = 0 : 1 : zipWith (+) fibs (tail fibs) wordSizeInBits :: Int wordSizeInBits = length $ takeWhile (/= 0) $ iterate (`div` 2) (maxBound :: Word) ways_plusWord2# :: [Word -> Word -> Bool] ways_plusWord2# = [ltTest, integerTest, primopTest] where ltTest x y = let r = x + y in r < x integerTest x y = let r = fromIntegral x + fromIntegral y :: Integer in r > fromIntegral (maxBound :: Word) primopTest (W# x) (W# y) = case plusWord2# x y of (# 0##, _ #) -> False (# 1##, _ #) -> True _ -> error "unexpected result from plusWord2#" ways_addIntC# :: [Int -> Int -> Bool] ways_addIntC# = [ltTest, integerTest, highBitTest, primopTest] where ltTest x y = let r = x + y in (y > 0 && r < x) || (y < 0 && r > x) integerTest x y = let r = fromIntegral x + fromIntegral y :: Integer in r < fromIntegral (minBound :: Int) || r > fromIntegral (maxBound :: Int) highBitTest x y = let r = x + y in testBit ((x `xor` r) .&. (y `xor` r)) (wordSizeInBits - 1) primopTest (I# x) (I# y) = case addIntC# x y of (# _, 0# #) -> False _ -> True ways_subIntC# :: [Int -> Int -> Bool] ways_subIntC# = [ltTest, integerTest, highBitTest, primopTest] where ltTest x y = let r = x - y in (y > 0 && r > x) || (y < 0 && r < x) integerTest x y = let r = fromIntegral x - fromIntegral y :: Integer in r < fromIntegral (minBound :: Int) || r > fromIntegral (maxBound :: Int) highBitTest x y = let r = x - y in testBit ((x `xor` r) .&. complement (y `xor` r)) (wordSizeInBits - 1) primopTest (I# x) (I# y) = case subIntC# x y of (# _, 0# #) -> False _ -> True runTest :: Show a => String -> [a -> a -> Bool] -> a -> a -> IO () runTest label ways x y = do let results = map (\f -> f x y) ways unless (allEqual results) $ do putStrLn $ "Failed (" ++ label ++ "): " ++ show (x,y) ++ " " ++ show results exitWith (ExitFailure 1) main :: IO () main = do forM_ testWords $ \x -> forM_ testWords $ \y -> do runTest "ways_plusWord2#" ways_plusWord2# x y runTest "ways_addIntC#" ways_addIntC# (fromIntegral x) (fromIntegral y) runTest "ways_subIntC#" ways_subIntC# (fromIntegral x) (fromIntegral y) putStrLn "Passed"
3ed2d97e43a5014f6e2d79b80bd19e2e18f7d44d6220808886ab2f934ed26ba5
albertoruiz/easyVision
Image.hs
module Image ( Image(), Size(..), ROI(..), Pixel(..), Point(..), I8u, I8u3, I32f, Word24(..), Gray, RGB, Channels(..), size, roi, modifyROI, setROI, saveImage, loadRGB, img2mat, mat2img, ) where import Image.Core import Image.Convert import Util.Geometry(Point(..)) data Channels = CHIm { yuv :: ImageYUV , yCh :: Image I8u , uCh :: Image I8u , vCh :: Image I8u , rgb :: Image Word24 , rCh :: Image I8u , gCh :: Image I8u , bCh :: Image I8u , hsv :: Image Word24 , hCh :: Image I8u , sCh :: Image I8u , fCh :: Image Float }
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/packages/base/src/Image.hs
haskell
module Image ( Image(), Size(..), ROI(..), Pixel(..), Point(..), I8u, I8u3, I32f, Word24(..), Gray, RGB, Channels(..), size, roi, modifyROI, setROI, saveImage, loadRGB, img2mat, mat2img, ) where import Image.Core import Image.Convert import Util.Geometry(Point(..)) data Channels = CHIm { yuv :: ImageYUV , yCh :: Image I8u , uCh :: Image I8u , vCh :: Image I8u , rgb :: Image Word24 , rCh :: Image I8u , gCh :: Image I8u , bCh :: Image I8u , hsv :: Image Word24 , hCh :: Image I8u , sCh :: Image I8u , fCh :: Image Float }
97c669be0c6ac3e490fde2e73d5de3c0732ad1bf8b5713cadc4256f038980e29
sorawee/fmt
kws.rkt
#lang racket/base (provide get-kws) (require racket/match pprint-compact (only-in fmt/conventions all-kws)) (define (flow xs) (match xs ['() empty-doc] [(cons x xs) (let loop ([xs xs] [acc (text x)]) (match xs ['() acc] [(list x xs ...) (define elem (text x)) (loop xs (alt (v-append acc elem) (hs-append acc elem)))]))])) (define (get-kws) (define xs (sort all-kws string<?)) (pretty-format (flow xs) #:width 64))
null
https://raw.githubusercontent.com/sorawee/fmt/2a068a29a7e043d88317a31d3fc0b6cc3de6d592/scribblings/kws.rkt
racket
#lang racket/base (provide get-kws) (require racket/match pprint-compact (only-in fmt/conventions all-kws)) (define (flow xs) (match xs ['() empty-doc] [(cons x xs) (let loop ([xs xs] [acc (text x)]) (match xs ['() acc] [(list x xs ...) (define elem (text x)) (loop xs (alt (v-append acc elem) (hs-append acc elem)))]))])) (define (get-kws) (define xs (sort all-kws string<?)) (pretty-format (flow xs) #:width 64))
136d9818582f8bdfdd02e6c43ba84aa42cda67acea84c227fa7a7a5a60e0f00d
symbiont-io/detsys-testkit
LineariseWithFault.hs
# LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE ScopedTypeVariables # module Lec04.LineariseWithFault where import Control.Concurrent.STM (TQueue, atomically, writeTQueue) import Data.Tree (Forest, Tree(Node)) import Test.QuickCheck hiding (Result) import Lec01SMTesting (Command, Response) import Lec02ConcurrentSMTesting (Pid(..)) ------------------------------------------------------------------------ newtype History' cmd resp = History [Operation' cmd resp] deriving (Show, Functor, Foldable) prettyHistory :: (Show cmd, Show resp) => History' cmd resp -> String prettyHistory = show type History = History' Command Response data FailureMode = FAIL | INFO deriving Show XXX : We probably do n't want to use Pid = ThreadId here , because if we have an INFO we do n't want any further operations executed by that Pid . data Operation' cmd resp = Invoke Pid cmd | Ok Pid resp | Fail Pid FailureMode -- should this has a cmd? deriving (Show, Functor, Foldable) type Operation = Operation' Command Response appendHistory :: TQueue (Operation' cmd resp) -> Operation' cmd resp -> IO () appendHistory hist op = atomically (writeTQueue hist op) data Result resp = OkWithResponse resp | OkWithNoResponse deriving Show isValidConcurrentHistory :: History' cmd resp -> Either String () isValidConcurrentHistory (History xs) = go [] [] xs where go _runningPids _infoPids [] = Right () go runningPids infoPids (op:ops) = case op of Invoke pid _ | pid `elem` runningPids -> Left $ show pid ++ " is already running. Each pid should only run one command at a time." | pid `elem` infoPids -> Left $ show pid ++ " have already returned an INFO and shouldn't make any more comands. But we see an INVOKE." | otherwise -> go (pid:runningPids) infoPids ops Ok pid _ -> go (filter (/= pid) runningPids) infoPids ops Fail pid FAIL -> go (filter (/= pid) runningPids) infoPids ops Fail pid INFO -> go (filter (/= pid) runningPids) (pid:infoPids) ops interleavings :: History' cmd resp -> Forest (cmd, Result resp) interleavings (History []) = [] interleavings (History ops) | all (not . isOk) ops = [] where isOk :: Operation' cmd resp -> Bool isOk (Ok{}) = True isOk _ = False interleavings (History ops0) = [ Node (cmd, resp) (interleavings (History ops')) | (tid, cmd) <- takeInvocations ops0 , (resp, ops') <- findResponse tid (filter1 (not . matchInvocation tid) ops0) ] where takeInvocations :: [Operation' cmd resp] -> [(Pid, cmd)] takeInvocations [] = [] takeInvocations ((Invoke pid cmd) : ops) = (pid, cmd) : takeInvocations ops takeInvocations ((Ok _pid _resp) : _) = [] takeInvocations ((Fail _pid _mode) : ops) = takeInvocations ops findResponse :: Pid -> [Operation' cmd resp] -> [(Result resp, [Operation' cmd resp])] findResponse _pid [] = [] findResponse pid ((Ok pid' resp) : ops) | pid == pid' = [(OkWithResponse resp, ops)] findResponse pid ((Fail pid' mode) : ops) | pid == pid' = case mode of FAIL -> [] INFO -> [(OkWithNoResponse, ops)] findResponse pid (op : ops) = [ (resp, op : ops') | (resp, ops') <- findResponse pid ops ] matchInvocation :: Pid -> Operation' cmd resp -> Bool matchInvocation pid (Invoke pid' _cmd) = pid == pid' matchInvocation _ _ = False filter1 :: (a -> Bool) -> [a] -> [a] filter1 _ [] = [] filter1 p (x : xs) | p x = x : filter1 p xs | otherwise = xs linearisable :: forall model cmd resp. Eq resp => Show cmd => Show resp => (model -> cmd -> (model, resp)) -> model -> Forest (cmd, Result resp) -> Bool linearisable step0 model0 = any' (go model0) where go :: model -> Tree (cmd, Result resp) -> Bool go model (Node (cmd, mresp) ts) = let (model', resp') = step0 model cmd in case mresp of OkWithResponse resp -> resp == resp' && any' (go model') ts OkWithNoResponse -> any' (go model') ts any' :: (a -> Bool) -> [a] -> Bool any' _p [] = True any' p xs = any p xs linearise :: forall model cmd resp. Eq resp => Show cmd => Show resp => (model -> cmd -> (model, resp)) -> model -> History' cmd resp -> Bool linearise step0 model0 history = case isValidConcurrentHistory history of Left err -> error err Right () -> linearisable step0 model0 (interleavings history) -------------------------------------------------------------------------------- -- Testing -------------------------------------------------------------------------------- example :: History' String String example = History [ Invoke p0 "A" , Invoke p2 "B" , Invoke p1 "C" , Ok p0 "RA" , Fail p2 INFO , Invoke p0 "D" , Ok p1 "RC" , Ok p0 "RD" ] where p0 = Pid 0 p1 = Pid 1 p2 = Pid 2 -------------------------------------------------------------------------------- -- QuickCheck -------------------------------------------------------------------------------- data LinearEvent cmd resp = LinearEvent Pid cmd resp deriving Show data PidStatus cmd resp = DoingNothing | MadeRequest cmd | CommitedRequest cmd (Maybe resp) | FailedRequest cmd selectOne will pick a random element , and also give the remaining elements could use NonEmpty but error is fine for now selectOne :: [x] -> Gen (x,[x]) selectOne [] = error "selectOne requires at least one element" selectOne xs = do i <- chooseInt (0, length xs - 1) -- we could have a specialised function for this that would have better performance return (xs !! i, take i xs ++ drop (succ i) xs) genHistory :: forall model cmd resp. (model -> cmd -> (model, resp)) -> model -> Gen cmd -> Int -> [Pid] -> Gen (History' cmd resp, [LinearEvent cmd resp]) genHistory step0 model0 genC nrOfNewPids pids0 = sized $ go [] [] model0 (zip pids0 $ repeat DoingNothing) nextPid0 where nextPid0 = nextPid (maximum pids0) lastPid = foldr (.) id (replicate nrOfNewPids nextPid) $ nextPid0 nextPid (Pid p) = Pid (succ p) go1 :: [Operation' cmd resp] -> [LinearEvent cmd resp] -> model -> Pid -> PidStatus cmd resp -> Bool -> Gen ( [Operation' cmd resp] , [LinearEvent cmd resp] , model , Maybe (PidStatus cmd resp) , Bool) go1 conc linear model pid state shouldStartNew = case state of DoingNothing | shouldStartNew -> do cmd <- genC return (Invoke pid cmd:conc, linear, model, Just $ MadeRequest cmd, True) | otherwise -> return (conc, linear, model, Nothing, False) MadeRequest cmd -> frequency [ (10, do -- request succeed, and response arrived let (model', resp) = step0 model cmd return (conc, LinearEvent pid cmd resp:linear, model', Just $ CommitedRequest cmd (Just resp), False) ) , (1, do -- request succeed, but response failed let (model', resp) = step0 model cmd return (conc, LinearEvent pid cmd resp:linear, model', Just $ CommitedRequest cmd Nothing, False) ) , (1, do -- request fails return (conc, linear, model, Just $ FailedRequest cmd, False) )] CommitedRequest _cmd mresp -> do let op = case mresp of Nothing -> Fail pid INFO Just resp-> Ok pid resp return (op:conc, linear, model, fmap (const DoingNothing) mresp, False) FailedRequest _cmd -> return (Fail pid INFO:conc, linear, model, Nothing, False) go conc linear _model [] _npid _size = pure (History $ reverse conc, reverse linear) go conc linear model pids npid size = do ((pid, state), pids') <- selectOne pids (conc', linear', model', status, shouldChangeSize) <- go1 conc linear model pid state (0 < size) let (pids'', npid') = case status of Nothing | size <= 0 || npid >= lastPid -> (pids', npid) | otherwise -> ((npid, DoingNothing):pids', nextPid npid) Just s -> ((pid,s):pids', npid) size' = if shouldChangeSize then pred size else size go conc' linear' model' pids'' npid' size' type SimpleModel = [Int] smStep :: SimpleModel -> Int -> (SimpleModel, [Int]) smStep xs x = (x:xs, x:xs) smModel :: SimpleModel smModel = [] prop_genHistory :: [Pid] -> Int -> Property prop_genHistory pids nrOfNewPids = forAll (genHistory smStep smModel arbitrary nrOfNewPids pids) $ \(ch, _) -> case isValidConcurrentHistory ch of Left err -> counterexample err False Right () -> property True prop_linearise :: [Pid] -> Int -> Property prop_linearise pids nrOfNewPids = forAll (genHistory smStep smModel arbitrary nrOfNewPids pids) $ \(ch, _) -> linearise smStep smModel ch
null
https://raw.githubusercontent.com/symbiont-io/detsys-testkit/08a43616994595c08965e7f9a543dff4af271051/doc/advanced-testing-mini-course/src/Lec04/LineariseWithFault.hs
haskell
---------------------------------------------------------------------- should this has a cmd? ------------------------------------------------------------------------------ Testing ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ QuickCheck ------------------------------------------------------------------------------ we could have a specialised function for this that would have better performance request succeed, and response arrived request succeed, but response failed request fails
# LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE ScopedTypeVariables # module Lec04.LineariseWithFault where import Control.Concurrent.STM (TQueue, atomically, writeTQueue) import Data.Tree (Forest, Tree(Node)) import Test.QuickCheck hiding (Result) import Lec01SMTesting (Command, Response) import Lec02ConcurrentSMTesting (Pid(..)) newtype History' cmd resp = History [Operation' cmd resp] deriving (Show, Functor, Foldable) prettyHistory :: (Show cmd, Show resp) => History' cmd resp -> String prettyHistory = show type History = History' Command Response data FailureMode = FAIL | INFO deriving Show XXX : We probably do n't want to use Pid = ThreadId here , because if we have an INFO we do n't want any further operations executed by that Pid . data Operation' cmd resp = Invoke Pid cmd | Ok Pid resp deriving (Show, Functor, Foldable) type Operation = Operation' Command Response appendHistory :: TQueue (Operation' cmd resp) -> Operation' cmd resp -> IO () appendHistory hist op = atomically (writeTQueue hist op) data Result resp = OkWithResponse resp | OkWithNoResponse deriving Show isValidConcurrentHistory :: History' cmd resp -> Either String () isValidConcurrentHistory (History xs) = go [] [] xs where go _runningPids _infoPids [] = Right () go runningPids infoPids (op:ops) = case op of Invoke pid _ | pid `elem` runningPids -> Left $ show pid ++ " is already running. Each pid should only run one command at a time." | pid `elem` infoPids -> Left $ show pid ++ " have already returned an INFO and shouldn't make any more comands. But we see an INVOKE." | otherwise -> go (pid:runningPids) infoPids ops Ok pid _ -> go (filter (/= pid) runningPids) infoPids ops Fail pid FAIL -> go (filter (/= pid) runningPids) infoPids ops Fail pid INFO -> go (filter (/= pid) runningPids) (pid:infoPids) ops interleavings :: History' cmd resp -> Forest (cmd, Result resp) interleavings (History []) = [] interleavings (History ops) | all (not . isOk) ops = [] where isOk :: Operation' cmd resp -> Bool isOk (Ok{}) = True isOk _ = False interleavings (History ops0) = [ Node (cmd, resp) (interleavings (History ops')) | (tid, cmd) <- takeInvocations ops0 , (resp, ops') <- findResponse tid (filter1 (not . matchInvocation tid) ops0) ] where takeInvocations :: [Operation' cmd resp] -> [(Pid, cmd)] takeInvocations [] = [] takeInvocations ((Invoke pid cmd) : ops) = (pid, cmd) : takeInvocations ops takeInvocations ((Ok _pid _resp) : _) = [] takeInvocations ((Fail _pid _mode) : ops) = takeInvocations ops findResponse :: Pid -> [Operation' cmd resp] -> [(Result resp, [Operation' cmd resp])] findResponse _pid [] = [] findResponse pid ((Ok pid' resp) : ops) | pid == pid' = [(OkWithResponse resp, ops)] findResponse pid ((Fail pid' mode) : ops) | pid == pid' = case mode of FAIL -> [] INFO -> [(OkWithNoResponse, ops)] findResponse pid (op : ops) = [ (resp, op : ops') | (resp, ops') <- findResponse pid ops ] matchInvocation :: Pid -> Operation' cmd resp -> Bool matchInvocation pid (Invoke pid' _cmd) = pid == pid' matchInvocation _ _ = False filter1 :: (a -> Bool) -> [a] -> [a] filter1 _ [] = [] filter1 p (x : xs) | p x = x : filter1 p xs | otherwise = xs linearisable :: forall model cmd resp. Eq resp => Show cmd => Show resp => (model -> cmd -> (model, resp)) -> model -> Forest (cmd, Result resp) -> Bool linearisable step0 model0 = any' (go model0) where go :: model -> Tree (cmd, Result resp) -> Bool go model (Node (cmd, mresp) ts) = let (model', resp') = step0 model cmd in case mresp of OkWithResponse resp -> resp == resp' && any' (go model') ts OkWithNoResponse -> any' (go model') ts any' :: (a -> Bool) -> [a] -> Bool any' _p [] = True any' p xs = any p xs linearise :: forall model cmd resp. Eq resp => Show cmd => Show resp => (model -> cmd -> (model, resp)) -> model -> History' cmd resp -> Bool linearise step0 model0 history = case isValidConcurrentHistory history of Left err -> error err Right () -> linearisable step0 model0 (interleavings history) example :: History' String String example = History [ Invoke p0 "A" , Invoke p2 "B" , Invoke p1 "C" , Ok p0 "RA" , Fail p2 INFO , Invoke p0 "D" , Ok p1 "RC" , Ok p0 "RD" ] where p0 = Pid 0 p1 = Pid 1 p2 = Pid 2 data LinearEvent cmd resp = LinearEvent Pid cmd resp deriving Show data PidStatus cmd resp = DoingNothing | MadeRequest cmd | CommitedRequest cmd (Maybe resp) | FailedRequest cmd selectOne will pick a random element , and also give the remaining elements could use NonEmpty but error is fine for now selectOne :: [x] -> Gen (x,[x]) selectOne [] = error "selectOne requires at least one element" selectOne xs = do i <- chooseInt (0, length xs - 1) return (xs !! i, take i xs ++ drop (succ i) xs) genHistory :: forall model cmd resp. (model -> cmd -> (model, resp)) -> model -> Gen cmd -> Int -> [Pid] -> Gen (History' cmd resp, [LinearEvent cmd resp]) genHistory step0 model0 genC nrOfNewPids pids0 = sized $ go [] [] model0 (zip pids0 $ repeat DoingNothing) nextPid0 where nextPid0 = nextPid (maximum pids0) lastPid = foldr (.) id (replicate nrOfNewPids nextPid) $ nextPid0 nextPid (Pid p) = Pid (succ p) go1 :: [Operation' cmd resp] -> [LinearEvent cmd resp] -> model -> Pid -> PidStatus cmd resp -> Bool -> Gen ( [Operation' cmd resp] , [LinearEvent cmd resp] , model , Maybe (PidStatus cmd resp) , Bool) go1 conc linear model pid state shouldStartNew = case state of DoingNothing | shouldStartNew -> do cmd <- genC return (Invoke pid cmd:conc, linear, model, Just $ MadeRequest cmd, True) | otherwise -> return (conc, linear, model, Nothing, False) MadeRequest cmd -> frequency let (model', resp) = step0 model cmd return (conc, LinearEvent pid cmd resp:linear, model', Just $ CommitedRequest cmd (Just resp), False) ) let (model', resp) = step0 model cmd return (conc, LinearEvent pid cmd resp:linear, model', Just $ CommitedRequest cmd Nothing, False) ) return (conc, linear, model, Just $ FailedRequest cmd, False) )] CommitedRequest _cmd mresp -> do let op = case mresp of Nothing -> Fail pid INFO Just resp-> Ok pid resp return (op:conc, linear, model, fmap (const DoingNothing) mresp, False) FailedRequest _cmd -> return (Fail pid INFO:conc, linear, model, Nothing, False) go conc linear _model [] _npid _size = pure (History $ reverse conc, reverse linear) go conc linear model pids npid size = do ((pid, state), pids') <- selectOne pids (conc', linear', model', status, shouldChangeSize) <- go1 conc linear model pid state (0 < size) let (pids'', npid') = case status of Nothing | size <= 0 || npid >= lastPid -> (pids', npid) | otherwise -> ((npid, DoingNothing):pids', nextPid npid) Just s -> ((pid,s):pids', npid) size' = if shouldChangeSize then pred size else size go conc' linear' model' pids'' npid' size' type SimpleModel = [Int] smStep :: SimpleModel -> Int -> (SimpleModel, [Int]) smStep xs x = (x:xs, x:xs) smModel :: SimpleModel smModel = [] prop_genHistory :: [Pid] -> Int -> Property prop_genHistory pids nrOfNewPids = forAll (genHistory smStep smModel arbitrary nrOfNewPids pids) $ \(ch, _) -> case isValidConcurrentHistory ch of Left err -> counterexample err False Right () -> property True prop_linearise :: [Pid] -> Int -> Property prop_linearise pids nrOfNewPids = forAll (genHistory smStep smModel arbitrary nrOfNewPids pids) $ \(ch, _) -> linearise smStep smModel ch
91396207f64cc81b60bbeb1b1bddb69b3d006bc8c38f24f743cb2fa3fdaead05
buntine/Simply-Scheme-Exercises
20-7.scm
; Another problem with ask-user is that it allows a user to request a square that ; isn't free. If the user does this, what happens? Fix ask-user to ensure that this can't ; happen. (define (ask-user position letter) (print-position position) (display letter) (display "’s move: ") (let ((answer (read))) (if (member? answer '(1 2 3 4 5 6 7 8 9)) (if (equal? (item answer position) '_) answer (fail-and-retry "Sorry, that square is taken." ask-user position letter)) (fail-and-retry "Invalid input. Please enter 1-9." ask-user position letter)))) (define (fail-and-retry msg func . args) (begin (show msg) (apply func args))) (define (print-position position) (show position))
null
https://raw.githubusercontent.com/buntine/Simply-Scheme-Exercises/c6cbf0bd60d6385b506b8df94c348ac5edc7f646/20-input-and-output/20-7.scm
scheme
Another problem with ask-user is that it allows a user to request a square that isn't free. If the user does this, what happens? Fix ask-user to ensure that this can't happen.
(define (ask-user position letter) (print-position position) (display letter) (display "’s move: ") (let ((answer (read))) (if (member? answer '(1 2 3 4 5 6 7 8 9)) (if (equal? (item answer position) '_) answer (fail-and-retry "Sorry, that square is taken." ask-user position letter)) (fail-and-retry "Invalid input. Please enter 1-9." ask-user position letter)))) (define (fail-and-retry msg func . args) (begin (show msg) (apply func args))) (define (print-position position) (show position))
f41fe80bdb1d3d7b35cfb85a64239c901a102833fa84404b9225f7dd0569e4e9
gsakkas/rite
3322.ml
let rec mulByDigit i l = match List.rev l with | [] -> [] | h::t -> [mulByDigit i (List.rev l); h * i];; (* fix let rec mulByDigit i l = match List.rev l with | [] -> [] | h::t -> (mulByDigit i (List.rev l)) @ [h * i];; *) changed spans ( 5,13)-(5,47 ) mulByDigit i ( List.rev l ) @ [ h * i ] AppG [ AppG [ EmptyG , EmptyG],ListG [ EmptyG ] ] (5,13)-(5,47) mulByDigit i (List.rev l) @ [h * i] AppG [AppG [EmptyG,EmptyG],ListG [EmptyG]] *) type error slice ( 2,4)-(5,49 ) ( ) ( 2,22)-(5,47 ) ( 3,3)-(5,47 ) ( 5,13)-(5,47 ) ( 5,14)-(5,24 ) ( 5,14)-(5,39 ) (2,4)-(5,49) (2,20)-(5,47) (2,22)-(5,47) (3,3)-(5,47) (5,13)-(5,47) (5,14)-(5,24) (5,14)-(5,39) *)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/3322.ml
ocaml
fix let rec mulByDigit i l = match List.rev l with | [] -> [] | h::t -> (mulByDigit i (List.rev l)) @ [h * i];;
let rec mulByDigit i l = match List.rev l with | [] -> [] | h::t -> [mulByDigit i (List.rev l); h * i];; changed spans ( 5,13)-(5,47 ) mulByDigit i ( List.rev l ) @ [ h * i ] AppG [ AppG [ EmptyG , EmptyG],ListG [ EmptyG ] ] (5,13)-(5,47) mulByDigit i (List.rev l) @ [h * i] AppG [AppG [EmptyG,EmptyG],ListG [EmptyG]] *) type error slice ( 2,4)-(5,49 ) ( ) ( 2,22)-(5,47 ) ( 3,3)-(5,47 ) ( 5,13)-(5,47 ) ( 5,14)-(5,24 ) ( 5,14)-(5,39 ) (2,4)-(5,49) (2,20)-(5,47) (2,22)-(5,47) (3,3)-(5,47) (5,13)-(5,47) (5,14)-(5,24) (5,14)-(5,39) *)
baf4b760c36ff627038f16e8de6dfade939567bfdfb11740d4fcfbf3e7e697cc
clojure-interop/google-cloud-clients
VideoIntelligenceServiceStubSettings.clj
(ns com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings "Settings class to configure an instance of VideoIntelligenceServiceStub. The default instance has everything set to sensible defaults: The default service address (videointelligence.googleapis.com) and default port (443) are used. Credentials are acquired automatically through Application Default Credentials. Retries are configured for idempotent methods but not for non-idempotent methods. The builder of this class is recursive, so contained classes are themselves builders. When build() is called, the tree of builders is called to create the complete settings object. For example, to set the total timeout of annotateVideoAsync to 30 seconds: VideoIntelligenceServiceStubSettings.Builder videoIntelligenceServiceSettingsBuilder = VideoIntelligenceServiceStubSettings.newBuilder(); videoIntelligenceServiceSettingsBuilder.annotateVideoSettings().getRetrySettings().toBuilder() .setTotalTimeout(Duration.ofSeconds(30)); VideoIntelligenceServiceStubSettings videoIntelligenceServiceSettings = videoIntelligenceServiceSettingsBuilder.build();" (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.videointelligence.v1.stub VideoIntelligenceServiceStubSettings])) (defn *default-executor-provider-builder "Returns a builder for the default ExecutorProvider for this service. returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`" (^com.google.api.gax.core.InstantiatingExecutorProvider.Builder [] (VideoIntelligenceServiceStubSettings/defaultExecutorProviderBuilder ))) (defn *get-default-endpoint "Returns the default service endpoint. returns: `java.lang.String`" (^java.lang.String [] (VideoIntelligenceServiceStubSettings/getDefaultEndpoint ))) (defn *get-default-service-scopes "Returns the default service scopes. returns: `java.util.List<java.lang.String>`" (^java.util.List [] (VideoIntelligenceServiceStubSettings/getDefaultServiceScopes ))) (defn *default-credentials-provider-builder "Returns a builder for the default credentials for this service. returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`" (^com.google.api.gax.core.GoogleCredentialsProvider.Builder [] (VideoIntelligenceServiceStubSettings/defaultCredentialsProviderBuilder ))) (defn *default-grpc-transport-provider-builder "Returns a builder for the default ChannelProvider for this service. returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`" (^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder [] (VideoIntelligenceServiceStubSettings/defaultGrpcTransportProviderBuilder ))) (defn *default-transport-channel-provider "returns: `com.google.api.gax.rpc.TransportChannelProvider`" (^com.google.api.gax.rpc.TransportChannelProvider [] (VideoIntelligenceServiceStubSettings/defaultTransportChannelProvider ))) (defn *default-api-client-header-provider-builder "returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`" ([] (VideoIntelligenceServiceStubSettings/defaultApiClientHeaderProviderBuilder ))) (defn *new-builder "Returns a new builder for this class. client-context - `com.google.api.gax.rpc.ClientContext` returns: `com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder`" (^com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context] (VideoIntelligenceServiceStubSettings/newBuilder client-context)) (^com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder [] (VideoIntelligenceServiceStubSettings/newBuilder ))) (defn annotate-video-settings "Returns the object with the settings used for calls to annotateVideo. returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.videointelligence.v1.AnnotateVideoRequest,com.google.longrunning.Operation>`" (^com.google.api.gax.rpc.UnaryCallSettings [^VideoIntelligenceServiceStubSettings this] (-> this (.annotateVideoSettings)))) (defn annotate-video-operation-settings "Returns the object with the settings used for calls to annotateVideo. returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallSettings<com.google.cloud.videointelligence.v1.AnnotateVideoRequest,com.google.cloud.videointelligence.v1.AnnotateVideoResponse,com.google.cloud.videointelligence.v1.AnnotateVideoProgress>`" ([^VideoIntelligenceServiceStubSettings this] (-> this (.annotateVideoOperationSettings)))) (defn create-stub "returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStub` throws: java.io.IOException" ([^VideoIntelligenceServiceStubSettings this] (-> this (.createStub)))) (defn to-builder "Returns a builder containing all the values of this settings class. returns: `com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder`" (^com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder [^VideoIntelligenceServiceStubSettings this] (-> this (.toBuilder))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.videointelligence/src/com/google/cloud/videointelligence/v1/stub/VideoIntelligenceServiceStubSettings.clj
clojure
"
(ns com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings "Settings class to configure an instance of VideoIntelligenceServiceStub. The default instance has everything set to sensible defaults: The default service address (videointelligence.googleapis.com) and default port (443) are used. Credentials are acquired automatically through Application Default Credentials. Retries are configured for idempotent methods but not for non-idempotent methods. The builder of this class is recursive, so contained classes are themselves builders. When build() is called, the tree of builders is called to create the complete settings object. For example, to set the total timeout of annotateVideoAsync to 30 seconds: VideoIntelligenceServiceStubSettings.Builder videoIntelligenceServiceSettingsBuilder = videoIntelligenceServiceSettingsBuilder.annotateVideoSettings().getRetrySettings().toBuilder() (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.videointelligence.v1.stub VideoIntelligenceServiceStubSettings])) (defn *default-executor-provider-builder "Returns a builder for the default ExecutorProvider for this service. returns: `com.google.api.gax.core.InstantiatingExecutorProvider.Builder`" (^com.google.api.gax.core.InstantiatingExecutorProvider.Builder [] (VideoIntelligenceServiceStubSettings/defaultExecutorProviderBuilder ))) (defn *get-default-endpoint "Returns the default service endpoint. returns: `java.lang.String`" (^java.lang.String [] (VideoIntelligenceServiceStubSettings/getDefaultEndpoint ))) (defn *get-default-service-scopes "Returns the default service scopes. returns: `java.util.List<java.lang.String>`" (^java.util.List [] (VideoIntelligenceServiceStubSettings/getDefaultServiceScopes ))) (defn *default-credentials-provider-builder "Returns a builder for the default credentials for this service. returns: `com.google.api.gax.core.GoogleCredentialsProvider.Builder`" (^com.google.api.gax.core.GoogleCredentialsProvider.Builder [] (VideoIntelligenceServiceStubSettings/defaultCredentialsProviderBuilder ))) (defn *default-grpc-transport-provider-builder "Returns a builder for the default ChannelProvider for this service. returns: `com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder`" (^com.google.api.gax.grpc.InstantiatingGrpcChannelProvider.Builder [] (VideoIntelligenceServiceStubSettings/defaultGrpcTransportProviderBuilder ))) (defn *default-transport-channel-provider "returns: `com.google.api.gax.rpc.TransportChannelProvider`" (^com.google.api.gax.rpc.TransportChannelProvider [] (VideoIntelligenceServiceStubSettings/defaultTransportChannelProvider ))) (defn *default-api-client-header-provider-builder "returns: `(value="The surface for customizing headers is not stable yet and may change in the future.") com.google.api.gax.rpc.ApiClientHeaderProvider.Builder`" ([] (VideoIntelligenceServiceStubSettings/defaultApiClientHeaderProviderBuilder ))) (defn *new-builder "Returns a new builder for this class. client-context - `com.google.api.gax.rpc.ClientContext` returns: `com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder`" (^com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder [^com.google.api.gax.rpc.ClientContext client-context] (VideoIntelligenceServiceStubSettings/newBuilder client-context)) (^com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder [] (VideoIntelligenceServiceStubSettings/newBuilder ))) (defn annotate-video-settings "Returns the object with the settings used for calls to annotateVideo. returns: `com.google.api.gax.rpc.UnaryCallSettings<com.google.cloud.videointelligence.v1.AnnotateVideoRequest,com.google.longrunning.Operation>`" (^com.google.api.gax.rpc.UnaryCallSettings [^VideoIntelligenceServiceStubSettings this] (-> this (.annotateVideoSettings)))) (defn annotate-video-operation-settings "Returns the object with the settings used for calls to annotateVideo. returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallSettings<com.google.cloud.videointelligence.v1.AnnotateVideoRequest,com.google.cloud.videointelligence.v1.AnnotateVideoResponse,com.google.cloud.videointelligence.v1.AnnotateVideoProgress>`" ([^VideoIntelligenceServiceStubSettings this] (-> this (.annotateVideoOperationSettings)))) (defn create-stub "returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStub` throws: java.io.IOException" ([^VideoIntelligenceServiceStubSettings this] (-> this (.createStub)))) (defn to-builder "Returns a builder containing all the values of this settings class. returns: `com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder`" (^com.google.cloud.videointelligence.v1.stub.VideoIntelligenceServiceStubSettings$Builder [^VideoIntelligenceServiceStubSettings this] (-> this (.toBuilder))))
10c2575035f06411cdac38a0e3eec09d61329f8f2fe9a91f8e307b7dd7955450
ucsd-progsys/nate
records.3.ml
(*F*) type 'a t = { a : 'a ; mutable b : 'a ; c : 'a list ; d : int ; } type s = { x : unit } let x : int t = { a = 0; b = 0; c = [0]; d = 0; x = () } let () = x.b <- 1
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/easyocaml-additional/exams/records.3.ml
ocaml
F
type 'a t = { a : 'a ; mutable b : 'a ; c : 'a list ; d : int ; } type s = { x : unit } let x : int t = { a = 0; b = 0; c = [0]; d = 0; x = () } let () = x.b <- 1
a54e6b8c05e6fe19734527f9e177690a85d65eb49a100d5029a17d7d038e7d25
GrammaTech/sel
cpp-project.lisp
cpp-project.lisp --- C++ Projects ;;; (defpackage :software-evolution-library/software/cpp-project (:nicknames :sel/software/cpp-project :sel/sw/cpp-project) (:use :gt/full :cl-json :functional-trees/attrs :software-evolution-library :software-evolution-library/software/simple :software-evolution-library/software/parseable :software-evolution-library/software/project :software-evolution-library/software/parseable-project :software-evolution-library/software/compilable :software-evolution-library/software/tree-sitter :software-evolution-library/software/c-cpp-project :software-evolution-library/software/directory) (:export :cpp-project)) (in-package :software-evolution-library/software/cpp-project) (in-readtable :curry-compose-reader-macros) (defparameter *cpp-extensions* '("h" "cpp" "cp" "cc" "cxx") "List of extensions we will consider for evolving.") (define-software cpp-project (c/cpp-project) () (:documentation "Project specialization for c++ software objects.")) (defmethod initialize-instance :after ((project cpp-project) &key) (unless (component-class project) (setf (component-class project) 'cpp)) (unless (compiler project) (setf (compiler project) "c++"))) (defmethod collect-evolve-files ((project cpp-project)) (collect-evolve-files* project :extensions *cpp-extensions*)) #+:TREE-SITTER-CPP (progn (defmethod multi-declaration-keys ((root cpp-project)) +cpp-multi-declaration-keys+) (defmethod attr-missing ((fn-name (eql 'namespace)) (node cpp-ast)) (let* ((attrs-root (attrs-root *attrs*)) (parents (get-parent-asts attrs-root node)) (root (find-if (of-type 'root-ast) parents))) (cond TODO : having to check for whether it 's an extra AST may be a bug from ;; somewhere else. ((and (null parents) (typep node '(or comment-ast parse-error-ast source-text-fragment))) (namespace node "")) (root (namespace root "")) (t (namespace attrs-root ""))))) ) ; #+:TREE-SITTER-CPP
null
https://raw.githubusercontent.com/GrammaTech/sel/f2d82b139ca6c05e81c482fd1bbc04fc8d9a6270/software/cpp-project.lisp
lisp
somewhere else. #+:TREE-SITTER-CPP
cpp-project.lisp --- C++ Projects (defpackage :software-evolution-library/software/cpp-project (:nicknames :sel/software/cpp-project :sel/sw/cpp-project) (:use :gt/full :cl-json :functional-trees/attrs :software-evolution-library :software-evolution-library/software/simple :software-evolution-library/software/parseable :software-evolution-library/software/project :software-evolution-library/software/parseable-project :software-evolution-library/software/compilable :software-evolution-library/software/tree-sitter :software-evolution-library/software/c-cpp-project :software-evolution-library/software/directory) (:export :cpp-project)) (in-package :software-evolution-library/software/cpp-project) (in-readtable :curry-compose-reader-macros) (defparameter *cpp-extensions* '("h" "cpp" "cp" "cc" "cxx") "List of extensions we will consider for evolving.") (define-software cpp-project (c/cpp-project) () (:documentation "Project specialization for c++ software objects.")) (defmethod initialize-instance :after ((project cpp-project) &key) (unless (component-class project) (setf (component-class project) 'cpp)) (unless (compiler project) (setf (compiler project) "c++"))) (defmethod collect-evolve-files ((project cpp-project)) (collect-evolve-files* project :extensions *cpp-extensions*)) #+:TREE-SITTER-CPP (progn (defmethod multi-declaration-keys ((root cpp-project)) +cpp-multi-declaration-keys+) (defmethod attr-missing ((fn-name (eql 'namespace)) (node cpp-ast)) (let* ((attrs-root (attrs-root *attrs*)) (parents (get-parent-asts attrs-root node)) (root (find-if (of-type 'root-ast) parents))) (cond TODO : having to check for whether it 's an extra AST may be a bug from ((and (null parents) (typep node '(or comment-ast parse-error-ast source-text-fragment))) (namespace node "")) (root (namespace root "")) (t (namespace attrs-root "")))))
d3549fb20aa988a1259f5ffb37ebc78fd6d8256fc0e4e46c4fd27155902d9b32
Zilliqa/scilla
Polynomial.ml
This file is part of scilla . Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd. scilla 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 . scilla 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 scilla . If not , see < / > . This file is part of scilla. Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd. scilla 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. scilla 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 scilla. If not, see </>. *) (* Library to create and operate on multivariate polynomials *) open Core exception Polynomial_error of string Variables in the polynomial are of type ' a. * Representation : co - efficient * ( variable ^ pow ) list * Example : ( 3 , [ ' A ' , 2 ] ) is 3 * ( a^2 ) * Representation: co-efficient * (variable ^ pow) list * Example: (3, ['A', 2]) is 3 * (a^2) *) type 'a term = int * ('a * int) list (* A polynomial is a sum of terms. * NOTE: * The representation used here does not in itself guarantee * a canonicalized form. Use canonicalize_* below as needed. *) type 'a polynomial = 'a term list (* If a variable occurs more than once in a term, * combine the occurrences by adding the powers. *) let canonicalize_term (t : 'a term) : 'a term = let c, vplist = t in if c = 0 then (0, []) else check if the first element of the list occurs again later , * and recursively , the rest of the list . * and recursively, the rest of the list. *) let rec merger vplist = match vplist with | (cur_v, cur_p) :: rem -> (* Split the remaining into those equal to cur and not equal to cur. *) let cureq, curneq = List.partition_tf rem ~f:(fun (v, _) -> Poly.(v = cur_v)) in Add the powers of cur_v and those in cureq . let p = List.fold cureq ~init:cur_p ~f:(fun acc (_, t_p) -> acc + t_p) in (* Recursively eliminate duplicates in the remaining part of the list. *) let merged_rem' = merger curneq in if p = 0 then merged_rem' else (cur_v, p) :: merged_rem' | [] -> [] in let res = merger vplist in (c, res) Check if two terms are equivalent . * = false ignores co - efficients in the comparison . * ~coef=false ignores co-efficients in the comparison. *) let eq_term ?(coef = true) (t1' : 'a term) (t2' : 'a term) = let t1, t2 = (canonicalize_term t1', canonicalize_term t2') in let (c1, vplist1), (c2, vplist2) = (t1, t2) in ((not coef) || c1 = c2) && List.length vplist1 = List.length vplist2 && List.for_all vplist1 ~f:(fun (cur_v, cur_p) -> List.exists vplist2 ~f:(fun (cur_v', cur_p') -> Poly.(cur_v = cur_v') && cur_p = cur_p')) let mul_term (t1 : 'a term) (t2 : 'a term) : 'a term = let (c1, vplist1), (c2, vplist2) = (t1, t2) in canonicalize_term (c1 * c2, vplist1 @ vplist2) (* If a term occurs more than once in a polynomial, * combine the occurrences by adding up the co-efficients. *) let canonicalize_pn (tlist' : 'a polynomial) : 'a polynomial = each term first . let tlist = List.map tlist' ~f:(fun t -> canonicalize_term t) in Combine first term with same terms later on , and recursively for the remaining terms . let rec merger = function | [] -> [] | h :: rem -> let c_h, t_h = h in (* If the coefficient of this term is 0, ignore it. *) if c_h = 0 then merger rem else (* Split the remaining terms into those equal to and not equal to h. *) let heq, hneq = List.partition_tf rem ~f:(fun t -> eq_term ~coef:false h t) in let h' = let coef' = List.fold heq ~init:c_h ~f:(fun acc t -> let c_t, _ = t in acc + c_t) in (coef', t_h) in h' :: merger hneq in merger tlist Check if two polynomials are equivalent . let eq_pn (p1' : 'a polynomial) (p2' : 'a polynomial) = let p1, p2 = (canonicalize_pn p1', canonicalize_pn p2') in List.length p1 = List.length p2 && List.for_all p1 ~f:(fun t1 -> List.exists p2 ~f:(fun t2 -> eq_term t1 t2)) Add two polynomials . let add_pn (p1 : 'a polynomial) (p2 : 'a polynomial) = canonicalize_pn (p1 @ p2) Multiply two polynomials . let mul_pn (p1 : 'a polynomial) (p2 : 'a polynomial) = let prods = List.map p1 ~f:(fun t1 -> (* multiply t1 with each term of p2. *) List.map p2 ~f:(fun t2 -> mul_term t1 t2)) in canonicalize_pn (List.concat prods) Combine two polynomials ( pairing each term in the first with those in the second ) * using a custom function f , which returns ( Some term ) if two terms are to be combined * using a custom function f, which returns (Some term) if two terms are to be combined *) let combine_pn ~(cf : 'a term -> 'a term -> 'a term option) (p1' : 'a polynomial) (p2' : 'a polynomial) = let p1 = canonicalize_pn p1' in let p2 = canonicalize_pn p2' in Fold over p1 terms , building them up , while removing terms from p2 . let p1', p2' = List.fold p1 ~init:([], p2) ~f:(fun (p1_acc, p2_acc) t1 -> Fold over p2_acc , combining with t1 as possible . let t1', p2_acc' = List.fold p2_acc ~init:(t1, []) ~f:(fun (t1_acc, p2_acc') t2 -> match cf t1_acc t2 with | Some t1' -> (t1', p2_acc') | None -> (t1_acc, t2 :: p2_acc')) in (t1' :: p1_acc, List.rev p2_acc')) in (* Just add up what's left of p2. *) canonicalize_pn (List.rev p1' @ p2') Combine two polynomials by choosing terms with higher co - efficient from one of them . let max_combine_pn (p1' : 'a polynomial) (p2' : 'a polynomial) = let p1 = canonicalize_pn p1' in let p2 = canonicalize_pn p2' in let res, p2' = List.fold p1 ~init:([], p2) ~f:(fun (res, p2') (c1, t1) -> let heq, hneq = List.partition_tf p2' ~f:(fun t -> eq_term ~coef:false (c1, t1) t) in TODO assert that ( heq < = 1 ) due to canonicalize_pn earlier . match heq with | [ (c2, t2) ] when c2 > c1 -> ((c2, t2) :: res, hneq) | _ -> ((c1, t1) :: res, hneq)) in res @ p2' (* Replace every variable in the polynomial using a replacer. *) let var_replace_pn (pn : 'a polynomial) ~(f : 'a -> 'a) = let term_replacer (ter : 'a term) = let coef, vlist = ter in let vlist' = List.map vlist ~f:(fun (v, i1) -> let v' = f v in (v', i1)) in (coef, vlist') in List.map pn ~f:(fun t -> term_replacer t) (* Expand parameters in a polynomial into full polynomials. * TODO: Make this efficient. *) let expand_parameters_pn (pn' : 'a polynomial) ~(f : 'a -> 'a polynomial option) = let pn = canonicalize_pn pn' in (* Expand at-most one variable in term. *) let expand_parameters_term ((coef, vplist) : 'a term) : 'a polynomial = (* Partition vplist based on whether a variable should be substituted. *) let nosubl, subl = List.partition_tf vplist ~f:(fun (v, _) -> is_none (f v)) in match subl with | (svar, spow) :: restsub -> Substitute svar only ( one substitution at - most to keep things simple ) . let rest_pol = [ (coef, nosubl @ restsub) ] in let subst_pol = Option.value_exn (f svar) in if spow < 0 then raise (Polynomial_error "Cannot expand paramter with non-positive power") else let subst_pols = List.init spow ~f:(fun _ -> subst_pol) in List.fold subst_pols ~init:rest_pol ~f:(fun acc p -> mul_pn acc p) | [] -> [ (coef, vplist) ] (* nothing to substitute *) in (* Until no more substitutions, keep expanding. *) let rec subst pn = (* Expand at-most once in each term and accummulate the result. *) let pn' = List.fold pn ~init:[] ~f:(fun accum t -> let t' = expand_parameters_term t in add_pn accum t') in let pn'' = canonicalize_pn pn' in (* Repeat, till stabilization. *) if eq_pn pn'' pn then pn'' else subst pn'' in subst pn (* Print a polynomial, calling ~f to print a variable. *) let sprint_pn (pn : 'a polynomial) ~(f : 'a -> string) = let sprint_term (coef, vplist) = if coef = 0 then "0" else List.fold_left vplist ~init:(Int.to_string coef) ~f:(fun acc (v, p) -> if p = 0 then acc else if p = 1 then acc ^ "(" ^ f v ^ ")" else acc ^ "(" ^ f v ^ " ^ " ^ Int.to_string p ^ ")") in if List.is_empty pn then "0" else List.fold_left pn ~init:"" ~f:(fun acc t -> (if String.is_empty acc then "" else acc ^ " + ") ^ sprint_term t) (*********** Utilities to build polynomials easily **************) (* Build a polynomial with only a constant term. *) let const_pn i : 'a polynomial = [ (i, []) ] (* Build an empty polynomial. *) let empty_pn : 'a polynomial = [] (* Build a polynomial with a single variable v. * p = v *) let single_simple_pn v : 'a polynomial = [ (1, [ (v, 1) ]) ] (* Is this is a simple constant? *) let is_const_term t = match t with _, [] -> true | _ -> false (* Is this is a simple constant? *) let is_const_pn p = let p' = canonicalize_pn p in match p' with [] -> true | [ t ] -> is_const_term t | _ -> false
null
https://raw.githubusercontent.com/Zilliqa/scilla/011323ac5da48ee16890b71424e057ffbc4216da/src/polynomials/Polynomial.ml
ocaml
Library to create and operate on multivariate polynomials A polynomial is a sum of terms. * NOTE: * The representation used here does not in itself guarantee * a canonicalized form. Use canonicalize_* below as needed. If a variable occurs more than once in a term, * combine the occurrences by adding the powers. Split the remaining into those equal to cur and not equal to cur. Recursively eliminate duplicates in the remaining part of the list. If a term occurs more than once in a polynomial, * combine the occurrences by adding up the co-efficients. If the coefficient of this term is 0, ignore it. Split the remaining terms into those equal to and not equal to h. multiply t1 with each term of p2. Just add up what's left of p2. Replace every variable in the polynomial using a replacer. Expand parameters in a polynomial into full polynomials. * TODO: Make this efficient. Expand at-most one variable in term. Partition vplist based on whether a variable should be substituted. nothing to substitute Until no more substitutions, keep expanding. Expand at-most once in each term and accummulate the result. Repeat, till stabilization. Print a polynomial, calling ~f to print a variable. ********** Utilities to build polynomials easily ************* Build a polynomial with only a constant term. Build an empty polynomial. Build a polynomial with a single variable v. * p = v Is this is a simple constant? Is this is a simple constant?
This file is part of scilla . Copyright ( c ) 2018 - present Zilliqa Research Pvt . Ltd. scilla 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 . scilla 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 scilla . If not , see < / > . This file is part of scilla. Copyright (c) 2018 - present Zilliqa Research Pvt. Ltd. scilla 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. scilla 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 scilla. If not, see </>. *) open Core exception Polynomial_error of string Variables in the polynomial are of type ' a. * Representation : co - efficient * ( variable ^ pow ) list * Example : ( 3 , [ ' A ' , 2 ] ) is 3 * ( a^2 ) * Representation: co-efficient * (variable ^ pow) list * Example: (3, ['A', 2]) is 3 * (a^2) *) type 'a term = int * ('a * int) list type 'a polynomial = 'a term list let canonicalize_term (t : 'a term) : 'a term = let c, vplist = t in if c = 0 then (0, []) else check if the first element of the list occurs again later , * and recursively , the rest of the list . * and recursively, the rest of the list. *) let rec merger vplist = match vplist with | (cur_v, cur_p) :: rem -> let cureq, curneq = List.partition_tf rem ~f:(fun (v, _) -> Poly.(v = cur_v)) in Add the powers of cur_v and those in cureq . let p = List.fold cureq ~init:cur_p ~f:(fun acc (_, t_p) -> acc + t_p) in let merged_rem' = merger curneq in if p = 0 then merged_rem' else (cur_v, p) :: merged_rem' | [] -> [] in let res = merger vplist in (c, res) Check if two terms are equivalent . * = false ignores co - efficients in the comparison . * ~coef=false ignores co-efficients in the comparison. *) let eq_term ?(coef = true) (t1' : 'a term) (t2' : 'a term) = let t1, t2 = (canonicalize_term t1', canonicalize_term t2') in let (c1, vplist1), (c2, vplist2) = (t1, t2) in ((not coef) || c1 = c2) && List.length vplist1 = List.length vplist2 && List.for_all vplist1 ~f:(fun (cur_v, cur_p) -> List.exists vplist2 ~f:(fun (cur_v', cur_p') -> Poly.(cur_v = cur_v') && cur_p = cur_p')) let mul_term (t1 : 'a term) (t2 : 'a term) : 'a term = let (c1, vplist1), (c2, vplist2) = (t1, t2) in canonicalize_term (c1 * c2, vplist1 @ vplist2) let canonicalize_pn (tlist' : 'a polynomial) : 'a polynomial = each term first . let tlist = List.map tlist' ~f:(fun t -> canonicalize_term t) in Combine first term with same terms later on , and recursively for the remaining terms . let rec merger = function | [] -> [] | h :: rem -> let c_h, t_h = h in if c_h = 0 then merger rem else let heq, hneq = List.partition_tf rem ~f:(fun t -> eq_term ~coef:false h t) in let h' = let coef' = List.fold heq ~init:c_h ~f:(fun acc t -> let c_t, _ = t in acc + c_t) in (coef', t_h) in h' :: merger hneq in merger tlist Check if two polynomials are equivalent . let eq_pn (p1' : 'a polynomial) (p2' : 'a polynomial) = let p1, p2 = (canonicalize_pn p1', canonicalize_pn p2') in List.length p1 = List.length p2 && List.for_all p1 ~f:(fun t1 -> List.exists p2 ~f:(fun t2 -> eq_term t1 t2)) Add two polynomials . let add_pn (p1 : 'a polynomial) (p2 : 'a polynomial) = canonicalize_pn (p1 @ p2) Multiply two polynomials . let mul_pn (p1 : 'a polynomial) (p2 : 'a polynomial) = let prods = List.map p1 ~f:(fun t1 -> List.map p2 ~f:(fun t2 -> mul_term t1 t2)) in canonicalize_pn (List.concat prods) Combine two polynomials ( pairing each term in the first with those in the second ) * using a custom function f , which returns ( Some term ) if two terms are to be combined * using a custom function f, which returns (Some term) if two terms are to be combined *) let combine_pn ~(cf : 'a term -> 'a term -> 'a term option) (p1' : 'a polynomial) (p2' : 'a polynomial) = let p1 = canonicalize_pn p1' in let p2 = canonicalize_pn p2' in Fold over p1 terms , building them up , while removing terms from p2 . let p1', p2' = List.fold p1 ~init:([], p2) ~f:(fun (p1_acc, p2_acc) t1 -> Fold over p2_acc , combining with t1 as possible . let t1', p2_acc' = List.fold p2_acc ~init:(t1, []) ~f:(fun (t1_acc, p2_acc') t2 -> match cf t1_acc t2 with | Some t1' -> (t1', p2_acc') | None -> (t1_acc, t2 :: p2_acc')) in (t1' :: p1_acc, List.rev p2_acc')) in canonicalize_pn (List.rev p1' @ p2') Combine two polynomials by choosing terms with higher co - efficient from one of them . let max_combine_pn (p1' : 'a polynomial) (p2' : 'a polynomial) = let p1 = canonicalize_pn p1' in let p2 = canonicalize_pn p2' in let res, p2' = List.fold p1 ~init:([], p2) ~f:(fun (res, p2') (c1, t1) -> let heq, hneq = List.partition_tf p2' ~f:(fun t -> eq_term ~coef:false (c1, t1) t) in TODO assert that ( heq < = 1 ) due to canonicalize_pn earlier . match heq with | [ (c2, t2) ] when c2 > c1 -> ((c2, t2) :: res, hneq) | _ -> ((c1, t1) :: res, hneq)) in res @ p2' let var_replace_pn (pn : 'a polynomial) ~(f : 'a -> 'a) = let term_replacer (ter : 'a term) = let coef, vlist = ter in let vlist' = List.map vlist ~f:(fun (v, i1) -> let v' = f v in (v', i1)) in (coef, vlist') in List.map pn ~f:(fun t -> term_replacer t) let expand_parameters_pn (pn' : 'a polynomial) ~(f : 'a -> 'a polynomial option) = let pn = canonicalize_pn pn' in let expand_parameters_term ((coef, vplist) : 'a term) : 'a polynomial = let nosubl, subl = List.partition_tf vplist ~f:(fun (v, _) -> is_none (f v)) in match subl with | (svar, spow) :: restsub -> Substitute svar only ( one substitution at - most to keep things simple ) . let rest_pol = [ (coef, nosubl @ restsub) ] in let subst_pol = Option.value_exn (f svar) in if spow < 0 then raise (Polynomial_error "Cannot expand paramter with non-positive power") else let subst_pols = List.init spow ~f:(fun _ -> subst_pol) in List.fold subst_pols ~init:rest_pol ~f:(fun acc p -> mul_pn acc p) | [] -> [ (coef, vplist) ] in let rec subst pn = let pn' = List.fold pn ~init:[] ~f:(fun accum t -> let t' = expand_parameters_term t in add_pn accum t') in let pn'' = canonicalize_pn pn' in if eq_pn pn'' pn then pn'' else subst pn'' in subst pn let sprint_pn (pn : 'a polynomial) ~(f : 'a -> string) = let sprint_term (coef, vplist) = if coef = 0 then "0" else List.fold_left vplist ~init:(Int.to_string coef) ~f:(fun acc (v, p) -> if p = 0 then acc else if p = 1 then acc ^ "(" ^ f v ^ ")" else acc ^ "(" ^ f v ^ " ^ " ^ Int.to_string p ^ ")") in if List.is_empty pn then "0" else List.fold_left pn ~init:"" ~f:(fun acc t -> (if String.is_empty acc then "" else acc ^ " + ") ^ sprint_term t) let const_pn i : 'a polynomial = [ (i, []) ] let empty_pn : 'a polynomial = [] let single_simple_pn v : 'a polynomial = [ (1, [ (v, 1) ]) ] let is_const_term t = match t with _, [] -> true | _ -> false let is_const_pn p = let p' = canonicalize_pn p in match p' with [] -> true | [ t ] -> is_const_term t | _ -> false
46613856e6678fa6eacbed39e2a65bb4f3400b15fc6fe7de17a281e37a78f36a
rd--/hsc3
iRandN.help.hs
riRandN ; two channel sin tones ; harmonic series sinOsc ar (55 * X.randN 2 1 17) 0 * 0.1 riRandN ; 5 - channel sin tones ; harmonic series splay (sinOsc ar (55 * X.randN 15 1 5) 0) 1 0.1 0 True riRandN ; 15 - channel sin tones ; harmonic series splay (sinOsc ar (55 * X.randN 12 1 17) 0) 1 0.1 0 True riRandN ; two channel sin tones ; harmonic series ; i d sinOsc ar (55 * X.randNId 2 'α' 1 17) 0 * 0.1 riRandN ; 5 - channel sin tones ; harmonic series ; i d splay (sinOsc ar (55 * X.randNId 15 'α' 1 5) 0) 1 0.1 0 True riRandN ; 15 - channel sin tones ; harmonic series ; i d splay (sinOsc ar (55 * X.randNId 12 'α' 1 17) 0) 1 0.1 0 True
null
https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/iRandN.help.hs
haskell
riRandN ; two channel sin tones ; harmonic series sinOsc ar (55 * X.randN 2 1 17) 0 * 0.1 riRandN ; 5 - channel sin tones ; harmonic series splay (sinOsc ar (55 * X.randN 15 1 5) 0) 1 0.1 0 True riRandN ; 15 - channel sin tones ; harmonic series splay (sinOsc ar (55 * X.randN 12 1 17) 0) 1 0.1 0 True riRandN ; two channel sin tones ; harmonic series ; i d sinOsc ar (55 * X.randNId 2 'α' 1 17) 0 * 0.1 riRandN ; 5 - channel sin tones ; harmonic series ; i d splay (sinOsc ar (55 * X.randNId 15 'α' 1 5) 0) 1 0.1 0 True riRandN ; 15 - channel sin tones ; harmonic series ; i d splay (sinOsc ar (55 * X.randNId 12 'α' 1 17) 0) 1 0.1 0 True
d305259a6f55ca2a051cf5a8296b7f0f070acc6fd97d5386ebb02fa9e01bd27f
f4814/Tetris
Field.hs
module Tetris.Field ( Field(..) , Fail(..) , createField , emptyField ) where import Data.Matrix import Tetris.Piece import Tetris.Color import System.Random data Fail = RotationImpossible | DropImpossible | ShiftImpossible | NothingDeleted | GameLost deriving (Eq, Show) data Field = Field { fieldMatrix :: Matrix Color , fieldPieceType :: [Piece] , fieldPieceCoordinates :: [(Int, Int)] , fieldPieceCenterPoint :: (Float, Float) , fieldPoints :: Integer } deriving (Eq) instance Show Field where show f = show m ++ "\n" ++ show c ++ "\n" ++ show e ++ "\n" ++ show p where m = fieldMatrix f c = fieldPieceCoordinates f e = fieldPieceCenterPoint f p = fieldPoints f | Create a empty ( all black ) Field with 4 additional rows on top ( b / c SRS)| createField :: Int -> Int -> IO Field createField x y = do g <- newStdGen return $ Field (matrix (x+4) y (\_ -> Black)) (stream g) [(-1,-1)] (-1,-1) 0 stream :: RandomGen g => g -> [Piece] stream g = randoms g {-| Create a field with predefined pieces. Only for testing -} emptyField :: Int -> Int -> Field emptyField x y = Field (matrix (x+4) y (\_ -> Black)) (cycle [I,J,L,O,S,T,Z]) [(-1,-1)] (-1,-1) 0
null
https://raw.githubusercontent.com/f4814/Tetris/b7e8fd82d46760e9c77f67a28d81aff137189e15/src/Tetris/Field.hs
haskell
| Create a field with predefined pieces. Only for testing
module Tetris.Field ( Field(..) , Fail(..) , createField , emptyField ) where import Data.Matrix import Tetris.Piece import Tetris.Color import System.Random data Fail = RotationImpossible | DropImpossible | ShiftImpossible | NothingDeleted | GameLost deriving (Eq, Show) data Field = Field { fieldMatrix :: Matrix Color , fieldPieceType :: [Piece] , fieldPieceCoordinates :: [(Int, Int)] , fieldPieceCenterPoint :: (Float, Float) , fieldPoints :: Integer } deriving (Eq) instance Show Field where show f = show m ++ "\n" ++ show c ++ "\n" ++ show e ++ "\n" ++ show p where m = fieldMatrix f c = fieldPieceCoordinates f e = fieldPieceCenterPoint f p = fieldPoints f | Create a empty ( all black ) Field with 4 additional rows on top ( b / c SRS)| createField :: Int -> Int -> IO Field createField x y = do g <- newStdGen return $ Field (matrix (x+4) y (\_ -> Black)) (stream g) [(-1,-1)] (-1,-1) 0 stream :: RandomGen g => g -> [Piece] stream g = randoms g emptyField :: Int -> Int -> Field emptyField x y = Field (matrix (x+4) y (\_ -> Black)) (cycle [I,J,L,O,S,T,Z]) [(-1,-1)] (-1,-1) 0
dae1207c96a04ca11dc8da0eb57945129928440c8e8e77e57cd1fe7eb93c34bb
progman1/genprintlib
time_travel.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. *) (* *) (**************************************************************************) (**************************** Time travel ******************************) open Int64ops open Instruct open Events open Debugcom open Primitives open Checkpoints open Breakpoints open Trap_barrier open Input_handling open Debugger_config open Program_loading open Question exception Current_checkpoint_lost exception Current_checkpoint_lost_start_at of int64 * int64 let remove_1st key list = let rec remove = function [] -> [] | a::l -> if a == key then l else a::(remove l) in remove list (*** Debugging. ***) let debug_time_travel = ref false (*** Internal utilities. ***) (* Insert a checkpoint in the checkpoint list. * Raise `Exit' if there is already a checkpoint at the same time. *) let insert_checkpoint ({c_time = time} as checkpoint) = let rec traverse = function [] -> [checkpoint] | (({c_time = t} as a)::l) as l' -> if t > time then a::(traverse l) else if t = time then raise Exit else checkpoint::l' in checkpoints := traverse !checkpoints (* Remove a checkpoint from the checkpoint list. * --- No error if not found. *) let remove_checkpoint checkpoint = checkpoints := remove_1st checkpoint !checkpoints (* Wait for the process used by `checkpoint' to connect. * --- Usually not called (the process is already connected). *) let wait_for_connection checkpoint = try Exec.unprotect (function () -> let old_controller = Input_handling.current_controller !connection in execute_with_other_controller (function fd -> old_controller fd; if checkpoint.c_valid = true then exit_main_loop ()) !connection main_loop) with Sys.Break -> checkpoint.c_parent <- root; remove_checkpoint checkpoint; checkpoint.c_pid <- -1; raise Sys.Break (* Select a checkpoint as current. *) let set_current_checkpoint checkpoint = if !debug_time_travel then prerr_endline ("Select: " ^ (Int.to_string checkpoint.c_pid)); if not checkpoint.c_valid then wait_for_connection checkpoint; current_checkpoint := checkpoint; let dead_frags = List.filter (fun frag -> not (List.mem frag checkpoint.c_code_fragments)) (Symbols.code_fragments ()) in List.iter Symbols.erase_symbols dead_frags; set_current_connection checkpoint.c_fd (* Kill `checkpoint'. *) let kill_checkpoint checkpoint = if !debug_time_travel then prerr_endline ("Kill: " ^ (Int.to_string checkpoint.c_pid)); if checkpoint.c_pid > 0 then (* Ghosts don't have to be killed ! *) (if not checkpoint.c_valid then wait_for_connection checkpoint; stop checkpoint.c_fd; if checkpoint.c_parent.c_pid > 0 then wait_child checkpoint.c_parent.c_fd; checkpoint.c_parent <- root; close_io checkpoint.c_fd; remove_file checkpoint.c_fd; remove_checkpoint checkpoint); checkpoint.c_pid <- -1 (* Don't exist anymore *) (*** Cleaning the checkpoint list. ***) (* Separate checkpoints before (<=) and after (>) `t'. *) # # # t checkpoints - > ( after , before ) let cut t = let rec cut_t = function [] -> ([], []) | ({c_time = t'} as a::l) as l' -> if t' <= t then ([], l') else let (b, e) = cut_t l in (a::b, e) in cut_t (* Partition the checkpoints list. *) let cut2 t0 t l = let rec cut2_t0 t = function [] -> [] | l -> let (after, before) = cut (t0 -- t -- _1) l in let l = cut2_t0 (t ++ t) before in after::l in let (after, before) = cut (t0 -- _1) l in after::(cut2_t0 t before) Separate first elements and last element of a list of checkpoints . let chk_merge2 cont = let rec chk_merge2_cont = function [] -> cont | [a] -> let (accepted, rejected) = cont in (a::accepted, rejected) | a::l -> let (accepted, rejected) = chk_merge2_cont l in (accepted, a::rejected) in chk_merge2_cont (* Separate the checkpoint list. *) # # # list - > accepted * rejected let rec chk_merge = function [] -> ([], []) | l::tail -> chk_merge2 (chk_merge tail) l let new_checkpoint_list checkpoint_count accepted rejected = if List.length accepted >= checkpoint_count then let (k, l) = list_truncate2 checkpoint_count accepted in (k, l @ rejected) else let (k, l) = list_truncate2 (checkpoint_count - List.length accepted) rejected in (List.merge (fun {c_time = t1} {c_time = t2} -> compare t2 t1) accepted k, l) (* Clean the checkpoint list. *) (* Reference time is `time'. *) let clean_checkpoints time checkpoint_count = let (after, before) = cut time !checkpoints in let (accepted, rejected) = chk_merge (cut2 time !checkpoint_small_step before) in let (kept, lost) = new_checkpoint_list checkpoint_count accepted after in List.iter kill_checkpoint (lost @ rejected); checkpoints := kept (*** Internal functions for moving. ***) Find the first checkpoint before ( or at ) ` time ' . * Ask for reloading the program if necessary . * Ask for reloading the program if necessary. *) let find_checkpoint_before time = let rec find = function [] -> print_string "Can't go that far in the past !"; print_newline (); if yes_or_no "Reload program" then begin load_program (); find !checkpoints end else raise Toplevel | { c_time = t } as a::l -> if t > time then find l else a in find !checkpoints (* Make a copy of the current checkpoint and clean the checkpoint list. *) (* --- The new checkpoint is not put in the list. *) let duplicate_current_checkpoint () = let checkpoint = !current_checkpoint in if not checkpoint.c_valid then wait_for_connection checkpoint; let new_checkpoint = (* Ghost *) {c_time = checkpoint.c_time; c_pid = 0; c_fd = checkpoint.c_fd; c_valid = false; c_report = checkpoint.c_report; c_state = C_stopped; c_parent = checkpoint; c_breakpoint_version = checkpoint.c_breakpoint_version; c_breakpoints = checkpoint.c_breakpoints; c_trap_barrier = checkpoint.c_trap_barrier; c_code_fragments = checkpoint.c_code_fragments} in checkpoints := list_replace checkpoint new_checkpoint !checkpoints; set_current_checkpoint checkpoint; clean_checkpoints (checkpoint.c_time ++ _1) (!checkpoint_max_count - 1); if new_checkpoint.c_pid = 0 then (* The ghost has not been killed *) (match do_checkpoint () with (* Duplicate checkpoint *) Checkpoint_done pid -> (new_checkpoint.c_pid <- pid; if !debug_time_travel then prerr_endline ("Waiting for connection: " ^ Int.to_string pid)) | Checkpoint_failed -> prerr_endline "A fork failed. Reducing maximum number of checkpoints."; checkpoint_max_count := List.length !checkpoints - 1; remove_checkpoint new_checkpoint) (* Was the movement interrupted ? *) (* --- An exception could have been used instead, *) (* --- but it is not clear where it should be caught. *) (* --- For instance, it should not be caught in `step' *) (* --- (as `step' is used in `next_1'). *) (* --- On the other side, other modules does not need to know *) (* --- about this exception. *) let interrupted = ref false (* Information about last breakpoint encountered *) let last_breakpoint = ref None (* Last debug info loaded *) let last_debug_info = ref None let rec do_go_dynlink steps = match do_go steps with | { rep_type = Code_loaded frag; rep_event_count = steps } as report -> begin match !last_debug_info with | Some di -> Symbols.add_symbols frag di; Symbols.set_all_events frag; last_debug_info := None | None -> assert false end; if !break_on_load then report else do_go_dynlink steps | { rep_type = Code_unloaded frag; rep_event_count = steps } -> Symbols.erase_symbols frag; do_go_dynlink steps | { rep_type = Debug_info di; rep_event_count = steps } -> last_debug_info := Some (Array.to_list di); do_go_dynlink steps | report -> report (* Ensure we stop on an event. *) let rec stop_on_event report = match report with {rep_type = Breakpoint; rep_program_pointer = pc; rep_stack_pointer = sp} -> last_breakpoint := Some (pc, sp); Symbols.update_current_event (); begin match !current_event with None -> find_event () | Some _ -> () end | {rep_type = Trap_barrier} -> (* No event at current position. *) find_event () | _ -> () and find_event () = if !debug_time_travel then begin print_string "Searching next event..."; print_newline () end; let report = do_go_dynlink _1 in !current_checkpoint.c_report <- Some report; stop_on_event report Internal function for running debugged program . * Requires ` duration > 0 ' . * Requires `duration > 0'. *) let internal_step duration = match current_report () with Some {rep_type = Exited | Uncaught_exc} -> () | _ -> Exec.protect (function () -> if !make_checkpoints then duplicate_current_checkpoint () else remove_checkpoint !current_checkpoint; update_breakpoints (); update_trap_barrier (); !current_checkpoint.c_state <- C_running duration; let report = do_go_dynlink duration in !current_checkpoint.c_report <- Some report; !current_checkpoint.c_state <- C_stopped; !current_checkpoint.c_code_fragments <- Symbols.code_fragments (); if report.rep_type = Event then begin !current_checkpoint.c_time <- !current_checkpoint.c_time ++ duration; interrupted := false; last_breakpoint := None end else begin !current_checkpoint.c_time <- !current_checkpoint.c_time ++ duration -- report.rep_event_count ++ _1; interrupted := true; last_breakpoint := None; stop_on_event report end; (try insert_checkpoint !current_checkpoint with Exit -> kill_checkpoint !current_checkpoint; set_current_checkpoint (find_checkpoint_before (current_time ())))); if !debug_time_travel then begin print_string "Checkpoints: pid(time)"; print_newline (); List.iter (function {c_time = time; c_pid = pid; c_valid = valid} -> Printf.printf "%d(%Ld)%s " pid time (if valid then "" else "(invalid)")) !checkpoints; print_newline () end (*** Miscellaneous functions (exported). ***) (* Create a checkpoint at time 0 (new program). *) let new_checkpoint pid fd = let new_checkpoint = {c_time = _0; c_pid = pid; c_fd = fd; c_valid = true; c_report = None; c_state = C_stopped; c_parent = root; c_breakpoint_version = 0; c_breakpoints = []; c_trap_barrier = 0; c_code_fragments = [0]} in insert_checkpoint new_checkpoint (* Set the file descriptor of a checkpoint *) (* (a new process has connected with the debugger). *) (* --- Return `true' on success (close the connection otherwise). *) let set_file_descriptor pid fd = let rec find = function [] -> prerr_endline "Unexpected connection"; close_io fd; false | ({c_pid = pid'} as checkpoint)::l -> if pid <> pid' then find l else (checkpoint.c_fd <- fd; checkpoint.c_valid <- true; true) in if !debug_time_travel then prerr_endline ("New connection: " ^(Int.to_string pid)); find (!current_checkpoint::!checkpoints) (* Kill all the checkpoints. *) let kill_all_checkpoints () = List.iter kill_checkpoint (!current_checkpoint::!checkpoints) (* Kill a checkpoint without killing the process. *) (* (used when connection with the process is lost). *) (* --- Assume that the checkpoint is valid. *) let forget_process fd pid = let checkpoint = List.find (function c -> c.c_pid = pid) (!current_checkpoint::!checkpoints) in if pid > 0 then begin Printf.eprintf "Lost connection with process %d" pid; let kont = if checkpoint == !current_checkpoint then begin Printf.eprintf " (active process)\n"; match !current_checkpoint.c_state with C_stopped -> Printf.eprintf "at time %Ld" !current_checkpoint.c_time; fun () -> raise Current_checkpoint_lost | C_running duration -> Printf.eprintf "between time %Ld and time %Ld" !current_checkpoint.c_time (!current_checkpoint.c_time ++ duration); fun () -> raise (Current_checkpoint_lost_start_at (!current_checkpoint.c_time, duration)) end else ignore in Printf.eprintf "\n"; flush stderr; Input_handling.remove_file fd; close_io checkpoint.c_fd; remove_file checkpoint.c_fd; remove_checkpoint checkpoint; checkpoint.c_pid <- -1; (* Don't exist anymore *) if checkpoint.c_parent.c_pid > 0 then wait_child checkpoint.c_parent.c_fd; kont () end (* Try to recover when the current checkpoint is lost. *) let recover () = set_current_checkpoint (find_checkpoint_before (current_time ())) (*** Simple movements. ***) (* Forward stepping. Requires `duration >= 0'. *) let rec step_forward duration = if duration > !checkpoint_small_step then begin let first_step = if duration > !checkpoint_big_step then !checkpoint_big_step else !checkpoint_small_step in internal_step first_step; if not !interrupted then step_forward (duration -- first_step) end else if duration != _0 then internal_step duration (* Go to time `time' from current checkpoint (internal). *) let internal_go_to time = let duration = time -- (current_time ()) in if duration > _0 then execute_without_breakpoints (function () -> step_forward duration) (* Move to a given time. *) let go_to time = let checkpoint = find_checkpoint_before time in set_current_checkpoint checkpoint; internal_go_to time (* Return the time of the last breakpoint *) (* between current time and `max_time'. *) let find_last_breakpoint max_time = let rec find break = let time = current_time () in step_forward (max_time -- time); match !last_breakpoint, !temporary_breakpoint_position with (Some _, _) when current_time () < max_time -> find !last_breakpoint | (Some (pc, _), Some pc') when pc = pc' -> (max_time, !last_breakpoint) | _ -> (time, break) in find (match current_pc_sp () with (Some (pc, _)) as state when breakpoint_at_pc pc -> state | _ -> None) Run from ` time_max ' back to ` time ' . (* --- Assume 0 <= time < time_max *) let rec back_to time time_max = let {c_time = t} = find_checkpoint_before (pre64 time_max) in go_to (max time t); let (new_time, break) = find_last_breakpoint time_max in if break <> None || (new_time <= time) then begin go_to new_time; interrupted := break <> None; last_breakpoint := break end else back_to time new_time (* Backward stepping. *) --- Assume duration > 1 let step_backward duration = let time = current_time () in if time > _0 then back_to (max _0 (time -- duration)) time (* Run the program from current time. *) Stop at the first breakpoint , or at the end of the program . let rec run () = internal_step !checkpoint_big_step; if not !interrupted then run () (* Run the program backward from current time. *) Stop at the first breakpoint , or at the beginning of the program . let back_run () = if current_time () > _0 then back_to _0 (current_time ()) (* Step in any direction. *) Stop at the first breakpoint , or after ` duration ' steps . let step duration = if duration >= _0 then step_forward duration else step_backward (_0 -- duration) (*** Next, finish. ***) (* Finish current function. *) let finish () = Symbols.update_current_event (); match !current_event with None -> prerr_endline "`finish' not meaningful in outermost frame."; raise Toplevel | Some {ev_ev={ev_stacksize}} -> set_initial_frame(); let (frame, pc) = up_frame ev_stacksize in if frame < 0 then begin prerr_endline "`finish' not meaningful in outermost frame."; raise Toplevel end; begin try ignore(Symbols.any_event_at_pc pc) with Not_found -> prerr_endline "Calling function has no debugging information."; raise Toplevel end; exec_with_trap_barrier frame (fun () -> exec_with_temporary_breakpoint pc (fun () -> while run (); match !last_breakpoint with Some (pc', frame') when pc = pc' -> interrupted := false; frame <> frame' | _ -> false do () done)) let next_1 () = Symbols.update_current_event (); match !current_event with None -> (* Beginning of the program. *) step _1 | Some {ev_ev={ev_stacksize=ev_stacksize1}} -> let (frame1, _pc1) = initial_frame() in step _1; if not !interrupted then begin Symbols.update_current_event (); match !current_event with None -> () | Some {ev_ev={ev_stacksize=ev_stacksize2}} -> let (frame2, _pc2) = initial_frame() in (* Call `finish' if we've entered a function. *) if frame1 >= 0 && frame2 >= 0 && frame2 - ev_stacksize2 > frame1 - ev_stacksize1 then finish() end (* Same as `step' (forward) but skip over function calls. *) let rec next = function 0 -> () | n -> next_1 (); if not !interrupted then next (n - 1) (* Run backward until just before current function. *) let start () = Symbols.update_current_event (); match !current_event with None -> prerr_endline "`start not meaningful in outermost frame."; raise Toplevel | Some {ev_ev={ev_stacksize}} -> let (frame, _) = initial_frame() in let (frame', pc) = up_frame ev_stacksize in if frame' < 0 then begin prerr_endline "`start not meaningful in outermost frame."; raise Toplevel end; let nargs = match try Symbols.any_event_at_pc pc with Not_found -> prerr_endline "Calling function has no debugging information."; raise Toplevel with {ev_ev = {ev_info = Event_return nargs}} -> nargs | _ -> Misc.fatal_error "Time_travel.start" in let offset = if nargs < 4 then 1 else 2 in let pc = { pc with pos = pc.pos - 4 * offset } in while exec_with_temporary_breakpoint pc back_run; match !last_breakpoint with Some (pc', frame') when pc = pc' -> step _minus1; (not !interrupted) && (frame' - nargs > frame - ev_stacksize) | _ -> false do () done let previous_1 () = Symbols.update_current_event (); match !current_event with None -> (* End of the program. *) step _minus1 | Some {ev_ev={ev_stacksize=ev_stacksize1}} -> let (frame1, _pc1) = initial_frame() in step _minus1; if not !interrupted then begin Symbols.update_current_event (); match !current_event with None -> () | Some {ev_ev={ev_stacksize=ev_stacksize2}} -> let (frame2, _pc2) = initial_frame() in (* Call `start' if we've entered a function. *) if frame1 >= 0 && frame2 >= 0 && frame2 - ev_stacksize2 > frame1 - ev_stacksize1 then start() end (* Same as `step' (backward) but skip over function calls. *) let rec previous = function 0 -> () | n -> previous_1 (); if not !interrupted then previous (n - 1)
null
https://raw.githubusercontent.com/progman1/genprintlib/acc1e5cc46b9ce6191d0306f51337581c93ffe94/debugger/4.10.0/time_travel.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. ************************************************************************ *************************** Time travel ***************************** ** Debugging. ** ** Internal utilities. ** Insert a checkpoint in the checkpoint list. * Raise `Exit' if there is already a checkpoint at the same time. Remove a checkpoint from the checkpoint list. * --- No error if not found. Wait for the process used by `checkpoint' to connect. * --- Usually not called (the process is already connected). Select a checkpoint as current. Kill `checkpoint'. Ghosts don't have to be killed ! Don't exist anymore ** Cleaning the checkpoint list. ** Separate checkpoints before (<=) and after (>) `t'. Partition the checkpoints list. Separate the checkpoint list. Clean the checkpoint list. Reference time is `time'. ** Internal functions for moving. ** Make a copy of the current checkpoint and clean the checkpoint list. --- The new checkpoint is not put in the list. Ghost The ghost has not been killed Duplicate checkpoint Was the movement interrupted ? --- An exception could have been used instead, --- but it is not clear where it should be caught. --- For instance, it should not be caught in `step' --- (as `step' is used in `next_1'). --- On the other side, other modules does not need to know --- about this exception. Information about last breakpoint encountered Last debug info loaded Ensure we stop on an event. No event at current position. ** Miscellaneous functions (exported). ** Create a checkpoint at time 0 (new program). Set the file descriptor of a checkpoint (a new process has connected with the debugger). --- Return `true' on success (close the connection otherwise). Kill all the checkpoints. Kill a checkpoint without killing the process. (used when connection with the process is lost). --- Assume that the checkpoint is valid. Don't exist anymore Try to recover when the current checkpoint is lost. ** Simple movements. ** Forward stepping. Requires `duration >= 0'. Go to time `time' from current checkpoint (internal). Move to a given time. Return the time of the last breakpoint between current time and `max_time'. --- Assume 0 <= time < time_max Backward stepping. Run the program from current time. Run the program backward from current time. Step in any direction. ** Next, finish. ** Finish current function. Beginning of the program. Call `finish' if we've entered a function. Same as `step' (forward) but skip over function calls. Run backward until just before current function. End of the program. Call `start' if we've entered a function. Same as `step' (backward) but skip over function calls.
, 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 Int64ops open Instruct open Events open Debugcom open Primitives open Checkpoints open Breakpoints open Trap_barrier open Input_handling open Debugger_config open Program_loading open Question exception Current_checkpoint_lost exception Current_checkpoint_lost_start_at of int64 * int64 let remove_1st key list = let rec remove = function [] -> [] | a::l -> if a == key then l else a::(remove l) in remove list let debug_time_travel = ref false let insert_checkpoint ({c_time = time} as checkpoint) = let rec traverse = function [] -> [checkpoint] | (({c_time = t} as a)::l) as l' -> if t > time then a::(traverse l) else if t = time then raise Exit else checkpoint::l' in checkpoints := traverse !checkpoints let remove_checkpoint checkpoint = checkpoints := remove_1st checkpoint !checkpoints let wait_for_connection checkpoint = try Exec.unprotect (function () -> let old_controller = Input_handling.current_controller !connection in execute_with_other_controller (function fd -> old_controller fd; if checkpoint.c_valid = true then exit_main_loop ()) !connection main_loop) with Sys.Break -> checkpoint.c_parent <- root; remove_checkpoint checkpoint; checkpoint.c_pid <- -1; raise Sys.Break let set_current_checkpoint checkpoint = if !debug_time_travel then prerr_endline ("Select: " ^ (Int.to_string checkpoint.c_pid)); if not checkpoint.c_valid then wait_for_connection checkpoint; current_checkpoint := checkpoint; let dead_frags = List.filter (fun frag -> not (List.mem frag checkpoint.c_code_fragments)) (Symbols.code_fragments ()) in List.iter Symbols.erase_symbols dead_frags; set_current_connection checkpoint.c_fd let kill_checkpoint checkpoint = if !debug_time_travel then prerr_endline ("Kill: " ^ (Int.to_string checkpoint.c_pid)); (if not checkpoint.c_valid then wait_for_connection checkpoint; stop checkpoint.c_fd; if checkpoint.c_parent.c_pid > 0 then wait_child checkpoint.c_parent.c_fd; checkpoint.c_parent <- root; close_io checkpoint.c_fd; remove_file checkpoint.c_fd; remove_checkpoint checkpoint); # # # t checkpoints - > ( after , before ) let cut t = let rec cut_t = function [] -> ([], []) | ({c_time = t'} as a::l) as l' -> if t' <= t then ([], l') else let (b, e) = cut_t l in (a::b, e) in cut_t let cut2 t0 t l = let rec cut2_t0 t = function [] -> [] | l -> let (after, before) = cut (t0 -- t -- _1) l in let l = cut2_t0 (t ++ t) before in after::l in let (after, before) = cut (t0 -- _1) l in after::(cut2_t0 t before) Separate first elements and last element of a list of checkpoints . let chk_merge2 cont = let rec chk_merge2_cont = function [] -> cont | [a] -> let (accepted, rejected) = cont in (a::accepted, rejected) | a::l -> let (accepted, rejected) = chk_merge2_cont l in (accepted, a::rejected) in chk_merge2_cont # # # list - > accepted * rejected let rec chk_merge = function [] -> ([], []) | l::tail -> chk_merge2 (chk_merge tail) l let new_checkpoint_list checkpoint_count accepted rejected = if List.length accepted >= checkpoint_count then let (k, l) = list_truncate2 checkpoint_count accepted in (k, l @ rejected) else let (k, l) = list_truncate2 (checkpoint_count - List.length accepted) rejected in (List.merge (fun {c_time = t1} {c_time = t2} -> compare t2 t1) accepted k, l) let clean_checkpoints time checkpoint_count = let (after, before) = cut time !checkpoints in let (accepted, rejected) = chk_merge (cut2 time !checkpoint_small_step before) in let (kept, lost) = new_checkpoint_list checkpoint_count accepted after in List.iter kill_checkpoint (lost @ rejected); checkpoints := kept Find the first checkpoint before ( or at ) ` time ' . * Ask for reloading the program if necessary . * Ask for reloading the program if necessary. *) let find_checkpoint_before time = let rec find = function [] -> print_string "Can't go that far in the past !"; print_newline (); if yes_or_no "Reload program" then begin load_program (); find !checkpoints end else raise Toplevel | { c_time = t } as a::l -> if t > time then find l else a in find !checkpoints let duplicate_current_checkpoint () = let checkpoint = !current_checkpoint in if not checkpoint.c_valid then wait_for_connection checkpoint; {c_time = checkpoint.c_time; c_pid = 0; c_fd = checkpoint.c_fd; c_valid = false; c_report = checkpoint.c_report; c_state = C_stopped; c_parent = checkpoint; c_breakpoint_version = checkpoint.c_breakpoint_version; c_breakpoints = checkpoint.c_breakpoints; c_trap_barrier = checkpoint.c_trap_barrier; c_code_fragments = checkpoint.c_code_fragments} in checkpoints := list_replace checkpoint new_checkpoint !checkpoints; set_current_checkpoint checkpoint; clean_checkpoints (checkpoint.c_time ++ _1) (!checkpoint_max_count - 1); Checkpoint_done pid -> (new_checkpoint.c_pid <- pid; if !debug_time_travel then prerr_endline ("Waiting for connection: " ^ Int.to_string pid)) | Checkpoint_failed -> prerr_endline "A fork failed. Reducing maximum number of checkpoints."; checkpoint_max_count := List.length !checkpoints - 1; remove_checkpoint new_checkpoint) let interrupted = ref false let last_breakpoint = ref None let last_debug_info = ref None let rec do_go_dynlink steps = match do_go steps with | { rep_type = Code_loaded frag; rep_event_count = steps } as report -> begin match !last_debug_info with | Some di -> Symbols.add_symbols frag di; Symbols.set_all_events frag; last_debug_info := None | None -> assert false end; if !break_on_load then report else do_go_dynlink steps | { rep_type = Code_unloaded frag; rep_event_count = steps } -> Symbols.erase_symbols frag; do_go_dynlink steps | { rep_type = Debug_info di; rep_event_count = steps } -> last_debug_info := Some (Array.to_list di); do_go_dynlink steps | report -> report let rec stop_on_event report = match report with {rep_type = Breakpoint; rep_program_pointer = pc; rep_stack_pointer = sp} -> last_breakpoint := Some (pc, sp); Symbols.update_current_event (); begin match !current_event with None -> find_event () | Some _ -> () end | {rep_type = Trap_barrier} -> find_event () | _ -> () and find_event () = if !debug_time_travel then begin print_string "Searching next event..."; print_newline () end; let report = do_go_dynlink _1 in !current_checkpoint.c_report <- Some report; stop_on_event report Internal function for running debugged program . * Requires ` duration > 0 ' . * Requires `duration > 0'. *) let internal_step duration = match current_report () with Some {rep_type = Exited | Uncaught_exc} -> () | _ -> Exec.protect (function () -> if !make_checkpoints then duplicate_current_checkpoint () else remove_checkpoint !current_checkpoint; update_breakpoints (); update_trap_barrier (); !current_checkpoint.c_state <- C_running duration; let report = do_go_dynlink duration in !current_checkpoint.c_report <- Some report; !current_checkpoint.c_state <- C_stopped; !current_checkpoint.c_code_fragments <- Symbols.code_fragments (); if report.rep_type = Event then begin !current_checkpoint.c_time <- !current_checkpoint.c_time ++ duration; interrupted := false; last_breakpoint := None end else begin !current_checkpoint.c_time <- !current_checkpoint.c_time ++ duration -- report.rep_event_count ++ _1; interrupted := true; last_breakpoint := None; stop_on_event report end; (try insert_checkpoint !current_checkpoint with Exit -> kill_checkpoint !current_checkpoint; set_current_checkpoint (find_checkpoint_before (current_time ())))); if !debug_time_travel then begin print_string "Checkpoints: pid(time)"; print_newline (); List.iter (function {c_time = time; c_pid = pid; c_valid = valid} -> Printf.printf "%d(%Ld)%s " pid time (if valid then "" else "(invalid)")) !checkpoints; print_newline () end let new_checkpoint pid fd = let new_checkpoint = {c_time = _0; c_pid = pid; c_fd = fd; c_valid = true; c_report = None; c_state = C_stopped; c_parent = root; c_breakpoint_version = 0; c_breakpoints = []; c_trap_barrier = 0; c_code_fragments = [0]} in insert_checkpoint new_checkpoint let set_file_descriptor pid fd = let rec find = function [] -> prerr_endline "Unexpected connection"; close_io fd; false | ({c_pid = pid'} as checkpoint)::l -> if pid <> pid' then find l else (checkpoint.c_fd <- fd; checkpoint.c_valid <- true; true) in if !debug_time_travel then prerr_endline ("New connection: " ^(Int.to_string pid)); find (!current_checkpoint::!checkpoints) let kill_all_checkpoints () = List.iter kill_checkpoint (!current_checkpoint::!checkpoints) let forget_process fd pid = let checkpoint = List.find (function c -> c.c_pid = pid) (!current_checkpoint::!checkpoints) in if pid > 0 then begin Printf.eprintf "Lost connection with process %d" pid; let kont = if checkpoint == !current_checkpoint then begin Printf.eprintf " (active process)\n"; match !current_checkpoint.c_state with C_stopped -> Printf.eprintf "at time %Ld" !current_checkpoint.c_time; fun () -> raise Current_checkpoint_lost | C_running duration -> Printf.eprintf "between time %Ld and time %Ld" !current_checkpoint.c_time (!current_checkpoint.c_time ++ duration); fun () -> raise (Current_checkpoint_lost_start_at (!current_checkpoint.c_time, duration)) end else ignore in Printf.eprintf "\n"; flush stderr; Input_handling.remove_file fd; close_io checkpoint.c_fd; remove_file checkpoint.c_fd; remove_checkpoint checkpoint; if checkpoint.c_parent.c_pid > 0 then wait_child checkpoint.c_parent.c_fd; kont () end let recover () = set_current_checkpoint (find_checkpoint_before (current_time ())) let rec step_forward duration = if duration > !checkpoint_small_step then begin let first_step = if duration > !checkpoint_big_step then !checkpoint_big_step else !checkpoint_small_step in internal_step first_step; if not !interrupted then step_forward (duration -- first_step) end else if duration != _0 then internal_step duration let internal_go_to time = let duration = time -- (current_time ()) in if duration > _0 then execute_without_breakpoints (function () -> step_forward duration) let go_to time = let checkpoint = find_checkpoint_before time in set_current_checkpoint checkpoint; internal_go_to time let find_last_breakpoint max_time = let rec find break = let time = current_time () in step_forward (max_time -- time); match !last_breakpoint, !temporary_breakpoint_position with (Some _, _) when current_time () < max_time -> find !last_breakpoint | (Some (pc, _), Some pc') when pc = pc' -> (max_time, !last_breakpoint) | _ -> (time, break) in find (match current_pc_sp () with (Some (pc, _)) as state when breakpoint_at_pc pc -> state | _ -> None) Run from ` time_max ' back to ` time ' . let rec back_to time time_max = let {c_time = t} = find_checkpoint_before (pre64 time_max) in go_to (max time t); let (new_time, break) = find_last_breakpoint time_max in if break <> None || (new_time <= time) then begin go_to new_time; interrupted := break <> None; last_breakpoint := break end else back_to time new_time --- Assume duration > 1 let step_backward duration = let time = current_time () in if time > _0 then back_to (max _0 (time -- duration)) time Stop at the first breakpoint , or at the end of the program . let rec run () = internal_step !checkpoint_big_step; if not !interrupted then run () Stop at the first breakpoint , or at the beginning of the program . let back_run () = if current_time () > _0 then back_to _0 (current_time ()) Stop at the first breakpoint , or after ` duration ' steps . let step duration = if duration >= _0 then step_forward duration else step_backward (_0 -- duration) let finish () = Symbols.update_current_event (); match !current_event with None -> prerr_endline "`finish' not meaningful in outermost frame."; raise Toplevel | Some {ev_ev={ev_stacksize}} -> set_initial_frame(); let (frame, pc) = up_frame ev_stacksize in if frame < 0 then begin prerr_endline "`finish' not meaningful in outermost frame."; raise Toplevel end; begin try ignore(Symbols.any_event_at_pc pc) with Not_found -> prerr_endline "Calling function has no debugging information."; raise Toplevel end; exec_with_trap_barrier frame (fun () -> exec_with_temporary_breakpoint pc (fun () -> while run (); match !last_breakpoint with Some (pc', frame') when pc = pc' -> interrupted := false; frame <> frame' | _ -> false do () done)) let next_1 () = Symbols.update_current_event (); match !current_event with step _1 | Some {ev_ev={ev_stacksize=ev_stacksize1}} -> let (frame1, _pc1) = initial_frame() in step _1; if not !interrupted then begin Symbols.update_current_event (); match !current_event with None -> () | Some {ev_ev={ev_stacksize=ev_stacksize2}} -> let (frame2, _pc2) = initial_frame() in if frame1 >= 0 && frame2 >= 0 && frame2 - ev_stacksize2 > frame1 - ev_stacksize1 then finish() end let rec next = function 0 -> () | n -> next_1 (); if not !interrupted then next (n - 1) let start () = Symbols.update_current_event (); match !current_event with None -> prerr_endline "`start not meaningful in outermost frame."; raise Toplevel | Some {ev_ev={ev_stacksize}} -> let (frame, _) = initial_frame() in let (frame', pc) = up_frame ev_stacksize in if frame' < 0 then begin prerr_endline "`start not meaningful in outermost frame."; raise Toplevel end; let nargs = match try Symbols.any_event_at_pc pc with Not_found -> prerr_endline "Calling function has no debugging information."; raise Toplevel with {ev_ev = {ev_info = Event_return nargs}} -> nargs | _ -> Misc.fatal_error "Time_travel.start" in let offset = if nargs < 4 then 1 else 2 in let pc = { pc with pos = pc.pos - 4 * offset } in while exec_with_temporary_breakpoint pc back_run; match !last_breakpoint with Some (pc', frame') when pc = pc' -> step _minus1; (not !interrupted) && (frame' - nargs > frame - ev_stacksize) | _ -> false do () done let previous_1 () = Symbols.update_current_event (); match !current_event with step _minus1 | Some {ev_ev={ev_stacksize=ev_stacksize1}} -> let (frame1, _pc1) = initial_frame() in step _minus1; if not !interrupted then begin Symbols.update_current_event (); match !current_event with None -> () | Some {ev_ev={ev_stacksize=ev_stacksize2}} -> let (frame2, _pc2) = initial_frame() in if frame1 >= 0 && frame2 >= 0 && frame2 - ev_stacksize2 > frame1 - ev_stacksize1 then start() end let rec previous = function 0 -> () | n -> previous_1 (); if not !interrupted then previous (n - 1)
a0b4bdbf2bd7ca96708dbf4440b0226d7ef1ee7808bd68c05bf689de88e7809f
realworldocaml/book
bench.ml
open! Base let%bench_module "Overheads" = (module struct (* Using [%bench_fun] to bind the input outside the benchmarked code actually has less overhead then using [%bench] naively. *) let%bench_fun "int overhead" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Fn.id n ;; let%bench_fun "int64 overhead" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Fn.id n ;; let%bench_fun "int32 overhead" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Fn.id n ;; let%bench_fun "nativeint overhead" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Fn.id n ;; end) ;; let%bench_module "Clz" = (module struct (* ocaml_intrinsics library *) let%bench_fun "int_clz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_leading_zeros n ;; let%bench_fun "int_clz2" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_leading_zeros2 n ;; let%bench_fun "int64_clz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Int64.count_leading_zeros n ;; let%bench_fun "nativeint_clz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Ocaml_intrinsics.Nativeint.count_leading_zeros n ;; let%bench_fun "int32_clz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Ocaml_intrinsics.Int32.count_leading_zeros n ;; (* Base *) let%bench_fun "base int_clz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Base.Int.clz n ;; let%bench_fun "base int64_clz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Base.Int64.clz n ;; let%bench_fun "base nativeint_clz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Base.Nativeint.clz n ;; let%bench_fun "base int32_clz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Base.Int32.clz n ;; end) ;; let%bench_module "Ctz" = (module struct (* ocaml_intrinsics library *) let%bench_fun "int_ctz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_trailing_zeros n ;; let%bench_fun "int64_ctz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Int64.count_trailing_zeros n ;; let%bench_fun "nativeint_ctz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Ocaml_intrinsics.Nativeint.count_trailing_zeros n ;; let%bench_fun "int32_ctz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Ocaml_intrinsics.Int32.count_trailing_zeros n ;; (* Base *) let%bench_fun "base int_ctz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Base.Int.ctz n ;; let%bench_fun "base int64_ctz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Base.Int64.ctz n ;; let%bench_fun "base nativeint_ctz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Base.Nativeint.ctz n ;; let%bench_fun "base int32_ctz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Base.Int32.ctz n ;; end) ;; let%bench_module "Popcnt" = (module struct (* ocaml_intrinsics library *) let%bench_fun "int_popcount" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_set_bits n ;; let%bench_fun "int_popcount2" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_set_bits2 n ;; let%bench_fun "int64_popcount" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Int64.count_set_bits n ;; let%bench_fun "nativeint_popcount" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Ocaml_intrinsics.Nativeint.count_set_bits n ;; let%bench_fun "int32_popcount" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Ocaml_intrinsics.Int32.count_set_bits n ;; (* Base *) let%bench_fun "base int_popcount" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Base.Int.popcount n ;; let%bench_fun "base int64_popcount" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Base.Int64.popcount n ;; let%bench_fun "base nativeint_popcount" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Base.Nativeint.popcount n ;; let%bench_fun "base int32_popcount" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Base.Int32.popcount n ;; end) ;; let%bench_module "Perfmon.rdtsc" = (module struct (* ocaml_intrinsics library *) let%bench_fun "rdtsc" = fun () -> Ocaml_intrinsics.Perfmon.rdtsc () (* ocaml_intrinsics library *) let%bench_fun "int_of_rdtsc" = fun () -> Int64.to_int_trunc (Ocaml_intrinsics.Perfmon.rdtsc ()) ;; (* Time_stamp_counter *) let%bench_fun "Time_stamp_counter.now" = fun () -> Time_stamp_counter.now () end) ;; let%bench_module "Perfmon.rdpmc" = (module struct let cpu_count_hw_cpu_cycles = (1 lsl 30) + 1 let%bench_fun "rdpmc" = fun () -> Ocaml_intrinsics.Perfmon.rdpmc (Int32.of_int_exn cpu_count_hw_cpu_cycles) ;; end) ;; let%bench_module "Crc" = (module struct (* ocaml_intrinsics library *) let%bench_fun "int_crc" = let initial = Sys.opaque_identity (Random.int Int.max_value) in let data = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Crc.int_crc ~initial ~data ;; let%bench_fun "int64_crc" = let initial = Sys.opaque_identity (Random.int Int.max_value) in let data = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Crc.int64_crc ~initial ~data ;; let%bench_fun "iterated_crc_exn" = let initial = Sys.opaque_identity (Random.int Int.max_value) in let data = Sys.opaque_identity (Random.int Int.max_value) in let iterations = Sys.opaque_identity 100 in fun () -> Ocaml_intrinsics.Crc.iterated_crc_exn ~initial ~data ~iterations ;; end) ;;
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ocaml_intrinsics/bench/bench.ml
ocaml
Using [%bench_fun] to bind the input outside the benchmarked code actually has less overhead then using [%bench] naively. ocaml_intrinsics library Base ocaml_intrinsics library Base ocaml_intrinsics library Base ocaml_intrinsics library ocaml_intrinsics library Time_stamp_counter ocaml_intrinsics library
open! Base let%bench_module "Overheads" = (module struct let%bench_fun "int overhead" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Fn.id n ;; let%bench_fun "int64 overhead" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Fn.id n ;; let%bench_fun "int32 overhead" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Fn.id n ;; let%bench_fun "nativeint overhead" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Fn.id n ;; end) ;; let%bench_module "Clz" = (module struct let%bench_fun "int_clz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_leading_zeros n ;; let%bench_fun "int_clz2" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_leading_zeros2 n ;; let%bench_fun "int64_clz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Int64.count_leading_zeros n ;; let%bench_fun "nativeint_clz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Ocaml_intrinsics.Nativeint.count_leading_zeros n ;; let%bench_fun "int32_clz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Ocaml_intrinsics.Int32.count_leading_zeros n ;; let%bench_fun "base int_clz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Base.Int.clz n ;; let%bench_fun "base int64_clz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Base.Int64.clz n ;; let%bench_fun "base nativeint_clz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Base.Nativeint.clz n ;; let%bench_fun "base int32_clz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Base.Int32.clz n ;; end) ;; let%bench_module "Ctz" = (module struct let%bench_fun "int_ctz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_trailing_zeros n ;; let%bench_fun "int64_ctz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Int64.count_trailing_zeros n ;; let%bench_fun "nativeint_ctz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Ocaml_intrinsics.Nativeint.count_trailing_zeros n ;; let%bench_fun "int32_ctz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Ocaml_intrinsics.Int32.count_trailing_zeros n ;; let%bench_fun "base int_ctz" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Base.Int.ctz n ;; let%bench_fun "base int64_ctz" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Base.Int64.ctz n ;; let%bench_fun "base nativeint_ctz" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Base.Nativeint.ctz n ;; let%bench_fun "base int32_ctz" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Base.Int32.ctz n ;; end) ;; let%bench_module "Popcnt" = (module struct let%bench_fun "int_popcount" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_set_bits n ;; let%bench_fun "int_popcount2" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Int.count_set_bits2 n ;; let%bench_fun "int64_popcount" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Int64.count_set_bits n ;; let%bench_fun "nativeint_popcount" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Ocaml_intrinsics.Nativeint.count_set_bits n ;; let%bench_fun "int32_popcount" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Ocaml_intrinsics.Int32.count_set_bits n ;; let%bench_fun "base int_popcount" = let n = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Base.Int.popcount n ;; let%bench_fun "base int64_popcount" = let n = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Base.Int64.popcount n ;; let%bench_fun "base nativeint_popcount" = let n = Sys.opaque_identity (Random.nativeint Nativeint.max_value) in fun () -> Base.Nativeint.popcount n ;; let%bench_fun "base int32_popcount" = let n = Sys.opaque_identity (Random.int32 Int32.max_value) in fun () -> Base.Int32.popcount n ;; end) ;; let%bench_module "Perfmon.rdtsc" = (module struct let%bench_fun "rdtsc" = fun () -> Ocaml_intrinsics.Perfmon.rdtsc () let%bench_fun "int_of_rdtsc" = fun () -> Int64.to_int_trunc (Ocaml_intrinsics.Perfmon.rdtsc ()) ;; let%bench_fun "Time_stamp_counter.now" = fun () -> Time_stamp_counter.now () end) ;; let%bench_module "Perfmon.rdpmc" = (module struct let cpu_count_hw_cpu_cycles = (1 lsl 30) + 1 let%bench_fun "rdpmc" = fun () -> Ocaml_intrinsics.Perfmon.rdpmc (Int32.of_int_exn cpu_count_hw_cpu_cycles) ;; end) ;; let%bench_module "Crc" = (module struct let%bench_fun "int_crc" = let initial = Sys.opaque_identity (Random.int Int.max_value) in let data = Sys.opaque_identity (Random.int Int.max_value) in fun () -> Ocaml_intrinsics.Crc.int_crc ~initial ~data ;; let%bench_fun "int64_crc" = let initial = Sys.opaque_identity (Random.int Int.max_value) in let data = Sys.opaque_identity (Random.int64 Int64.max_value) in fun () -> Ocaml_intrinsics.Crc.int64_crc ~initial ~data ;; let%bench_fun "iterated_crc_exn" = let initial = Sys.opaque_identity (Random.int Int.max_value) in let data = Sys.opaque_identity (Random.int Int.max_value) in let iterations = Sys.opaque_identity 100 in fun () -> Ocaml_intrinsics.Crc.iterated_crc_exn ~initial ~data ~iterations ;; end) ;;
7b8c581fe6d7729b197c7d21f3f84ff504091ee035449edb0db25f17ad867304
input-output-hk/offchain-metadata-tools
Main.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Main where import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Logger ( runStdoutLoggingT ) import qualified Data.ByteString.Char8 as C8 import qualified Data.Text as T import qualified Database.Persist.Postgresql as Postgresql import qualified Network.Wai.Handler.Warp as Warp import qualified Options.Applicative as Opt import System.Environment ( lookupEnv ) import qualified Cardano.Metadata.Store.Postgres as Store import Cardano.Metadata.Store.Postgres.Config ( Opts (..), pgConnectionString ) import Cardano.Metadata.Webhook.Server import Cardano.Metadata.Webhook.Types import Config ( opts ) main :: IO () main = do key <- maybe mempty C8.pack <$> lookupEnv "METADATA_WEBHOOK_SECRET" githubToken <- GitHubToken . maybe "" T.pack <$> lookupEnv "METADATA_GITHUB_TOKEN" options@(Opts { optDbConnections = numDbConns , optDbMetadataTableName = tableName , optServerPort = port }) <- Opt.execParser opts let pgConnString = pgConnectionString options putStrLn $ "Connecting to database using connection string: " <> C8.unpack pgConnString runStdoutLoggingT $ Postgresql.withPostgresqlPool pgConnString numDbConns $ \pool -> liftIO $ do putStrLn $ "Initializing table '" <> tableName <> "'." intf <- Store.postgresStore pool (T.pack tableName) putStrLn $ "Metadata webhook is starting on port " <> show port <> "." liftIO $ Warp.run port (appSigned (gitHubKey $ pure key) intf (getFileContent githubToken))
null
https://raw.githubusercontent.com/input-output-hk/offchain-metadata-tools/794f08cedbf555e9d207bccc45c08abbcf98add9/metadata-webhook/src/Main.hs
haskell
# LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes #
# LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # module Main where import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Logger ( runStdoutLoggingT ) import qualified Data.ByteString.Char8 as C8 import qualified Data.Text as T import qualified Database.Persist.Postgresql as Postgresql import qualified Network.Wai.Handler.Warp as Warp import qualified Options.Applicative as Opt import System.Environment ( lookupEnv ) import qualified Cardano.Metadata.Store.Postgres as Store import Cardano.Metadata.Store.Postgres.Config ( Opts (..), pgConnectionString ) import Cardano.Metadata.Webhook.Server import Cardano.Metadata.Webhook.Types import Config ( opts ) main :: IO () main = do key <- maybe mempty C8.pack <$> lookupEnv "METADATA_WEBHOOK_SECRET" githubToken <- GitHubToken . maybe "" T.pack <$> lookupEnv "METADATA_GITHUB_TOKEN" options@(Opts { optDbConnections = numDbConns , optDbMetadataTableName = tableName , optServerPort = port }) <- Opt.execParser opts let pgConnString = pgConnectionString options putStrLn $ "Connecting to database using connection string: " <> C8.unpack pgConnString runStdoutLoggingT $ Postgresql.withPostgresqlPool pgConnString numDbConns $ \pool -> liftIO $ do putStrLn $ "Initializing table '" <> tableName <> "'." intf <- Store.postgresStore pool (T.pack tableName) putStrLn $ "Metadata webhook is starting on port " <> show port <> "." liftIO $ Warp.run port (appSigned (gitHubKey $ pure key) intf (getFileContent githubToken))
6e30f68a8dd57bbfdea25246532a6a49fc59aa6640c825dae1c4690c9373f3ff
yawaramin/re-web
Let.ml
module Option = struct let (let*) = Option.bind let (let+) option f = Option.map f option end module Result = struct let (let*) result f = match result with | Ok value -> f value | Error e -> Error e let (let+) result f = match result with | Ok value -> Ok (f value) | Error e -> Error e end
null
https://raw.githubusercontent.com/yawaramin/re-web/7b407c1b98ddfac32a81c32481c40cc535c7452a/ReWeb/Let.ml
ocaml
module Option = struct let (let*) = Option.bind let (let+) option f = Option.map f option end module Result = struct let (let*) result f = match result with | Ok value -> f value | Error e -> Error e let (let+) result f = match result with | Ok value -> Ok (f value) | Error e -> Error e end
c701179aba534e824f9c83d59e9e22deac7258539564fcfff4a47829d6242e2e
SonarQubeCommunity/sonar-erlang
branchesofrecursion.erl
-module(a). quicksort([H|T]) -> {Smaller_Ones,Larger_Ones} = a:split(H,T,{[],[]}), lists:append( quicksort(Smaller_Ones), [H | quicksort(Larger_Ones)] ); quicksort([]) -> []. split(Pivot, [H|T], {Acc_S, Acc_L}) -> if Pivot > H -> New_Acc = { [H|Acc_S] , Acc_L }; true -> New_Acc = { Acc_S , [H|Acc_L] } end, split(Pivot,T,New_Acc); split(_,[],Acc) -> Acc.
null
https://raw.githubusercontent.com/SonarQubeCommunity/sonar-erlang/279eb7ccd84787c1c0cfd34b9a07981eb20183e3/erlang-squid/src/test/resources/metrics/branchesofrecursion.erl
erlang
-module(a). quicksort([H|T]) -> {Smaller_Ones,Larger_Ones} = a:split(H,T,{[],[]}), lists:append( quicksort(Smaller_Ones), [H | quicksort(Larger_Ones)] ); quicksort([]) -> []. split(Pivot, [H|T], {Acc_S, Acc_L}) -> if Pivot > H -> New_Acc = { [H|Acc_S] , Acc_L }; true -> New_Acc = { Acc_S , [H|Acc_L] } end, split(Pivot,T,New_Acc); split(_,[],Acc) -> Acc.
334acb56c5ac6bbc85b02e55e60f195f36e2a9cd17fc10966b045a205d0dd301
scalaris-team/scalaris
bench_load.erl
2007 - 2014 Zuse Institute Berlin 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. @author < > %% @doc Load generator %% @end %% @version $Id$ -module(bench_load). -author(''). -vsn('$Id$'). -export([start/1]). -include("scalaris.hrl"). -spec start(Gap::pos_integer()) -> ok. start(Gap) -> loop(Gap, []). -spec loop(Gap::pos_integer(), [pid()]) -> ok. loop(Gap, Pids) -> trace_mpath:thread_yield(), receive ?SCALARIS_RECV( {load_stop}, %%-> begin _ = [erlang:exit(Pid, kill) || Pid <- Pids], ok end ) after Gap -> Pid = spawn_new(), loop(Gap, [Pid | Pids]) end. spawn_new() -> io:format("spawn~n", []), spawn(fun() -> worker() end). worker() -> Key1 = randoms:getRandomString(), Key2 = randoms:getRandomString(), read_read_iter(Key1, Key2, 1000, 0), worker(). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read_read ( reads two items in one transaction ) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% read_read_tx(Key1, Key2) -> {_, Result} = api_tx:req_list([{read, Key1}, {read, Key2}, {commit}]), Result. read_read_iter(_Key1, _Key2, 0, Aborts) -> Aborts; read_read_iter(Key1, Key2, Iterations, Aborts) -> case read_read_tx(Key1, Key2) of [{ok, 0},{ok,0},{ok}] -> read_read_iter(Key1, Key2, Iterations - 1, Aborts); _ -> read_read_iter(Key1, Key2, Iterations, Aborts + 1) end.
null
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/bench_load.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc Load generator @end @version $Id$ ->
2007 - 2014 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > -module(bench_load). -author(''). -vsn('$Id$'). -export([start/1]). -include("scalaris.hrl"). -spec start(Gap::pos_integer()) -> ok. start(Gap) -> loop(Gap, []). -spec loop(Gap::pos_integer(), [pid()]) -> ok. loop(Gap, Pids) -> trace_mpath:thread_yield(), receive ?SCALARIS_RECV( begin _ = [erlang:exit(Pid, kill) || Pid <- Pids], ok end ) after Gap -> Pid = spawn_new(), loop(Gap, [Pid | Pids]) end. spawn_new() -> io:format("spawn~n", []), spawn(fun() -> worker() end). worker() -> Key1 = randoms:getRandomString(), Key2 = randoms:getRandomString(), read_read_iter(Key1, Key2, 1000, 0), worker(). read_read ( reads two items in one transaction ) read_read_tx(Key1, Key2) -> {_, Result} = api_tx:req_list([{read, Key1}, {read, Key2}, {commit}]), Result. read_read_iter(_Key1, _Key2, 0, Aborts) -> Aborts; read_read_iter(Key1, Key2, Iterations, Aborts) -> case read_read_tx(Key1, Key2) of [{ok, 0},{ok,0},{ok}] -> read_read_iter(Key1, Key2, Iterations - 1, Aborts); _ -> read_read_iter(Key1, Key2, Iterations, Aborts + 1) end.
7aefab948fd7314a4d68d5ca249170a49f01a62d075468b45ac4f11d3acea8e9
zenspider/schemers
exercise.4.66.scm
#!/usr/bin/env csi -s (require rackunit) (require-library logic-eval) (import logic-eval) (initialize-data-base microshaft-data-base) Exercise 4.66 has been generalizing the query system to ;; provide statistics about the company. For example, to find the ;; total salaries of all the computer programmers one will be able to ;; say ;; ;; (sum ?amount ;; (and (job ?x (computer programmer)) ;; (salary ?x ?amount))) ;; In general , 's new system allows expressions of the form ;; ;; (accumulation-function <VARIABLE> ;; <QUERY PATTERN>) ;; ;; where `accumulation-function' can be things like `sum', `average', or ` maximum ' . reasons that it should be a cinch to implement ;; this. He will simply feed the query pattern to `qeval'. This ;; will produce a stream of frames. He will then pass this stream ;; through a mapping function that extracts the value of the ;; designated variable from each frame in the stream and feed the ;; resulting stream of values to the accumulation function. Just as completes the implementation and is about to try it out , Cy ;; walks by, still puzzling over the `wheel' query result in exercise * Note Exercise 4 - 65 : : . When Cy shows the system 's response , , " Oh , no , my simple accumulation scheme wo n't work ! " ;; What has just realized ? Outline a method he can use to ;; salvage the situation. ;; No clue what he just realized, but it can't be that hard, because ;; we did most of it via all-of: (test 458000 (fold + 0 (map third (all-of '(salary ?who ?amount))))) (define (accumulation-function fun identity var query) (let ((index (list-index (lambda (x) (eq? var x)) query))) (fold fun identity (map (lambda (l) (list-ref l index)) (all-of query))))) (test 458000 (accumulation-function + 0 '?amount '(salary ?who ?amount))) (test '((Bitdiddle Ben) (Hacker Alyssa P) (Fect Cy D) (Tweakit Lem E) (Reasoner Louis) (Warbucks Oliver) (Scrooge Eben) (Cratchet Robert) (Aull DeWitt)) (accumulation-function cons '() '?who '(salary ?who ?amount))) ;; maybe he's just a bad programmer? ;; I'd call it stream-map-fold personally
null
https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_4/exercise.4.66.scm
scheme
provide statistics about the company. For example, to find the total salaries of all the computer programmers one will be able to say (sum ?amount (and (job ?x (computer programmer)) (salary ?x ?amount))) (accumulation-function <VARIABLE> <QUERY PATTERN>) where `accumulation-function' can be things like `sum', `average', this. He will simply feed the query pattern to `qeval'. This will produce a stream of frames. He will then pass this stream through a mapping function that extracts the value of the designated variable from each frame in the stream and feed the resulting stream of values to the accumulation function. Just as walks by, still puzzling over the `wheel' query result in exercise salvage the situation. No clue what he just realized, but it can't be that hard, because we did most of it via all-of: maybe he's just a bad programmer? I'd call it stream-map-fold personally
#!/usr/bin/env csi -s (require rackunit) (require-library logic-eval) (import logic-eval) (initialize-data-base microshaft-data-base) Exercise 4.66 has been generalizing the query system to In general , 's new system allows expressions of the form or ` maximum ' . reasons that it should be a cinch to implement completes the implementation and is about to try it out , Cy * Note Exercise 4 - 65 : : . When Cy shows the system 's response , , " Oh , no , my simple accumulation scheme wo n't work ! " What has just realized ? Outline a method he can use to (test 458000 (fold + 0 (map third (all-of '(salary ?who ?amount))))) (define (accumulation-function fun identity var query) (let ((index (list-index (lambda (x) (eq? var x)) query))) (fold fun identity (map (lambda (l) (list-ref l index)) (all-of query))))) (test 458000 (accumulation-function + 0 '?amount '(salary ?who ?amount))) (test '((Bitdiddle Ben) (Hacker Alyssa P) (Fect Cy D) (Tweakit Lem E) (Reasoner Louis) (Warbucks Oliver) (Scrooge Eben) (Cratchet Robert) (Aull DeWitt)) (accumulation-function cons '() '?who '(salary ?who ?amount)))
42b438c3869de74be58ada1c290e90fd2fca94512efca3796b526b54b64dd28b
typedclojure/typedclojure
typedclojure_config.cljc
{:spec1-extensions [typed-example.register-spec1-extensions]}
null
https://raw.githubusercontent.com/typedclojure/typedclojure/1bac938743fd98bbf494fdab68ca58846993d1f1/example-projects/spec1-type-providers/src/typedclojure_config.cljc
clojure
{:spec1-extensions [typed-example.register-spec1-extensions]}
82766968c089fc0068596cba8c5b6263f1e7a5b2b189871bed98049afd5fd0ee
falsetru/htdp
25.2.2.scm
(define (quick-sort alon) (cond [(empty? alon) empty] [(empty? (rest alon)) alon] [else (append (quick-sort (smaller-items alon (first alon))) (list (first alon)) (quick-sort (larger-items alon (first alon))))])) (define (larger-items alon threshold) (cond [(empty? alon) empty] [else (if (> (first alon) threshold) (cons (first alon) (larger-items (rest alon) threshold)) (larger-items (rest alon) threshold))])) (define (smaller-items alon threshold) (cond [(empty? alon) empty] [else (if (< (first alon) threshold) (cons (first alon) (smaller-items (rest alon) threshold)) (smaller-items (rest alon) threshold))])) (require rackunit) (require rackunit/text-ui) (define quick-sort-tests (test-suite "Test for quick-sort" (check-equal? (quick-sort '(11 9 2 18 12 14 4 1)) '(1 2 4 9 11 12 14 18)) )) (exit (run-tests quick-sort-tests))
null
https://raw.githubusercontent.com/falsetru/htdp/4cdad3b999f19b89ff4fa7561839cbcbaad274df/25/25.2.2.scm
scheme
(define (quick-sort alon) (cond [(empty? alon) empty] [(empty? (rest alon)) alon] [else (append (quick-sort (smaller-items alon (first alon))) (list (first alon)) (quick-sort (larger-items alon (first alon))))])) (define (larger-items alon threshold) (cond [(empty? alon) empty] [else (if (> (first alon) threshold) (cons (first alon) (larger-items (rest alon) threshold)) (larger-items (rest alon) threshold))])) (define (smaller-items alon threshold) (cond [(empty? alon) empty] [else (if (< (first alon) threshold) (cons (first alon) (smaller-items (rest alon) threshold)) (smaller-items (rest alon) threshold))])) (require rackunit) (require rackunit/text-ui) (define quick-sort-tests (test-suite "Test for quick-sort" (check-equal? (quick-sort '(11 9 2 18 12 14 4 1)) '(1 2 4 9 11 12 14 18)) )) (exit (run-tests quick-sort-tests))
a4cb09bf9425562e30a3f2d13cf795dc68544ef73947dfefec57d5bd4a1bdff8
phoe/safe-read
package.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; GATEWAY " phoe " Herda 2016 package.lisp (defpackage #:safe-read (:use #:cl :trivial-garbage) (:export #:safe-read #:with-temp-package #:buffer-of #:*stream-buffers* #:*max-input-size*))
null
https://raw.githubusercontent.com/phoe/safe-read/5a128cb1199ddca182cc970af29240e43f4def49/package.lisp
lisp
GATEWAY
" phoe " Herda 2016 package.lisp (defpackage #:safe-read (:use #:cl :trivial-garbage) (:export #:safe-read #:with-temp-package #:buffer-of #:*stream-buffers* #:*max-input-size*))
27e7523e55976b057218a9e54faa8b130e91c7f2fbaca45ca194a5fd1b57f15e
cdepillabout/password
Validate.hs
# LANGUAGE CPP # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # | Module : Data . Password . Validate Copyright : ( c ) , 2020 ; , 2020 License : BSD - style ( see LICENSE file ) Maintainer : Stability : experimental Portability : POSIX = Password Validation It is common for passwords to have a set of requirements . The most obvious requirement being a minimum length , but another common requirement is for the password to at least include a certain amount of characters of a certain category , like uppercase and lowercase alphabetic characters , numbers and/or other special characters . /Though , nowadays , this last type of requirement is/ /discouraged by security experts/. This module provides an API which enables you to set up your own ' PasswordPolicy ' to validate the format of ' Password 's . = = /Recommendations by the NIST/ For policy recommendations and more , look to the following publication by the National Institute of Standards and Technology ( especially the addendum ): < -63b.pdf > A short summary : * Enforcing inclusion of specific character types ( like special characters , numbers , lowercase and uppercase letters ) actually makes passwords _ _ less secure _ _ . * The length of a password is _ _ the most important _ _ factor , so let users make their passwords as lengthy as they want , within reason . ( keep in mind some algorithms have length limitations , like /bcrypt/ 's 72 character limit ) * Do allow spaces so users can use sentences for passwords . * Showing the " strength " of user 's passwords is advised . A good algorithm to use is /zxcvbn/. * The best way to mitigate online attacks is to limit the rate of login attempts . = = Password Policies The most important part is to have a valid and robust ' PasswordPolicy ' . A ' defaultPasswordPolicy _ ' is provided to quickly set up a NIST recommended validation of passwords , but you can also adjust it , or just create your own . Just remember that a ' PasswordPolicy ' must be validated first to make sure it is actually a ' ValidPasswordPolicy ' . Otherwise , you 'd never be able to validate any given ' Password 's . = Example usage So let 's say we 're fine with the default policy , which requires the password to be between 8 - 64 characters , and does n't enforce any specific character category usage , then our function would look like the following : @ myValidateFunc : : ' Password ' - > Bool myValidateFunc = ' isValidPassword ' ' defaultPasswordPolicy _ ' @ = = Custom policies But , for example , if you 'd like to enforce that a ' Password ' includes at least one special character , and be at least 12 characters long , you 'll have to make your own ' PasswordPolicy ' . @ customPolicy : : ' PasswordPolicy ' customPolicy = ' defaultPasswordPolicy ' { = 12 , specialChars = 1 } @ This custom policy will then have to be validated first , so it can be used to validate ' Password 's further on . = = The easiest way to validate a custom ' PasswordPolicy ' is by using a Template Haskell splice . Just turn on the @\{\-\ # LANGUAGE TemplateHaskell \#\-\}@ pragma , pass your policy to ' validatePasswordPolicyTH ' , surround it by @\$( ... )@ and if it compiles it will be a ' ValidPasswordPolicy ' . @ { -\ # LANGUAGE TemplateHaskell \ # Module : Data.Password.Validate Copyright : (c) Hiroto Shioi, 2020; Felix Paulusma, 2020 License : BSD-style (see LICENSE file) Maintainer : Stability : experimental Portability : POSIX = Password Validation It is common for passwords to have a set of requirements. The most obvious requirement being a minimum length, but another common requirement is for the password to at least include a certain amount of characters of a certain category, like uppercase and lowercase alphabetic characters, numbers and/or other special characters. /Though, nowadays, this last type of requirement is/ /discouraged by security experts/. This module provides an API which enables you to set up your own 'PasswordPolicy' to validate the format of 'Password's. == /Recommendations by the NIST/ For policy recommendations and more, look to the following publication by the National Institute of Standards and Technology (especially the addendum): <-63b.pdf> A short summary: * Enforcing inclusion of specific character types (like special characters, numbers, lowercase and uppercase letters) actually makes passwords __less secure__. * The length of a password is __the most important__ factor, so let users make their passwords as lengthy as they want, within reason. (keep in mind some algorithms have length limitations, like /bcrypt/'s 72 character limit) * Do allow spaces so users can use sentences for passwords. * Showing the "strength" of user's passwords is advised. A good algorithm to use is /zxcvbn/. * The best way to mitigate online attacks is to limit the rate of login attempts. == Password Policies The most important part is to have a valid and robust 'PasswordPolicy'. A 'defaultPasswordPolicy_' is provided to quickly set up a NIST recommended validation of passwords, but you can also adjust it, or just create your own. Just remember that a 'PasswordPolicy' must be validated first to make sure it is actually a 'ValidPasswordPolicy'. Otherwise, you'd never be able to validate any given 'Password's. = Example usage So let's say we're fine with the default policy, which requires the password to be between 8-64 characters, and doesn't enforce any specific character category usage, then our function would look like the following: @ myValidateFunc :: 'Password' -> Bool myValidateFunc = 'isValidPassword' 'defaultPasswordPolicy_' @ == Custom policies But, for example, if you'd like to enforce that a 'Password' includes at least one special character, and be at least 12 characters long, you'll have to make your own 'PasswordPolicy'. @ customPolicy :: 'PasswordPolicy' customPolicy = 'defaultPasswordPolicy' { minimumLength = 12 , specialChars = 1 } @ This custom policy will then have to be validated first, so it can be used to validate 'Password's further on. == Template Haskell The easiest way to validate a custom 'PasswordPolicy' is by using a Template Haskell splice. Just turn on the @\{\-\# LANGUAGE TemplateHaskell \#\-\}@ pragma, pass your policy to 'validatePasswordPolicyTH', surround it by @\$(...)@ and if it compiles it will be a 'ValidPasswordPolicy'. @ {-\# LANGUAGE TemplateHaskell \#-} customValidPolicy :: 'ValidPasswordPolicy' customValidPolicy = $('validatePasswordPolicyTH' customPolicy) @ __NB: any custom 'CharSetPredicate' will be ignored by 'validatePasswordPolicyTH'__ __and replaced with the 'defaultCharSetPredicate'.__ So if you want to use your own 'CharSetPredicate', you won't be able to validate your policy using 'validatePasswordPolicyTH'. Most users, however, will find 'defaultCharSetPredicate' to be sufficient. == At runtime Another way of validating your custom policy is 'validatePasswordPolicy'. In an application, this might be implemented in the following way. @ main :: IO () main = case ('validatePasswordPolicy' customPolicy) of Left reasons -> error $ show reasons Right validPolicy -> app \`runReaderT\` validPolicy customValidateFunc :: 'Password' -> ReaderT 'ValidPasswordPolicy' IO Bool customValidateFunc pwd = do policy <- ask return $ 'isValidPassword' policy pwd @ == Let's get dangerous Or, if you like living on the edge, you could also just match on 'Right'. I hope you're certain your policy is valid, though. So please have at least a unit test to verify that passing your 'PasswordPolicy' to 'validatePasswordPolicy' actually returns a 'Right'. @ Right validPolicy = 'validatePasswordPolicy' customPolicy customValidateFunc :: 'Password' -> Bool customValidateFunc = 'isValidPassword' validPolicy @ -} module Data.Password.Validate ( -- * Validating passwords -- -- | -- The main function of this module is probably 'isValidPassword', -- as it is simple and straightforward. -- -- Though if you'd want to know why a 'Password' failed to validate, -- because you'd maybe like to communicate those 'InvalidReason's back to the user , ' ' is here to help you out . validatePassword, isValidPassword, ValidationResult(..), -- ** Password Policy -- -- | -- A 'PasswordPolicy' has to be validated before it can be used to validate a -- 'Password'. -- This is done using 'validatePasswordPolicy' or 'validatePasswordPolicyTH'. -- -- Next to the obvious lower and upper bounds for the length of a 'Password', -- a 'PasswordPolicy' can dictate how many lowercase letters, uppercase letters, -- digits and/or special characters are minimally required to be used in the -- 'Password' to be considered a valid 'Password'. -- -- An observant user might have also seen that a 'PasswordPolicy' includes a -- 'CharSetPredicate'. Very few users will want to change this from the -- 'defaultCharSetPredicate', since this includes all non-control ASCII characters. -- -- If, for some reason, you'd like to accept more characters (e.g. é, ø, か, 事) -- or maybe you want to only allow alpha-numeric characters, 'charSetPredicate' is -- the place to do so. validatePasswordPolicy, validatePasswordPolicyTH, PasswordPolicy (..), ValidPasswordPolicy, fromValidPasswordPolicy, defaultPasswordPolicy, defaultPasswordPolicy_, CharSetPredicate(..), defaultCharSetPredicate, InvalidReason (..), InvalidPolicyReason(..), CharacterCategory(..), MinimumLength, MaximumLength, ProvidedLength, MinimumAmount, ProvidedAmount, -- * For internal use -- -- | These are used in the test suite. You should not need these. -- -- These are basically internal functions and as such have NO guarantee (__NONE__) -- to be consistent between releases. defaultCharSet, validateCharSetPredicate, categoryToPredicate, isSpecial, allButCSP ) where import Data.Char (chr, isAsciiLower, isAsciiUpper, isDigit, ord) import Data.Function (on) import Data.List (foldl') import Data.Text (Text) import qualified Data.Text as T import Language.Haskell.TH (Exp, Q, appE) import Language.Haskell.TH.Syntax (Lift (..)) import Data.Password.Types (Password, unsafeShowPassword) -- $setup -- >>> :set -XOverloadedStrings -- -- Import needed libraries. -- -- >>> import Data.Password.Types -- | Set of policies used to validate a 'Password'. -- -- When defining your own 'PasswordPolicy', please keep in mind that: -- * The value of ' maximumLength ' must be bigger than 0 * The value of ' maximumLength ' must be bigger than ' ' * If any other field has a negative value ( e.g. ' ' ) , it will be defaulted to 0 -- * The total sum of all character category values (i.e. all fields ending in @-Chars@) must not be larger than the value of ' maximumLength ' . * The provided ' CharSetPredicate ' needs to allow at least one of the characters in the categories which require more than 0 characters . ( e.g. if ' lowercaseChars ' is > 0 , the ' charSetPredicate ' must allow at least one of the characters in @[\'a\' .. \'z\']@ ) -- or else the validation functions will return one or more ' 's . -- -- If you're unsure of what to do, please use the default: 'defaultPasswordPolicy_' -- -- @since 2.1.0.0 data PasswordPolicy = PasswordPolicy { minimumLength :: !Int -- ^ Required password minimum length , maximumLength :: !Int -- ^ Required password maximum length , uppercaseChars :: !Int -- ^ Required number of upper-case characters , lowercaseChars :: !Int -- ^ Required number of lower-case characters , specialChars :: !Int -- ^ Required number of special characters , digitChars :: !Int -- ^ Required number of ASCII-digit characters , charSetPredicate :: CharSetPredicate -- ^ Which characters are acceptable for use in passwords (cf. 'defaultCharSetPredicate') } NB : KEEP THIS THE SAME ORDER AS THE PasswordPolicy FIELDS ! -- OTHERWISE THE 'validatePasswordPolicyTH' FUNCTION WILL BREAK. -- @since 2.1.0.0 -- | All 'Int' fields of the 'PasswordPolicy' in a row allButCSP :: PasswordPolicy -> [Int] allButCSP PasswordPolicy{..} = [ minimumLength , maximumLength , uppercaseChars , lowercaseChars , specialChars , digitChars ] -- | N.B. This will not check equality on the 'charSetPredicate' instance Eq PasswordPolicy where (==) = go `on` allButCSP where go a b = and $ zipWith (==) a b -- | N.B. This will not check order on the 'charSetPredicate' instance Ord PasswordPolicy where compare = go `on` allButCSP where go a b = check $ zipWith compare a b check [] = EQ check (EQ : xs) = check xs check (x : _) = x instance Show PasswordPolicy where show PasswordPolicy{..} = mconcat [ "PasswordPolicy {" , "minimumLength = ", show minimumLength , ", maximumLength = ", show maximumLength , ", uppercaseChars = ", show uppercaseChars , ", lowercaseChars = ", show lowercaseChars , ", specialChars = ", show specialChars , ", digitChars = ", show digitChars , ", charSetPredicate = <FUNCTION>}" ] -- | A 'PasswordPolicy' that has been checked to be valid -- -- @since 2.1.0.0 newtype ValidPasswordPolicy = VPP { fromValidPasswordPolicy :: PasswordPolicy -- ^ -- In case you'd want to retrieve the 'PasswordPolicy' -- from the 'ValidPasswordPolicy' -- -- @since 2.1.0.0 } deriving (Eq, Ord, Show) -- | Default value for the 'PasswordPolicy'. -- -- Enforces that a password must be between 8-64 characters long, -- though can easily be adjusted by using record update syntax: -- -- @ myPolicy = defaultPasswordPolicy = 12 } -- @ -- -- /Do note that this being a default policy doesn't make it a good/ /enough policy in every situation . The most important field , ' /has 8 characters as the default , because it is the bare minimum for some/ -- /sense of security. The longer the password, the more difficult it will be/ /to guess or brute - force , so a minimum of 12 or 16 would be advised in/ -- /a production setting./ -- -- This policy on it's own is guaranteed to be valid. Any changes made to it might result in ' validatePasswordPolicy ' returning one or more ' 's . -- -- >>> defaultPasswordPolicy PasswordPolicy = 8 , maximumLength = 64 , uppercaseChars = 0 , = 0 , specialChars = 0 , = 0 , charSetPredicate = < FUNCTION > } -- -- @since 2.1.0.0 defaultPasswordPolicy :: PasswordPolicy defaultPasswordPolicy = PasswordPolicy { minimumLength = 8, maximumLength = 64, uppercaseChars = 0, lowercaseChars = 0, specialChars = 0, digitChars = 0, charSetPredicate = defaultCharSetPredicate } -- | Unchangeable 'defaultPasswordPolicy', but guaranteed to be valid. -- -- @since 2.1.0.0 defaultPasswordPolicy_ :: ValidPasswordPolicy defaultPasswordPolicy_ = VPP defaultPasswordPolicy -- | Predicate which defines the characters that can be used for a password. -- -- @since 2.1.0.0 newtype CharSetPredicate = CharSetPredicate { getCharSetPredicate :: Char -> Bool } -- | The default character set consists of uppercase and lowercase letters, numbers, and special characters from the @ASCII@ character set . ( i.e. everything from the @ASCII@ set except the control characters ) -- -- @since 2.1.0.0 defaultCharSetPredicate :: CharSetPredicate defaultCharSetPredicate = CharSetPredicate $ \c -> ord c >= 32 && ord c <= 126 # INLINE defaultCharSetPredicate # -- @since 2.1.0.0 | Check if given ' ' is a special character . -- (i.e. any non-alphanumeric non-control ASCII character) isSpecial :: Char -> Bool isSpecial = \c -> isDefault c && not (isAsciiUpper c || isAsciiLower c || isDigit c) where CharSetPredicate isDefault = defaultCharSetPredicate -- | Character categories -- -- @since 2.1.0.0 data CharacterCategory = Uppercase -- ^ Uppercase letters | Lowercase -- ^ Lowercase letters | Special -- ^ Special characters | Digit -- ^ ASCII digits deriving (Eq, Ord, Show) -- @since 2.1.0.0 -- | Convert a 'CharacterCategory' into its associated predicate function categoryToPredicate :: CharacterCategory -> (Char -> Bool) categoryToPredicate = \case Uppercase -> isAsciiUpper Lowercase -> isAsciiLower Special -> isSpecial Digit -> isDigit type MinimumLength = Int type MaximumLength = Int type ProvidedLength = Int type MinimumAmount = Int type ProvidedAmount = Int -- | Possible reasons for a 'Password' to be invalid. -- -- @since 2.1.0.0 data InvalidReason = PasswordTooShort !MinimumLength !ProvidedLength -- ^ Length of 'Password' is too short. | PasswordTooLong !MaximumLength !ProvidedLength -- ^ Length of 'Password' is too long. | NotEnoughReqChars !CharacterCategory !MinimumAmount !ProvidedAmount -- ^ 'Password' does not contain required number of characters. | InvalidCharacters !Text -- ^ 'Password' contains characters that cannot be used deriving (Eq, Ord, Show) -- | Possible reasons for a 'PasswordPolicy' to be invalid -- -- @since 2.1.0.0 data InvalidPolicyReason = InvalidLength !MinimumLength !MaximumLength ^ Value of ' ' is bigger than ' maximumLength ' -- @InvalidLength maximumLength@ | MaxLengthBelowZero !MaximumLength ^ Value of ' maximumLength ' is zero or less -- -- @MaxLengthBelowZero maximumLength@ | CategoryAmountsAboveMaxLength !MaximumLength !Int -- ^ The total of the character category amount requirements are -- higher than the maximum length of the password. (i.e. the 'Int' signifies -- the total of 'lowercaseChars' + 'uppercaseChars' + 'digitChars' + 'specialChars') -- @CategoryAmountsAboveMaxLength maximumLength totalRequiredChars@ | InvalidCharSetPredicate !CharacterCategory !MinimumAmount -- ^ 'charSetPredicate' does not return 'True' for a 'CharacterCategory' that requires at least ' MinimumAmount ' characters in the password deriving (Eq, Ord, Show) -- | Result of validating a 'Password'. -- -- @since 2.1.0.0 data ValidationResult = ValidPassword | InvalidPassword [InvalidReason] deriving (Eq, Show) -- | This function is equivalent to: -- -- @'validatePassword' policy password == 'ValidPassword'@ -- > > > let pass = mkPassword " " -- >>> isValidPassword defaultPasswordPolicy_ pass -- True -- -- @since 2.1.0.0 isValidPassword :: ValidPasswordPolicy -> Password -> Bool isValidPassword policy pass = validatePassword policy pass == ValidPassword # INLINE isValidPassword # -- | Checks if a given 'Password' adheres to the provided 'ValidPasswordPolicy'. -- -- In case of an invalid password, returns the reasons why it wasn't valid. -- -- >>> let pass = mkPassword "This_Is_Valid_Password1234" > > > defaultPasswordPolicy _ pass ValidPassword -- -- @since 2.1.0.0 validatePassword :: ValidPasswordPolicy -> Password -> ValidationResult validatePassword (VPP PasswordPolicy{..}) pass = case validationFailures of [] -> ValidPassword _:_ -> InvalidPassword validationFailures where password = unsafeShowPassword pass validationFailures = mconcat [ isTooShort , isTooLong , isUsingValidCharacters , hasRequiredChar uppercaseChars Uppercase , hasRequiredChar lowercaseChars Lowercase , hasRequiredChar specialChars Special , hasRequiredChar digitChars Digit ] len = T.length password isTooLong = [PasswordTooLong maximumLength len | len > maximumLength] isTooShort = [PasswordTooShort minimumLength len | len < minimumLength] CharSetPredicate predicate = charSetPredicate isUsingValidCharacters :: [InvalidReason] isUsingValidCharacters = let filteredText = T.filter (not . predicate) password in [InvalidCharacters filteredText | not $ T.null filteredText] hasRequiredChar :: Int -> CharacterCategory -> [InvalidReason] hasRequiredChar requiredCharNum characterCategory | requiredCharNum <= 0 = [] | otherwise = let p = categoryToPredicate characterCategory actualRequiredCharNum = T.length $ T.filter p password in [ NotEnoughReqChars characterCategory requiredCharNum actualRequiredCharNum | actualRequiredCharNum < requiredCharNum ] | Validate ' CharSetPredicate ' to return ' True ' on at least one of the characters -- that is required. -- -- For instance, if 'PasswordPolicy' states that the password requires at least one uppercase letter , then ' CharSetPredicate ' should return True on at least one uppercase letter . validateCharSetPredicate :: PasswordPolicy -> [InvalidPolicyReason] validateCharSetPredicate PasswordPolicy{..} = let charSets = accumulateCharSet [ (uppercaseChars, Uppercase) , (lowercaseChars, Lowercase) , (specialChars, Special) , (digitChars, Digit) ] in concatMap checkPredicate charSets where CharSetPredicate predicate = charSetPredicate checkPredicate :: (Int, CharacterCategory, String) -> [InvalidPolicyReason] checkPredicate (num, category, sets) = [InvalidCharSetPredicate category num | not $ any predicate sets] accumulateCharSet :: [(Int, CharacterCategory)] -> [(Int, CharacterCategory, String)] accumulateCharSet xs = [ (num, c, categoryToString c) | (num, c) <- xs , num > 0 ] categoryToString :: CharacterCategory -> String categoryToString category = filter (categoryToPredicate category) defaultCharSet | Template Haskell validation function for ' PasswordPolicy 's . -- -- @ { -\ # LANGUAGE TemplateHaskell \#- } -- myPolicy :: 'PasswordPolicy' myPolicy = ' defaultPasswordPolicy ' { specialChars = 1 } -- : : ' ValidPasswordPolicy ' -- myValidPolicy = $('validatePasswordPolicyTH' myPolicy) -- @ -- -- For technical reasons, the 'charSetPredicate' field is ignored and the -- 'defaultCharSetPredicate' is used. If, for any reason, you do need to use a -- custom 'CharSetPredicate', please use 'validatePasswordPolicy' and either handle -- the failure case at runtime and/or use a unit test to make sure your policy is valid. -- -- @since 2.1.0.0 validatePasswordPolicyTH :: PasswordPolicy -> Q Exp validatePasswordPolicyTH pp = either (fail . showReasons) go $ validatePasswordPolicy withDefault where withDefault = pp{charSetPredicate = defaultCharSetPredicate} showReasons rs = "Bad password policy: " ++ show rs go _ = [|VPP|] `appE` newPP allButCSPQ = lift <$> allButCSP withDefault newPP = foldl' appE [|PasswordPolicy|] allButCSPQ `appE` [|defaultCharSetPredicate|] -- | Verifies that a 'PasswordPolicy' is valid and converts it into a 'ValidPasswordPolicy'. -- -- >>> validatePasswordPolicy defaultPasswordPolicy -- Right (...) -- -- @since 2.1.0.0 validatePasswordPolicy :: PasswordPolicy -> Either [InvalidPolicyReason] ValidPasswordPolicy validatePasswordPolicy policy@PasswordPolicy{..} = case allReasons of [] -> Right $ VPP policy _ -> Left allReasons where allReasons = mconcat [validMaxLength, validLength, validCategoryAmount, validPredicate] validLength, validMaxLength, validCategoryAmount, validPredicate :: [InvalidPolicyReason] validLength = [InvalidLength minimumLength maximumLength | minimumLength > maximumLength] validMaxLength = [MaxLengthBelowZero maximumLength | maximumLength <= 0] validCategoryAmount = We do n't report this reason if the maximumLength is already invalid [CategoryAmountsAboveMaxLength maximumLength total | total > maximumLength, maximumLength > 0] where capToZero = max 0 total = sum $ capToZero <$> [lowercaseChars, uppercaseChars, digitChars, specialChars] validPredicate = validateCharSetPredicate policy -- @since 2.1.0.0 -- | Default character set -- -- Should be all non-control characters in the ASCII character set. defaultCharSet :: String defaultCharSet = chr <$> [32 .. 126]
null
https://raw.githubusercontent.com/cdepillabout/password/e90b7481af2d63de6b2d9ead3c03ddb798707d22/password/src/Data/Password/Validate.hs
haskell
# LANGUAGE OverloadedStrings # \# LANGUAGE TemplateHaskell \# * Validating passwords | The main function of this module is probably 'isValidPassword', as it is simple and straightforward. Though if you'd want to know why a 'Password' failed to validate, because you'd maybe like to communicate those 'InvalidReason's ** Password Policy | A 'PasswordPolicy' has to be validated before it can be used to validate a 'Password'. This is done using 'validatePasswordPolicy' or 'validatePasswordPolicyTH'. Next to the obvious lower and upper bounds for the length of a 'Password', a 'PasswordPolicy' can dictate how many lowercase letters, uppercase letters, digits and/or special characters are minimally required to be used in the 'Password' to be considered a valid 'Password'. An observant user might have also seen that a 'PasswordPolicy' includes a 'CharSetPredicate'. Very few users will want to change this from the 'defaultCharSetPredicate', since this includes all non-control ASCII characters. If, for some reason, you'd like to accept more characters (e.g. é, ø, か, 事) or maybe you want to only allow alpha-numeric characters, 'charSetPredicate' is the place to do so. * For internal use | These are used in the test suite. You should not need these. These are basically internal functions and as such have NO guarantee (__NONE__) to be consistent between releases. $setup >>> :set -XOverloadedStrings Import needed libraries. >>> import Data.Password.Types | Set of policies used to validate a 'Password'. When defining your own 'PasswordPolicy', please keep in mind that: * The total sum of all character category values (i.e. all fields ending in @-Chars@) If you're unsure of what to do, please use the default: 'defaultPasswordPolicy_' @since 2.1.0.0 ^ Required password minimum length ^ Required password maximum length ^ Required number of upper-case characters ^ Required number of lower-case characters ^ Required number of special characters ^ Required number of ASCII-digit characters ^ Which characters are acceptable for use in passwords (cf. 'defaultCharSetPredicate') OTHERWISE THE 'validatePasswordPolicyTH' FUNCTION WILL BREAK. @since 2.1.0.0 | All 'Int' fields of the 'PasswordPolicy' in a row | N.B. This will not check equality on the 'charSetPredicate' | N.B. This will not check order on the 'charSetPredicate' | A 'PasswordPolicy' that has been checked to be valid @since 2.1.0.0 ^ In case you'd want to retrieve the 'PasswordPolicy' from the 'ValidPasswordPolicy' @since 2.1.0.0 | Default value for the 'PasswordPolicy'. Enforces that a password must be between 8-64 characters long, though can easily be adjusted by using record update syntax: @ @ /Do note that this being a default policy doesn't make it a good/ /sense of security. The longer the password, the more difficult it will be/ /a production setting./ This policy on it's own is guaranteed to be valid. Any changes made to >>> defaultPasswordPolicy @since 2.1.0.0 | Unchangeable 'defaultPasswordPolicy', but guaranteed to be valid. @since 2.1.0.0 | Predicate which defines the characters that can be used for a password. @since 2.1.0.0 | The default character set consists of uppercase and lowercase letters, numbers, @since 2.1.0.0 @since 2.1.0.0 (i.e. any non-alphanumeric non-control ASCII character) | Character categories @since 2.1.0.0 ^ Uppercase letters ^ Lowercase letters ^ Special characters ^ ASCII digits @since 2.1.0.0 | Convert a 'CharacterCategory' into its associated predicate function | Possible reasons for a 'Password' to be invalid. @since 2.1.0.0 ^ Length of 'Password' is too short. ^ Length of 'Password' is too long. ^ 'Password' does not contain required number of characters. ^ 'Password' contains characters that cannot be used | Possible reasons for a 'PasswordPolicy' to be invalid @since 2.1.0.0 @MaxLengthBelowZero maximumLength@ ^ The total of the character category amount requirements are higher than the maximum length of the password. (i.e. the 'Int' signifies the total of 'lowercaseChars' + 'uppercaseChars' + 'digitChars' + 'specialChars') ^ 'charSetPredicate' does not return 'True' for a 'CharacterCategory' that | Result of validating a 'Password'. @since 2.1.0.0 | This function is equivalent to: @'validatePassword' policy password == 'ValidPassword'@ >>> isValidPassword defaultPasswordPolicy_ pass True @since 2.1.0.0 | Checks if a given 'Password' adheres to the provided 'ValidPasswordPolicy'. In case of an invalid password, returns the reasons why it wasn't valid. >>> let pass = mkPassword "This_Is_Valid_Password1234" @since 2.1.0.0 that is required. For instance, if 'PasswordPolicy' states that the password requires at least @ myPolicy :: 'PasswordPolicy' myValidPolicy = $('validatePasswordPolicyTH' myPolicy) @ For technical reasons, the 'charSetPredicate' field is ignored and the 'defaultCharSetPredicate' is used. If, for any reason, you do need to use a custom 'CharSetPredicate', please use 'validatePasswordPolicy' and either handle the failure case at runtime and/or use a unit test to make sure your policy is valid. @since 2.1.0.0 | Verifies that a 'PasswordPolicy' is valid and converts it into a 'ValidPasswordPolicy'. >>> validatePasswordPolicy defaultPasswordPolicy Right (...) @since 2.1.0.0 @since 2.1.0.0 | Default character set Should be all non-control characters in the ASCII character set.
# LANGUAGE CPP # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # | Module : Data . Password . Validate Copyright : ( c ) , 2020 ; , 2020 License : BSD - style ( see LICENSE file ) Maintainer : Stability : experimental Portability : POSIX = Password Validation It is common for passwords to have a set of requirements . The most obvious requirement being a minimum length , but another common requirement is for the password to at least include a certain amount of characters of a certain category , like uppercase and lowercase alphabetic characters , numbers and/or other special characters . /Though , nowadays , this last type of requirement is/ /discouraged by security experts/. This module provides an API which enables you to set up your own ' PasswordPolicy ' to validate the format of ' Password 's . = = /Recommendations by the NIST/ For policy recommendations and more , look to the following publication by the National Institute of Standards and Technology ( especially the addendum ): < -63b.pdf > A short summary : * Enforcing inclusion of specific character types ( like special characters , numbers , lowercase and uppercase letters ) actually makes passwords _ _ less secure _ _ . * The length of a password is _ _ the most important _ _ factor , so let users make their passwords as lengthy as they want , within reason . ( keep in mind some algorithms have length limitations , like /bcrypt/ 's 72 character limit ) * Do allow spaces so users can use sentences for passwords . * Showing the " strength " of user 's passwords is advised . A good algorithm to use is /zxcvbn/. * The best way to mitigate online attacks is to limit the rate of login attempts . = = Password Policies The most important part is to have a valid and robust ' PasswordPolicy ' . A ' defaultPasswordPolicy _ ' is provided to quickly set up a NIST recommended validation of passwords , but you can also adjust it , or just create your own . Just remember that a ' PasswordPolicy ' must be validated first to make sure it is actually a ' ValidPasswordPolicy ' . Otherwise , you 'd never be able to validate any given ' Password 's . = Example usage So let 's say we 're fine with the default policy , which requires the password to be between 8 - 64 characters , and does n't enforce any specific character category usage , then our function would look like the following : @ myValidateFunc : : ' Password ' - > Bool myValidateFunc = ' isValidPassword ' ' defaultPasswordPolicy _ ' @ = = Custom policies But , for example , if you 'd like to enforce that a ' Password ' includes at least one special character , and be at least 12 characters long , you 'll have to make your own ' PasswordPolicy ' . @ customPolicy : : ' PasswordPolicy ' customPolicy = ' defaultPasswordPolicy ' { = 12 , specialChars = 1 } @ This custom policy will then have to be validated first , so it can be used to validate ' Password 's further on . = = The easiest way to validate a custom ' PasswordPolicy ' is by using a Template Haskell splice . Just turn on the @\{\-\ # LANGUAGE TemplateHaskell \#\-\}@ pragma , pass your policy to ' validatePasswordPolicyTH ' , surround it by @\$( ... )@ and if it compiles it will be a ' ValidPasswordPolicy ' . @ { -\ # LANGUAGE TemplateHaskell \ # Module : Data.Password.Validate Copyright : (c) Hiroto Shioi, 2020; Felix Paulusma, 2020 License : BSD-style (see LICENSE file) Maintainer : Stability : experimental Portability : POSIX = Password Validation It is common for passwords to have a set of requirements. The most obvious requirement being a minimum length, but another common requirement is for the password to at least include a certain amount of characters of a certain category, like uppercase and lowercase alphabetic characters, numbers and/or other special characters. /Though, nowadays, this last type of requirement is/ /discouraged by security experts/. This module provides an API which enables you to set up your own 'PasswordPolicy' to validate the format of 'Password's. == /Recommendations by the NIST/ For policy recommendations and more, look to the following publication by the National Institute of Standards and Technology (especially the addendum): <-63b.pdf> A short summary: * Enforcing inclusion of specific character types (like special characters, numbers, lowercase and uppercase letters) actually makes passwords __less secure__. * The length of a password is __the most important__ factor, so let users make their passwords as lengthy as they want, within reason. (keep in mind some algorithms have length limitations, like /bcrypt/'s 72 character limit) * Do allow spaces so users can use sentences for passwords. * Showing the "strength" of user's passwords is advised. A good algorithm to use is /zxcvbn/. * The best way to mitigate online attacks is to limit the rate of login attempts. == Password Policies The most important part is to have a valid and robust 'PasswordPolicy'. A 'defaultPasswordPolicy_' is provided to quickly set up a NIST recommended validation of passwords, but you can also adjust it, or just create your own. Just remember that a 'PasswordPolicy' must be validated first to make sure it is actually a 'ValidPasswordPolicy'. Otherwise, you'd never be able to validate any given 'Password's. = Example usage So let's say we're fine with the default policy, which requires the password to be between 8-64 characters, and doesn't enforce any specific character category usage, then our function would look like the following: @ myValidateFunc :: 'Password' -> Bool myValidateFunc = 'isValidPassword' 'defaultPasswordPolicy_' @ == Custom policies But, for example, if you'd like to enforce that a 'Password' includes at least one special character, and be at least 12 characters long, you'll have to make your own 'PasswordPolicy'. @ customPolicy :: 'PasswordPolicy' customPolicy = 'defaultPasswordPolicy' { minimumLength = 12 , specialChars = 1 } @ This custom policy will then have to be validated first, so it can be used to validate 'Password's further on. == Template Haskell The easiest way to validate a custom 'PasswordPolicy' is by using a Template Haskell splice. Just turn on the @\{\-\# LANGUAGE TemplateHaskell \#\-\}@ pragma, pass your policy to 'validatePasswordPolicyTH', surround it by @\$(...)@ and if it compiles it will be a 'ValidPasswordPolicy'. @ customValidPolicy :: 'ValidPasswordPolicy' customValidPolicy = $('validatePasswordPolicyTH' customPolicy) @ __NB: any custom 'CharSetPredicate' will be ignored by 'validatePasswordPolicyTH'__ __and replaced with the 'defaultCharSetPredicate'.__ So if you want to use your own 'CharSetPredicate', you won't be able to validate your policy using 'validatePasswordPolicyTH'. Most users, however, will find 'defaultCharSetPredicate' to be sufficient. == At runtime Another way of validating your custom policy is 'validatePasswordPolicy'. In an application, this might be implemented in the following way. @ main :: IO () main = case ('validatePasswordPolicy' customPolicy) of Left reasons -> error $ show reasons Right validPolicy -> app \`runReaderT\` validPolicy customValidateFunc :: 'Password' -> ReaderT 'ValidPasswordPolicy' IO Bool customValidateFunc pwd = do policy <- ask return $ 'isValidPassword' policy pwd @ == Let's get dangerous Or, if you like living on the edge, you could also just match on 'Right'. I hope you're certain your policy is valid, though. So please have at least a unit test to verify that passing your 'PasswordPolicy' to 'validatePasswordPolicy' actually returns a 'Right'. @ Right validPolicy = 'validatePasswordPolicy' customPolicy customValidateFunc :: 'Password' -> Bool customValidateFunc = 'isValidPassword' validPolicy @ -} module Data.Password.Validate back to the user , ' ' is here to help you out . validatePassword, isValidPassword, ValidationResult(..), validatePasswordPolicy, validatePasswordPolicyTH, PasswordPolicy (..), ValidPasswordPolicy, fromValidPasswordPolicy, defaultPasswordPolicy, defaultPasswordPolicy_, CharSetPredicate(..), defaultCharSetPredicate, InvalidReason (..), InvalidPolicyReason(..), CharacterCategory(..), MinimumLength, MaximumLength, ProvidedLength, MinimumAmount, ProvidedAmount, defaultCharSet, validateCharSetPredicate, categoryToPredicate, isSpecial, allButCSP ) where import Data.Char (chr, isAsciiLower, isAsciiUpper, isDigit, ord) import Data.Function (on) import Data.List (foldl') import Data.Text (Text) import qualified Data.Text as T import Language.Haskell.TH (Exp, Q, appE) import Language.Haskell.TH.Syntax (Lift (..)) import Data.Password.Types (Password, unsafeShowPassword) * The value of ' maximumLength ' must be bigger than 0 * The value of ' maximumLength ' must be bigger than ' ' * If any other field has a negative value ( e.g. ' ' ) , it will be defaulted to 0 must not be larger than the value of ' maximumLength ' . * The provided ' CharSetPredicate ' needs to allow at least one of the characters in the categories which require more than 0 characters . ( e.g. if ' lowercaseChars ' is > 0 , the ' charSetPredicate ' must allow at least one of the characters in @[\'a\' .. \'z\']@ ) or else the validation functions will return one or more ' 's . data PasswordPolicy = PasswordPolicy { minimumLength :: !Int , maximumLength :: !Int , uppercaseChars :: !Int , lowercaseChars :: !Int , specialChars :: !Int , digitChars :: !Int , charSetPredicate :: CharSetPredicate } NB : KEEP THIS THE SAME ORDER AS THE PasswordPolicy FIELDS ! allButCSP :: PasswordPolicy -> [Int] allButCSP PasswordPolicy{..} = [ minimumLength , maximumLength , uppercaseChars , lowercaseChars , specialChars , digitChars ] instance Eq PasswordPolicy where (==) = go `on` allButCSP where go a b = and $ zipWith (==) a b instance Ord PasswordPolicy where compare = go `on` allButCSP where go a b = check $ zipWith compare a b check [] = EQ check (EQ : xs) = check xs check (x : _) = x instance Show PasswordPolicy where show PasswordPolicy{..} = mconcat [ "PasswordPolicy {" , "minimumLength = ", show minimumLength , ", maximumLength = ", show maximumLength , ", uppercaseChars = ", show uppercaseChars , ", lowercaseChars = ", show lowercaseChars , ", specialChars = ", show specialChars , ", digitChars = ", show digitChars , ", charSetPredicate = <FUNCTION>}" ] newtype ValidPasswordPolicy = VPP { fromValidPasswordPolicy :: PasswordPolicy } deriving (Eq, Ord, Show) myPolicy = defaultPasswordPolicy = 12 } /enough policy in every situation . The most important field , ' /has 8 characters as the default , because it is the bare minimum for some/ /to guess or brute - force , so a minimum of 12 or 16 would be advised in/ it might result in ' validatePasswordPolicy ' returning one or more ' 's . PasswordPolicy = 8 , maximumLength = 64 , uppercaseChars = 0 , = 0 , specialChars = 0 , = 0 , charSetPredicate = < FUNCTION > } defaultPasswordPolicy :: PasswordPolicy defaultPasswordPolicy = PasswordPolicy { minimumLength = 8, maximumLength = 64, uppercaseChars = 0, lowercaseChars = 0, specialChars = 0, digitChars = 0, charSetPredicate = defaultCharSetPredicate } defaultPasswordPolicy_ :: ValidPasswordPolicy defaultPasswordPolicy_ = VPP defaultPasswordPolicy newtype CharSetPredicate = CharSetPredicate { getCharSetPredicate :: Char -> Bool } and special characters from the @ASCII@ character set . ( i.e. everything from the @ASCII@ set except the control characters ) defaultCharSetPredicate :: CharSetPredicate defaultCharSetPredicate = CharSetPredicate $ \c -> ord c >= 32 && ord c <= 126 # INLINE defaultCharSetPredicate # | Check if given ' ' is a special character . isSpecial :: Char -> Bool isSpecial = \c -> isDefault c && not (isAsciiUpper c || isAsciiLower c || isDigit c) where CharSetPredicate isDefault = defaultCharSetPredicate data CharacterCategory = Uppercase | Lowercase | Special | Digit deriving (Eq, Ord, Show) categoryToPredicate :: CharacterCategory -> (Char -> Bool) categoryToPredicate = \case Uppercase -> isAsciiUpper Lowercase -> isAsciiLower Special -> isSpecial Digit -> isDigit type MinimumLength = Int type MaximumLength = Int type ProvidedLength = Int type MinimumAmount = Int type ProvidedAmount = Int data InvalidReason = PasswordTooShort !MinimumLength !ProvidedLength | PasswordTooLong !MaximumLength !ProvidedLength | NotEnoughReqChars !CharacterCategory !MinimumAmount !ProvidedAmount | InvalidCharacters !Text deriving (Eq, Ord, Show) data InvalidPolicyReason = InvalidLength !MinimumLength !MaximumLength ^ Value of ' ' is bigger than ' maximumLength ' @InvalidLength maximumLength@ | MaxLengthBelowZero !MaximumLength ^ Value of ' maximumLength ' is zero or less | CategoryAmountsAboveMaxLength !MaximumLength !Int @CategoryAmountsAboveMaxLength maximumLength totalRequiredChars@ | InvalidCharSetPredicate !CharacterCategory !MinimumAmount requires at least ' MinimumAmount ' characters in the password deriving (Eq, Ord, Show) data ValidationResult = ValidPassword | InvalidPassword [InvalidReason] deriving (Eq, Show) > > > let pass = mkPassword " " isValidPassword :: ValidPasswordPolicy -> Password -> Bool isValidPassword policy pass = validatePassword policy pass == ValidPassword # INLINE isValidPassword # > > > defaultPasswordPolicy _ pass ValidPassword validatePassword :: ValidPasswordPolicy -> Password -> ValidationResult validatePassword (VPP PasswordPolicy{..}) pass = case validationFailures of [] -> ValidPassword _:_ -> InvalidPassword validationFailures where password = unsafeShowPassword pass validationFailures = mconcat [ isTooShort , isTooLong , isUsingValidCharacters , hasRequiredChar uppercaseChars Uppercase , hasRequiredChar lowercaseChars Lowercase , hasRequiredChar specialChars Special , hasRequiredChar digitChars Digit ] len = T.length password isTooLong = [PasswordTooLong maximumLength len | len > maximumLength] isTooShort = [PasswordTooShort minimumLength len | len < minimumLength] CharSetPredicate predicate = charSetPredicate isUsingValidCharacters :: [InvalidReason] isUsingValidCharacters = let filteredText = T.filter (not . predicate) password in [InvalidCharacters filteredText | not $ T.null filteredText] hasRequiredChar :: Int -> CharacterCategory -> [InvalidReason] hasRequiredChar requiredCharNum characterCategory | requiredCharNum <= 0 = [] | otherwise = let p = categoryToPredicate characterCategory actualRequiredCharNum = T.length $ T.filter p password in [ NotEnoughReqChars characterCategory requiredCharNum actualRequiredCharNum | actualRequiredCharNum < requiredCharNum ] | Validate ' CharSetPredicate ' to return ' True ' on at least one of the characters one uppercase letter , then ' CharSetPredicate ' should return True on at least one uppercase letter . validateCharSetPredicate :: PasswordPolicy -> [InvalidPolicyReason] validateCharSetPredicate PasswordPolicy{..} = let charSets = accumulateCharSet [ (uppercaseChars, Uppercase) , (lowercaseChars, Lowercase) , (specialChars, Special) , (digitChars, Digit) ] in concatMap checkPredicate charSets where CharSetPredicate predicate = charSetPredicate checkPredicate :: (Int, CharacterCategory, String) -> [InvalidPolicyReason] checkPredicate (num, category, sets) = [InvalidCharSetPredicate category num | not $ any predicate sets] accumulateCharSet :: [(Int, CharacterCategory)] -> [(Int, CharacterCategory, String)] accumulateCharSet xs = [ (num, c, categoryToString c) | (num, c) <- xs , num > 0 ] categoryToString :: CharacterCategory -> String categoryToString category = filter (categoryToPredicate category) defaultCharSet | Template Haskell validation function for ' PasswordPolicy 's . { -\ # LANGUAGE TemplateHaskell \#- } myPolicy = ' defaultPasswordPolicy ' { specialChars = 1 } : : ' ValidPasswordPolicy ' validatePasswordPolicyTH :: PasswordPolicy -> Q Exp validatePasswordPolicyTH pp = either (fail . showReasons) go $ validatePasswordPolicy withDefault where withDefault = pp{charSetPredicate = defaultCharSetPredicate} showReasons rs = "Bad password policy: " ++ show rs go _ = [|VPP|] `appE` newPP allButCSPQ = lift <$> allButCSP withDefault newPP = foldl' appE [|PasswordPolicy|] allButCSPQ `appE` [|defaultCharSetPredicate|] validatePasswordPolicy :: PasswordPolicy -> Either [InvalidPolicyReason] ValidPasswordPolicy validatePasswordPolicy policy@PasswordPolicy{..} = case allReasons of [] -> Right $ VPP policy _ -> Left allReasons where allReasons = mconcat [validMaxLength, validLength, validCategoryAmount, validPredicate] validLength, validMaxLength, validCategoryAmount, validPredicate :: [InvalidPolicyReason] validLength = [InvalidLength minimumLength maximumLength | minimumLength > maximumLength] validMaxLength = [MaxLengthBelowZero maximumLength | maximumLength <= 0] validCategoryAmount = We do n't report this reason if the maximumLength is already invalid [CategoryAmountsAboveMaxLength maximumLength total | total > maximumLength, maximumLength > 0] where capToZero = max 0 total = sum $ capToZero <$> [lowercaseChars, uppercaseChars, digitChars, specialChars] validPredicate = validateCharSetPredicate policy defaultCharSet :: String defaultCharSet = chr <$> [32 .. 126]
8a622b1c2e47b8915cf7cb02bf979da22ec8192b7cfc2c4e3d94b8b69939cc8c
TrustInSoft/tis-kernel
tis_kernel_init.ml
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) let () = let gc_params = Gc.get () in Gc.set { gc_params with Gc.minor_heap_size = 1 lsl 18 ; major_heap_increment = 1 lsl 22; space_overhead = 40 ; = 100 } let () = Printexc.record_backtrace true
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_internals/runtime/tis_kernel_init.ml
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . let () = let gc_params = Gc.get () in Gc.set { gc_params with Gc.minor_heap_size = 1 lsl 18 ; major_heap_increment = 1 lsl 22; space_overhead = 40 ; = 100 } let () = Printexc.record_backtrace true
75bee3844e0e1ab81f58b3c1eb46b933f0d1c3635caa741f83b6c6a06e6b8288
cky/guile
box-mixed.scm
;;; examples/box-dynamic-module/box-mixed.scm -- Scheme module using some functionality from the shared library libbox - module , but do not ;;; export procedures from the module. ;;; Commentary: ;;; This is the Scheme module box-mixed. It uses some functionality from the shared library libbox - module , but does not export it . ;;; Code: Author : Date : 2001 - 06 - 08 Changed : 2001 - 06 - 14 by , some commenting , cleanup and integration . (define-module (box-mixed)) First , load the library . ;; (load-extension "libbox-module" "scm_init_box") Create a list of boxes , each containing one element from ARGS . ;; (define (make-box-list . args) (map (lambda (el) (let ((b (make-box))) (box-set! b el) b)) args)) Map the procedure over all elements of LST , which must be a ;; list of boxes. The result is a list of freshly allocated boxes, each containing the result of an application of . (define (box-map func lst) (map (lambda (el) (let ((b (make-box))) (box-set! b (func (box-ref el))) b)) lst)) ;; Export the procedures, so that they can be used by others. ;; (export make-box-list box-map) ;;; End of file.
null
https://raw.githubusercontent.com/cky/guile/89ce9fb31b00f1f243fe6f2450db50372cc0b86d/examples/box-dynamic-module/box-mixed.scm
scheme
examples/box-dynamic-module/box-mixed.scm -- Scheme module using some export procedures from the module. Commentary: This is the Scheme module box-mixed. It uses some functionality Code: list of boxes. The result is a list of freshly allocated boxes, Export the procedures, so that they can be used by others. End of file.
functionality from the shared library libbox - module , but do not from the shared library libbox - module , but does not export it . Author : Date : 2001 - 06 - 08 Changed : 2001 - 06 - 14 by , some commenting , cleanup and integration . (define-module (box-mixed)) First , load the library . (load-extension "libbox-module" "scm_init_box") Create a list of boxes , each containing one element from ARGS . (define (make-box-list . args) (map (lambda (el) (let ((b (make-box))) (box-set! b el) b)) args)) Map the procedure over all elements of LST , which must be a each containing the result of an application of . (define (box-map func lst) (map (lambda (el) (let ((b (make-box))) (box-set! b (func (box-ref el))) b)) lst)) (export make-box-list box-map)
5ae99469ebaa31caf3c4a2d1d8db454bb4ac18be23d92eb99a1b43a6d7908f23
jnjcc/cl-qrencode-deprecated
qr-data-bstring.lisp
Copyright ( C ) 2010 , 2011 johnc < > ;; ;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 , or ( at your option ) ;; any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program; if not, see </>. ;;;; qr-data-bstring.lisp This file contains utilies that convert QR - INPUT to binary string ( bstring , ;;;; or bitstream, we may say). In particular , this file contains the four functions for encoding real data . ;;;; (in-package #:cl-qrencode) ( 0 ) NUMERIC mode : input data string is divided into groups of three digits . (defun group->decimal (num-group) "NUM-GROUP is either 1 digit, 2 digits, or 3 digits long, encode them into decimal." (declare (type string num-group)) (let ((len (length num-group)) (result 0)) (when (or (< len 1) (> len 3)) (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "group->decimal" :arguments '(num-group) :how "Under NUMERIC mode, input is divided into groups of 3 (or less) digits.")) (dotimes (idx len) (let ((ch (char num-group idx))) (when (not (digit-char-p ch)) (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "group->decimal" :arguments '(num-group) :how "Non-digit character appears under NUMERIC mode")) (setf result (+ (* result 10) (- (char-code ch) (char-code #\0)))))) result)) (defun group->bstring (num-group) "Encode NUM-GROUP into bstring." (declare (type string num-group)) (case (length num-group) 10 bits long for 3 digits 7 bits long for 2 digits 4 bits long for 1 digits (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "group->bstring" :arguments '(num-group) :how "Under NUMERIC mode, input is diviede into groups of 3 (or less) digits.")))) (defun numeric->bstring (data) "Convert input DATA string to bstring under NUMERIC mode." (declare (type string data)) (let ((len (length data)) (bstring "")) (do ((idx 0 (incf idx 3))) ((>= idx len) nil) (cond more than 3 chars left (setf bstring (concatenate 'string bstring (group->bstring (subseq data idx (+ idx 3)))))) 2 chars left (setf bstring (concatenate 'string bstring (group->bstring (subseq data idx (+ idx 2)))))) only 1 char left (setf bstring (concatenate 'string bstring (group->bstring (subseq data idx (+ idx 1)))))))) bstring)) ( 1 ) ALPHANUMERIC mode : data is divided into groups of two characters , we call it " pair " (defun char->decimal (char) "Only digits, capital letters, and some special characters available." (declare (type character char)) (cond ((char<= #\0 char #\9) (- (char-code char) (char-code #\0))) ((char<= #\A char #\Z) (+ (- (char-code char) (char-code #\A)) 10)) ((char= char #\Space) 36) ((char= char #\$) 37) ((char= char #\%) 38) ((char= char #\*) 39) ((char= char #\+) 40) ((char= char #\-) 41) ((char= char #\.) 42) ((char= char #\/) 43) ((char= char #\:) 44) (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "char->decimal" :arguments char :how "Character not recognized under ALPHANUMERIC mode.")))) (defun pair->decimal (alpha-pair) "ALPHA-PAIR is either 2 char or 1 char long, encode them into decimal." (declare (type string alpha-pair)) (setf alpha-pair (string-upcase alpha-pair)) (let ((len (length alpha-pair))) (cond ((= len 1) (char->decimal (char alpha-pair 0))) ((= len 2) (+ (* 45 (char->decimal (char alpha-pair 0))) (char->decimal (char alpha-pair 1)))) (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "pair->decimal" :arguments alpha-pair :how "Under ALPHANUMERIC mode, data is divided into pair of 2."))))) (defun pair->bstring (alpha-pair) "Encode ALPHA-PAIR to bstring: 11 bits for two char long, 6 bits for 1 char long." (declare (type string alpha-pair)) (let ((len (length alpha-pair))) (cond ((= len 2) (decimal->bstring (pair->decimal alpha-pair) 11)) ((= len 1) (decimal->bstring (pair->decimal alpha-pair) 6)) (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "pair->bstring" :arguments alpha-pair :how "Under ALPHANUMERIC mode, data is divided into pair of 2."))))) (defun alnum->bstring (data) "Convert input DATA string to bstring under ALPHANUMERIC mode." (declare (type string data)) (let ((len (length data)) (data (string-upcase data)) (bstring "")) (do ((idx 0 (incf idx 2))) ((>= idx len) nil) only 1 char left (setf bstring (concatenate 'string bstring (pair->bstring (subseq data idx (+ idx 1))))) (setf bstring (concatenate 'string bstring (pair->bstring (subseq data idx (+ idx 2))))))) bstring)) ( 3 ) BINARY mode : each value is directly encoded in 8 bit long binary representation ;; TODO: JIS X 0201 character sets? I have to look into it. (defun binary->bstring (data) "Convert input DATA string to bstring under BINARY mode." (declare (type string data)) (labels ((concat (prev cur) ; PREV is the result by now (concatenate 'string prev (decimal->bstring (char-code cur) 8)))) (reduce #'concat data :initial-value ""))) ( 4 ) KANJI mode : Shift JIS system , two bytes for a single character . JIS X 0208 (defun word->decimal (kanji-word) "Encode a KANJI-WORD to decimal." Use BABEL library to erase SBCL - specific problem . ; Thanks to xach <> (let ((result (babel-encodings::ucs-to-cp932 (char-code kanji-word))) (subtractor 0)) (setf subtractor (cond ((<= #x8140 result #x9FFC) #x8140) ((<= #xE040 result #xEBBF) #xC140))) (decf result subtractor) (setf result (+ (* (ash result -8) #xC0) (boole boole-and result #xFF))))) (defun word->bstring (kanji-word) "Encode a KANJI-WORD to bstring using 13 bits." (decimal->bstring (word->decimal kanji-word) 13)) (defun kanji->bstring (data) "Convert input DATA string to bstring under KANJI mode." (declare (type string data)) (let ((result "")) (loop for kanji-word across data do (setf result (concatenate 'string result (word->bstring kanji-word)))) result))
null
https://raw.githubusercontent.com/jnjcc/cl-qrencode-deprecated/b31498adf81d771310be871ff6a50bd54f574336/src/qr-data-bstring.lisp
lisp
This program is free software; you can redistribute it and/or modify either version 2 , or ( at your option ) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, see </>. qr-data-bstring.lisp or bitstream, we may say). TODO: JIS X 0201 character sets? I have to look into it. PREV is the result by now Thanks to xach <>
Copyright ( C ) 2010 , 2011 johnc < > it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License This file contains utilies that convert QR - INPUT to binary string ( bstring , In particular , this file contains the four functions for encoding real data . (in-package #:cl-qrencode) ( 0 ) NUMERIC mode : input data string is divided into groups of three digits . (defun group->decimal (num-group) "NUM-GROUP is either 1 digit, 2 digits, or 3 digits long, encode them into decimal." (declare (type string num-group)) (let ((len (length num-group)) (result 0)) (when (or (< len 1) (> len 3)) (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "group->decimal" :arguments '(num-group) :how "Under NUMERIC mode, input is divided into groups of 3 (or less) digits.")) (dotimes (idx len) (let ((ch (char num-group idx))) (when (not (digit-char-p ch)) (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "group->decimal" :arguments '(num-group) :how "Non-digit character appears under NUMERIC mode")) (setf result (+ (* result 10) (- (char-code ch) (char-code #\0)))))) result)) (defun group->bstring (num-group) "Encode NUM-GROUP into bstring." (declare (type string num-group)) (case (length num-group) 10 bits long for 3 digits 7 bits long for 2 digits 4 bits long for 1 digits (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "group->bstring" :arguments '(num-group) :how "Under NUMERIC mode, input is diviede into groups of 3 (or less) digits.")))) (defun numeric->bstring (data) "Convert input DATA string to bstring under NUMERIC mode." (declare (type string data)) (let ((len (length data)) (bstring "")) (do ((idx 0 (incf idx 3))) ((>= idx len) nil) (cond more than 3 chars left (setf bstring (concatenate 'string bstring (group->bstring (subseq data idx (+ idx 3)))))) 2 chars left (setf bstring (concatenate 'string bstring (group->bstring (subseq data idx (+ idx 2)))))) only 1 char left (setf bstring (concatenate 'string bstring (group->bstring (subseq data idx (+ idx 1)))))))) bstring)) ( 1 ) ALPHANUMERIC mode : data is divided into groups of two characters , we call it " pair " (defun char->decimal (char) "Only digits, capital letters, and some special characters available." (declare (type character char)) (cond ((char<= #\0 char #\9) (- (char-code char) (char-code #\0))) ((char<= #\A char #\Z) (+ (- (char-code char) (char-code #\A)) 10)) ((char= char #\Space) 36) ((char= char #\$) 37) ((char= char #\%) 38) ((char= char #\*) 39) ((char= char #\+) 40) ((char= char #\-) 41) ((char= char #\.) 42) ((char= char #\/) 43) ((char= char #\:) 44) (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "char->decimal" :arguments char :how "Character not recognized under ALPHANUMERIC mode.")))) (defun pair->decimal (alpha-pair) "ALPHA-PAIR is either 2 char or 1 char long, encode them into decimal." (declare (type string alpha-pair)) (setf alpha-pair (string-upcase alpha-pair)) (let ((len (length alpha-pair))) (cond ((= len 1) (char->decimal (char alpha-pair 0))) ((= len 2) (+ (* 45 (char->decimal (char alpha-pair 0))) (char->decimal (char alpha-pair 1)))) (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "pair->decimal" :arguments alpha-pair :how "Under ALPHANUMERIC mode, data is divided into pair of 2."))))) (defun pair->bstring (alpha-pair) "Encode ALPHA-PAIR to bstring: 11 bits for two char long, 6 bits for 1 char long." (declare (type string alpha-pair)) (let ((len (length alpha-pair))) (cond ((= len 2) (decimal->bstring (pair->decimal alpha-pair) 11)) ((= len 1) (decimal->bstring (pair->decimal alpha-pair) 6)) (t (error 'qr-bad-arguments :file-name "qr-data-bstring.lisp" :function-name "pair->bstring" :arguments alpha-pair :how "Under ALPHANUMERIC mode, data is divided into pair of 2."))))) (defun alnum->bstring (data) "Convert input DATA string to bstring under ALPHANUMERIC mode." (declare (type string data)) (let ((len (length data)) (data (string-upcase data)) (bstring "")) (do ((idx 0 (incf idx 2))) ((>= idx len) nil) only 1 char left (setf bstring (concatenate 'string bstring (pair->bstring (subseq data idx (+ idx 1))))) (setf bstring (concatenate 'string bstring (pair->bstring (subseq data idx (+ idx 2))))))) bstring)) ( 3 ) BINARY mode : each value is directly encoded in 8 bit long binary representation (defun binary->bstring (data) "Convert input DATA string to bstring under BINARY mode." (declare (type string data)) (concatenate 'string prev (decimal->bstring (char-code cur) 8)))) (reduce #'concat data :initial-value ""))) ( 4 ) KANJI mode : Shift JIS system , two bytes for a single character . JIS X 0208 (defun word->decimal (kanji-word) "Encode a KANJI-WORD to decimal." Use BABEL library to erase SBCL - specific problem . (let ((result (babel-encodings::ucs-to-cp932 (char-code kanji-word))) (subtractor 0)) (setf subtractor (cond ((<= #x8140 result #x9FFC) #x8140) ((<= #xE040 result #xEBBF) #xC140))) (decf result subtractor) (setf result (+ (* (ash result -8) #xC0) (boole boole-and result #xFF))))) (defun word->bstring (kanji-word) "Encode a KANJI-WORD to bstring using 13 bits." (decimal->bstring (word->decimal kanji-word) 13)) (defun kanji->bstring (data) "Convert input DATA string to bstring under KANJI mode." (declare (type string data)) (let ((result "")) (loop for kanji-word across data do (setf result (concatenate 'string result (word->bstring kanji-word)))) result))
bb1f163531d4cacd75b95b5d5c1c95bc14f99fd95317f5829c42994f57994e76
cljfx/cljfx
button.clj
(ns cljfx.fx.button "Part of a public API" (:require [cljfx.composite :as composite] [cljfx.fx.button-base :as fx.button-base] [cljfx.lifecycle :as lifecycle] [cljfx.coerce :as coerce]) (:import [javafx.scene.control Button] [javafx.scene AccessibleRole])) (set! *warn-on-reflection* true) (def props (merge fx.button-base/props (composite/props Button ;; overrides :style-class [:list lifecycle/scalar :coerce coerce/style-class :default "button"] :accessible-role [:setter lifecycle/scalar :coerce (coerce/enum AccessibleRole) :default :button] :mnemonic-parsing [:setter lifecycle/scalar :default true] ;; definitions :cancel-button [:setter lifecycle/scalar :default false] :default-button [:setter lifecycle/scalar :default false]))) (def lifecycle (lifecycle/annotate (composite/describe Button :ctor [] :props props) :button))
null
https://raw.githubusercontent.com/cljfx/cljfx/543f7409290051e9444771d2cd86dadeb8cdce33/src/cljfx/fx/button.clj
clojure
overrides definitions
(ns cljfx.fx.button "Part of a public API" (:require [cljfx.composite :as composite] [cljfx.fx.button-base :as fx.button-base] [cljfx.lifecycle :as lifecycle] [cljfx.coerce :as coerce]) (:import [javafx.scene.control Button] [javafx.scene AccessibleRole])) (set! *warn-on-reflection* true) (def props (merge fx.button-base/props (composite/props Button :style-class [:list lifecycle/scalar :coerce coerce/style-class :default "button"] :accessible-role [:setter lifecycle/scalar :coerce (coerce/enum AccessibleRole) :default :button] :mnemonic-parsing [:setter lifecycle/scalar :default true] :cancel-button [:setter lifecycle/scalar :default false] :default-button [:setter lifecycle/scalar :default false]))) (def lifecycle (lifecycle/annotate (composite/describe Button :ctor [] :props props) :button))
6159d1b1b4d1ba51aabe7f3acef9bc3d49ebf97eeb67f1112ed469da80d5030d
xguerin/netml
NetML_Layer_IV_UDP.mli
type t = { source : int; destination : int; length : int; checksum : int; } [@@deriving yojson] val decode : Bitstring.t -> t option val expand : Bitstring.t -> Bitstring.t option
null
https://raw.githubusercontent.com/xguerin/netml/de9d277d2f1ac055aea391b89391df6830f80eff/src/NetML_Layer_IV_UDP.mli
ocaml
type t = { source : int; destination : int; length : int; checksum : int; } [@@deriving yojson] val decode : Bitstring.t -> t option val expand : Bitstring.t -> Bitstring.t option
539ddcbc87de4020eb709b0ecf19e72e49a969e926d21cc5812aeddf0ee65698
input-output-hk/plutus
Scope.hs
-- editorconfig-checker-disable-file {-# LANGUAGE BangPatterns #-} # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # module UntypedPlutusCore.Check.Scope (checkScope) where import Control.Lens hiding (index) import UntypedPlutusCore.Core.Type as UPLC import UntypedPlutusCore.DeBruijn as UPLC import Control.Monad.Error.Lens import Control.Monad.Except | A pass to check that the input term : 1 ) does not contain free variables and 2 ) that all binders are set to debruijn index 0 . Feeding the result of the debruijnification to this function is expected to pass . On the other hand , because of ( 2 ) , this pass is stricter than the undebruijnification 's ( indirect ) scope - checking , see NOTE : [ indices of Binders ] . Inlining this function makes a big difference , since it will usually be called in a context where all the type variables are known . That then means that GHC can optimize go locally in a completely monomorphic setting , which helps a lot . 1) does not contain free variables and 2) that all binders are set to debruijn index 0. Feeding the result of the debruijnification to this function is expected to pass. On the other hand, because of (2), this pass is stricter than the undebruijnification's (indirect) scope-checking, see NOTE: [DeBruijn indices of Binders]. Inlining this function makes a big difference, since it will usually be called in a context where all the type variables are known. That then means that GHC can optimize go locally in a completely monomorphic setting, which helps a lot. -} # INLINE checkScope # checkScope :: forall e m name uni fun a. (HasIndex name, MonadError e m, AsFreeVariableError e) => UPLC.Term name uni fun a -> m () checkScope = go 0 where -- the current level as a reader value go :: Word -> UPLC.Term name uni fun a -> m () go !lvl = \case Var _ n -> do let i = n ^. index -- var index must be larger than 0 var index must be LEQ to the current level unless (i > 0 && fromIntegral i <= lvl) $ throwing _FreeVariableError $ FreeIndex i LamAbs _ binder t -> do let bIx = binder^.index binder index must be equal to 0 unless (bIx == 0) $ throwing _FreeVariableError $ FreeIndex bIx go (lvl+1) t Apply _ t1 t2 -> go lvl t1 >> go lvl t2 Force _ t -> go lvl t Delay _ t -> go lvl t _ -> pure ()
null
https://raw.githubusercontent.com/input-output-hk/plutus/c8d4364d0e639fef4d5b93f7d6c0912d992b54f9/plutus-core/untyped-plutus-core/src/UntypedPlutusCore/Check/Scope.hs
haskell
editorconfig-checker-disable-file # LANGUAGE BangPatterns # the current level as a reader value var index must be larger than 0
# LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # module UntypedPlutusCore.Check.Scope (checkScope) where import Control.Lens hiding (index) import UntypedPlutusCore.Core.Type as UPLC import UntypedPlutusCore.DeBruijn as UPLC import Control.Monad.Error.Lens import Control.Monad.Except | A pass to check that the input term : 1 ) does not contain free variables and 2 ) that all binders are set to debruijn index 0 . Feeding the result of the debruijnification to this function is expected to pass . On the other hand , because of ( 2 ) , this pass is stricter than the undebruijnification 's ( indirect ) scope - checking , see NOTE : [ indices of Binders ] . Inlining this function makes a big difference , since it will usually be called in a context where all the type variables are known . That then means that GHC can optimize go locally in a completely monomorphic setting , which helps a lot . 1) does not contain free variables and 2) that all binders are set to debruijn index 0. Feeding the result of the debruijnification to this function is expected to pass. On the other hand, because of (2), this pass is stricter than the undebruijnification's (indirect) scope-checking, see NOTE: [DeBruijn indices of Binders]. Inlining this function makes a big difference, since it will usually be called in a context where all the type variables are known. That then means that GHC can optimize go locally in a completely monomorphic setting, which helps a lot. -} # INLINE checkScope # checkScope :: forall e m name uni fun a. (HasIndex name, MonadError e m, AsFreeVariableError e) => UPLC.Term name uni fun a -> m () checkScope = go 0 where go :: Word -> UPLC.Term name uni fun a -> m () go !lvl = \case Var _ n -> do let i = n ^. index var index must be LEQ to the current level unless (i > 0 && fromIntegral i <= lvl) $ throwing _FreeVariableError $ FreeIndex i LamAbs _ binder t -> do let bIx = binder^.index binder index must be equal to 0 unless (bIx == 0) $ throwing _FreeVariableError $ FreeIndex bIx go (lvl+1) t Apply _ t1 t2 -> go lvl t1 >> go lvl t2 Force _ t -> go lvl t Delay _ t -> go lvl t _ -> pure ()
a30902ca4d91fcb02bd67fc51bf5cb91c3cfcc6e257f416d55aba68b45355e4d
manuel-serrano/bigloo
btags.scm
;*=====================================================================*/ * serrano / prgm / project / bigloo / bde / btags / btags.scm * / ;* ------------------------------------------------------------- */ * Author : * / * Creation : Thu May 28 07:24:34 1998 * / * Last change : We d Jul 24 07:42:08 2013 ( serrano ) * / * Copyright : 2000 - 13 * / ;* ------------------------------------------------------------- */ * The tag generator . * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module btags (main main)) ;*---------------------------------------------------------------------*/ ;* Global parameters */ ;*---------------------------------------------------------------------*/ (define *btags-version* "0.3") (define *btags-append* #f) (define *btags-language* #f) (define *btags-table-name* "TAGS") (define *btags-etags* "etags") (define *btags-files* '()) (define *btags-modules* #f) (define *btags-extern?* #f) (define *oport* #f) (define *btags-define-var-list* '(define define-struct define-parameter)) (define *btags-define-fun-list* '(define define-inline define-generic define-macro define-expander)) (define *btags-module-list* '(module)) (define *btags-suffixes* '("scm" "sch" "bgl")) (define *btags-ignore-errors* #f) ;*---------------------------------------------------------------------*/ ;* main ... */ ;*---------------------------------------------------------------------*/ (define (main argv) ;; we parse command line arguments (parse-args argv) ;; we start erasing the old table if not in append mode (if (not *btags-append*) (delete-file *btags-table-name*)) ;; we emit the argument option for other bee tools (such as kbrowse) (btags-emit-configuration) ;; we produce tags entrie regarding the source language (for-each btags-file (reverse! *btags-files*)) ;; we close the output port if currently opened (if (output-port? *oport*) (begin (close-output-port *oport*) (set! *oport* #f)))) ;*---------------------------------------------------------------------*/ ;* parse-args ... */ ;*---------------------------------------------------------------------*/ (define (parse-args cmd-args) (define (usage args-parse-usage level) (print "usage: bgltags [options] file ...") (newline) (args-parse-usage #f) (newline)) (args-parse (cdr cmd-args) (("?") (usage args-parse-usage 1) (exit 1)) ((("-help" "--help") (help "This help message")) (usage args-parse-usage 1) (exit 0)) (("-a" (help "-a, --append" "Append to existing tag file.")) (set! *btags-append* #t)) ((("-s" "-suffix" "--suffix") ?suffix (help "Add source suffix")) (set! *btags-suffixes* (cons suffix *btags-suffixes*))) (("--append") (set! *btags-append* #t)) (("-e" (help "-e, --extern" "Parse Bigloo extern clauses")) (set! *btags-extern?* #t)) (("--extern") (set! *btags-extern?* #t)) (("-l" ?language (help "-l language, --language-language" "Parse the following files according to the given language.")) (if (string=? language "none") (set! *btags-language* #f) (set! *btags-language* language))) (("-l=?language") (if (string=? language "none") (set! *btags-language* #f) (set! *btags-language* language))) (("-o" ?tagfile (help "-o tagfile, --output=tagfile" "Explict name of file for tag table (default `TAGS').")) (set! *btags-table-name* tagfile)) (("--output=?tagfile") (set! *btags-table-name* tagfile)) (("-module" (help "Generate tag entry for module identifier")) (set! *btags-modules* #t)) (("-v" (help "-v, --version" "Print the current-version of the program")) (print *btags-version*) (exit 0)) (("--version") (print *btags-version*) (exit 0)) (("--define-var" ?k (synopsis "Add define keyword `(KWD VAR VAL)'")) (set! *btags-define-var-list* (cons (string->symbol k) *btags-define-var-list*))) (("--define-fun" ?k (synopsis "Add define keyword `(KWD (ID ...) VAL)'")) (set! *btags-define-fun-list* (cons (string->symbol k) *btags-define-fun-list*))) (("--module" ?k (synopsis "Add module keyword `(KWD ID ...)'")) (set! *btags-module-list* (cons (string->symbol k) *btags-module-list*))) (("--ignore-error" (synopsis "Ignore errors")) (set! *btags-ignore-errors* #t)) (else (if (string? *btags-language*) (set! *btags-files* (cons (cons else *btags-language*) *btags-files*)) (set! *btags-files* (cons else *btags-files*)))))) ;*---------------------------------------------------------------------*/ ;* btags-file ... */ ;*---------------------------------------------------------------------*/ (define (btags-file file) (if (pair? file) (let ((fname (car file)) (language (cdr file))) (if (string=? language "bigloo") (bigloo-btags fname) (other-btags fname language))) (let ((suffix (suffix file))) (cond ((member suffix *btags-suffixes*) (bigloo-btags file)) (else (other-btags file #f)))))) ;*---------------------------------------------------------------------*/ ;* other-btags ... */ ;* ------------------------------------------------------------- */ ;* We produce tags entries for other languages. This is quiet */ ;* easy because we just call `etags' */ ;*---------------------------------------------------------------------*/ (define (other-btags file language) (if (output-port? *oport*) (begin (close-output-port *oport*) (set! *oport* #f))) (let ((command (string-append *btags-etags* (if language (string-append " --language=" language) "") " --append" " --output=" *btags-table-name* " " file))) (system command))) ;*---------------------------------------------------------------------*/ ;* btags-emit-configuration ... */ ;*---------------------------------------------------------------------*/ (define (btags-emit-configuration) (define (btags-list l) (for-each (lambda (x) (display "(meta-define define " *oport*) (display (string-downcase (symbol->string x)) *oport*) (fprint *oport* (string #a127 #\0 #\, #\0))) l)) ;; first, we open the output file (if (not (output-port? *oport*)) (begin (set! *oport* (append-output-file *btags-table-name*)) (if (not (output-port? *oport*)) (error 'bgltags "Can't open file for output" *btags-table-name*)))) ;; then we do the real job (if (or (pair? *btags-define-var-list*) (pair? *btags-define-fun-list*) (pair? *btags-module-list*)) (begin (fprint *oport* #a012) (fprint *oport* "-,0") (if (pair? *btags-define-var-list*) (btags-list *btags-define-var-list*)) (if (pair? *btags-define-fun-list*) (btags-list *btags-define-fun-list*)) (if (pair? *btags-module-list*) (btags-list *btags-module-list*))))) ;*---------------------------------------------------------------------*/ * ... * / ;* ------------------------------------------------------------- */ * The true jobs , the tags generator ... * / ;*---------------------------------------------------------------------*/ (define (bigloo-btags file) ;; first, we open the output file (if (not (output-port? *oport*)) (begin (set! *oport* (append-output-file *btags-table-name*)) (if (not (output-port? *oport*)) (error 'bgltags "Can't open file for output" *btags-table-name*)))) ;; the real btags jobs (if *btags-ignore-errors* (with-handler (lambda (e) #f) (bigloo-btags-file *oport* file)) (bigloo-btags-file *oport* file))) ;*---------------------------------------------------------------------*/ * - file ... * / ;* ------------------------------------------------------------- */ ;* Because we want to avoid parsing source file without reading */ * ( with the regular reader ) , we process two readings of * / * a source file . The first one , we locate declarations and * / * in the second one , we emit tags declarations . * / ;*---------------------------------------------------------------------*/ (define (bigloo-btags-file oport file) (let ((decl-lines (find-declaration-lines file))) (let ((iport (and (file-exists? file) (open-input-file file)))) (if (not (input-port? iport)) (error 'bgltags "Can't open file for input" file) (unwind-protect ;; we have to reset the reader other line numbering is ;; erroneous (reader-reset!) ;; we now scan the file in order to emit the TAGs decls (let loop ((line (read-line iport)) (lnum 1) (pos 1) (lines decl-lines) (tags "")) (if (and (pair? lines) (not (eof-object? line))) (if (=fx lnum (car (car lines))) ;; this is a declaration line (let ((tag (tags-substring line (cdr (car lines))))) (loop line lnum pos (cdr lines) (if (string? tag) (string-append tags tag (make-string 1 #a127) (number->string lnum) "," we have to remove 1 to the position otherwise etags ( at least the one comes with gnu - emacs 21.2 ) gets ;; wrong and search the next tag ;; match (number->string (-fx pos 1)) #"\n") tags))) (loop (read-line iport) (+fx lnum 1) (+fx pos (+fx 1 (string-length line))) lines tags)) (begin ;; we emit the file header (fprint oport #a012) (let ((len (string-length tags))) (fprint oport file "," len) (display tags oport))))) (close-input-port iport)))))) ;*---------------------------------------------------------------------*/ ;* tags-substring ... */ ;*---------------------------------------------------------------------*/ (define (tags-substring str1 str2) (define (substring-at? start str1 str2) (let ((len2 (string-length str2))) (let loop ((i1 start) (i2 0)) (cond ((=fx i2 len2) #t) ((char-ci=? (string-ref str1 i1) (string-ref str2 i2)) (loop (+fx i1 1) (+fx i2 1))) (else #f))))) (let ((len1 (string-length str1))) (cond ((pair? str2) ;; if the argument is a pair instead of a string, it means that ;; it is a typed identifier (such as a class or a method) that ;; must be written with its type information. Nevertheless we ;; have to take care that we must strip off all the extra ;; information found at the line. For instead for a class declaration ;; such as: (class point-3d::point (z (default 0))) ;; we have to write: ;; (class point-3d::point^?...) (let loop ((r 0)) (cond ((=fx r len1) str1) ((or (char=? (string-ref str1 r) #\)) (char=? (string-ref str1 r) #\;)) (substring str1 0 r)) (else (loop (+fx r 1)))))) ((vector? str2) (string-append "(define (" (vector-ref str2 1))) ((cell? str2) (string-append "(define-parameter " (cell-ref str2) "-set!")) (else ;; this is neither a class nor a method... (let* ((len2 (string-length str2)) (stop (-fx len1 len2)) (start (let loop ((j 0)) (cond ((=fx j len1) #f) ((char=? (string-ref str1 j) #\space) (+fx j 1)) (else (loop (+fx j 1))))))) (if (fixnum? start) (let loop ((i start)) (cond ((>fx i stop) #f) ((substring-at? i str1 str2) (substring str1 0 (+fx i len2))) (else (loop (+fx i 1))))) #f)))))) ;*---------------------------------------------------------------------*/ ;* find-declaration-lines ... */ ;* ------------------------------------------------------------- */ ;* During this stage, we walk thru the code in order to find */ ;* all the source lines that contains a declaration. For each */ ;* of these lines, we allocate a pair containing the line number */ ;* and a delimiter sentinel string. */ ;*---------------------------------------------------------------------*/ (define (find-declaration-lines file) (let ((iport (and (file-exists? file) (open-input-file file)))) (if (not (input-port? iport)) (error 'bgltags "Can't open file for input" file) (unwind-protect (let ((exp (read iport #t))) (if (not (eof-object? exp)) (let ((lines (if (module? exp) (append (btags-module exp) (btags-expression exp)) (btags-expression exp)))) (let loop ((exp (read iport #t)) (lines lines)) (if (eof-object? exp) (reverse! lines) (begin (loop (read iport #t) (append (btags-expression exp) lines)))))))) (close-input-port iport))))) ;*---------------------------------------------------------------------*/ ;* module? ... */ ;* ------------------------------------------------------------- */ ;* Is an expression a module expression. */ ;*---------------------------------------------------------------------*/ (define (module? expr) (match-case expr (((? (lambda (x) (memq x *btags-module-list*))) (? symbol?) . ?-) #t) ((directives . ?-) #t) (else #f))) ;*---------------------------------------------------------------------*/ ;* line-number ... */ ;*---------------------------------------------------------------------*/ (define (line-number expr) (and (epair? expr) (match-case (cer expr) ((at ?fname ?pos) (file-position->line (+fx pos 1) fname)) (else #f)))) ;*---------------------------------------------------------------------*/ ;* id->string ... */ ;*---------------------------------------------------------------------*/ (define (id->string id decl) (cond ((and (pair? id) (symbol? (car id))) (symbol->string (car id))) ((string? id) id) ((not (symbol? id)) (error 'bgltags "Illegal identifier" decl)) (else (let* ((string (symbol->string id)) (len (string-length string))) (let loop ((walker 0)) (cond ((=fx walker len) (symbol->string id)) ((and (char=? (string-ref string walker) #\:) (<fx walker (-fx len 1)) (char=? (string-ref string (+fx walker 1)) #\:)) (substring string 0 walker)) (else (loop (+fx walker 1))))))))) ;*---------------------------------------------------------------------*/ * btags - module ... * / ;*---------------------------------------------------------------------*/ (define (btags-module expr) (define (tags-module-clause lines clauses) (let loop ((clauses clauses) (lines lines)) (if (pair? clauses) (let ((clause (car clauses))) (loop (cdr clauses) (if (pair? clause) (case (car clause) ((eval) (append (btags-eval-clause clause) lines)) ((static export) (append (btags-static+export-clause clause) lines)) ((extern) (if *btags-extern?* (append (btags-extern-clause clause) lines) lines)) (else lines)) lines))) lines))) (match-case expr ((module (and ?name (? symbol?)) . ?clauses) (tags-module-clause (if (and (epair? expr) *btags-modules*) (let ((lnum (line-number expr))) (list (cons lnum (symbol->string name)))) '()) clauses)) ((directives . ?clauses) (tags-module-clause '() clauses)))) ;*---------------------------------------------------------------------*/ * - walker ... * / ;*---------------------------------------------------------------------*/ (define (btags-clause-walker parser clause) (let loop ((decls clause) (lines '())) (if (pair? decls) (let ((nlines (parser (car decls)))) (loop (cdr decls) (if (list? nlines) (append nlines lines) lines))) lines))) ;*---------------------------------------------------------------------*/ * ... * / ;*---------------------------------------------------------------------*/ (define (btags-eval-clause clause) (define (eval-parse decl) (match-case decl ((import (and (? symbol?) ?var)) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (symbol->string var)))))))) (btags-clause-walker eval-parse clause)) ;*---------------------------------------------------------------------*/ ;* btags-static+export-clause ... */ ;*---------------------------------------------------------------------*/ (define (btags-static+export-clause clause) (define (static+export-parse decl) (match-case decl (((and ?class (or class final-class wide-class)) ?name . ?clauses) (btags-class-clause decl class name clauses)))) (btags-clause-walker static+export-parse clause)) ;*---------------------------------------------------------------------*/ ;* btags-class-clause ... */ ;*---------------------------------------------------------------------*/ (define (btags-class-clause decl class id slots) (let ((name (id->string id decl))) (define (clines l cid ro cs) (let ((sid (symbol->string cid))) (if (number? l) (if ro (cons (cons l (vector cid (string-append name "-" sid))) cs) (cons* (cons l (vector cid (string-append name "-" sid))) (cons l (vector cid (string-append name "-" sid "-set!"))) cs)) cs))) (let loop ((slots slots) (lines '())) (if (null? slots) (let ((l (line-number decl))) (if (number? l) (reverse! (cons* (cons l (vector name (string-append name "?"))) (cons l (vector name (string-append "make-" name))) (cons l (vector name (string-append "fill-" name "!"))) (cons l name) (reverse! lines))) (reverse! lines))) (match-case (car slots) ((? symbol?) (let ((l (line-number slots))) (loop (cdr slots) (clines l (car slots) #f lines)))) ((* (and ?id (? symbol?)) . ?att) (let ((l (or (line-number (cdr (car slots))) (line-number (car slots)) (line-number slots))) (ro (and (list? att) (memq 'read-only att)))) (loop (cdr slots) (clines l id ro lines)))) (((and ?id (? symbol?)) . ?att) (let ((l (or (line-number (cdr (car slots))) (line-number (car slots)) (line-number slots))) (ro (and (list? att) (memq 'read-only att)))) (loop (cdr slots) (clines l id ro lines)))) (else (loop (cdr slots) lines))))))) ;*---------------------------------------------------------------------*/ * - clause ... * / ;*---------------------------------------------------------------------*/ (define (btags-extern-clause clause) (define (extern-parse decl) (if (epair? decl) (match-case decl ((export (and (? symbol?) ?bname) (and (? string?) ?cname)) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (string-append "\"" cname "\"")))))) ((or (macro ?l-name ?proto ?c-name) (infix macro ?l-name ?proto ?c-name)) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl)))))) ((macro ?l-name ?c-name) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl)))))) ((?l-name ?proto ?c-name) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl)))))) ((?l-name ?c-name) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl))))))))) (btags-clause-walker extern-parse (cdr clause))) ;*---------------------------------------------------------------------*/ ;* btags-expression ... */ ;*---------------------------------------------------------------------*/ (define (btags-expression expr) (define (var-keyword? id) (and (symbol? id) (memq id *btags-define-var-list*))) (define (fun-keyword? id) (and (symbol? id) (memq id *btags-define-fun-list*))) (define (module-keyword? id) (and (symbol? id) (memq id *btags-module-list*))) (match-case expr (((kwote cond-expand) . ?clauses) (letrec ((match-cond (lambda (requirement) (match-case requirement (((kwote and) . ?rest) (every match-cond rest)) (((kwote or) . ?rest) (any match-cond rest)) (((kwote not) ?req) (not (match-cond req))) ((or srfi-0 srfi-1 srfi-2 srfi-6 srfi-8 srfi-9 srfi-22 srfi-28 srfi-30 srfi-33 bigloo bigloo-c bigloo-compile bigloo-debug bigloo3 bigloo38 debug) #t) ((kwote else) ;; cond-expand's else-clause #t) (else ;; no feature match #f))))) (let ((first-match (find (lambda (clause) (match-cond (car clause))) clauses))) (if (and (pair? first-match) (pair? (cdr first-match))) ;; definition might be any expression (btags-expression (cadr first-match)) ;; requirement, but empty definition '())))) ((begin . ?rest) (apply append (map btags-expression rest))) ((define-method (?fun . ?-) . ?-) ;; method are special because we are not seeking an exact match ;; for method because we want to write the type for which the ;; method overrides (let ((lnum (line-number expr))) (if (number? lnum) (list (cons lnum (list (id->string fun expr)))) '()))) (((? fun-keyword?) (?fun . ?-) . ?-) (let ((lnum (line-number expr))) (if (number? lnum) (list (cons lnum (id->string fun expr))) '()))) (((and ?def (? var-keyword?)) (and (? symbol?) ?var) . ?-) (let ((lnum (line-number expr))) (if (number? lnum) (if (eq? def 'define-parameter) (let ((s (id->string var expr))) (list (cons lnum s) (cons lnum (make-cell s)))) (list (cons lnum (id->string var expr)))) '()))) (((? module-keyword?) (and (? symbol?) ?var) . ?-) (let ((lnum (line-number expr))) (if (number? lnum) (list (cons lnum (id->string var expr))) '()))) (else '())))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/bde/btags/btags.scm
scheme
*=====================================================================*/ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * Global parameters */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * main ... */ *---------------------------------------------------------------------*/ we parse command line arguments we start erasing the old table if not in append mode we emit the argument option for other bee tools (such as kbrowse) we produce tags entrie regarding the source language we close the output port if currently opened *---------------------------------------------------------------------*/ * parse-args ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * btags-file ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * other-btags ... */ * ------------------------------------------------------------- */ * We produce tags entries for other languages. This is quiet */ * easy because we just call `etags' */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * btags-emit-configuration ... */ *---------------------------------------------------------------------*/ first, we open the output file then we do the real job *---------------------------------------------------------------------*/ * ------------------------------------------------------------- */ *---------------------------------------------------------------------*/ first, we open the output file the real btags jobs *---------------------------------------------------------------------*/ * ------------------------------------------------------------- */ * Because we want to avoid parsing source file without reading */ *---------------------------------------------------------------------*/ we have to reset the reader other line numbering is erroneous we now scan the file in order to emit the TAGs decls this is a declaration line wrong and search the next tag match we emit the file header *---------------------------------------------------------------------*/ * tags-substring ... */ *---------------------------------------------------------------------*/ if the argument is a pair instead of a string, it means that it is a typed identifier (such as a class or a method) that must be written with its type information. Nevertheless we have to take care that we must strip off all the extra information found at the line. For instead for a class declaration such as: (class point-3d::point (z (default 0))) we have to write: (class point-3d::point^?...) )) this is neither a class nor a method... *---------------------------------------------------------------------*/ * find-declaration-lines ... */ * ------------------------------------------------------------- */ * During this stage, we walk thru the code in order to find */ * all the source lines that contains a declaration. For each */ * of these lines, we allocate a pair containing the line number */ * and a delimiter sentinel string. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * module? ... */ * ------------------------------------------------------------- */ * Is an expression a module expression. */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * line-number ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * id->string ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * btags-static+export-clause ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * btags-class-clause ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * btags-expression ... */ *---------------------------------------------------------------------*/ cond-expand's else-clause no feature match definition might be any expression requirement, but empty definition method are special because we are not seeking an exact match for method because we want to write the type for which the method overrides
* serrano / prgm / project / bigloo / bde / btags / btags.scm * / * Author : * / * Creation : Thu May 28 07:24:34 1998 * / * Last change : We d Jul 24 07:42:08 2013 ( serrano ) * / * Copyright : 2000 - 13 * / * The tag generator . * / (module btags (main main)) (define *btags-version* "0.3") (define *btags-append* #f) (define *btags-language* #f) (define *btags-table-name* "TAGS") (define *btags-etags* "etags") (define *btags-files* '()) (define *btags-modules* #f) (define *btags-extern?* #f) (define *oport* #f) (define *btags-define-var-list* '(define define-struct define-parameter)) (define *btags-define-fun-list* '(define define-inline define-generic define-macro define-expander)) (define *btags-module-list* '(module)) (define *btags-suffixes* '("scm" "sch" "bgl")) (define *btags-ignore-errors* #f) (define (main argv) (parse-args argv) (if (not *btags-append*) (delete-file *btags-table-name*)) (btags-emit-configuration) (for-each btags-file (reverse! *btags-files*)) (if (output-port? *oport*) (begin (close-output-port *oport*) (set! *oport* #f)))) (define (parse-args cmd-args) (define (usage args-parse-usage level) (print "usage: bgltags [options] file ...") (newline) (args-parse-usage #f) (newline)) (args-parse (cdr cmd-args) (("?") (usage args-parse-usage 1) (exit 1)) ((("-help" "--help") (help "This help message")) (usage args-parse-usage 1) (exit 0)) (("-a" (help "-a, --append" "Append to existing tag file.")) (set! *btags-append* #t)) ((("-s" "-suffix" "--suffix") ?suffix (help "Add source suffix")) (set! *btags-suffixes* (cons suffix *btags-suffixes*))) (("--append") (set! *btags-append* #t)) (("-e" (help "-e, --extern" "Parse Bigloo extern clauses")) (set! *btags-extern?* #t)) (("--extern") (set! *btags-extern?* #t)) (("-l" ?language (help "-l language, --language-language" "Parse the following files according to the given language.")) (if (string=? language "none") (set! *btags-language* #f) (set! *btags-language* language))) (("-l=?language") (if (string=? language "none") (set! *btags-language* #f) (set! *btags-language* language))) (("-o" ?tagfile (help "-o tagfile, --output=tagfile" "Explict name of file for tag table (default `TAGS').")) (set! *btags-table-name* tagfile)) (("--output=?tagfile") (set! *btags-table-name* tagfile)) (("-module" (help "Generate tag entry for module identifier")) (set! *btags-modules* #t)) (("-v" (help "-v, --version" "Print the current-version of the program")) (print *btags-version*) (exit 0)) (("--version") (print *btags-version*) (exit 0)) (("--define-var" ?k (synopsis "Add define keyword `(KWD VAR VAL)'")) (set! *btags-define-var-list* (cons (string->symbol k) *btags-define-var-list*))) (("--define-fun" ?k (synopsis "Add define keyword `(KWD (ID ...) VAL)'")) (set! *btags-define-fun-list* (cons (string->symbol k) *btags-define-fun-list*))) (("--module" ?k (synopsis "Add module keyword `(KWD ID ...)'")) (set! *btags-module-list* (cons (string->symbol k) *btags-module-list*))) (("--ignore-error" (synopsis "Ignore errors")) (set! *btags-ignore-errors* #t)) (else (if (string? *btags-language*) (set! *btags-files* (cons (cons else *btags-language*) *btags-files*)) (set! *btags-files* (cons else *btags-files*)))))) (define (btags-file file) (if (pair? file) (let ((fname (car file)) (language (cdr file))) (if (string=? language "bigloo") (bigloo-btags fname) (other-btags fname language))) (let ((suffix (suffix file))) (cond ((member suffix *btags-suffixes*) (bigloo-btags file)) (else (other-btags file #f)))))) (define (other-btags file language) (if (output-port? *oport*) (begin (close-output-port *oport*) (set! *oport* #f))) (let ((command (string-append *btags-etags* (if language (string-append " --language=" language) "") " --append" " --output=" *btags-table-name* " " file))) (system command))) (define (btags-emit-configuration) (define (btags-list l) (for-each (lambda (x) (display "(meta-define define " *oport*) (display (string-downcase (symbol->string x)) *oport*) (fprint *oport* (string #a127 #\0 #\, #\0))) l)) (if (not (output-port? *oport*)) (begin (set! *oport* (append-output-file *btags-table-name*)) (if (not (output-port? *oport*)) (error 'bgltags "Can't open file for output" *btags-table-name*)))) (if (or (pair? *btags-define-var-list*) (pair? *btags-define-fun-list*) (pair? *btags-module-list*)) (begin (fprint *oport* #a012) (fprint *oport* "-,0") (if (pair? *btags-define-var-list*) (btags-list *btags-define-var-list*)) (if (pair? *btags-define-fun-list*) (btags-list *btags-define-fun-list*)) (if (pair? *btags-module-list*) (btags-list *btags-module-list*))))) * ... * / * The true jobs , the tags generator ... * / (define (bigloo-btags file) (if (not (output-port? *oport*)) (begin (set! *oport* (append-output-file *btags-table-name*)) (if (not (output-port? *oport*)) (error 'bgltags "Can't open file for output" *btags-table-name*)))) (if *btags-ignore-errors* (with-handler (lambda (e) #f) (bigloo-btags-file *oport* file)) (bigloo-btags-file *oport* file))) * - file ... * / * ( with the regular reader ) , we process two readings of * / * a source file . The first one , we locate declarations and * / * in the second one , we emit tags declarations . * / (define (bigloo-btags-file oport file) (let ((decl-lines (find-declaration-lines file))) (let ((iport (and (file-exists? file) (open-input-file file)))) (if (not (input-port? iport)) (error 'bgltags "Can't open file for input" file) (unwind-protect (reader-reset!) (let loop ((line (read-line iport)) (lnum 1) (pos 1) (lines decl-lines) (tags "")) (if (and (pair? lines) (not (eof-object? line))) (if (=fx lnum (car (car lines))) (let ((tag (tags-substring line (cdr (car lines))))) (loop line lnum pos (cdr lines) (if (string? tag) (string-append tags tag (make-string 1 #a127) (number->string lnum) "," we have to remove 1 to the position otherwise etags ( at least the one comes with gnu - emacs 21.2 ) gets (number->string (-fx pos 1)) #"\n") tags))) (loop (read-line iport) (+fx lnum 1) (+fx pos (+fx 1 (string-length line))) lines tags)) (begin (fprint oport #a012) (let ((len (string-length tags))) (fprint oport file "," len) (display tags oport))))) (close-input-port iport)))))) (define (tags-substring str1 str2) (define (substring-at? start str1 str2) (let ((len2 (string-length str2))) (let loop ((i1 start) (i2 0)) (cond ((=fx i2 len2) #t) ((char-ci=? (string-ref str1 i1) (string-ref str2 i2)) (loop (+fx i1 1) (+fx i2 1))) (else #f))))) (let ((len1 (string-length str1))) (cond ((pair? str2) (let loop ((r 0)) (cond ((=fx r len1) str1) ((or (char=? (string-ref str1 r) #\)) (substring str1 0 r)) (else (loop (+fx r 1)))))) ((vector? str2) (string-append "(define (" (vector-ref str2 1))) ((cell? str2) (string-append "(define-parameter " (cell-ref str2) "-set!")) (else (let* ((len2 (string-length str2)) (stop (-fx len1 len2)) (start (let loop ((j 0)) (cond ((=fx j len1) #f) ((char=? (string-ref str1 j) #\space) (+fx j 1)) (else (loop (+fx j 1))))))) (if (fixnum? start) (let loop ((i start)) (cond ((>fx i stop) #f) ((substring-at? i str1 str2) (substring str1 0 (+fx i len2))) (else (loop (+fx i 1))))) #f)))))) (define (find-declaration-lines file) (let ((iport (and (file-exists? file) (open-input-file file)))) (if (not (input-port? iport)) (error 'bgltags "Can't open file for input" file) (unwind-protect (let ((exp (read iport #t))) (if (not (eof-object? exp)) (let ((lines (if (module? exp) (append (btags-module exp) (btags-expression exp)) (btags-expression exp)))) (let loop ((exp (read iport #t)) (lines lines)) (if (eof-object? exp) (reverse! lines) (begin (loop (read iport #t) (append (btags-expression exp) lines)))))))) (close-input-port iport))))) (define (module? expr) (match-case expr (((? (lambda (x) (memq x *btags-module-list*))) (? symbol?) . ?-) #t) ((directives . ?-) #t) (else #f))) (define (line-number expr) (and (epair? expr) (match-case (cer expr) ((at ?fname ?pos) (file-position->line (+fx pos 1) fname)) (else #f)))) (define (id->string id decl) (cond ((and (pair? id) (symbol? (car id))) (symbol->string (car id))) ((string? id) id) ((not (symbol? id)) (error 'bgltags "Illegal identifier" decl)) (else (let* ((string (symbol->string id)) (len (string-length string))) (let loop ((walker 0)) (cond ((=fx walker len) (symbol->string id)) ((and (char=? (string-ref string walker) #\:) (<fx walker (-fx len 1)) (char=? (string-ref string (+fx walker 1)) #\:)) (substring string 0 walker)) (else (loop (+fx walker 1))))))))) * btags - module ... * / (define (btags-module expr) (define (tags-module-clause lines clauses) (let loop ((clauses clauses) (lines lines)) (if (pair? clauses) (let ((clause (car clauses))) (loop (cdr clauses) (if (pair? clause) (case (car clause) ((eval) (append (btags-eval-clause clause) lines)) ((static export) (append (btags-static+export-clause clause) lines)) ((extern) (if *btags-extern?* (append (btags-extern-clause clause) lines) lines)) (else lines)) lines))) lines))) (match-case expr ((module (and ?name (? symbol?)) . ?clauses) (tags-module-clause (if (and (epair? expr) *btags-modules*) (let ((lnum (line-number expr))) (list (cons lnum (symbol->string name)))) '()) clauses)) ((directives . ?clauses) (tags-module-clause '() clauses)))) * - walker ... * / (define (btags-clause-walker parser clause) (let loop ((decls clause) (lines '())) (if (pair? decls) (let ((nlines (parser (car decls)))) (loop (cdr decls) (if (list? nlines) (append nlines lines) lines))) lines))) * ... * / (define (btags-eval-clause clause) (define (eval-parse decl) (match-case decl ((import (and (? symbol?) ?var)) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (symbol->string var)))))))) (btags-clause-walker eval-parse clause)) (define (btags-static+export-clause clause) (define (static+export-parse decl) (match-case decl (((and ?class (or class final-class wide-class)) ?name . ?clauses) (btags-class-clause decl class name clauses)))) (btags-clause-walker static+export-parse clause)) (define (btags-class-clause decl class id slots) (let ((name (id->string id decl))) (define (clines l cid ro cs) (let ((sid (symbol->string cid))) (if (number? l) (if ro (cons (cons l (vector cid (string-append name "-" sid))) cs) (cons* (cons l (vector cid (string-append name "-" sid))) (cons l (vector cid (string-append name "-" sid "-set!"))) cs)) cs))) (let loop ((slots slots) (lines '())) (if (null? slots) (let ((l (line-number decl))) (if (number? l) (reverse! (cons* (cons l (vector name (string-append name "?"))) (cons l (vector name (string-append "make-" name))) (cons l (vector name (string-append "fill-" name "!"))) (cons l name) (reverse! lines))) (reverse! lines))) (match-case (car slots) ((? symbol?) (let ((l (line-number slots))) (loop (cdr slots) (clines l (car slots) #f lines)))) ((* (and ?id (? symbol?)) . ?att) (let ((l (or (line-number (cdr (car slots))) (line-number (car slots)) (line-number slots))) (ro (and (list? att) (memq 'read-only att)))) (loop (cdr slots) (clines l id ro lines)))) (((and ?id (? symbol?)) . ?att) (let ((l (or (line-number (cdr (car slots))) (line-number (car slots)) (line-number slots))) (ro (and (list? att) (memq 'read-only att)))) (loop (cdr slots) (clines l id ro lines)))) (else (loop (cdr slots) lines))))))) * - clause ... * / (define (btags-extern-clause clause) (define (extern-parse decl) (if (epair? decl) (match-case decl ((export (and (? symbol?) ?bname) (and (? string?) ?cname)) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (string-append "\"" cname "\"")))))) ((or (macro ?l-name ?proto ?c-name) (infix macro ?l-name ?proto ?c-name)) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl)))))) ((macro ?l-name ?c-name) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl)))))) ((?l-name ?proto ?c-name) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl)))))) ((?l-name ?c-name) (let ((lnum (line-number decl))) (if (number? lnum) (list (cons lnum (id->string l-name decl))))))))) (btags-clause-walker extern-parse (cdr clause))) (define (btags-expression expr) (define (var-keyword? id) (and (symbol? id) (memq id *btags-define-var-list*))) (define (fun-keyword? id) (and (symbol? id) (memq id *btags-define-fun-list*))) (define (module-keyword? id) (and (symbol? id) (memq id *btags-module-list*))) (match-case expr (((kwote cond-expand) . ?clauses) (letrec ((match-cond (lambda (requirement) (match-case requirement (((kwote and) . ?rest) (every match-cond rest)) (((kwote or) . ?rest) (any match-cond rest)) (((kwote not) ?req) (not (match-cond req))) ((or srfi-0 srfi-1 srfi-2 srfi-6 srfi-8 srfi-9 srfi-22 srfi-28 srfi-30 srfi-33 bigloo bigloo-c bigloo-compile bigloo-debug bigloo3 bigloo38 debug) #t) ((kwote else) #t) (else #f))))) (let ((first-match (find (lambda (clause) (match-cond (car clause))) clauses))) (if (and (pair? first-match) (pair? (cdr first-match))) (btags-expression (cadr first-match)) '())))) ((begin . ?rest) (apply append (map btags-expression rest))) ((define-method (?fun . ?-) . ?-) (let ((lnum (line-number expr))) (if (number? lnum) (list (cons lnum (list (id->string fun expr)))) '()))) (((? fun-keyword?) (?fun . ?-) . ?-) (let ((lnum (line-number expr))) (if (number? lnum) (list (cons lnum (id->string fun expr))) '()))) (((and ?def (? var-keyword?)) (and (? symbol?) ?var) . ?-) (let ((lnum (line-number expr))) (if (number? lnum) (if (eq? def 'define-parameter) (let ((s (id->string var expr))) (list (cons lnum s) (cons lnum (make-cell s)))) (list (cons lnum (id->string var expr)))) '()))) (((? module-keyword?) (and (? symbol?) ?var) . ?-) (let ((lnum (line-number expr))) (if (number? lnum) (list (cons lnum (id->string var expr))) '()))) (else '())))
bc2ce7df5210c97aaf4c2c9a7e64fbb423b99e6e9f5b42278408268f851c17ba
facebook/flow
autofix_prop_typo.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. *) class mapper target fixed_prop_name = object (this) inherit [Loc.t] Flow_ast_contains_mapper.mapper as super method private target_contained_by loc = Loc.contains loc target method private is_target loc = Loc.equal target loc method loc_annot_contains_target = this#target_contained_by method! expression e = let open Flow_ast.Expression in match e with | (loc, Member ({ Member.property; _ } as m)) -> (match property with | Member.PropertyIdentifier (property_id_loc, { Flow_ast.Identifier.comments; _ }) when this#is_target property_id_loc -> ( loc, Member { m with Member.property = Member.PropertyIdentifier (property_id_loc, { Flow_ast.Identifier.name = fixed_prop_name; comments }); } ) | Member.PropertyExpression ( property_literal_loc, Literal { Flow_ast.Literal.value = Flow_ast.Literal.String _; comments; _ } ) when this#is_target property_literal_loc -> let fixed_prop_name_literal = Ast_builder.Literals.string ~comments fixed_prop_name in ( loc, Member { m with Member.property = Member.PropertyExpression (property_literal_loc, Literal fixed_prop_name_literal); } ) | _ -> super#expression e) | _ -> super#expression e end let replace_prop_typo_at_target ~fixed_prop_name ast loc = let mapper = new mapper loc fixed_prop_name in mapper#program ast
null
https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/services/code_action/autofix_prop_typo.ml
ocaml
* 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. *) class mapper target fixed_prop_name = object (this) inherit [Loc.t] Flow_ast_contains_mapper.mapper as super method private target_contained_by loc = Loc.contains loc target method private is_target loc = Loc.equal target loc method loc_annot_contains_target = this#target_contained_by method! expression e = let open Flow_ast.Expression in match e with | (loc, Member ({ Member.property; _ } as m)) -> (match property with | Member.PropertyIdentifier (property_id_loc, { Flow_ast.Identifier.comments; _ }) when this#is_target property_id_loc -> ( loc, Member { m with Member.property = Member.PropertyIdentifier (property_id_loc, { Flow_ast.Identifier.name = fixed_prop_name; comments }); } ) | Member.PropertyExpression ( property_literal_loc, Literal { Flow_ast.Literal.value = Flow_ast.Literal.String _; comments; _ } ) when this#is_target property_literal_loc -> let fixed_prop_name_literal = Ast_builder.Literals.string ~comments fixed_prop_name in ( loc, Member { m with Member.property = Member.PropertyExpression (property_literal_loc, Literal fixed_prop_name_literal); } ) | _ -> super#expression e) | _ -> super#expression e end let replace_prop_typo_at_target ~fixed_prop_name ast loc = let mapper = new mapper loc fixed_prop_name in mapper#program ast
1738b02b47efa86153ba1ae04307a71393b3959859b605f2ed3f8fcf959acda2
elaforge/karya
ValType.hs
Copyright 2015 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt -- | Type descriptions of the 'Val'. -- This is in its own module so " Derive . Deriver . " can import it without importing " Derive . " . module Derive.ValType where import qualified Data.Text as Text import qualified Util.Texts as Texts import Derive.DeriveT (Val(..)) import qualified Derive.ScoreT as ScoreT import qualified Ui.Id as Id import Global data Type = TNum NumType NumValue | TAttributes | TControlRef | TPControlRef | TPitch | TNotePitch -- | Text string, with enum values if it's an enum. | TStr (Maybe [Text]) | TControl | TPControl | TNotGiven | TSeparator | TMaybe Type | TEither Type Type -- | This is the \"any\" type. | TVal | Two types in sequence . This has no corresponding instance since it does n't correspond to a single Val , but is used by " Derive . Sig " -- for documentation. | TPair Type Type | A ' VQuoted ' . This has no instance so it should never show -- up as a call argument. | TQuoted | TControlFunction | TList !Type | TDeriver !Text | instances that do n't correspond directly to a Val type -- get this, as a plain description. | TOther !Text deriving (Eq, Ord, Show) -- | These are kind of muddled. This is because they were originally just -- documentation, so the more specific the better, but are also used for -- typechecking in 'Derive.Env.put_val', so the subtype relations need to be respected . But since some are just documentation ( e.g. ) , they should never show up on the LHS of a put_val typecheck . data NumType = TUntyped | TInt | TTranspose | TDefaultDiatonic | TDefaultChromatic | TNoteNumber | TTime | TDefaultReal | TDefaultScore | TRealTime | TScoreTime deriving (Eq, Ord, Show) -- | Numeric subtypes. data NumValue = TAny | > = 0 | TNonNegative | > 0 | TPositive | 0 < = a < = 1 | TNormalized | -1 < = a < = 1 | TNormalizedBipolar deriving (Eq, Ord, Show) | This typechecking already exists in the instances , but all it can do is go from a to a @Typecheck a = > Maybe a@. So I ca n't reuse it -- to check a type against a type, so it has to be duplicated, similar to how -- 'type_of' can't reuse 'to_type'. -- -- The result is I have redundant functions like 'subtypes_of' and 'type_of' -- and 'to_num_type', and a mistake or inconsistency with 'to_type' or 'to_val' -- will cause typechecking to fail in some subtle case. Fortunately there are -- relatively few types and hopefully won't be many more, and it only affects -- 'Derive.Env.put_val'. It could all do with a cleanup. I'm sure there's a -- right way to do this sort of thing. types_match :: Type -> Type -> Bool types_match t1 t2 = case (t1, t2) of (TNum n1 v1, TNum n2 v2) -> num_types_match n1 n2 && num_vals_match v1 v2 (TMaybe t1, TMaybe t2) -> types_match t1 t2 (TPair t1 t2, TPair u1 u2) -> types_match t1 u1 && types_match t2 u2 (TEither t1 u1, TEither t2 u2) -> types_match t1 t2 && types_match u1 u2 (TList t1, TList t2) -> types_match t1 t2 (t1, t2) -> t1 == t2 where num_types_match n1 n2 = n2 `elem` subtypes_of n1 num_vals_match v1 v2 = v1 <= v2 | Nothing if the type of the rhs matches the lhs , otherwise the expected -- type. val_types_match :: Val -> Val -> Maybe Type val_types_match lhs rhs | types_match expected (type_of rhs) = Nothing | otherwise = Just expected where expected = infer_type_of False lhs subtypes_of :: NumType -> [NumType] subtypes_of n | n `elem` [TTime, TDefaultReal, TDefaultScore] = [TTime, TDefaultReal, TDefaultScore, TRealTime, TScoreTime] | n `elem` transpose = transpose | otherwise = [n] where transpose = [TTranspose, TDefaultDiatonic, TDefaultChromatic, TNoteNumber] instance Pretty Type where pretty (TMaybe typ) = "Maybe " <> pretty typ pretty (TEither a b) = pretty a <> " or " <> pretty b pretty (TPair a b) = "(" <> pretty a <> ", " <> pretty b <> ")" pretty (TNum typ val) = append_parens "Num" $ Texts.join2 ", " (pretty typ) (pretty val) pretty (TStr enums) = append_parens "Str" $ maybe "" Text.unwords enums There is no corresponding type for these , so I might as well be -- clear about what they mean. pretty TControl = append_parens "Control" Id.symbol_description pretty TPControl = append_parens "PControl" ("#" <> Id.symbol_description) pretty (TList typ) = "list of " <> pretty typ pretty (TOther text) = text pretty TNotGiven = "_" pretty (TDeriver name) = name <> " deriver" pretty typ = Text.drop 1 (showt typ) append_parens :: Text -> Text -> Text append_parens name desc | Text.null desc = name | otherwise = name <> " (" <> desc <> ")" instance Pretty NumType where pretty t = case t of TUntyped -> "" TInt -> "integral" TTranspose -> "Transposition" TDefaultDiatonic -> "Transposition, default diatonic" TDefaultChromatic -> "Transposition, default chromatic" TTime -> "Time" TDefaultReal -> "Time, default real" TDefaultScore -> "Time, default score" TRealTime -> "RealTime" TScoreTime -> "ScoreTime" TNoteNumber -> "NN" instance Pretty NumValue where pretty t = case t of TAny -> "" TNonNegative -> ">=0" TPositive -> ">0" TNormalized -> "0 <= x <= 1" TNormalizedBipolar -> "-1 <= x <= 1" type_of :: Val -> Type type_of = infer_type_of True infer_type_of :: Bool -- ^ If True, infer the most specific type possible. -- Otherwise, infer a general type. This is because if ' Derive . Env.put_val ' gets a 1 it does n't mean it 's intended to be a -- TPositive. -> Val -> Type infer_type_of specific val = case val of VNum (ScoreT.Typed typ val) -> TNum (to_num_type typ) $ if specific then (if val > 0 then TPositive else if val >= 0 then TNonNegative else TAny) else TAny VAttributes {} -> TAttributes VControlRef {} -> TControlRef VPControlRef {} -> TPControlRef VPitch {} -> TPitch VNotePitch {} -> TNotePitch VStr {} -> TStr Nothing VQuoted {} -> TQuoted VControlFunction {} -> TControlFunction VNotGiven -> TNotGiven VSeparator -> TSeparator VList {} -> TList TVal to_num_type :: ScoreT.Type -> NumType to_num_type typ = case typ of ScoreT.Untyped -> TUntyped ScoreT.Real -> TRealTime ScoreT.Score -> TScoreTime ScoreT.Diatonic -> TTranspose ScoreT.Chromatic -> TTranspose ScoreT.Nn -> TNoteNumber
null
https://raw.githubusercontent.com/elaforge/karya/471a2131f5a68b3b10b1a138e6f9ed1282980a18/Derive/ValType.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt | Type descriptions of the 'Val'. | Text string, with enum values if it's an enum. | This is the \"any\" type. for documentation. up as a call argument. get this, as a plain description. | These are kind of muddled. This is because they were originally just documentation, so the more specific the better, but are also used for typechecking in 'Derive.Env.put_val', so the subtype relations need to be | Numeric subtypes. to check a type against a type, so it has to be duplicated, similar to how 'type_of' can't reuse 'to_type'. The result is I have redundant functions like 'subtypes_of' and 'type_of' and 'to_num_type', and a mistake or inconsistency with 'to_type' or 'to_val' will cause typechecking to fail in some subtle case. Fortunately there are relatively few types and hopefully won't be many more, and it only affects 'Derive.Env.put_val'. It could all do with a cleanup. I'm sure there's a right way to do this sort of thing. type. clear about what they mean. ^ If True, infer the most specific type possible. Otherwise, infer a general type. This is because if TPositive.
Copyright 2015 This is in its own module so " Derive . Deriver . " can import it without importing " Derive . " . module Derive.ValType where import qualified Data.Text as Text import qualified Util.Texts as Texts import Derive.DeriveT (Val(..)) import qualified Derive.ScoreT as ScoreT import qualified Ui.Id as Id import Global data Type = TNum NumType NumValue | TAttributes | TControlRef | TPControlRef | TPitch | TNotePitch | TStr (Maybe [Text]) | TControl | TPControl | TNotGiven | TSeparator | TMaybe Type | TEither Type Type | TVal | Two types in sequence . This has no corresponding instance since it does n't correspond to a single Val , but is used by " Derive . Sig " | TPair Type Type | A ' VQuoted ' . This has no instance so it should never show | TQuoted | TControlFunction | TList !Type | TDeriver !Text | instances that do n't correspond directly to a Val type | TOther !Text deriving (Eq, Ord, Show) respected . But since some are just documentation ( e.g. ) , they should never show up on the LHS of a put_val typecheck . data NumType = TUntyped | TInt | TTranspose | TDefaultDiatonic | TDefaultChromatic | TNoteNumber | TTime | TDefaultReal | TDefaultScore | TRealTime | TScoreTime deriving (Eq, Ord, Show) data NumValue = TAny | > = 0 | TNonNegative | > 0 | TPositive | 0 < = a < = 1 | TNormalized | -1 < = a < = 1 | TNormalizedBipolar deriving (Eq, Ord, Show) | This typechecking already exists in the instances , but all it can do is go from a to a @Typecheck a = > Maybe a@. So I ca n't reuse it types_match :: Type -> Type -> Bool types_match t1 t2 = case (t1, t2) of (TNum n1 v1, TNum n2 v2) -> num_types_match n1 n2 && num_vals_match v1 v2 (TMaybe t1, TMaybe t2) -> types_match t1 t2 (TPair t1 t2, TPair u1 u2) -> types_match t1 u1 && types_match t2 u2 (TEither t1 u1, TEither t2 u2) -> types_match t1 t2 && types_match u1 u2 (TList t1, TList t2) -> types_match t1 t2 (t1, t2) -> t1 == t2 where num_types_match n1 n2 = n2 `elem` subtypes_of n1 num_vals_match v1 v2 = v1 <= v2 | Nothing if the type of the rhs matches the lhs , otherwise the expected val_types_match :: Val -> Val -> Maybe Type val_types_match lhs rhs | types_match expected (type_of rhs) = Nothing | otherwise = Just expected where expected = infer_type_of False lhs subtypes_of :: NumType -> [NumType] subtypes_of n | n `elem` [TTime, TDefaultReal, TDefaultScore] = [TTime, TDefaultReal, TDefaultScore, TRealTime, TScoreTime] | n `elem` transpose = transpose | otherwise = [n] where transpose = [TTranspose, TDefaultDiatonic, TDefaultChromatic, TNoteNumber] instance Pretty Type where pretty (TMaybe typ) = "Maybe " <> pretty typ pretty (TEither a b) = pretty a <> " or " <> pretty b pretty (TPair a b) = "(" <> pretty a <> ", " <> pretty b <> ")" pretty (TNum typ val) = append_parens "Num" $ Texts.join2 ", " (pretty typ) (pretty val) pretty (TStr enums) = append_parens "Str" $ maybe "" Text.unwords enums There is no corresponding type for these , so I might as well be pretty TControl = append_parens "Control" Id.symbol_description pretty TPControl = append_parens "PControl" ("#" <> Id.symbol_description) pretty (TList typ) = "list of " <> pretty typ pretty (TOther text) = text pretty TNotGiven = "_" pretty (TDeriver name) = name <> " deriver" pretty typ = Text.drop 1 (showt typ) append_parens :: Text -> Text -> Text append_parens name desc | Text.null desc = name | otherwise = name <> " (" <> desc <> ")" instance Pretty NumType where pretty t = case t of TUntyped -> "" TInt -> "integral" TTranspose -> "Transposition" TDefaultDiatonic -> "Transposition, default diatonic" TDefaultChromatic -> "Transposition, default chromatic" TTime -> "Time" TDefaultReal -> "Time, default real" TDefaultScore -> "Time, default score" TRealTime -> "RealTime" TScoreTime -> "ScoreTime" TNoteNumber -> "NN" instance Pretty NumValue where pretty t = case t of TAny -> "" TNonNegative -> ">=0" TPositive -> ">0" TNormalized -> "0 <= x <= 1" TNormalizedBipolar -> "-1 <= x <= 1" type_of :: Val -> Type type_of = infer_type_of True ' Derive . Env.put_val ' gets a 1 it does n't mean it 's intended to be a -> Val -> Type infer_type_of specific val = case val of VNum (ScoreT.Typed typ val) -> TNum (to_num_type typ) $ if specific then (if val > 0 then TPositive else if val >= 0 then TNonNegative else TAny) else TAny VAttributes {} -> TAttributes VControlRef {} -> TControlRef VPControlRef {} -> TPControlRef VPitch {} -> TPitch VNotePitch {} -> TNotePitch VStr {} -> TStr Nothing VQuoted {} -> TQuoted VControlFunction {} -> TControlFunction VNotGiven -> TNotGiven VSeparator -> TSeparator VList {} -> TList TVal to_num_type :: ScoreT.Type -> NumType to_num_type typ = case typ of ScoreT.Untyped -> TUntyped ScoreT.Real -> TRealTime ScoreT.Score -> TScoreTime ScoreT.Diatonic -> TTranspose ScoreT.Chromatic -> TTranspose ScoreT.Nn -> TNoteNumber
9a243987809646cf507359cb5dfd12dd68b48197ae43f8d632bfb494932c3142
cfcs/mirage-framebuffer
framebuffer__S.ml
module Keycodes = Framebuffer__Keycodes type backend_event = | Clipboard_paste of string (** When the user pastes [string] in the window*) | Clipboard_request (** When the backend requests our window's clipboard *) | Keypress of { pressed : bool ; (** pressed (true) || released (false) *) scancode : int ; (** The scancode exposed by the backend *) mask : int ; (** The modifier mask exposed by the backend *) mods : Keycodes.kmod list ; (** The parsed modifier mask *) keysym : Keycodes.keysym option ; (** The parsed keysym *) }(** When a keyboard key is pressed or released *) | Mouse_button of { x : int; y : int} * When a mouse button is pressed or released . y = 0 at the top . TODO Need to expose which button , and the state ( pressed / released ) etc TODO Need to expose which button, and the state (pressed/released) etc*) | Mouse_motion of { x: int ; y : int} (** When the mouse is moved (not necessarily within window) *) | Window_close | Window_focus (* | Window_focus *) | Resize of int * int module type Backend_S = sig type backend type color type line type 'a ret type init_handle module Compile : sig val rgb : ?r:char -> ?g:char -> ?b:char -> backend -> color val line : color list -> backend -> line val lineiter : (int -> color) -> int -> backend ->line end val init_backend : init_handle -> unit Lwt.t val window : init_handle -> width:int -> height:int -> backend Lwt.t val resize : width:int -> height:int -> backend -> unit Lwt.t val recv_event : backend -> backend_event Lwt.t val redraw : backend -> unit Lwt.t val set_title : backend -> string -> unit ret val pixel : backend -> x:int -> y:int -> color -> unit val horizontal : backend -> x:int -> y:int -> x_end:int -> color -> unit val draw_line : backend -> x:int -> y:int -> line -> unit val rect : backend -> x:int -> y:int -> x_end:int -> y_end:int -> color -> unit val rect_lineiter : backend -> x:int -> y:int -> y_end:int -> (int -> line) -> unit val keysym_of_scancode : int -> Framebuffer__Keycodes.keysym option val kmod_of_constant : int -> Framebuffer__Keycodes.kmod end type uchar = int module type Framebuffer_S = sig type color type line type t val compile_rgb : ?r:char -> ?g:char -> ?b:char -> t -> color val compile_line : color list -> t -> line val redraw : t -> unit Lwt.t val letter : t -> uchar -> x:int -> y:int -> unit val letters : t -> string -> x:int -> y:int -> unit val output_tty : t -> int * int -> string -> unit Lwt.t val pixel : t -> x:int -> y:int -> color -> unit val line_bresenham : ?cb:(t -> x:int -> y:int -> color -> unit) -> t -> x:int -> y:int -> x_end:int -> y_end:int -> color -> unit val line_bresenham_antialias : t -> x:int -> y:int -> x_end:int -> y_end:int -> int -> color -> unit val rect : t -> x:int -> y:int -> x_end:int -> y_end:int -> color -> unit val rect_lineiter : t -> x:int -> y:int -> y_end:int -> (int -> line) -> unit val dim : t -> int * int (** [dim t] returns the (width,height) dimensions of the window. *) val term_size : t -> int * int (** [term_size t] returns the (width,height) dimensions currently available for a text console using the builtin font *) val window : width:int -> height:int -> t Lwt.t * [ window ~width ~height ] opens a new window [ t ] val resize : width:int -> height:int -> t -> unit Lwt.t * [ resize ~width ~height t ] attempts to resize the window [ t ] TODO error handling ? TODO error handling? *) val recv_event : t -> backend_event Lwt.t val keysym_of_scancode : int -> Keycodes.keysym option val kmod_of_constant : int -> Keycodes.kmod end module type Framebuffer_M = functor (B : Backend_S) -> sig val init : B.init_handle -> (module Framebuffer_S) Lwt.t end
null
https://raw.githubusercontent.com/cfcs/mirage-framebuffer/f63d54dd86f4ab723cc471fbf127d5fc105aa656/lib/framebuffer__S.ml
ocaml
* When the user pastes [string] in the window * When the backend requests our window's clipboard * pressed (true) || released (false) * The scancode exposed by the backend * The modifier mask exposed by the backend * The parsed modifier mask * The parsed keysym * When a keyboard key is pressed or released * When the mouse is moved (not necessarily within window) | Window_focus * [dim t] returns the (width,height) dimensions of the window. * [term_size t] returns the (width,height) dimensions currently available for a text console using the builtin font
module Keycodes = Framebuffer__Keycodes type backend_event = | Mouse_button of { x : int; y : int} * When a mouse button is pressed or released . y = 0 at the top . TODO Need to expose which button , and the state ( pressed / released ) etc TODO Need to expose which button, and the state (pressed/released) etc*) | Mouse_motion of { x: int ; y : int} | Window_close | Window_focus | Resize of int * int module type Backend_S = sig type backend type color type line type 'a ret type init_handle module Compile : sig val rgb : ?r:char -> ?g:char -> ?b:char -> backend -> color val line : color list -> backend -> line val lineiter : (int -> color) -> int -> backend ->line end val init_backend : init_handle -> unit Lwt.t val window : init_handle -> width:int -> height:int -> backend Lwt.t val resize : width:int -> height:int -> backend -> unit Lwt.t val recv_event : backend -> backend_event Lwt.t val redraw : backend -> unit Lwt.t val set_title : backend -> string -> unit ret val pixel : backend -> x:int -> y:int -> color -> unit val horizontal : backend -> x:int -> y:int -> x_end:int -> color -> unit val draw_line : backend -> x:int -> y:int -> line -> unit val rect : backend -> x:int -> y:int -> x_end:int -> y_end:int -> color -> unit val rect_lineiter : backend -> x:int -> y:int -> y_end:int -> (int -> line) -> unit val keysym_of_scancode : int -> Framebuffer__Keycodes.keysym option val kmod_of_constant : int -> Framebuffer__Keycodes.kmod end type uchar = int module type Framebuffer_S = sig type color type line type t val compile_rgb : ?r:char -> ?g:char -> ?b:char -> t -> color val compile_line : color list -> t -> line val redraw : t -> unit Lwt.t val letter : t -> uchar -> x:int -> y:int -> unit val letters : t -> string -> x:int -> y:int -> unit val output_tty : t -> int * int -> string -> unit Lwt.t val pixel : t -> x:int -> y:int -> color -> unit val line_bresenham : ?cb:(t -> x:int -> y:int -> color -> unit) -> t -> x:int -> y:int -> x_end:int -> y_end:int -> color -> unit val line_bresenham_antialias : t -> x:int -> y:int -> x_end:int -> y_end:int -> int -> color -> unit val rect : t -> x:int -> y:int -> x_end:int -> y_end:int -> color -> unit val rect_lineiter : t -> x:int -> y:int -> y_end:int -> (int -> line) -> unit val dim : t -> int * int val term_size : t -> int * int val window : width:int -> height:int -> t Lwt.t * [ window ~width ~height ] opens a new window [ t ] val resize : width:int -> height:int -> t -> unit Lwt.t * [ resize ~width ~height t ] attempts to resize the window [ t ] TODO error handling ? TODO error handling? *) val recv_event : t -> backend_event Lwt.t val keysym_of_scancode : int -> Keycodes.keysym option val kmod_of_constant : int -> Keycodes.kmod end module type Framebuffer_M = functor (B : Backend_S) -> sig val init : B.init_handle -> (module Framebuffer_S) Lwt.t end
0e613f19bff24614ba03502ceed9987a7eb278864193bbaeceec93013c4c4ffd
juxt/reap
rfc4647.clj
Copyright © 2020 , JUXT LTD . (ns juxt.reap.alpha.decoders.rfc4647 (:require [juxt.reap.alpha.regex :as re] [juxt.reap.alpha.combinators :as p] [juxt.reap.alpha.decoders.rfc5234 :as rfc5234 :refer [ALPHA DIGIT]])) ;; alphanum = ALPHA / DIGIT (def alphanum (rfc5234/merge-alternatives ALPHA DIGIT)) language - range = ( 1 * 8ALPHA * ( " - " 1 * ) ) / " * " (defn language-range [_] (p/alternatives (p/pattern-parser (re-pattern (re/re-compose "[%s]{1,8}(?:\\-[%s]{1,8})*" ALPHA alphanum))) (p/pattern-parser #"\*")))
null
https://raw.githubusercontent.com/juxt/reap/29ffc8664df26041ebd93a53f009d2606d1a5b6c/src/juxt/reap/alpha/decoders/rfc4647.clj
clojure
alphanum = ALPHA / DIGIT
Copyright © 2020 , JUXT LTD . (ns juxt.reap.alpha.decoders.rfc4647 (:require [juxt.reap.alpha.regex :as re] [juxt.reap.alpha.combinators :as p] [juxt.reap.alpha.decoders.rfc5234 :as rfc5234 :refer [ALPHA DIGIT]])) (def alphanum (rfc5234/merge-alternatives ALPHA DIGIT)) language - range = ( 1 * 8ALPHA * ( " - " 1 * ) ) / " * " (defn language-range [_] (p/alternatives (p/pattern-parser (re-pattern (re/re-compose "[%s]{1,8}(?:\\-[%s]{1,8})*" ALPHA alphanum))) (p/pattern-parser #"\*")))
b0f1bf44bb70d62b1056ffc895973a3e60fce5dffb6d20cd89f56b01af0ab3f3
metosin/sormilla
swing.clj
(ns sormilla.swing (:require [clojure.java.io :as io] [sormilla.world :refer [world]]) (:import [java.awt Graphics2D Shape Color KeyboardFocusManager KeyEventDispatcher Toolkit] [java.awt.geom Path2D$Double Ellipse2D$Double] [java.awt.event KeyEvent])) (set! *warn-on-reflection* true) (defn ->shape ^Shape [& [x y & points]] (let [p (Path2D$Double.)] (.moveTo p x y) (doseq [[x y] (partition 2 points)] (.lineTo p x y)) p)) (defn draw-circle [^Graphics2D g x y r] (let [x1 (- x r) y1 (- y r) d (* 2 r)] (.draw g (Ellipse2D$Double. x1 y1 d d)))) (defmacro with-transforms [^Graphics2D g & body] `(let [a# (.getTransform ~g)] (do ~@body) (.setTransform ~g a#))) ;; ;; Keys ;; (doseq [[key-code key-name] (partition 2 [37 :left 38 :up 39 :right 40 :down 27 :esc 32 :space 10 :enter])] (intern *ns* (symbol (str "key-" (name key-name))) key-code)) (def key-types {KeyEvent/KEY_TYPED :typed KeyEvent/KEY_PRESSED :pressed KeyEvent/KEY_RELEASED :released}) (defn ->key-event [^KeyEvent e] {:type (key-types (.getID e)) :ch (.getKeyChar e) :code (.getKeyCode e) :action (.isActionKey e) :shift (.isShiftDown e) :ctrl (.isControlDown e) :meta (.isMetaDown e) :alt (.isAltDown e)}) (def key-listeners (atom {})) (defonce key-event-dispatcher (let [d (proxy [KeyEventDispatcher] [] (dispatchKeyEvent [e] (let [e (->key-event e)] (doseq [f (remove nil? (map (fn [[k v]] (when (= (select-keys e (keys k)) k) v)) @key-listeners))] (f e))) true))] (.addKeyEventDispatcher (KeyboardFocusManager/getCurrentKeyboardFocusManager) d) d)) (defn add-key-listener! [event listener] (swap! key-listeners assoc event listener)) (defn remove-key-listener! [event] (swap! key-listeners dissoc event)) (doseq [[code key-name] (partition 2 [key-left :left key-right :right key-up :up key-down :down])] (add-key-listener! {:type :pressed :code code} (fn [_] (swap! world assoc-in [:keys key-name] true))) (add-key-listener! {:type :released :code code} (fn [_] (swap! world assoc-in [:keys key-name] false))))
null
https://raw.githubusercontent.com/metosin/sormilla/e50930930c41f64272f06c4bd02a4e3ab58e923f/src/sormilla/swing.clj
clojure
Keys
(ns sormilla.swing (:require [clojure.java.io :as io] [sormilla.world :refer [world]]) (:import [java.awt Graphics2D Shape Color KeyboardFocusManager KeyEventDispatcher Toolkit] [java.awt.geom Path2D$Double Ellipse2D$Double] [java.awt.event KeyEvent])) (set! *warn-on-reflection* true) (defn ->shape ^Shape [& [x y & points]] (let [p (Path2D$Double.)] (.moveTo p x y) (doseq [[x y] (partition 2 points)] (.lineTo p x y)) p)) (defn draw-circle [^Graphics2D g x y r] (let [x1 (- x r) y1 (- y r) d (* 2 r)] (.draw g (Ellipse2D$Double. x1 y1 d d)))) (defmacro with-transforms [^Graphics2D g & body] `(let [a# (.getTransform ~g)] (do ~@body) (.setTransform ~g a#))) (doseq [[key-code key-name] (partition 2 [37 :left 38 :up 39 :right 40 :down 27 :esc 32 :space 10 :enter])] (intern *ns* (symbol (str "key-" (name key-name))) key-code)) (def key-types {KeyEvent/KEY_TYPED :typed KeyEvent/KEY_PRESSED :pressed KeyEvent/KEY_RELEASED :released}) (defn ->key-event [^KeyEvent e] {:type (key-types (.getID e)) :ch (.getKeyChar e) :code (.getKeyCode e) :action (.isActionKey e) :shift (.isShiftDown e) :ctrl (.isControlDown e) :meta (.isMetaDown e) :alt (.isAltDown e)}) (def key-listeners (atom {})) (defonce key-event-dispatcher (let [d (proxy [KeyEventDispatcher] [] (dispatchKeyEvent [e] (let [e (->key-event e)] (doseq [f (remove nil? (map (fn [[k v]] (when (= (select-keys e (keys k)) k) v)) @key-listeners))] (f e))) true))] (.addKeyEventDispatcher (KeyboardFocusManager/getCurrentKeyboardFocusManager) d) d)) (defn add-key-listener! [event listener] (swap! key-listeners assoc event listener)) (defn remove-key-listener! [event] (swap! key-listeners dissoc event)) (doseq [[code key-name] (partition 2 [key-left :left key-right :right key-up :up key-down :down])] (add-key-listener! {:type :pressed :code code} (fn [_] (swap! world assoc-in [:keys key-name] true))) (add-key-listener! {:type :released :code code} (fn [_] (swap! world assoc-in [:keys key-name] false))))
761ff098c0c3871349fa8cc1d3c6c0940de1cd87e05dd7e15f565a28143b868b
josephwilk/musical-creativity
midnight.clj
(ns data.midnight (:require [midi-mash.core :refer :all])) (def midnight (map (fn [event] [(:time event) (:pitch event) (:velocity event) (:channel event) (:instrument event)]) (csv->events "data/midnight.csv"))) (def midnight-raw (csv->events "data/midnight.csv"))
null
https://raw.githubusercontent.com/josephwilk/musical-creativity/c2e6aab2a26d69ee2e51f4fad84fa3a71805e6ca/src/data/midnight.clj
clojure
(ns data.midnight (:require [midi-mash.core :refer :all])) (def midnight (map (fn [event] [(:time event) (:pitch event) (:velocity event) (:channel event) (:instrument event)]) (csv->events "data/midnight.csv"))) (def midnight-raw (csv->events "data/midnight.csv"))
59b63a9e7091040a5c5f403ad8728f00ccc7d694010cce592644d9357590b705
rd--/hsc3
Composite.hs
-- | Common unit generator graphs. module Sound.Sc3.Ugen.Bindings.Composite where import Data.List {- base -} import Data.Maybe {- base -} import Sound.Sc3.Common.Enum import Sound.Sc3.Common.Envelope import Sound.Sc3.Common.Math import Sound.Sc3.Common.Math.Filter.Beq import Sound.Sc3.Common.Math.Operator import Sound.Sc3.Common.Rate import Sound.Sc3.Common.Uid import Sound.Sc3.Common.Unsafe import Sound.Sc3.Ugen.Bindings.Db import Sound.Sc3.Ugen.Bindings.Hw import Sound.Sc3.Ugen.Math import Sound.Sc3.Ugen.Mce import Sound.Sc3.Ugen.Types import Sound.Sc3.Ugen.Util -- | Generate a localBuf and use setBuf to initialise it. asLocalBufId :: ID i => i -> [Ugen] -> Ugen asLocalBufId z xs = let b = localBufId z 1 (fromIntegral (length xs)) s = setBuf' b xs 0 in mrg2 b s asLocalBufM :: Uid m => [Ugen] -> m Ugen asLocalBufM = liftUid1 asLocalBufId asLocalBuf :: [Ugen] -> Ugen asLocalBuf = liftUnsafe1 asLocalBufM | balance2 with Mce input . balanceStereo :: Ugen -> Ugen -> Ugen -> Ugen balanceStereo sig pos level = let (x,y) = unmce2 sig in balance2 x y pos level | 24db / oct rolloff - 4th order resonant Low Pass Filter bLowPass4 :: Ugen -> Ugen -> Ugen -> Ugen bLowPass4 i f rq = let (a0, a1, a2, b1, b2) = bLowPassCoef sampleRate f rq flt z = sos z a0 a1 a2 b1 b2 in flt (flt i) | 24db / oct rolloff - 4th order resonant Hi Pass Filter bHiPass4 :: Ugen -> Ugen -> Ugen -> Ugen bHiPass4 i f rq = let (a0, a1, a2, b1, b2) = bHiPassCoef sampleRate f rq flt z = sos z a0 a1 a2 b1 b2 in flt (flt i) -- | Buffer reader (no interpolation). bufRdN :: Int -> Rate -> Ugen -> Ugen -> Loop Ugen -> Ugen bufRdN n r b p l = bufRd n r b p l NoInterpolation -- | Buffer reader (linear interpolation). bufRdL :: Int -> Rate -> Ugen -> Ugen -> Loop Ugen -> Ugen bufRdL n r b p l = bufRd n r b p l LinearInterpolation -- | Buffer reader (cubic interpolation). bufRdC :: Int -> Rate -> Ugen -> Ugen -> Loop Ugen -> Ugen bufRdC n r b p l = bufRd n r b p l CubicInterpolation -- | Triggers when a value changes changed :: Ugen -> Ugen -> Ugen changed input threshold = abs (hpz1 input) `greater_than` threshold | ' mce ' variant of ' lchoose ' . chooseId :: ID m => m -> Ugen -> Ugen chooseId z = lchooseId z . mceChannels -- | 'liftUid' of 'choose'. chooseM :: Uid m => Ugen -> m Ugen chooseM = liftUid1 chooseId choose :: Ugen -> Ugen choose = liftUnsafe1 chooseM -- | 'clearBuf' of 'localBuf'. clearLocalBufId :: ID a => a -> Ugen -> Ugen -> Ugen clearLocalBufId z nc nf = clearBuf (localBufId z nc nf) clearLocalBufM :: Uid m => Ugen -> Ugen -> m Ugen clearLocalBufM = liftUid2 clearLocalBufId clearLocalBuf :: Ugen -> Ugen -> Ugen clearLocalBuf = liftUnsafe2 clearLocalBufM -- | Demand rate (:) function. dconsId :: ID m => (m,m,m) -> Ugen -> Ugen -> Ugen dconsId (z0,z1,z2) x xs = let i = dseqId z0 1 (mce2 0 1) a = dseqId z1 1 (mce2 x xs) in dswitchId z2 i a -- | Demand rate (:) function. dconsM :: (Uid m) => Ugen -> Ugen -> m Ugen dconsM x xs = do i <- dseqM 1 (mce2 0 1) a <- dseqM 1 (mce2 x xs) dswitchM i a dcons :: Ugen -> Ugen -> Ugen dcons = liftUnsafe2 dconsM -- | Dynamic klang, dynamic sine oscillator bank dynKlang :: Rate -> Ugen -> Ugen -> Ugen -> Ugen dynKlang r fs fo s = let gen (f:a:ph:xs) = sinOsc r (f * fs + fo) ph * a + gen xs gen _ = 0 in gen (mceChannels s) -- | Dynamic klank, set of non-fixed resonating filters. dynKlank :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen dynKlank i fs fo ds s = let gen (f:a:d:xs) = ringz i (f * fs + fo) (d * ds) * a + gen xs gen _ = 0 in gen (mceChannels s) -- | Pan2 without (k-rate only) level input eqPan2 :: Ugen -> Ugen -> Ugen eqPan2 input pos = pan2 input pos 1 -- | 'linExp' with input range of (-1,1). exprange :: Ugen -> Ugen -> Ugen -> Ugen exprange l r s = linExp s (-1) 1 l r -- | Variant of `exprange` with arguments to make writing post-fix nicer. in_exprange :: Ugen -> (Ugen, Ugen) -> Ugen in_exprange s (l,r) = exprange l r s | Variant FFT constructor with default values for hop size ( 0.5 ) , window type ( 0 ) , active status ( 1 ) and window size ( 0 ) . fft' :: Ugen -> Ugen -> Ugen fft' buf i = fft buf i 0.5 0 1 0 -- | 'fft' variant that allocates 'localBuf'. -- > let c = ffta ' α ' 2048 ( soundIn 0 ) 0.5 0 1 0 -- > in audition (out 0 (ifft c 0 0)) fftAllocId :: ID i => i -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen fftAllocId z nf i h wt a ws = let b = localBufId z 1 nf in fft b i h wt a ws fftAllocM :: Uid m => Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> m Ugen fftAllocM = liftUid6 fftAllocId fftAlloc :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen fftAlloc = liftUnsafe6 fftAllocM -- | Sum of 'numInputBuses' and 'numOutputBuses'. firstPrivateBus :: Ugen firstPrivateBus = numInputBuses + numOutputBuses -- | Frequency shifter, in terms of 'hilbert' (see also 'freqShift'). freqShift_hilbert :: Ugen -> Ugen -> Ugen -> Ugen freqShift_hilbert i f p = let o = sinOsc ar f (mce [p + 0.5 * pi, p]) h = hilbert i in mix (h * o) | Ugen function to re - trigger an EnvGen envelope . Inputs are /gate/ ( as set at EnvGen ) and /reset/. The four state logic is : ( 1,0)->1 ( 1,1)->-1 ( 0,1)->0 ( 0,0)->0 . If the gate input to EnvGen.kr is -1 the envelope ramps to zero in one control period . The reset input sequence 0,1,0 when the gate is open produces ( 1,-1,1 ) , which resets the envelope . > map ( uncurry gateReset ) [ ( 1,0),(1,1),(0,1),(0,0 ) ] = = [ 1,-1,0,0 ] Inputs are /gate/ (as set at EnvGen) and /reset/. The four state logic is: (1,0)->1 (1,1)->-1 (0,1)->0 (0,0)->0. If the gate input to EnvGen.kr is -1 the envelope ramps to zero in one control period. The reset input sequence 0,1,0 when the gate is open produces (1,-1,1), which resets the envelope. > map (uncurry gateReset) [(1,0),(1,1),(0,1),(0,0)] == [1,-1,0,0] -} gateReset :: Num a => a -> a -> a gateReset gt tr = gt - (gt * tr * 2) | Variant of ' hilbert ' using FFT ( with a delay ) for better results . Buffer should be 2048 or 1024 . 2048 = better results , more delay . -- 1024 = less delay, little choppier results. hilbertFIR :: Ugen -> Ugen -> Ugen hilbertFIR s b = let c0 = fft' b s c1 = pv_PhaseShift90 c0 delay = bufDur kr b in mce2 (delayN s delay delay) (ifft' c1) -- | Variant ifft with default value for window type. ifft' :: Ugen -> Ugen ifft' buf = ifft buf 0 0 -- | Linear interpolating variant on index . indexL : : Ugen - > Ugen - > Ugen indexL b i = let x = index b i y = index b ( i + 1 ) in linLin ( frac i ) 0 1 x y -- | Linear interpolating variant on index. indexL :: Ugen -> Ugen -> Ugen indexL b i = let x = index b i y = index b (i + 1) in linLin (frac i) 0 1 x y -} | Generalised Klan(k / g ) specification rule . /f/ unwraps inputs , /g/ wraps output . -- > let r = [ 220,0.2,0,219,0.1,1,221,0.1,2 ] > in i d i d [ 220,219,221 ] [ 0.2,0.1,0.1 ] [ 0,1,2 ] = = r klanx_spec_f :: (a -> [b]) -> ([b] -> c) -> a -> a -> a -> c klanx_spec_f f g fr am z = g ((concat . transpose) [f fr,f am,f z]) | Format frequency , amplitude and decay time data as required for klank . klangSpec :: [Ugen] -> [Ugen] -> [Ugen] -> Ugen klangSpec = klanx_spec_f id mce | Variant of ' klangSpec ' for non - Ugen inputs . klangSpec_k :: Real n => [n] -> [n] -> [n] -> Ugen klangSpec_k = klanx_spec_f (map constant) mce -- | Variant of 'klangSpec' for 'Mce' inputs. klangSpec_mce :: Ugen -> Ugen -> Ugen -> Ugen klangSpec_mce = klanx_spec_f mceChannels mce | Format frequency , amplitude and decay time data as required for klank . klankSpec :: [Ugen] -> [Ugen] -> [Ugen] -> Ugen klankSpec = klanx_spec_f id mce | Variant for non - Ugen inputs . klankSpec_k :: Real n => [n] -> [n] -> [n] -> Ugen klankSpec_k = klanx_spec_f (map constant) mce -- | Variant of 'klankSpec' for 'Mce' inputs. klankSpec_mce :: Ugen -> Ugen -> Ugen -> Ugen klankSpec_mce = klanx_spec_f mceChannels mce | Randomly select one of a list of ( initialisation rate ) . lchooseId :: ID m => m -> [Ugen] -> Ugen lchooseId z a = select (iRandId z 0 (fromIntegral (length a))) (mce a) -- | 'liftUid' of 'lchoose'. lchooseM :: Uid m => [Ugen] -> m Ugen lchooseM = liftUid1 lchooseId lchoose :: [Ugen] -> Ugen lchoose = liftUnsafe1 lchooseM -- | 'linExp' of (-1,1). linExp_b :: Ugen -> Ugen -> Ugen -> Ugen linExp_b i = linExp i (-1) 1 | ' linExp ' of ( 0,1 ) . linExp_u :: Ugen -> Ugen -> Ugen -> Ugen linExp_u i = linExp i 0 1 | Map from one linear range to another linear range . linLin :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen linLin = linlin_ma mulAdd | ' linLin ' where source is ( 0,1 ) . linLin_u :: Ugen -> Ugen -> Ugen -> Ugen linLin_u i = linLin i 0 1 -- | 'linLin' where source is (-1,1). linLin_b :: Ugen -> Ugen -> Ugen -> Ugen linLin_b i = linLin i (-1) 1 | Variant with defaults of zero . localIn' :: Int -> Rate -> Ugen localIn' nc r = localIn nc r (mce (replicate nc 0)) | Generate an ' envGen ' Ugen with @fadeTime@ and @gate@ controls . -- > import Sound . Sc3 > audition ( out 0 ( makeFadeEnv 1 * sinOsc ar 440 0 * 0.1 ) ) -- > withSc3 (send (n_set1 (-1) "gate" 0)) makeFadeEnv :: Double -> Ugen makeFadeEnv fadeTime = let dt = control kr "fadeTime" (realToFrac fadeTime) gate_ = control kr "gate" 1 startVal = dt `less_than_or_equal_to` 0 env = Envelope [startVal,1,0] [1,1] [EnvLin,EnvLin] (Just 1) Nothing 0 in envGen kr gate_ 1 0 dt RemoveSynth env -- | Variant that is randomly pressed. mouseButtonRand :: Rate -> Ugen -> Ugen -> Ugen -> Ugen mouseButtonRand rt l r tm = let o = lfClipNoiseId 'z' rt 1 in lag (linLin o (-1) 1 l r) tm | Randomised mouse Ugen ( see also ' mouseX '' and ' mouseY '' ) . mouseRandId :: ID a => a -> Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseRandId z rt l r ty tm = let f = case ty of Linear -> linLin Exponential -> linExp _ -> undefined in lag (f (lfNoise1Id z rt 1) (-1) 1 l r) tm mouseRandM :: Uid m => Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> m Ugen mouseRandM = liftUid5 mouseRandId mouseRand :: Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseRand = liftUnsafe5 mouseRandM -- | Variant that randomly traverses the mouseX space. mouseXRand :: Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseXRand = mouseRandId 'x' -- | Variant that randomly traverses the mouseY space. mouseYRand :: Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseYRand = mouseRandId 'y' | Translate onset type string to constant Ugen value . onsetType :: Num a => String -> a onsetType s = let t = ["power", "magsum", "complex", "rcomplex", "phase", "wphase", "mkl"] in fromIntegral (fromMaybe 3 (elemIndex s t)) -- | Onset detector with default values for minor parameters. onsetsDefault :: Ugen -> Ugen -> Ugen -> Ugen onsetsDefault c t o = onsets c t o 1 0.1 10 11 1 0 -- | Format magnitude and phase data data as required for packFFT. packFFTSpec :: [Ugen] -> [Ugen] -> Ugen packFFTSpec m p = let interleave x = concat . zipWith (\a b -> [a,b]) x in mce (interleave m p) | Calculate size of accumulation buffer given FFT and IR sizes . partConv_calcAccumSize :: Int -> Int -> Int partConv_calcAccumSize fft_size ir_length = let partition_size = fft_size `div` 2 num_partitions = (ir_length `div` partition_size) + 1 in fft_size * num_partitions -- | PM oscillator. cf = carrier frequency , mf = modulation frequency , pm = pm - index = 0.0 , mp = mod - phase = 0.0 pmOsc :: Rate -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen pmOsc r cf mf pm mp = sinOsc r cf (sinOsc r mf mp * pm) | Variant of ' poll ' that generates an ' mrg ' value with the input -- signal at left, and that allows a constant /frequency/ input in -- place of a trigger. pollExt :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen pollExt optTrig in_ label_ trigId = let tr = if isConstant optTrig then impulse kr optTrig 0 else optTrig in mrg [in_,poll tr in_ label_ trigId] | Variant of ' in '' offset so zero if the first private bus . privateIn :: Int -> Rate -> Ugen -> Ugen privateIn nc rt k = in' nc rt (k + firstPrivateBus) | Variant of ' out ' offset so zero if the first private bus . privateOut :: Ugen -> Ugen -> Ugen privateOut k = out (k + firstPrivateBus) -- | Apply function /f/ to each bin of an @FFT@ chain, /f/ receives -- magnitude, phase and index and returns a (magnitude,phase). pvcollect :: Ugen -> Int -> (Ugen -> Ugen -> Int -> (Ugen, Ugen)) -> Int -> Int -> Ugen -> Ugen pvcollect c nf f from to z = let m = unpackFFT c nf from to 0 p = unpackFFT c nf from to 1 i = [from .. to] e = zipWith3 f m p i mp = uncurry packFFTSpec (unzip e) in packFFT c nf from to z mp | /dur/ and /hop/ are in seconds , /frameSize/ and /sampleRate/ in -- frames, though the latter maybe fractional. -- > pv_calcPVRecSize 4.2832879818594 1024 0.25 48000.0 = = 823299 pv_calcPVRecSize :: Double -> Int -> Double -> Double -> Int pv_calcPVRecSize dur frame_size hop sample_rate = let frame_size' = fromIntegral frame_size raw_size = ceiling ((dur * sample_rate) / frame_size') * frame_size in ceiling (fromIntegral raw_size * recip hop + 3) | ' rand ' with left edge set to zero . rand0Id :: ID a => a -> Ugen -> Ugen rand0Id z = randId z 0 | ' Uid ' form of ' ' . rand0M :: Uid m => Ugen -> m Ugen rand0M = randM 0 rand0 :: Ugen -> Ugen rand0 = liftUnsafe1 rand0M | ' rand ' with left edge set to negative /n/. Note rand2 is also a UnaryOp Ugen , however hsc3 does not store Ids for operators . Note rand2 is also a UnaryOp Ugen, however hsc3 does not store Ids for operators. -} rand2Id :: ID a => a -> Ugen -> Ugen rand2Id z n = randId z (negate n) n -- | 'Uid' form of 'rand2'. rand2M :: Uid m => Ugen -> m Ugen rand2M n = randM (negate n) n rand2 :: Ugen -> Ugen rand2 = liftUnsafe1 rand2M | with Mce input . rotateStereo :: Ugen -> Ugen -> Ugen rotateStereo sig pos = let (x,y) = unmce2 sig in rotate2 x y pos -- | RMS variant of 'runningSum'. runningSumRMS :: Ugen -> Ugen -> Ugen runningSumRMS z n = sqrt (runningSum (z * z) n * recip n) | Mix one output from many sources selectX :: Ugen -> Ugen -> Ugen selectX ix xs = let s0 = select (roundTo ix 2) xs s1 = select (trunc ix 2 + 1) xs in xFade2 s0 s1 (fold2 (ix * 2 - 1) 1) 1 -- | Set local buffer values. setBuf' :: Ugen -> [Ugen] -> Ugen -> Ugen setBuf' b xs o = Sound.Sc3.Ugen.Bindings.Db.setBuf b o (fromIntegral (length xs)) (mce xs) -- | Silence. silent :: Int -> Ugen silent n = let s = dc ar 0 in mce (replicate n s) | Zero indexed audio input buses . Optimises case of consecutive Ugens . > soundIn ( mce2 0 1 ) = = in ' 2 ar numOutputBuses > soundIn ( mce2 0 2 ) = = in ' 1 ar ( numOutputBuses + mce2 0 2 ) Optimises case of consecutive Ugens. > soundIn (mce2 0 1) == in' 2 ar numOutputBuses > soundIn (mce2 0 2) == in' 1 ar (numOutputBuses + mce2 0 2) -} soundIn :: Ugen -> Ugen soundIn u = let r = in' 1 ar (numOutputBuses + u) in case u of Mce_U m -> let n = mceProxies m in if all (==1) (zipWith (-) (tail n) n) then in' (length n) ar (numOutputBuses + head n) else r _ -> r -- | Pan a set of channels across the stereo field. -- > input , , , center:0 , levelComp : true splay :: Ugen -> Ugen -> Ugen -> Ugen -> Bool -> Ugen splay i s l c lc = let n = max 2 (fromIntegral (fromMaybe 1 (mceDegree i))) m = n - 1 p = map ((+ (-1.0)) . (* (2 / m))) [0 .. m] a = if lc then sqrt (1 / n) else 1 in mix (pan2 i (s * mce p + c) 1) * l * a -- | Single tap into a delayline. ar only. tap :: Int -> Rate -> Ugen -> Ugen -> Ugen tap numChannels rt bufnum delaytime = let n = delaytime * negate sampleRate in playBuf numChannels rt bufnum 1 0 n Loop DoNothing | Randomly select one of several inputs on trigger . tChooseId :: ID m => m -> Ugen -> Ugen -> Ugen tChooseId z t a = select (tiRandId z 0 (mceSize a - 1) t) a | Randomly select one of several inputs . tChooseM :: (Uid m) => Ugen -> Ugen -> m Ugen tChooseM t a = do r <- tiRandM 0 (constant (length (mceChannels a) - 1)) t return (select r a) tChoose :: Ugen -> Ugen -> Ugen tChoose = liftUnsafe2 tChooseM | Triggered Line , implemented in terms of EnvGen . tLine :: Rate -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen tLine rt start end dur trig_ = let p = envCoord [(0,0),(0,start),(dur,end)] 1 1 EnvLin in envGen rt trig_ 1 0 1 DoNothing p | Triggered xLine , implemented in terms of EnvGen . tXLine :: Rate -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen tXLine rt start end dur trig_ = let p = envCoord [(0,0),(0,start),(dur,end)] 1 1 EnvExp in envGen rt trig_ 1 0 1 DoNothing p -- | Triangle wave as sum of /n/ sines. For partial n , amplitude is ( 1 / square n ) and phase is pi at every other odd partial . triAS :: Int -> Ugen -> Ugen triAS n f0 = let mk_freq i = f0 * fromIntegral i mk_amp i = if even i then 0 else 1 / fromIntegral (i * i) mk_ph i = if i + 1 `mod` 4 == 0 then pi else 0 m = [1,3 .. n] param = zip3 (map mk_freq m) (map mk_ph m) (map mk_amp m) in sum_opt (map (\(fr,ph,am) -> sinOsc ar fr ph * am) param) | Randomly select one of several inputs on trigger ( weighted ) . tWChooseId :: ID m => m -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen tWChooseId z t a w n = let i = tWindexId z t n w in select i a | Randomly select one of several inputs ( weighted ) . tWChooseM :: (Uid m) => Ugen -> Ugen -> Ugen -> Ugen -> m Ugen tWChooseM t a w n = do i <- tWindexM t n w return (select i a) tWChoose :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen tWChoose = liftUnsafe4 tWChooseM | Unpack an FFT chain into separate demand - rate FFT bin streams . unpackFFT :: Ugen -> Int -> Int -> Int -> Ugen -> [Ugen] unpackFFT c nf from to w = map (\i -> unpack1FFT c (constant nf) (constant i) w) [from .. to] -- | VarLag in terms of envGen. Note: in SC3 curvature and warp are separate arguments. varLag_env :: Ugen -> Ugen -> Envelope_Curve Ugen -> Maybe Ugen -> Ugen varLag_env in_ time warp start = let rt = rateOf in_ start_ = fromMaybe in_ start e = Envelope [start_,in_] [time] [warp] Nothing Nothing 0 -- e[6] = curve; e[7] = curvature; time_ch = if rateOf time == InitialisationRate then 0 else changed time 0 tr = changed in_ 0 + time_ch + impulse rt 0 0 in envGen rt tr 1 0 1 DoNothing e | k channel white noise . > whiteNoiseN 2 ar * 0.1 > whiteNoiseN 2 ar * 0.1 -} whiteNoiseMN :: Uid m => Int -> Rate -> m Ugen whiteNoiseMN k r = fmap mce (mapM (\_ -> whiteNoiseM r) [1 .. k]) whiteNoiseN :: Int -> Rate -> Ugen whiteNoiseN k = liftUnsafe1 (whiteNoiseMN k) | If @z@ is n't a sink node route to an @out@ node writing to @bus@. If @fadeTime@ is given multiply by ' makeFadeEnv ' . > import Sound . Sc3 { - hsc3 If @fadeTime@ is given multiply by 'makeFadeEnv'. > import Sound.Sc3 {- hsc3 -} > audition (wrapOut (Just 1) (sinOsc ar 440 0 * 0.1)) > import Sound.Osc {- hosc -} > withSc3 (sendMessage (n_set1 (-1) "gate" 0)) -} wrapOut :: Maybe Double -> Ugen -> Ugen wrapOut fadeTime z = if isSink z then z else out (control kr "out" 0) (maybe z ((* z) . makeFadeEnv) fadeTime) -- * wslib -- | Cross-fading version of 'playBuf'. playBufCF :: Int -> Ugen -> Ugen -> Ugen -> Ugen -> Loop Ugen -> Ugen -> Int -> Ugen playBufCF nc bufnum rate trigger startPos loop lag' n = let trigger' = if rateOf trigger == DemandRate then tDuty ar trigger 0 DoNothing 1 0 else trigger index' = stepper trigger' 0 0 (constant n - 1) 1 0 on = map (\i -> inRange index' (i - 0.5) (i + 0.5)) [0 .. constant n - 1] rate' = case rateOf rate of DemandRate -> map (\on' -> demand on' 0 rate) on ControlRate -> map (gate rate) on AudioRate -> map (gate rate) on InitialisationRate -> map (const rate) on startPos' = if rateOf startPos == DemandRate then demand trigger' 0 startPos else startPos lag'' = 1 / lag' s = zipWith (\on' r -> let p = playBuf nc ar bufnum r on' startPos' loop DoNothing in p * sqrt (slew on' lag'' lag'')) on rate' in sum_opt s -- * adc -- | An oscillator that reads through a table once. osc1 :: Rate -> Ugen -> Ugen -> DoneAction Ugen -> Ugen osc1 rt buf dur doneAction = let ph = line rt 0 (bufFrames ir buf - 1) dur doneAction in bufRd 1 rt buf ph NoLoop LinearInterpolation
null
https://raw.githubusercontent.com/rd--/hsc3/03aca8ef471cb82094c9ec0778bb3beaf8781428/Sound/Sc3/Ugen/Bindings/Composite.hs
haskell
| Common unit generator graphs. base base | Generate a localBuf and use setBuf to initialise it. | Buffer reader (no interpolation). | Buffer reader (linear interpolation). | Buffer reader (cubic interpolation). | Triggers when a value changes | 'liftUid' of 'choose'. | 'clearBuf' of 'localBuf'. | Demand rate (:) function. | Demand rate (:) function. | Dynamic klang, dynamic sine oscillator bank | Dynamic klank, set of non-fixed resonating filters. | Pan2 without (k-rate only) level input | 'linExp' with input range of (-1,1). | Variant of `exprange` with arguments to make writing post-fix nicer. | 'fft' variant that allocates 'localBuf'. > in audition (out 0 (ifft c 0 0)) | Sum of 'numInputBuses' and 'numOutputBuses'. | Frequency shifter, in terms of 'hilbert' (see also 'freqShift'). 1024 = less delay, little choppier results. | Variant ifft with default value for window type. | Linear interpolating variant on index . | Linear interpolating variant on index. | Variant of 'klangSpec' for 'Mce' inputs. | Variant of 'klankSpec' for 'Mce' inputs. | 'liftUid' of 'lchoose'. | 'linExp' of (-1,1). | 'linLin' where source is (-1,1). > withSc3 (send (n_set1 (-1) "gate" 0)) | Variant that is randomly pressed. | Variant that randomly traverses the mouseX space. | Variant that randomly traverses the mouseY space. | Onset detector with default values for minor parameters. | Format magnitude and phase data data as required for packFFT. | PM oscillator. signal at left, and that allows a constant /frequency/ input in place of a trigger. | Apply function /f/ to each bin of an @FFT@ chain, /f/ receives magnitude, phase and index and returns a (magnitude,phase). frames, though the latter maybe fractional. | 'Uid' form of 'rand2'. | RMS variant of 'runningSum'. | Set local buffer values. | Silence. | Pan a set of channels across the stereo field. | Single tap into a delayline. ar only. | Triangle wave as sum of /n/ sines. | VarLag in terms of envGen. Note: in SC3 curvature and warp are separate arguments. e[6] = curve; e[7] = curvature; hsc3 hosc * wslib | Cross-fading version of 'playBuf'. * adc | An oscillator that reads through a table once.
module Sound.Sc3.Ugen.Bindings.Composite where import Sound.Sc3.Common.Enum import Sound.Sc3.Common.Envelope import Sound.Sc3.Common.Math import Sound.Sc3.Common.Math.Filter.Beq import Sound.Sc3.Common.Math.Operator import Sound.Sc3.Common.Rate import Sound.Sc3.Common.Uid import Sound.Sc3.Common.Unsafe import Sound.Sc3.Ugen.Bindings.Db import Sound.Sc3.Ugen.Bindings.Hw import Sound.Sc3.Ugen.Math import Sound.Sc3.Ugen.Mce import Sound.Sc3.Ugen.Types import Sound.Sc3.Ugen.Util asLocalBufId :: ID i => i -> [Ugen] -> Ugen asLocalBufId z xs = let b = localBufId z 1 (fromIntegral (length xs)) s = setBuf' b xs 0 in mrg2 b s asLocalBufM :: Uid m => [Ugen] -> m Ugen asLocalBufM = liftUid1 asLocalBufId asLocalBuf :: [Ugen] -> Ugen asLocalBuf = liftUnsafe1 asLocalBufM | balance2 with Mce input . balanceStereo :: Ugen -> Ugen -> Ugen -> Ugen balanceStereo sig pos level = let (x,y) = unmce2 sig in balance2 x y pos level | 24db / oct rolloff - 4th order resonant Low Pass Filter bLowPass4 :: Ugen -> Ugen -> Ugen -> Ugen bLowPass4 i f rq = let (a0, a1, a2, b1, b2) = bLowPassCoef sampleRate f rq flt z = sos z a0 a1 a2 b1 b2 in flt (flt i) | 24db / oct rolloff - 4th order resonant Hi Pass Filter bHiPass4 :: Ugen -> Ugen -> Ugen -> Ugen bHiPass4 i f rq = let (a0, a1, a2, b1, b2) = bHiPassCoef sampleRate f rq flt z = sos z a0 a1 a2 b1 b2 in flt (flt i) bufRdN :: Int -> Rate -> Ugen -> Ugen -> Loop Ugen -> Ugen bufRdN n r b p l = bufRd n r b p l NoInterpolation bufRdL :: Int -> Rate -> Ugen -> Ugen -> Loop Ugen -> Ugen bufRdL n r b p l = bufRd n r b p l LinearInterpolation bufRdC :: Int -> Rate -> Ugen -> Ugen -> Loop Ugen -> Ugen bufRdC n r b p l = bufRd n r b p l CubicInterpolation changed :: Ugen -> Ugen -> Ugen changed input threshold = abs (hpz1 input) `greater_than` threshold | ' mce ' variant of ' lchoose ' . chooseId :: ID m => m -> Ugen -> Ugen chooseId z = lchooseId z . mceChannels chooseM :: Uid m => Ugen -> m Ugen chooseM = liftUid1 chooseId choose :: Ugen -> Ugen choose = liftUnsafe1 chooseM clearLocalBufId :: ID a => a -> Ugen -> Ugen -> Ugen clearLocalBufId z nc nf = clearBuf (localBufId z nc nf) clearLocalBufM :: Uid m => Ugen -> Ugen -> m Ugen clearLocalBufM = liftUid2 clearLocalBufId clearLocalBuf :: Ugen -> Ugen -> Ugen clearLocalBuf = liftUnsafe2 clearLocalBufM dconsId :: ID m => (m,m,m) -> Ugen -> Ugen -> Ugen dconsId (z0,z1,z2) x xs = let i = dseqId z0 1 (mce2 0 1) a = dseqId z1 1 (mce2 x xs) in dswitchId z2 i a dconsM :: (Uid m) => Ugen -> Ugen -> m Ugen dconsM x xs = do i <- dseqM 1 (mce2 0 1) a <- dseqM 1 (mce2 x xs) dswitchM i a dcons :: Ugen -> Ugen -> Ugen dcons = liftUnsafe2 dconsM dynKlang :: Rate -> Ugen -> Ugen -> Ugen -> Ugen dynKlang r fs fo s = let gen (f:a:ph:xs) = sinOsc r (f * fs + fo) ph * a + gen xs gen _ = 0 in gen (mceChannels s) dynKlank :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen dynKlank i fs fo ds s = let gen (f:a:d:xs) = ringz i (f * fs + fo) (d * ds) * a + gen xs gen _ = 0 in gen (mceChannels s) eqPan2 :: Ugen -> Ugen -> Ugen eqPan2 input pos = pan2 input pos 1 exprange :: Ugen -> Ugen -> Ugen -> Ugen exprange l r s = linExp s (-1) 1 l r in_exprange :: Ugen -> (Ugen, Ugen) -> Ugen in_exprange s (l,r) = exprange l r s | Variant FFT constructor with default values for hop size ( 0.5 ) , window type ( 0 ) , active status ( 1 ) and window size ( 0 ) . fft' :: Ugen -> Ugen -> Ugen fft' buf i = fft buf i 0.5 0 1 0 > let c = ffta ' α ' 2048 ( soundIn 0 ) 0.5 0 1 0 fftAllocId :: ID i => i -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen fftAllocId z nf i h wt a ws = let b = localBufId z 1 nf in fft b i h wt a ws fftAllocM :: Uid m => Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> m Ugen fftAllocM = liftUid6 fftAllocId fftAlloc :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen fftAlloc = liftUnsafe6 fftAllocM firstPrivateBus :: Ugen firstPrivateBus = numInputBuses + numOutputBuses freqShift_hilbert :: Ugen -> Ugen -> Ugen -> Ugen freqShift_hilbert i f p = let o = sinOsc ar f (mce [p + 0.5 * pi, p]) h = hilbert i in mix (h * o) | Ugen function to re - trigger an EnvGen envelope . Inputs are /gate/ ( as set at EnvGen ) and /reset/. The four state logic is : ( 1,0)->1 ( 1,1)->-1 ( 0,1)->0 ( 0,0)->0 . If the gate input to EnvGen.kr is -1 the envelope ramps to zero in one control period . The reset input sequence 0,1,0 when the gate is open produces ( 1,-1,1 ) , which resets the envelope . > map ( uncurry gateReset ) [ ( 1,0),(1,1),(0,1),(0,0 ) ] = = [ 1,-1,0,0 ] Inputs are /gate/ (as set at EnvGen) and /reset/. The four state logic is: (1,0)->1 (1,1)->-1 (0,1)->0 (0,0)->0. If the gate input to EnvGen.kr is -1 the envelope ramps to zero in one control period. The reset input sequence 0,1,0 when the gate is open produces (1,-1,1), which resets the envelope. > map (uncurry gateReset) [(1,0),(1,1),(0,1),(0,0)] == [1,-1,0,0] -} gateReset :: Num a => a -> a -> a gateReset gt tr = gt - (gt * tr * 2) | Variant of ' hilbert ' using FFT ( with a delay ) for better results . Buffer should be 2048 or 1024 . 2048 = better results , more delay . hilbertFIR :: Ugen -> Ugen -> Ugen hilbertFIR s b = let c0 = fft' b s c1 = pv_PhaseShift90 c0 delay = bufDur kr b in mce2 (delayN s delay delay) (ifft' c1) ifft' :: Ugen -> Ugen ifft' buf = ifft buf 0 0 indexL : : Ugen - > Ugen - > Ugen indexL b i = let x = index b i y = index b ( i + 1 ) in linLin ( frac i ) 0 1 x y indexL :: Ugen -> Ugen -> Ugen indexL b i = let x = index b i y = index b (i + 1) in linLin (frac i) 0 1 x y -} | Generalised Klan(k / g ) specification rule . /f/ unwraps inputs , /g/ wraps output . > let r = [ 220,0.2,0,219,0.1,1,221,0.1,2 ] > in i d i d [ 220,219,221 ] [ 0.2,0.1,0.1 ] [ 0,1,2 ] = = r klanx_spec_f :: (a -> [b]) -> ([b] -> c) -> a -> a -> a -> c klanx_spec_f f g fr am z = g ((concat . transpose) [f fr,f am,f z]) | Format frequency , amplitude and decay time data as required for klank . klangSpec :: [Ugen] -> [Ugen] -> [Ugen] -> Ugen klangSpec = klanx_spec_f id mce | Variant of ' klangSpec ' for non - Ugen inputs . klangSpec_k :: Real n => [n] -> [n] -> [n] -> Ugen klangSpec_k = klanx_spec_f (map constant) mce klangSpec_mce :: Ugen -> Ugen -> Ugen -> Ugen klangSpec_mce = klanx_spec_f mceChannels mce | Format frequency , amplitude and decay time data as required for klank . klankSpec :: [Ugen] -> [Ugen] -> [Ugen] -> Ugen klankSpec = klanx_spec_f id mce | Variant for non - Ugen inputs . klankSpec_k :: Real n => [n] -> [n] -> [n] -> Ugen klankSpec_k = klanx_spec_f (map constant) mce klankSpec_mce :: Ugen -> Ugen -> Ugen -> Ugen klankSpec_mce = klanx_spec_f mceChannels mce | Randomly select one of a list of ( initialisation rate ) . lchooseId :: ID m => m -> [Ugen] -> Ugen lchooseId z a = select (iRandId z 0 (fromIntegral (length a))) (mce a) lchooseM :: Uid m => [Ugen] -> m Ugen lchooseM = liftUid1 lchooseId lchoose :: [Ugen] -> Ugen lchoose = liftUnsafe1 lchooseM linExp_b :: Ugen -> Ugen -> Ugen -> Ugen linExp_b i = linExp i (-1) 1 | ' linExp ' of ( 0,1 ) . linExp_u :: Ugen -> Ugen -> Ugen -> Ugen linExp_u i = linExp i 0 1 | Map from one linear range to another linear range . linLin :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen linLin = linlin_ma mulAdd | ' linLin ' where source is ( 0,1 ) . linLin_u :: Ugen -> Ugen -> Ugen -> Ugen linLin_u i = linLin i 0 1 linLin_b :: Ugen -> Ugen -> Ugen -> Ugen linLin_b i = linLin i (-1) 1 | Variant with defaults of zero . localIn' :: Int -> Rate -> Ugen localIn' nc r = localIn nc r (mce (replicate nc 0)) | Generate an ' envGen ' Ugen with @fadeTime@ and @gate@ controls . > import Sound . Sc3 > audition ( out 0 ( makeFadeEnv 1 * sinOsc ar 440 0 * 0.1 ) ) makeFadeEnv :: Double -> Ugen makeFadeEnv fadeTime = let dt = control kr "fadeTime" (realToFrac fadeTime) gate_ = control kr "gate" 1 startVal = dt `less_than_or_equal_to` 0 env = Envelope [startVal,1,0] [1,1] [EnvLin,EnvLin] (Just 1) Nothing 0 in envGen kr gate_ 1 0 dt RemoveSynth env mouseButtonRand :: Rate -> Ugen -> Ugen -> Ugen -> Ugen mouseButtonRand rt l r tm = let o = lfClipNoiseId 'z' rt 1 in lag (linLin o (-1) 1 l r) tm | Randomised mouse Ugen ( see also ' mouseX '' and ' mouseY '' ) . mouseRandId :: ID a => a -> Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseRandId z rt l r ty tm = let f = case ty of Linear -> linLin Exponential -> linExp _ -> undefined in lag (f (lfNoise1Id z rt 1) (-1) 1 l r) tm mouseRandM :: Uid m => Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> m Ugen mouseRandM = liftUid5 mouseRandId mouseRand :: Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseRand = liftUnsafe5 mouseRandM mouseXRand :: Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseXRand = mouseRandId 'x' mouseYRand :: Rate -> Ugen -> Ugen -> Warp Ugen -> Ugen -> Ugen mouseYRand = mouseRandId 'y' | Translate onset type string to constant Ugen value . onsetType :: Num a => String -> a onsetType s = let t = ["power", "magsum", "complex", "rcomplex", "phase", "wphase", "mkl"] in fromIntegral (fromMaybe 3 (elemIndex s t)) onsetsDefault :: Ugen -> Ugen -> Ugen -> Ugen onsetsDefault c t o = onsets c t o 1 0.1 10 11 1 0 packFFTSpec :: [Ugen] -> [Ugen] -> Ugen packFFTSpec m p = let interleave x = concat . zipWith (\a b -> [a,b]) x in mce (interleave m p) | Calculate size of accumulation buffer given FFT and IR sizes . partConv_calcAccumSize :: Int -> Int -> Int partConv_calcAccumSize fft_size ir_length = let partition_size = fft_size `div` 2 num_partitions = (ir_length `div` partition_size) + 1 in fft_size * num_partitions cf = carrier frequency , mf = modulation frequency , pm = pm - index = 0.0 , mp = mod - phase = 0.0 pmOsc :: Rate -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen pmOsc r cf mf pm mp = sinOsc r cf (sinOsc r mf mp * pm) | Variant of ' poll ' that generates an ' mrg ' value with the input pollExt :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen pollExt optTrig in_ label_ trigId = let tr = if isConstant optTrig then impulse kr optTrig 0 else optTrig in mrg [in_,poll tr in_ label_ trigId] | Variant of ' in '' offset so zero if the first private bus . privateIn :: Int -> Rate -> Ugen -> Ugen privateIn nc rt k = in' nc rt (k + firstPrivateBus) | Variant of ' out ' offset so zero if the first private bus . privateOut :: Ugen -> Ugen -> Ugen privateOut k = out (k + firstPrivateBus) pvcollect :: Ugen -> Int -> (Ugen -> Ugen -> Int -> (Ugen, Ugen)) -> Int -> Int -> Ugen -> Ugen pvcollect c nf f from to z = let m = unpackFFT c nf from to 0 p = unpackFFT c nf from to 1 i = [from .. to] e = zipWith3 f m p i mp = uncurry packFFTSpec (unzip e) in packFFT c nf from to z mp | /dur/ and /hop/ are in seconds , /frameSize/ and /sampleRate/ in > pv_calcPVRecSize 4.2832879818594 1024 0.25 48000.0 = = 823299 pv_calcPVRecSize :: Double -> Int -> Double -> Double -> Int pv_calcPVRecSize dur frame_size hop sample_rate = let frame_size' = fromIntegral frame_size raw_size = ceiling ((dur * sample_rate) / frame_size') * frame_size in ceiling (fromIntegral raw_size * recip hop + 3) | ' rand ' with left edge set to zero . rand0Id :: ID a => a -> Ugen -> Ugen rand0Id z = randId z 0 | ' Uid ' form of ' ' . rand0M :: Uid m => Ugen -> m Ugen rand0M = randM 0 rand0 :: Ugen -> Ugen rand0 = liftUnsafe1 rand0M | ' rand ' with left edge set to negative /n/. Note rand2 is also a UnaryOp Ugen , however hsc3 does not store Ids for operators . Note rand2 is also a UnaryOp Ugen, however hsc3 does not store Ids for operators. -} rand2Id :: ID a => a -> Ugen -> Ugen rand2Id z n = randId z (negate n) n rand2M :: Uid m => Ugen -> m Ugen rand2M n = randM (negate n) n rand2 :: Ugen -> Ugen rand2 = liftUnsafe1 rand2M | with Mce input . rotateStereo :: Ugen -> Ugen -> Ugen rotateStereo sig pos = let (x,y) = unmce2 sig in rotate2 x y pos runningSumRMS :: Ugen -> Ugen -> Ugen runningSumRMS z n = sqrt (runningSum (z * z) n * recip n) | Mix one output from many sources selectX :: Ugen -> Ugen -> Ugen selectX ix xs = let s0 = select (roundTo ix 2) xs s1 = select (trunc ix 2 + 1) xs in xFade2 s0 s1 (fold2 (ix * 2 - 1) 1) 1 setBuf' :: Ugen -> [Ugen] -> Ugen -> Ugen setBuf' b xs o = Sound.Sc3.Ugen.Bindings.Db.setBuf b o (fromIntegral (length xs)) (mce xs) silent :: Int -> Ugen silent n = let s = dc ar 0 in mce (replicate n s) | Zero indexed audio input buses . Optimises case of consecutive Ugens . > soundIn ( mce2 0 1 ) = = in ' 2 ar numOutputBuses > soundIn ( mce2 0 2 ) = = in ' 1 ar ( numOutputBuses + mce2 0 2 ) Optimises case of consecutive Ugens. > soundIn (mce2 0 1) == in' 2 ar numOutputBuses > soundIn (mce2 0 2) == in' 1 ar (numOutputBuses + mce2 0 2) -} soundIn :: Ugen -> Ugen soundIn u = let r = in' 1 ar (numOutputBuses + u) in case u of Mce_U m -> let n = mceProxies m in if all (==1) (zipWith (-) (tail n) n) then in' (length n) ar (numOutputBuses + head n) else r _ -> r > input , , , center:0 , levelComp : true splay :: Ugen -> Ugen -> Ugen -> Ugen -> Bool -> Ugen splay i s l c lc = let n = max 2 (fromIntegral (fromMaybe 1 (mceDegree i))) m = n - 1 p = map ((+ (-1.0)) . (* (2 / m))) [0 .. m] a = if lc then sqrt (1 / n) else 1 in mix (pan2 i (s * mce p + c) 1) * l * a tap :: Int -> Rate -> Ugen -> Ugen -> Ugen tap numChannels rt bufnum delaytime = let n = delaytime * negate sampleRate in playBuf numChannels rt bufnum 1 0 n Loop DoNothing | Randomly select one of several inputs on trigger . tChooseId :: ID m => m -> Ugen -> Ugen -> Ugen tChooseId z t a = select (tiRandId z 0 (mceSize a - 1) t) a | Randomly select one of several inputs . tChooseM :: (Uid m) => Ugen -> Ugen -> m Ugen tChooseM t a = do r <- tiRandM 0 (constant (length (mceChannels a) - 1)) t return (select r a) tChoose :: Ugen -> Ugen -> Ugen tChoose = liftUnsafe2 tChooseM | Triggered Line , implemented in terms of EnvGen . tLine :: Rate -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen tLine rt start end dur trig_ = let p = envCoord [(0,0),(0,start),(dur,end)] 1 1 EnvLin in envGen rt trig_ 1 0 1 DoNothing p | Triggered xLine , implemented in terms of EnvGen . tXLine :: Rate -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen tXLine rt start end dur trig_ = let p = envCoord [(0,0),(0,start),(dur,end)] 1 1 EnvExp in envGen rt trig_ 1 0 1 DoNothing p For partial n , amplitude is ( 1 / square n ) and phase is pi at every other odd partial . triAS :: Int -> Ugen -> Ugen triAS n f0 = let mk_freq i = f0 * fromIntegral i mk_amp i = if even i then 0 else 1 / fromIntegral (i * i) mk_ph i = if i + 1 `mod` 4 == 0 then pi else 0 m = [1,3 .. n] param = zip3 (map mk_freq m) (map mk_ph m) (map mk_amp m) in sum_opt (map (\(fr,ph,am) -> sinOsc ar fr ph * am) param) | Randomly select one of several inputs on trigger ( weighted ) . tWChooseId :: ID m => m -> Ugen -> Ugen -> Ugen -> Ugen -> Ugen tWChooseId z t a w n = let i = tWindexId z t n w in select i a | Randomly select one of several inputs ( weighted ) . tWChooseM :: (Uid m) => Ugen -> Ugen -> Ugen -> Ugen -> m Ugen tWChooseM t a w n = do i <- tWindexM t n w return (select i a) tWChoose :: Ugen -> Ugen -> Ugen -> Ugen -> Ugen tWChoose = liftUnsafe4 tWChooseM | Unpack an FFT chain into separate demand - rate FFT bin streams . unpackFFT :: Ugen -> Int -> Int -> Int -> Ugen -> [Ugen] unpackFFT c nf from to w = map (\i -> unpack1FFT c (constant nf) (constant i) w) [from .. to] varLag_env :: Ugen -> Ugen -> Envelope_Curve Ugen -> Maybe Ugen -> Ugen varLag_env in_ time warp start = let rt = rateOf in_ start_ = fromMaybe in_ start e = Envelope [start_,in_] [time] [warp] Nothing Nothing 0 time_ch = if rateOf time == InitialisationRate then 0 else changed time 0 tr = changed in_ 0 + time_ch + impulse rt 0 0 in envGen rt tr 1 0 1 DoNothing e | k channel white noise . > whiteNoiseN 2 ar * 0.1 > whiteNoiseN 2 ar * 0.1 -} whiteNoiseMN :: Uid m => Int -> Rate -> m Ugen whiteNoiseMN k r = fmap mce (mapM (\_ -> whiteNoiseM r) [1 .. k]) whiteNoiseN :: Int -> Rate -> Ugen whiteNoiseN k = liftUnsafe1 (whiteNoiseMN k) | If @z@ is n't a sink node route to an @out@ node writing to @bus@. If @fadeTime@ is given multiply by ' makeFadeEnv ' . > import Sound . Sc3 { - hsc3 If @fadeTime@ is given multiply by 'makeFadeEnv'. > audition (wrapOut (Just 1) (sinOsc ar 440 0 * 0.1)) > withSc3 (sendMessage (n_set1 (-1) "gate" 0)) -} wrapOut :: Maybe Double -> Ugen -> Ugen wrapOut fadeTime z = if isSink z then z else out (control kr "out" 0) (maybe z ((* z) . makeFadeEnv) fadeTime) playBufCF :: Int -> Ugen -> Ugen -> Ugen -> Ugen -> Loop Ugen -> Ugen -> Int -> Ugen playBufCF nc bufnum rate trigger startPos loop lag' n = let trigger' = if rateOf trigger == DemandRate then tDuty ar trigger 0 DoNothing 1 0 else trigger index' = stepper trigger' 0 0 (constant n - 1) 1 0 on = map (\i -> inRange index' (i - 0.5) (i + 0.5)) [0 .. constant n - 1] rate' = case rateOf rate of DemandRate -> map (\on' -> demand on' 0 rate) on ControlRate -> map (gate rate) on AudioRate -> map (gate rate) on InitialisationRate -> map (const rate) on startPos' = if rateOf startPos == DemandRate then demand trigger' 0 startPos else startPos lag'' = 1 / lag' s = zipWith (\on' r -> let p = playBuf nc ar bufnum r on' startPos' loop DoNothing in p * sqrt (slew on' lag'' lag'')) on rate' in sum_opt s osc1 :: Rate -> Ugen -> Ugen -> DoneAction Ugen -> Ugen osc1 rt buf dur doneAction = let ph = line rt 0 (bufFrames ir buf - 1) dur doneAction in bufRd 1 rt buf ph NoLoop LinearInterpolation
30350fb25fc8d2642027b094e2be918c784e89e9bda45b8f48ca40c815cf9040
tek/proteome
ReplaceTest.hs
module Proteome.Test.ReplaceTest where import Control.Lens.Regex.Text (group, regex) import qualified Data.Text as Text import qualified Data.Text.IO as Text import Path (Abs, File, Path, reldir, relfile, toFilePath) import qualified Polysemy.Test as Test import Polysemy.Test (Hedgehog, UnitTest, (===)) import Prelude hiding (group) import Ribosome.Api (vimGetBuffers) import Ribosome.Api.Buffer (buflisted, currentBufferContent, setCurrentBufferContent) import Ribosome.Menu (promptInput) import Ribosome.Menu.Prompt (PromptEvent (Mapping)) import qualified Proteome.Grep as Grep import Proteome.Grep (grepWith) import Proteome.Grep.Replace (proReplaceQuit, proReplaceSave) import Proteome.Test.Run (proteomeTest) pat :: Text pat = "target" replacement :: Text replacement = "replaced" replaceEvents :: [PromptEvent] replaceEvents = Mapping <$> ["*", "r"] file1Lines :: [Text] file1Lines = [ "garbage 0", "target", "garbage 1", "and target here" ] file2Lines :: [Text] file2Lines = [ "garbage 2", "and target" ] file3Lines :: [Text] file3Lines = [ "delete me target 1", "", "keep me 1", "", "delete me target 2", "", "keep me 2", "delete me target 3", "keep me 3", "", "keep me 4", "delete me target 4", "" ] file1Target :: [Text] file1Target = [ "garbage 0", "replaced", "garbage 1", "and replaced here" ] file2Target :: [Text] file2Target = [ "garbage 2", "and replaced" ] file3Target :: [Text] file3Target = [ "keep me 1", "", "keep me 2", "keep me 3", "", "keep me 4" ] checkContent :: Members [Hedgehog IO, Embed IO] r => Path Abs File -> [Text] -> Sem r () checkContent file target = (target ===) . lines . toText =<< embed (Text.readFile (toFilePath file)) test_grepReplace :: UnitTest test_grepReplace = proteomeTest do dir <- Test.tempDir [reldir|grep/replace|] file1 <- Test.tempFile file1Lines [relfile|grep/replace/file1|] file2 <- Test.tempFile file2Lines [relfile|grep/replace/file2|] file3 <- Test.tempFile file3Lines [relfile|grep/replace/file3|] Grep.handleErrors (promptInput replaceEvents (grepWith [] dir pat)) replaceContent <- currentBufferContent 7 === length replaceContent setCurrentBufferContent $ ([regex|^(delete me.*)$|] . group 0 .~ "") . Text.replace pat replacement <$> replaceContent proReplaceSave proReplaceQuit (2 ===) . length =<< filterM buflisted =<< vimGetBuffers checkContent file1 file1Target checkContent file2 file2Target checkContent file3 file3Target deleteEvents :: [PromptEvent] deleteEvents = Mapping <$> ["k", "<space>", "k", "<space>", "d"] deleteFile1Lines :: [Text] deleteFile1Lines = [ "target 0", "", "target 1", "", "garbage", "target 2", "target 4", "garbage" ] deleteFile1Target :: [Text] deleteFile1Target = [ "target 0", "", "garbage", "target 2", "garbage" ] test_grepDelete :: UnitTest test_grepDelete = proteomeTest do dir <- Test.tempDir [reldir|grep/delete|] file1 <- Test.tempFile deleteFile1Lines [relfile|grep/delete/file1|] Grep.handleErrors (promptInput deleteEvents (grepWith [] dir pat)) checkContent file1 deleteFile1Target
null
https://raw.githubusercontent.com/tek/proteome/019928432bd5f5ba87d35eab19e341a5c98b1bba/packages/proteome/test/Proteome/Test/ReplaceTest.hs
haskell
module Proteome.Test.ReplaceTest where import Control.Lens.Regex.Text (group, regex) import qualified Data.Text as Text import qualified Data.Text.IO as Text import Path (Abs, File, Path, reldir, relfile, toFilePath) import qualified Polysemy.Test as Test import Polysemy.Test (Hedgehog, UnitTest, (===)) import Prelude hiding (group) import Ribosome.Api (vimGetBuffers) import Ribosome.Api.Buffer (buflisted, currentBufferContent, setCurrentBufferContent) import Ribosome.Menu (promptInput) import Ribosome.Menu.Prompt (PromptEvent (Mapping)) import qualified Proteome.Grep as Grep import Proteome.Grep (grepWith) import Proteome.Grep.Replace (proReplaceQuit, proReplaceSave) import Proteome.Test.Run (proteomeTest) pat :: Text pat = "target" replacement :: Text replacement = "replaced" replaceEvents :: [PromptEvent] replaceEvents = Mapping <$> ["*", "r"] file1Lines :: [Text] file1Lines = [ "garbage 0", "target", "garbage 1", "and target here" ] file2Lines :: [Text] file2Lines = [ "garbage 2", "and target" ] file3Lines :: [Text] file3Lines = [ "delete me target 1", "", "keep me 1", "", "delete me target 2", "", "keep me 2", "delete me target 3", "keep me 3", "", "keep me 4", "delete me target 4", "" ] file1Target :: [Text] file1Target = [ "garbage 0", "replaced", "garbage 1", "and replaced here" ] file2Target :: [Text] file2Target = [ "garbage 2", "and replaced" ] file3Target :: [Text] file3Target = [ "keep me 1", "", "keep me 2", "keep me 3", "", "keep me 4" ] checkContent :: Members [Hedgehog IO, Embed IO] r => Path Abs File -> [Text] -> Sem r () checkContent file target = (target ===) . lines . toText =<< embed (Text.readFile (toFilePath file)) test_grepReplace :: UnitTest test_grepReplace = proteomeTest do dir <- Test.tempDir [reldir|grep/replace|] file1 <- Test.tempFile file1Lines [relfile|grep/replace/file1|] file2 <- Test.tempFile file2Lines [relfile|grep/replace/file2|] file3 <- Test.tempFile file3Lines [relfile|grep/replace/file3|] Grep.handleErrors (promptInput replaceEvents (grepWith [] dir pat)) replaceContent <- currentBufferContent 7 === length replaceContent setCurrentBufferContent $ ([regex|^(delete me.*)$|] . group 0 .~ "") . Text.replace pat replacement <$> replaceContent proReplaceSave proReplaceQuit (2 ===) . length =<< filterM buflisted =<< vimGetBuffers checkContent file1 file1Target checkContent file2 file2Target checkContent file3 file3Target deleteEvents :: [PromptEvent] deleteEvents = Mapping <$> ["k", "<space>", "k", "<space>", "d"] deleteFile1Lines :: [Text] deleteFile1Lines = [ "target 0", "", "target 1", "", "garbage", "target 2", "target 4", "garbage" ] deleteFile1Target :: [Text] deleteFile1Target = [ "target 0", "", "garbage", "target 2", "garbage" ] test_grepDelete :: UnitTest test_grepDelete = proteomeTest do dir <- Test.tempDir [reldir|grep/delete|] file1 <- Test.tempFile deleteFile1Lines [relfile|grep/delete/file1|] Grep.handleErrors (promptInput deleteEvents (grepWith [] dir pat)) checkContent file1 deleteFile1Target
881ca675fe73a1572e6f34d22526d05abb80f1cdb47633f5c3102c3b2e46e889
sharplispers/ironclad
testfuns.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- (in-package :crypto-tests) (defun hex-string-to-byte-array (string &key (start 0) (end nil)) This function disappears from profiles if SBCL can inline the ;; POSITION call, so declare SPEED high enough to trigger that. (declare (type string string) (optimize (speed 2))) (let* ((end (or end (length string))) (length (/ (- end start) 2)) (key (make-array length :element-type '(unsigned-byte 8)))) (declare (type (simple-array (unsigned-byte 8) (*)) key)) (flet ((char-to-digit (char) (declare (type base-char char)) (let ((x (cl:position char #.(coerce "0123456789abcdef" 'simple-base-string) :test #'char-equal))) (or x (error "Invalid hex key ~A specified" string))))) (loop for i from 0 for j from start below end by 2 do (setf (aref key i) (+ (* (char-to-digit (char string j)) 16) (char-to-digit (char string (1+ j))))) finally (return key))))) ;;; test vector files (defun test-vector-filename (ident) (merge-pathnames (make-pathname :directory '(:relative "test-vectors") :name (substitute #\- #\/ (format nil "~(~A~)" ident)) :type "testvec") #.*compile-file-pathname*)) (defun sharp-a (stream sub-char numarg) (declare (ignore sub-char numarg)) (crypto:ascii-string-to-byte-array (read stream t nil t))) (defun sharp-h (stream sub-char numarg) (declare (ignore sub-char numarg)) (hex-string-to-byte-array (read stream t nil t))) (defun run-test-vector-file (name function-map) (let ((filename (test-vector-filename name)) (*readtable* (copy-readtable))) (set-dispatch-macro-character #\# #\a #'sharp-a *readtable*) (set-dispatch-macro-character #\# #\h #'sharp-h *readtable*) (with-open-file (stream filename :direction :input :element-type 'character :if-does-not-exist :error) (loop for form = (read stream nil stream) until (eq form stream) do (cond ((not (listp form)) (error "Invalid form in test vector file ~A: ~A" filename form)) (t (let ((test-function (cdr (assoc (car form) function-map)))) (unless test-function (error "No test function defined for ~A" (car form))) (apply test-function name (cdr form))))) finally (return t))))) ;;; cipher testing (defun cipher-test-guts (cipher-name mode key input output &optional extra-make-cipher-args) (let ((cipher (apply #'crypto:make-cipher cipher-name :key key :mode mode extra-make-cipher-args)) (scratch (copy-seq input))) (crypto:encrypt cipher input scratch) (when (mismatch scratch output) (error "encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output)) (apply #'reinitialize-instance cipher :key key extra-make-cipher-args) (crypto:decrypt cipher output scratch) (when (mismatch scratch input) (error "decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input)))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun cipher-stream-test-guts (cipher-name mode key input output &optional extra-args) (let* ((out-stream (crypto:make-octet-output-stream)) (enc-stream (apply #'crypto:make-encrypting-stream out-stream cipher-name mode key extra-args)) (in-stream (crypto:make-octet-input-stream output)) (dec-stream (apply #'crypto:make-decrypting-stream in-stream cipher-name mode key extra-args))) (write-byte (aref input 0) enc-stream) (write-sequence input enc-stream :start 1) (let ((result (crypto:get-output-stream-octets out-stream))) (when (mismatch result output) (error "stream encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output))) (let ((result (copy-seq output))) (setf (aref result 0) (read-byte dec-stream)) (read-sequence result dec-stream :start 1) (when (mismatch result input) (error "stream decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input))))) (defun ecb-mode-test (cipher-name hexkey hexinput hexoutput) (cipher-test-guts cipher-name :ecb hexkey hexinput hexoutput)) (defun ecb-tweak-mode-test (cipher-name hexkey hextweak hexinput hexoutput) (cipher-test-guts cipher-name :ecb hexkey hexinput hexoutput (list :tweak hextweak))) (defun stream-mode-test (cipher-name hexkey hexinput hexoutput) (cipher-test-guts cipher-name :stream hexkey hexinput hexoutput)) (defun stream-nonce-mode-test (cipher-name hexkey hexiv hexinput hexoutput) (cipher-test-guts cipher-name :stream hexkey hexinput hexoutput (list :initialization-vector hexiv))) (defun keystream-test (cipher-name key iv keystream) (let* ((mode (if (= 1 (crypto:block-length cipher-name)) :stream :ctr)) (cipher (crypto:make-cipher cipher-name :key key :mode mode :initialization-vector iv)) (buffer (make-array 1000 :element-type '(unsigned-byte 8) :initial-element 0))) (crypto:keystream-position cipher 100) (crypto:encrypt-in-place cipher buffer :start 100 :end 213) (crypto:keystream-position cipher 500) (crypto:encrypt-in-place cipher buffer :start 500 :end 1000) (crypto:keystream-position cipher 213) (crypto:encrypt-in-place cipher buffer :start 213 :end 500) (crypto:keystream-position cipher 0) (crypto:encrypt-in-place cipher buffer :end 100) (crypto:keystream-position cipher 765) (when (or (/= (crypto:keystream-position cipher) 765) (mismatch buffer keystream)) (error "getting/setting key stream position failed for ~A on key ~A" cipher-name key)))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun stream-mode-test/stream (cipher-name hexkey hexinput hexoutput) (cipher-stream-test-guts cipher-name :stream hexkey hexinput hexoutput)) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun stream-nonce-mode-test/stream (cipher-name hexkey hexiv hexinput hexoutput) (cipher-stream-test-guts cipher-name :stream hexkey hexinput hexoutput (list :initialization-vector hexiv))) (defparameter *cipher-tests* (list (cons :ecb-mode-test 'ecb-mode-test) (cons :ecb-tweak-mode-test 'ecb-tweak-mode-test) (cons :stream-mode-test 'stream-mode-test) (cons :stream-nonce-mode-test 'stream-nonce-mode-test) (cons :keystream-test 'keystream-test))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defparameter *cipher-stream-tests* (list (cons :ecb-mode-test 'ignore-test) (cons :ecb-tweak-mode-test 'ignore-test) (cons :stream-mode-test 'stream-mode-test/stream) (cons :stream-nonce-mode-test 'stream-nonce-mode-test/stream) (cons :keystream-test 'ignore-test))) ;;; encryption mode consistency checking tests from NIST (defun mode-test (mode cipher-name key iv input output) (labels ((frob-hex-string (cipher func input) (let ((scratch (copy-seq input))) (funcall func cipher input scratch) scratch)) (cipher-test (cipher func input output) (not (mismatch (frob-hex-string cipher func input) output)))) (let ((cipher (crypto:make-cipher cipher-name :key key :mode mode :initialization-vector iv))) (unless (cipher-test cipher 'crypto:encrypt input output) (error "encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output)) (reinitialize-instance cipher :key key :mode mode :initialization-vector iv) (unless (cipher-test cipher 'crypto:decrypt output input) (error "decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input))))) (defun mode-padding-test (mode cipher-name padding key iv input output) (let ((cipher (crypto:make-cipher cipher-name :key key :mode mode :initialization-vector iv :padding padding)) (buffer1 (make-array (length input) :element-type '(unsigned-byte 8))) (buffer2 (make-array (length output) :element-type '(unsigned-byte 8)))) (crypto:encrypt cipher input buffer2 :handle-final-block t) (when (mismatch buffer2 output) (error "encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output)) (reinitialize-instance cipher :key key :mode mode :initialization-vector iv :padding padding) (crypto:decrypt cipher output buffer1 :handle-final-block t) (when (mismatch buffer1 input) (error "decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input)))) (defparameter *mode-tests* (list (cons :mode-test 'mode-test) (cons :mode-padding-test 'ignore-test))) (defparameter *mode-padding-tests* (list (cons :mode-test 'ignore-test) (cons :mode-padding-test 'mode-padding-test))) ;;; digest testing routines (defun digest-test/base (digest-name input expected-digest) (let ((result (crypto:digest-sequence digest-name input))) (when (mismatch result expected-digest) (error "one-shot ~A digest of ~S failed" digest-name input)))) (defun digest-test/incremental (digest-name input expected-digest) (loop with length = (length input) with digester = (crypto:make-digest digest-name) for i from 0 below length do (crypto:update-digest digester input :start i :end (1+ i)) finally (let ((result (crypto:produce-digest digester))) (when (mismatch result expected-digest) (error "incremental ~A digest of ~S failed" digest-name input))))) (defun digest-test/fill-pointer (digest-name octets expected-digest) (let* ((input (let ((x (make-array (* 2 (length octets)) :fill-pointer 0 :element-type '(unsigned-byte 8)))) (dotimes (i (length octets) x) (vector-push (aref octets i) x)))) (result (crypto:digest-sequence digest-name input))) (when (mismatch result expected-digest) (error "fill-pointer'd ~A digest of ~S failed" digest-name input)))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun digest-test/stream (digest-name input expected-digest) (let* ((stream (crypto:make-digesting-stream digest-name))) (when (plusp (length input)) (write-byte (aref input 0) stream) (write-sequence input stream :start 1)) (crypto:produce-digest stream) ; Calling produce-digest twice should not give a wrong hash (when (mismatch (crypto:produce-digest stream) expected-digest) (error "stream-y ~A digest of ~S failed" digest-name input)))) (defun digest-test/reinitialize-instance (digest-name input expected-digest) (let* ((digest (crypto:make-digest digest-name)) (result (progn (crypto:digest-sequence digest input) (crypto:digest-sequence (reinitialize-instance digest) input)))) (when (mismatch result expected-digest) (error "testing reinitialize-instance ~A digest of ~S failed" digest-name input)))) (defun digest-bit-test (digest-name leading byte trailing expected-digest) (let* ((input (let ((vector (make-array (+ 1 leading trailing) :element-type '(unsigned-byte 8) :initial-element 0))) (setf (aref vector leading) byte) vector)) (result (crypto:digest-sequence digest-name input))) (when (mismatch result expected-digest) (error "individual bit test ~A digest of (~D #x~2,'0X ~D) failed" digest-name leading byte trailing)))) (defun xof-digest-test (digest-name output-length input expected-digest) (let* ((digest (crypto:make-digest digest-name :output-length output-length)) (result (crypto:digest-sequence digest input))) (when (mismatch result expected-digest) (error "one-shot ~A xof digest of ~S failed" digest-name input)))) (defparameter *digest-tests* (list (cons :digest-test 'digest-test/base) (cons :digest-bit-test 'digest-bit-test) (cons :xof-digest-test 'xof-digest-test))) (defun ignore-test (&rest args) (declare (ignore args)) nil) (defparameter *digest-incremental-tests* (list (cons :digest-test 'digest-test/incremental) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) (defparameter *digest-fill-pointer-tests* (list (cons :digest-test 'digest-test/fill-pointer) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defparameter *digest-stream-tests* (list (cons :digest-test 'digest-test/stream) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) (defparameter *digest-reinitialize-instance-tests* (list (cons :digest-test 'digest-test/reinitialize-instance) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) ;;; mac testing routines (defun mac-test/base (mac-name key data expected-digest &rest args) (let ((mac (apply #'crypto:make-mac mac-name key args))) (crypto:update-mac mac data) (let ((result (crypto:produce-mac mac))) (when (mismatch result expected-digest) (error "one-shot ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) (defun mac-test/incremental (mac-name key data expected-digest &rest args) (loop with length = (length data) with mac = (apply #'crypto:make-mac mac-name key args) for i from 0 below length do (crypto:update-mac mac data :start i :end (1+ i)) finally (let ((result (crypto:produce-mac mac))) (when (mismatch result expected-digest) (error "incremental ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun mac-test/stream (mac-name key data expected-digest &rest args) (let ((stream (apply #'crypto:make-authenticating-stream mac-name key args))) (when (plusp (length data)) (write-byte (aref data 0) stream) (write-sequence data stream :start 1)) Calling produce - mac twice should not give a wrong MAC (let ((result (crypto:produce-mac stream))) (when (mismatch result expected-digest) (error "stream ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) (defun mac-test/reinitialize-instance (mac-name key data expected-digest &rest args) (let* ((mac (apply #'crypto:make-mac mac-name key args)) (result1 (progn (crypto:update-mac mac data) (crypto:produce-mac mac)))) (declare (ignorable result1)) (cond ((typep mac 'ironclad:gmac) (reinitialize-instance mac :key key :initialization-vector (car (last args)))) (t (reinitialize-instance mac :key key))) (let ((result2 (progn (crypto:update-mac mac data) (crypto:produce-mac mac)))) (when (mismatch result2 expected-digest) (error "testing reinitialize-instance ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) (defparameter *mac-tests* (list (cons :mac-test 'mac-test/base))) (defparameter *mac-incremental-tests* (list (cons :mac-test 'mac-test/incremental))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defparameter *mac-stream-tests* (list (cons :mac-test 'mac-test/stream))) (defparameter *mac-reinitialize-instance-tests* (list (cons :mac-test 'mac-test/reinitialize-instance))) ;;; PRNG testing routines (defun fortuna-test (name seed entropy expected-sequence) (declare (ignore name)) (let ((prng (crypto:make-prng :fortuna :seed (coerce seed 'crypto::simple-octet-vector))) (num-bytes (length expected-sequence))) (loop for (source pool-id event) in entropy do (crypto:add-random-event source pool-id event prng)) (assert (equalp expected-sequence (crypto:random-data num-bytes prng))))) (defun generator-test (name cipher seeds expected-sequences) (declare (ignore name)) (let ((generator (make-instance 'crypto:fortuna-generator :cipher cipher))) (loop for seed in seeds do (crypto:prng-reseed (coerce seed '(vector (unsigned-byte 8))) generator)) (every (lambda (sequence) (assert (zerop (mod (length sequence) 16))) (assert (equalp sequence (crypto:random-data (length sequence) generator)))) expected-sequences))) (defparameter *prng-tests* `((:fortuna-test . ,'fortuna-test) (:generator-test . ,'generator-test))) ;;; Public key testing routines (defun rsa-oaep-encryption-test (name n e d input seed output) Redefine oaep - encode to use a defined seed for the test instead of a random one (setf (symbol-function 'ironclad::oaep-encode) (lambda (digest-name message num-bytes &optional label) (let* ((digest-name (if (eq digest-name t) :sha1 digest-name)) (digest-len (ironclad:digest-length digest-name))) (assert (<= (length message) (- num-bytes (* 2 digest-len) 2))) (let* ((digest (ironclad:make-digest digest-name)) (label (or label (coerce #() '(vector (unsigned-byte 8))))) (padding-len (- num-bytes (length message) (* 2 digest-len) 2)) (padding (make-array padding-len :element-type '(unsigned-byte 8) :initial-element 0)) (l-hash (ironclad:digest-sequence digest label)) (db (concatenate '(vector (unsigned-byte 8)) l-hash padding #(1) message)) (db-mask (ironclad::mgf digest-name seed (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask)) (seed-mask (ironclad::mgf digest-name masked-db digest-len)) (masked-seed (map '(vector (unsigned-byte 8)) #'logxor seed seed-mask))) (concatenate '(vector (unsigned-byte 8)) #(0) masked-seed masked-db))))) (let* ((pk (ironclad:make-public-key :rsa :n n :e e)) (sk (ironclad:make-private-key :rsa :n n :d d)) (c (ironclad:encrypt-message pk input :oaep t)) (m (ironclad:decrypt-message sk output :oaep t))) (when (mismatch c output) (error "encryption failed for ~A on pkey (~A ~A), input ~A, output ~A" name n e input output)) (when (mismatch m input) (error "decryption failed for ~A on skey (~A ~A), input ~A, output ~A" name n d input output)))) (defun elgamal-encryption-test (name p g x y input k output) (let* ((ironclad::*signature-nonce-for-test* k) (pk (ironclad:make-public-key :elgamal :p p :g g :y y)) (sk (ironclad:make-private-key :elgamal :p p :g g :x x :y y)) (c (ironclad:encrypt-message pk input)) (m (ironclad:decrypt-message sk output))) (when (mismatch c output) (error "encryption failed for ~A on pkey (~A ~A ~A), input ~A, output ~A" name p g y input output)) (when (mismatch m input) (error "decryption failed for ~A on skey (~A ~A ~A ~A), input ~A, output ~A" name p g x y input output)))) (defun rsa-pss-signature-test (name n e d input salt signature) Redefine pss - encode to use a defined salt for the test instead of a random one (setf (symbol-function 'ironclad::pss-encode) (lambda (digest-name message num-bytes) (let* ((digest-name (if (eq digest-name t) :sha1 digest-name)) (digest-len (ironclad:digest-length digest-name))) (assert (>= num-bytes (+ (* 2 digest-len) 2))) (let* ((m-hash (ironclad:digest-sequence digest-name message)) (m1 (concatenate '(vector (unsigned-byte 8)) #(0 0 0 0 0 0 0 0) m-hash salt)) (h (ironclad:digest-sequence digest-name m1)) (ps (make-array (- num-bytes (* 2 digest-len) 2) :element-type '(unsigned-byte 8) :initial-element 0)) (db (concatenate '(vector (unsigned-byte 8)) ps #(1) salt)) (db-mask (ironclad::mgf digest-name h (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask))) (setf (ldb (byte 1 7) (elt masked-db 0)) 0) (concatenate '(vector (unsigned-byte 8)) masked-db h #(188)))))) (let* ((pk (ironclad:make-public-key :rsa :n n :e e)) (sk (ironclad:make-private-key :rsa :n n :d d)) (s (ironclad:sign-message sk input :pss t))) (when (mismatch s signature) (error "signature failed for ~A on skey (~A ~A), input ~A, signature ~A" name n d input signature)) (unless (ironclad:verify-signature pk input signature :pss t) (error "signature verification failed for ~A on pkey (~A ~A), input ~A, signature ~A" name n e input signature)))) (defun elgamal-signature-test (name p g x y input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (pk (ironclad:make-public-key :elgamal :p p :g g :y y)) (sk (ironclad:make-private-key :elgamal :p p :g g :x x :y y)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey (~A ~A ~A ~A), input ~A, signature ~A" name p g x y input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey (~A ~A ~A), input ~A, signature ~A" name p g y input signature)))) (defun dsa-signature-test (name p q g x y input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :dsa :p p :q q :g g :x x :y y)) (pk (ironclad:make-public-key :dsa :p p :q q :g g :y y)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey (~A ~A ~A ~A ~A), input ~A, signature ~A" name p q g x y input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey (~A ~A ~A ~A), input ~A, signature ~A" name p q g y input signature)))) (defun ed25519-signature-test (name skey pkey input signature) (let* ((sk (ironclad:make-private-key :ed25519 :x skey :y pkey)) (pk (ironclad:make-public-key :ed25519 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun ed448-signature-test (name skey pkey input signature) (let* ((sk (ironclad:make-private-key :ed448 :x skey :y pkey)) (pk (ironclad:make-public-key :ed448 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp256k1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp256k1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp256k1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp256r1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp256r1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp256r1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp384r1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp384r1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp384r1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp521r1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp521r1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp521r1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun curve25519-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :curve25519 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :curve25519 :y pkey1)) (sk2 (ironclad:make-private-key :curve25519 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :curve25519 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun curve448-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :curve448 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :curve448 :y pkey1)) (sk2 (ironclad:make-private-key :curve448 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :curve448 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun elgamal-dh-test (name p g skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :elgamal :p p :g g :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :elgamal :p p :g g :y pkey1)) (sk2 (ironclad:make-private-key :elgamal :p p :g g :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :elgamal :p p :g g :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp256k1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp256k1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp256k1 :y pkey1)) (sk2 (ironclad:make-private-key :secp256k1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp256k1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp256r1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp256r1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp256r1 :y pkey1)) (sk2 (ironclad:make-private-key :secp256r1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp256r1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp384r1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp384r1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp384r1 :y pkey1)) (sk2 (ironclad:make-private-key :secp384r1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp384r1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp521r1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp521r1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp521r1 :y pkey1)) (sk2 (ironclad:make-private-key :secp521r1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp521r1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defparameter *public-key-encryption-tests* (list (cons :rsa-oaep-encryption-test 'rsa-oaep-encryption-test) (cons :elgamal-encryption-test 'elgamal-encryption-test))) (defparameter *public-key-signature-tests* (list (cons :rsa-pss-signature-test 'rsa-pss-signature-test) (cons :elgamal-signature-test 'elgamal-signature-test) (cons :dsa-signature-test 'dsa-signature-test) (cons :ed25519-signature-test 'ed25519-signature-test) (cons :ed448-signature-test 'ed448-signature-test) (cons :secp256k1-signature-test 'secp256k1-signature-test) (cons :secp256r1-signature-test 'secp256r1-signature-test) (cons :secp384r1-signature-test 'secp384r1-signature-test) (cons :secp521r1-signature-test 'secp521r1-signature-test))) (defparameter *public-key-diffie-hellman-tests* (list (cons :curve25519-dh-test 'curve25519-dh-test) (cons :curve448-dh-test 'curve448-dh-test) (cons :elgamal-dh-test 'elgamal-dh-test) (cons :secp256k1-dh-test 'secp256k1-dh-test) (cons :secp256r1-dh-test 'secp256r1-dh-test) (cons :secp384r1-dh-test 'secp384r1-dh-test) (cons :secp521r1-dh-test 'secp521r1-dh-test))) ;;; authenticated encryption testing routines (defun aead-test (mode-name input ad output tag &rest args) (let* ((parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) (list :cipher-name (car args) :key (cadr args) :initialization-vector (caddr args))) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (ae (apply #'crypto:make-authenticated-encryption-mode mode-name parameters)) (ciphertext (crypto:encrypt-message ae input :associated-data ad))) (when (or (mismatch ciphertext output) (mismatch (crypto:produce-tag ae) tag)) (error "encryption failed for ~A, input ~A, output ~A" mode-name input output)) (setf parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) parameters) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (apply #'reinitialize-instance ae :tag tag parameters) (let ((plaintext (crypto:decrypt-message ae output :associated-data ad))) (when (or (mismatch plaintext input) (mismatch (crypto:produce-tag ae) tag)) (error "decryption failed for ~A, input ~A, output ~A" mode-name input output))))) (defun aead-test/incremental (mode-name input ad output tag &rest args) (let* ((parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) (list :cipher-name (car args) :key (cadr args) :initialization-vector (caddr args))) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (ae (apply #'crypto:make-authenticated-encryption-mode mode-name parameters)) (plaintext (make-array (length input) :element-type '(unsigned-byte 8))) (ciphertext (make-array (length output) :element-type '(unsigned-byte 8)))) (dotimes (i (length ad)) (crypto:process-associated-data ae ad :start i :end (1+ i))) (dotimes (i (length input)) (crypto:encrypt ae input ciphertext :plaintext-start i :plaintext-end (1+ i) :ciphertext-start i :handle-final-block (= i (1- (length input))))) (when (or (mismatch ciphertext output) (mismatch (crypto:produce-tag ae) tag)) (error "encryption failed for ~A, input ~A, output ~A" mode-name input output)) (setf parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) parameters) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (apply #'reinitialize-instance ae :tag tag parameters) (dotimes (i (length ad)) (crypto:process-associated-data ae ad :start i :end (1+ i))) (dotimes (i (length output)) (crypto:decrypt ae output plaintext :ciphertext-start i :ciphertext-end (1+ i) :plaintext-start i :handle-final-block (= i (1- (length output))))) (when (or (mismatch plaintext input) (mismatch (crypto:produce-tag ae) tag)) (error "decryption failed for ~A, input ~A, output ~A" mode-name input output)))) (defparameter *authenticated-encryption-tests* (list (cons :aead-test 'aead-test))) (defparameter *authenticated-encryption-incremental-tests* (list (cons :aead-test 'aead-test/incremental)))
null
https://raw.githubusercontent.com/sharplispers/ironclad/bf4a2366518b0fcaa3476b10e5d2d8ab33131355/testing/testfuns.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*- POSITION call, so declare SPEED high enough to trigger that. test vector files cipher testing encryption mode consistency checking digest testing routines Calling produce-digest twice should not give a wrong hash mac testing routines PRNG testing routines Public key testing routines authenticated encryption testing routines
(in-package :crypto-tests) (defun hex-string-to-byte-array (string &key (start 0) (end nil)) This function disappears from profiles if SBCL can inline the (declare (type string string) (optimize (speed 2))) (let* ((end (or end (length string))) (length (/ (- end start) 2)) (key (make-array length :element-type '(unsigned-byte 8)))) (declare (type (simple-array (unsigned-byte 8) (*)) key)) (flet ((char-to-digit (char) (declare (type base-char char)) (let ((x (cl:position char #.(coerce "0123456789abcdef" 'simple-base-string) :test #'char-equal))) (or x (error "Invalid hex key ~A specified" string))))) (loop for i from 0 for j from start below end by 2 do (setf (aref key i) (+ (* (char-to-digit (char string j)) 16) (char-to-digit (char string (1+ j))))) finally (return key))))) (defun test-vector-filename (ident) (merge-pathnames (make-pathname :directory '(:relative "test-vectors") :name (substitute #\- #\/ (format nil "~(~A~)" ident)) :type "testvec") #.*compile-file-pathname*)) (defun sharp-a (stream sub-char numarg) (declare (ignore sub-char numarg)) (crypto:ascii-string-to-byte-array (read stream t nil t))) (defun sharp-h (stream sub-char numarg) (declare (ignore sub-char numarg)) (hex-string-to-byte-array (read stream t nil t))) (defun run-test-vector-file (name function-map) (let ((filename (test-vector-filename name)) (*readtable* (copy-readtable))) (set-dispatch-macro-character #\# #\a #'sharp-a *readtable*) (set-dispatch-macro-character #\# #\h #'sharp-h *readtable*) (with-open-file (stream filename :direction :input :element-type 'character :if-does-not-exist :error) (loop for form = (read stream nil stream) until (eq form stream) do (cond ((not (listp form)) (error "Invalid form in test vector file ~A: ~A" filename form)) (t (let ((test-function (cdr (assoc (car form) function-map)))) (unless test-function (error "No test function defined for ~A" (car form))) (apply test-function name (cdr form))))) finally (return t))))) (defun cipher-test-guts (cipher-name mode key input output &optional extra-make-cipher-args) (let ((cipher (apply #'crypto:make-cipher cipher-name :key key :mode mode extra-make-cipher-args)) (scratch (copy-seq input))) (crypto:encrypt cipher input scratch) (when (mismatch scratch output) (error "encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output)) (apply #'reinitialize-instance cipher :key key extra-make-cipher-args) (crypto:decrypt cipher output scratch) (when (mismatch scratch input) (error "decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input)))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun cipher-stream-test-guts (cipher-name mode key input output &optional extra-args) (let* ((out-stream (crypto:make-octet-output-stream)) (enc-stream (apply #'crypto:make-encrypting-stream out-stream cipher-name mode key extra-args)) (in-stream (crypto:make-octet-input-stream output)) (dec-stream (apply #'crypto:make-decrypting-stream in-stream cipher-name mode key extra-args))) (write-byte (aref input 0) enc-stream) (write-sequence input enc-stream :start 1) (let ((result (crypto:get-output-stream-octets out-stream))) (when (mismatch result output) (error "stream encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output))) (let ((result (copy-seq output))) (setf (aref result 0) (read-byte dec-stream)) (read-sequence result dec-stream :start 1) (when (mismatch result input) (error "stream decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input))))) (defun ecb-mode-test (cipher-name hexkey hexinput hexoutput) (cipher-test-guts cipher-name :ecb hexkey hexinput hexoutput)) (defun ecb-tweak-mode-test (cipher-name hexkey hextweak hexinput hexoutput) (cipher-test-guts cipher-name :ecb hexkey hexinput hexoutput (list :tweak hextweak))) (defun stream-mode-test (cipher-name hexkey hexinput hexoutput) (cipher-test-guts cipher-name :stream hexkey hexinput hexoutput)) (defun stream-nonce-mode-test (cipher-name hexkey hexiv hexinput hexoutput) (cipher-test-guts cipher-name :stream hexkey hexinput hexoutput (list :initialization-vector hexiv))) (defun keystream-test (cipher-name key iv keystream) (let* ((mode (if (= 1 (crypto:block-length cipher-name)) :stream :ctr)) (cipher (crypto:make-cipher cipher-name :key key :mode mode :initialization-vector iv)) (buffer (make-array 1000 :element-type '(unsigned-byte 8) :initial-element 0))) (crypto:keystream-position cipher 100) (crypto:encrypt-in-place cipher buffer :start 100 :end 213) (crypto:keystream-position cipher 500) (crypto:encrypt-in-place cipher buffer :start 500 :end 1000) (crypto:keystream-position cipher 213) (crypto:encrypt-in-place cipher buffer :start 213 :end 500) (crypto:keystream-position cipher 0) (crypto:encrypt-in-place cipher buffer :end 100) (crypto:keystream-position cipher 765) (when (or (/= (crypto:keystream-position cipher) 765) (mismatch buffer keystream)) (error "getting/setting key stream position failed for ~A on key ~A" cipher-name key)))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun stream-mode-test/stream (cipher-name hexkey hexinput hexoutput) (cipher-stream-test-guts cipher-name :stream hexkey hexinput hexoutput)) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun stream-nonce-mode-test/stream (cipher-name hexkey hexiv hexinput hexoutput) (cipher-stream-test-guts cipher-name :stream hexkey hexinput hexoutput (list :initialization-vector hexiv))) (defparameter *cipher-tests* (list (cons :ecb-mode-test 'ecb-mode-test) (cons :ecb-tweak-mode-test 'ecb-tweak-mode-test) (cons :stream-mode-test 'stream-mode-test) (cons :stream-nonce-mode-test 'stream-nonce-mode-test) (cons :keystream-test 'keystream-test))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defparameter *cipher-stream-tests* (list (cons :ecb-mode-test 'ignore-test) (cons :ecb-tweak-mode-test 'ignore-test) (cons :stream-mode-test 'stream-mode-test/stream) (cons :stream-nonce-mode-test 'stream-nonce-mode-test/stream) (cons :keystream-test 'ignore-test))) tests from NIST (defun mode-test (mode cipher-name key iv input output) (labels ((frob-hex-string (cipher func input) (let ((scratch (copy-seq input))) (funcall func cipher input scratch) scratch)) (cipher-test (cipher func input output) (not (mismatch (frob-hex-string cipher func input) output)))) (let ((cipher (crypto:make-cipher cipher-name :key key :mode mode :initialization-vector iv))) (unless (cipher-test cipher 'crypto:encrypt input output) (error "encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output)) (reinitialize-instance cipher :key key :mode mode :initialization-vector iv) (unless (cipher-test cipher 'crypto:decrypt output input) (error "decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input))))) (defun mode-padding-test (mode cipher-name padding key iv input output) (let ((cipher (crypto:make-cipher cipher-name :key key :mode mode :initialization-vector iv :padding padding)) (buffer1 (make-array (length input) :element-type '(unsigned-byte 8))) (buffer2 (make-array (length output) :element-type '(unsigned-byte 8)))) (crypto:encrypt cipher input buffer2 :handle-final-block t) (when (mismatch buffer2 output) (error "encryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key input output)) (reinitialize-instance cipher :key key :mode mode :initialization-vector iv :padding padding) (crypto:decrypt cipher output buffer1 :handle-final-block t) (when (mismatch buffer1 input) (error "decryption failed for ~A on key ~A, input ~A, output ~A" cipher-name key output input)))) (defparameter *mode-tests* (list (cons :mode-test 'mode-test) (cons :mode-padding-test 'ignore-test))) (defparameter *mode-padding-tests* (list (cons :mode-test 'ignore-test) (cons :mode-padding-test 'mode-padding-test))) (defun digest-test/base (digest-name input expected-digest) (let ((result (crypto:digest-sequence digest-name input))) (when (mismatch result expected-digest) (error "one-shot ~A digest of ~S failed" digest-name input)))) (defun digest-test/incremental (digest-name input expected-digest) (loop with length = (length input) with digester = (crypto:make-digest digest-name) for i from 0 below length do (crypto:update-digest digester input :start i :end (1+ i)) finally (let ((result (crypto:produce-digest digester))) (when (mismatch result expected-digest) (error "incremental ~A digest of ~S failed" digest-name input))))) (defun digest-test/fill-pointer (digest-name octets expected-digest) (let* ((input (let ((x (make-array (* 2 (length octets)) :fill-pointer 0 :element-type '(unsigned-byte 8)))) (dotimes (i (length octets) x) (vector-push (aref octets i) x)))) (result (crypto:digest-sequence digest-name input))) (when (mismatch result expected-digest) (error "fill-pointer'd ~A digest of ~S failed" digest-name input)))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun digest-test/stream (digest-name input expected-digest) (let* ((stream (crypto:make-digesting-stream digest-name))) (when (plusp (length input)) (write-byte (aref input 0) stream) (write-sequence input stream :start 1)) (when (mismatch (crypto:produce-digest stream) expected-digest) (error "stream-y ~A digest of ~S failed" digest-name input)))) (defun digest-test/reinitialize-instance (digest-name input expected-digest) (let* ((digest (crypto:make-digest digest-name)) (result (progn (crypto:digest-sequence digest input) (crypto:digest-sequence (reinitialize-instance digest) input)))) (when (mismatch result expected-digest) (error "testing reinitialize-instance ~A digest of ~S failed" digest-name input)))) (defun digest-bit-test (digest-name leading byte trailing expected-digest) (let* ((input (let ((vector (make-array (+ 1 leading trailing) :element-type '(unsigned-byte 8) :initial-element 0))) (setf (aref vector leading) byte) vector)) (result (crypto:digest-sequence digest-name input))) (when (mismatch result expected-digest) (error "individual bit test ~A digest of (~D #x~2,'0X ~D) failed" digest-name leading byte trailing)))) (defun xof-digest-test (digest-name output-length input expected-digest) (let* ((digest (crypto:make-digest digest-name :output-length output-length)) (result (crypto:digest-sequence digest input))) (when (mismatch result expected-digest) (error "one-shot ~A xof digest of ~S failed" digest-name input)))) (defparameter *digest-tests* (list (cons :digest-test 'digest-test/base) (cons :digest-bit-test 'digest-bit-test) (cons :xof-digest-test 'xof-digest-test))) (defun ignore-test (&rest args) (declare (ignore args)) nil) (defparameter *digest-incremental-tests* (list (cons :digest-test 'digest-test/incremental) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) (defparameter *digest-fill-pointer-tests* (list (cons :digest-test 'digest-test/fill-pointer) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defparameter *digest-stream-tests* (list (cons :digest-test 'digest-test/stream) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) (defparameter *digest-reinitialize-instance-tests* (list (cons :digest-test 'digest-test/reinitialize-instance) (cons :digest-bit-test 'ignore-test) (cons :xof-digest-test 'ignore-test))) (defun mac-test/base (mac-name key data expected-digest &rest args) (let ((mac (apply #'crypto:make-mac mac-name key args))) (crypto:update-mac mac data) (let ((result (crypto:produce-mac mac))) (when (mismatch result expected-digest) (error "one-shot ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) (defun mac-test/incremental (mac-name key data expected-digest &rest args) (loop with length = (length data) with mac = (apply #'crypto:make-mac mac-name key args) for i from 0 below length do (crypto:update-mac mac data :start i :end (1+ i)) finally (let ((result (crypto:produce-mac mac))) (when (mismatch result expected-digest) (error "incremental ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defun mac-test/stream (mac-name key data expected-digest &rest args) (let ((stream (apply #'crypto:make-authenticating-stream mac-name key args))) (when (plusp (length data)) (write-byte (aref data 0) stream) (write-sequence data stream :start 1)) Calling produce - mac twice should not give a wrong MAC (let ((result (crypto:produce-mac stream))) (when (mismatch result expected-digest) (error "stream ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) (defun mac-test/reinitialize-instance (mac-name key data expected-digest &rest args) (let* ((mac (apply #'crypto:make-mac mac-name key args)) (result1 (progn (crypto:update-mac mac data) (crypto:produce-mac mac)))) (declare (ignorable result1)) (cond ((typep mac 'ironclad:gmac) (reinitialize-instance mac :key key :initialization-vector (car (last args)))) (t (reinitialize-instance mac :key key))) (let ((result2 (progn (crypto:update-mac mac data) (crypto:produce-mac mac)))) (when (mismatch result2 expected-digest) (error "testing reinitialize-instance ~A mac of ~A failed on key ~A, args ~A" mac-name data key args))))) (defparameter *mac-tests* (list (cons :mac-test 'mac-test/base))) (defparameter *mac-incremental-tests* (list (cons :mac-test 'mac-test/incremental))) #+(or lispworks sbcl cmucl openmcl allegro abcl ecl clisp) (defparameter *mac-stream-tests* (list (cons :mac-test 'mac-test/stream))) (defparameter *mac-reinitialize-instance-tests* (list (cons :mac-test 'mac-test/reinitialize-instance))) (defun fortuna-test (name seed entropy expected-sequence) (declare (ignore name)) (let ((prng (crypto:make-prng :fortuna :seed (coerce seed 'crypto::simple-octet-vector))) (num-bytes (length expected-sequence))) (loop for (source pool-id event) in entropy do (crypto:add-random-event source pool-id event prng)) (assert (equalp expected-sequence (crypto:random-data num-bytes prng))))) (defun generator-test (name cipher seeds expected-sequences) (declare (ignore name)) (let ((generator (make-instance 'crypto:fortuna-generator :cipher cipher))) (loop for seed in seeds do (crypto:prng-reseed (coerce seed '(vector (unsigned-byte 8))) generator)) (every (lambda (sequence) (assert (zerop (mod (length sequence) 16))) (assert (equalp sequence (crypto:random-data (length sequence) generator)))) expected-sequences))) (defparameter *prng-tests* `((:fortuna-test . ,'fortuna-test) (:generator-test . ,'generator-test))) (defun rsa-oaep-encryption-test (name n e d input seed output) Redefine oaep - encode to use a defined seed for the test instead of a random one (setf (symbol-function 'ironclad::oaep-encode) (lambda (digest-name message num-bytes &optional label) (let* ((digest-name (if (eq digest-name t) :sha1 digest-name)) (digest-len (ironclad:digest-length digest-name))) (assert (<= (length message) (- num-bytes (* 2 digest-len) 2))) (let* ((digest (ironclad:make-digest digest-name)) (label (or label (coerce #() '(vector (unsigned-byte 8))))) (padding-len (- num-bytes (length message) (* 2 digest-len) 2)) (padding (make-array padding-len :element-type '(unsigned-byte 8) :initial-element 0)) (l-hash (ironclad:digest-sequence digest label)) (db (concatenate '(vector (unsigned-byte 8)) l-hash padding #(1) message)) (db-mask (ironclad::mgf digest-name seed (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask)) (seed-mask (ironclad::mgf digest-name masked-db digest-len)) (masked-seed (map '(vector (unsigned-byte 8)) #'logxor seed seed-mask))) (concatenate '(vector (unsigned-byte 8)) #(0) masked-seed masked-db))))) (let* ((pk (ironclad:make-public-key :rsa :n n :e e)) (sk (ironclad:make-private-key :rsa :n n :d d)) (c (ironclad:encrypt-message pk input :oaep t)) (m (ironclad:decrypt-message sk output :oaep t))) (when (mismatch c output) (error "encryption failed for ~A on pkey (~A ~A), input ~A, output ~A" name n e input output)) (when (mismatch m input) (error "decryption failed for ~A on skey (~A ~A), input ~A, output ~A" name n d input output)))) (defun elgamal-encryption-test (name p g x y input k output) (let* ((ironclad::*signature-nonce-for-test* k) (pk (ironclad:make-public-key :elgamal :p p :g g :y y)) (sk (ironclad:make-private-key :elgamal :p p :g g :x x :y y)) (c (ironclad:encrypt-message pk input)) (m (ironclad:decrypt-message sk output))) (when (mismatch c output) (error "encryption failed for ~A on pkey (~A ~A ~A), input ~A, output ~A" name p g y input output)) (when (mismatch m input) (error "decryption failed for ~A on skey (~A ~A ~A ~A), input ~A, output ~A" name p g x y input output)))) (defun rsa-pss-signature-test (name n e d input salt signature) Redefine pss - encode to use a defined salt for the test instead of a random one (setf (symbol-function 'ironclad::pss-encode) (lambda (digest-name message num-bytes) (let* ((digest-name (if (eq digest-name t) :sha1 digest-name)) (digest-len (ironclad:digest-length digest-name))) (assert (>= num-bytes (+ (* 2 digest-len) 2))) (let* ((m-hash (ironclad:digest-sequence digest-name message)) (m1 (concatenate '(vector (unsigned-byte 8)) #(0 0 0 0 0 0 0 0) m-hash salt)) (h (ironclad:digest-sequence digest-name m1)) (ps (make-array (- num-bytes (* 2 digest-len) 2) :element-type '(unsigned-byte 8) :initial-element 0)) (db (concatenate '(vector (unsigned-byte 8)) ps #(1) salt)) (db-mask (ironclad::mgf digest-name h (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask))) (setf (ldb (byte 1 7) (elt masked-db 0)) 0) (concatenate '(vector (unsigned-byte 8)) masked-db h #(188)))))) (let* ((pk (ironclad:make-public-key :rsa :n n :e e)) (sk (ironclad:make-private-key :rsa :n n :d d)) (s (ironclad:sign-message sk input :pss t))) (when (mismatch s signature) (error "signature failed for ~A on skey (~A ~A), input ~A, signature ~A" name n d input signature)) (unless (ironclad:verify-signature pk input signature :pss t) (error "signature verification failed for ~A on pkey (~A ~A), input ~A, signature ~A" name n e input signature)))) (defun elgamal-signature-test (name p g x y input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (pk (ironclad:make-public-key :elgamal :p p :g g :y y)) (sk (ironclad:make-private-key :elgamal :p p :g g :x x :y y)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey (~A ~A ~A ~A), input ~A, signature ~A" name p g x y input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey (~A ~A ~A), input ~A, signature ~A" name p g y input signature)))) (defun dsa-signature-test (name p q g x y input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :dsa :p p :q q :g g :x x :y y)) (pk (ironclad:make-public-key :dsa :p p :q q :g g :y y)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey (~A ~A ~A ~A ~A), input ~A, signature ~A" name p q g x y input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey (~A ~A ~A ~A), input ~A, signature ~A" name p q g y input signature)))) (defun ed25519-signature-test (name skey pkey input signature) (let* ((sk (ironclad:make-private-key :ed25519 :x skey :y pkey)) (pk (ironclad:make-public-key :ed25519 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun ed448-signature-test (name skey pkey input signature) (let* ((sk (ironclad:make-private-key :ed448 :x skey :y pkey)) (pk (ironclad:make-public-key :ed448 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp256k1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp256k1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp256k1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp256r1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp256r1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp256r1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp384r1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp384r1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp384r1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun secp521r1-signature-test (name skey pkey input k signature) (let* ((ironclad::*signature-nonce-for-test* k) (sk (ironclad:make-private-key :secp521r1 :x skey :y pkey)) (pk (ironclad:make-public-key :secp521r1 :y pkey)) (s (ironclad:sign-message sk input))) (when (mismatch s signature) (error "signature failed for ~A on skey ~A, input ~A, signature ~A" name skey input signature)) (unless (ironclad:verify-signature pk input signature) (error "signature verification failed for ~A on pkey ~A, input ~A, signature ~A" name pkey input signature)))) (defun curve25519-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :curve25519 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :curve25519 :y pkey1)) (sk2 (ironclad:make-private-key :curve25519 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :curve25519 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun curve448-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :curve448 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :curve448 :y pkey1)) (sk2 (ironclad:make-private-key :curve448 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :curve448 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun elgamal-dh-test (name p g skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :elgamal :p p :g g :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :elgamal :p p :g g :y pkey1)) (sk2 (ironclad:make-private-key :elgamal :p p :g g :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :elgamal :p p :g g :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp256k1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp256k1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp256k1 :y pkey1)) (sk2 (ironclad:make-private-key :secp256k1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp256k1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp256r1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp256r1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp256r1 :y pkey1)) (sk2 (ironclad:make-private-key :secp256r1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp256r1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp384r1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp384r1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp384r1 :y pkey1)) (sk2 (ironclad:make-private-key :secp384r1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp384r1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defun secp521r1-dh-test (name skey1 pkey1 skey2 pkey2 shared-secret) (let* ((sk1 (ironclad:make-private-key :secp521r1 :x skey1 :y pkey1)) (pk1 (ironclad:make-public-key :secp521r1 :y pkey1)) (sk2 (ironclad:make-private-key :secp521r1 :x skey2 :y pkey2)) (pk2 (ironclad:make-public-key :secp521r1 :y pkey2)) (ss1 (ironclad:diffie-hellman sk1 pk2)) (ss2 (ironclad:diffie-hellman sk2 pk1))) (when (mismatch ss1 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey1 pkey2 shared-secret)) (when (mismatch ss2 shared-secret) (error "shared secret computation failed for ~A on skey ~A, pkey ~A, secret ~A" name skey2 pkey1 shared-secret)))) (defparameter *public-key-encryption-tests* (list (cons :rsa-oaep-encryption-test 'rsa-oaep-encryption-test) (cons :elgamal-encryption-test 'elgamal-encryption-test))) (defparameter *public-key-signature-tests* (list (cons :rsa-pss-signature-test 'rsa-pss-signature-test) (cons :elgamal-signature-test 'elgamal-signature-test) (cons :dsa-signature-test 'dsa-signature-test) (cons :ed25519-signature-test 'ed25519-signature-test) (cons :ed448-signature-test 'ed448-signature-test) (cons :secp256k1-signature-test 'secp256k1-signature-test) (cons :secp256r1-signature-test 'secp256r1-signature-test) (cons :secp384r1-signature-test 'secp384r1-signature-test) (cons :secp521r1-signature-test 'secp521r1-signature-test))) (defparameter *public-key-diffie-hellman-tests* (list (cons :curve25519-dh-test 'curve25519-dh-test) (cons :curve448-dh-test 'curve448-dh-test) (cons :elgamal-dh-test 'elgamal-dh-test) (cons :secp256k1-dh-test 'secp256k1-dh-test) (cons :secp256r1-dh-test 'secp256r1-dh-test) (cons :secp384r1-dh-test 'secp384r1-dh-test) (cons :secp521r1-dh-test 'secp521r1-dh-test))) (defun aead-test (mode-name input ad output tag &rest args) (let* ((parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) (list :cipher-name (car args) :key (cadr args) :initialization-vector (caddr args))) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (ae (apply #'crypto:make-authenticated-encryption-mode mode-name parameters)) (ciphertext (crypto:encrypt-message ae input :associated-data ad))) (when (or (mismatch ciphertext output) (mismatch (crypto:produce-tag ae) tag)) (error "encryption failed for ~A, input ~A, output ~A" mode-name input output)) (setf parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) parameters) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (apply #'reinitialize-instance ae :tag tag parameters) (let ((plaintext (crypto:decrypt-message ae output :associated-data ad))) (when (or (mismatch plaintext input) (mismatch (crypto:produce-tag ae) tag)) (error "decryption failed for ~A, input ~A, output ~A" mode-name input output))))) (defun aead-test/incremental (mode-name input ad output tag &rest args) (let* ((parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) (list :cipher-name (car args) :key (cadr args) :initialization-vector (caddr args))) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (ae (apply #'crypto:make-authenticated-encryption-mode mode-name parameters)) (plaintext (make-array (length input) :element-type '(unsigned-byte 8))) (ciphertext (make-array (length output) :element-type '(unsigned-byte 8)))) (dotimes (i (length ad)) (crypto:process-associated-data ae ad :start i :end (1+ i))) (dotimes (i (length input)) (crypto:encrypt ae input ciphertext :plaintext-start i :plaintext-end (1+ i) :ciphertext-start i :handle-final-block (= i (1- (length input))))) (when (or (mismatch ciphertext output) (mismatch (crypto:produce-tag ae) tag)) (error "encryption failed for ~A, input ~A, output ~A" mode-name input output)) (setf parameters (case mode-name ((:gcm gcm crypto:gcm :eax eax crypto:eax) parameters) ((:etm etm crypto:etm) (destructuring-bind (cipher-name ckey mode iv mac-name mkey mparam) args (let ((cipher (crypto:make-cipher cipher-name :key ckey :mode mode :initialization-vector iv)) (mac (if mparam (crypto:make-mac mac-name mkey mparam) (crypto:make-mac mac-name mkey)))) (list :cipher cipher :mac mac)))))) (apply #'reinitialize-instance ae :tag tag parameters) (dotimes (i (length ad)) (crypto:process-associated-data ae ad :start i :end (1+ i))) (dotimes (i (length output)) (crypto:decrypt ae output plaintext :ciphertext-start i :ciphertext-end (1+ i) :plaintext-start i :handle-final-block (= i (1- (length output))))) (when (or (mismatch plaintext input) (mismatch (crypto:produce-tag ae) tag)) (error "decryption failed for ~A, input ~A, output ~A" mode-name input output)))) (defparameter *authenticated-encryption-tests* (list (cons :aead-test 'aead-test))) (defparameter *authenticated-encryption-incremental-tests* (list (cons :aead-test 'aead-test/incremental)))
f11ab9251201b2adee416f8c95c0188f8d426965b4a06eb187673f8a7842f9c6
Frama-C/Frama-C-snapshot
sign_domain.mli
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (** Abstraction of the sign of integer variables. *) include Abstract_domain.Leaf with type value = Sign_value.t and type location = Precise_locs.precise_location
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/domains/sign_domain.mli
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * Abstraction of the sign of integer variables.
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . include Abstract_domain.Leaf with type value = Sign_value.t and type location = Precise_locs.precise_location
eaf5eb53e173a4f60f91d21a38e836e304e235df79bae77e101d0e6ff09a7665
haskell/cabal
ForeignLibOption.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} module Distribution.Types.ForeignLibOption( ForeignLibOption(..) ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Pretty import Distribution.Parsec import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp data ForeignLibOption = -- | Merge in all dependent libraries (i.e., use -- @ghc -shared -static@ rather than just record -- the dependencies, ala @ghc -shared -dynamic@). This option is compulsory on Windows and unsupported -- on other platforms. ForeignLibStandalone deriving (Generic, Show, Read, Eq, Ord, Typeable, Data) instance Pretty ForeignLibOption where pretty ForeignLibStandalone = Disp.text "standalone" instance Parsec ForeignLibOption where parsec = do name <- P.munch1 (\c -> isAlphaNum c || c == '-') case name of "standalone" -> return ForeignLibStandalone _ -> fail "unrecognized foreign-library option" instance Binary ForeignLibOption instance Structured ForeignLibOption instance NFData ForeignLibOption where rnf = genericRnf
null
https://raw.githubusercontent.com/haskell/cabal/23536274bb7baabe5c33140620471e897cf34cf2/Cabal-syntax/src/Distribution/Types/ForeignLibOption.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE OverloadedStrings # | Merge in all dependent libraries (i.e., use @ghc -shared -static@ rather than just record the dependencies, ala @ghc -shared -dynamic@). on other platforms.
# LANGUAGE DeriveGeneric # module Distribution.Types.ForeignLibOption( ForeignLibOption(..) ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Pretty import Distribution.Parsec import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp data ForeignLibOption = This option is compulsory on Windows and unsupported ForeignLibStandalone deriving (Generic, Show, Read, Eq, Ord, Typeable, Data) instance Pretty ForeignLibOption where pretty ForeignLibStandalone = Disp.text "standalone" instance Parsec ForeignLibOption where parsec = do name <- P.munch1 (\c -> isAlphaNum c || c == '-') case name of "standalone" -> return ForeignLibStandalone _ -> fail "unrecognized foreign-library option" instance Binary ForeignLibOption instance Structured ForeignLibOption instance NFData ForeignLibOption where rnf = genericRnf
8dc0e99f5bd5fbb29fdd8cea676d4031da9f362e2a656210222d68eab6b08e44
emqx/emqx
emqx_logger_textfmt.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_logger_textfmt). -export([format/2]). -export([check_config/1]). -export([try_format_unicode/1]). check_config(X) -> logger_formatter:check_config(X). format(#{msg := {report, ReportMap}, meta := Meta} = Event, Config) when is_map(ReportMap) -> ReportList = enrich_report(ReportMap, Meta), Report = case is_list_report_acceptable(Meta) of true -> ReportList; false -> maps:from_list(ReportList) end, logger_formatter:format(Event#{msg := {report, Report}}, Config); format(#{msg := {string, String}} = Event, Config) -> format(Event#{msg => {"~ts ", [String]}}, Config); %% trace format(#{msg := Msg0, meta := Meta} = Event, Config) -> Msg1 = enrich_client_info(Msg0, Meta), Msg2 = enrich_mfa(Msg1, Meta), Msg3 = enrich_topic(Msg2, Meta), logger_formatter:format(Event#{msg := Msg3}, Config). is_list_report_acceptable(#{report_cb := Cb}) -> Cb =:= fun logger:format_otp_report/1 orelse Cb =:= fun logger:format_report/1; is_list_report_acceptable(_) -> false. enrich_report(ReportRaw, Meta) -> clientid and peername always in emqx_conn 's process metadata . %% topic can be put in meta using ?SLOG/3, or put in msg's report by ?SLOG/2 Topic = case maps:get(topic, Meta, undefined) of undefined -> maps:get(topic, ReportRaw, undefined); Topic0 -> Topic0 end, ClientId = maps:get(clientid, Meta, undefined), Peer = maps:get(peername, Meta, undefined), MFA = maps:get(mfa, Meta, undefined), Line = maps:get(line, Meta, undefined), Msg = maps:get(msg, ReportRaw, undefined), %% turn it into a list so that the order of the fields is determined lists:foldl( fun ({_, undefined}, Acc) -> Acc; (Item, Acc) -> [Item | Acc] end, maps:to_list(maps:without([topic, msg, clientid], ReportRaw)), [ {topic, try_format_unicode(Topic)}, {clientid, try_format_unicode(ClientId)}, {peername, Peer}, {line, Line}, {mfa, mfa(MFA)}, {msg, Msg} ] ). try_format_unicode(undefined) -> undefined; try_format_unicode(Char) -> List = try case unicode:characters_to_list(Char) of {error, _, _} -> error; {incomplete, _, _} -> error; Binary -> Binary end catch _:_ -> error end, case List of error -> io_lib:format("~0p", [Char]); _ -> List end. enrich_mfa({Fmt, Args}, #{mfa := Mfa, line := Line}) when is_list(Fmt) -> {Fmt ++ " mfa: ~ts line: ~w", Args ++ [mfa(Mfa), Line]}; enrich_mfa(Msg, _) -> Msg. enrich_client_info({Fmt, Args}, #{clientid := ClientId, peername := Peer}) when is_list(Fmt) -> {" ~ts@~ts " ++ Fmt, [ClientId, Peer | Args]}; enrich_client_info({Fmt, Args}, #{clientid := ClientId}) when is_list(Fmt) -> {" ~ts " ++ Fmt, [ClientId | Args]}; enrich_client_info({Fmt, Args}, #{peername := Peer}) when is_list(Fmt) -> {" ~ts " ++ Fmt, [Peer | Args]}; enrich_client_info(Msg, _) -> Msg. enrich_topic({Fmt, Args}, #{topic := Topic}) when is_list(Fmt) -> {" topic: ~ts" ++ Fmt, [Topic | Args]}; enrich_topic(Msg, _) -> Msg. mfa(undefined) -> undefined; mfa({M, F, A}) -> [atom_to_list(M), ":", atom_to_list(F), "/" ++ integer_to_list(A)].
null
https://raw.githubusercontent.com/emqx/emqx/73d5592b5af0cbbf347e5dc2b9b865b41228249f/apps/emqx/src/emqx_logger_textfmt.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. -------------------------------------------------------------------- trace topic can be put in meta using ?SLOG/3, or put in msg's report by ?SLOG/2 turn it into a list so that the order of the fields is determined
Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_logger_textfmt). -export([format/2]). -export([check_config/1]). -export([try_format_unicode/1]). check_config(X) -> logger_formatter:check_config(X). format(#{msg := {report, ReportMap}, meta := Meta} = Event, Config) when is_map(ReportMap) -> ReportList = enrich_report(ReportMap, Meta), Report = case is_list_report_acceptable(Meta) of true -> ReportList; false -> maps:from_list(ReportList) end, logger_formatter:format(Event#{msg := {report, Report}}, Config); format(#{msg := {string, String}} = Event, Config) -> format(Event#{msg => {"~ts ", [String]}}, Config); format(#{msg := Msg0, meta := Meta} = Event, Config) -> Msg1 = enrich_client_info(Msg0, Meta), Msg2 = enrich_mfa(Msg1, Meta), Msg3 = enrich_topic(Msg2, Meta), logger_formatter:format(Event#{msg := Msg3}, Config). is_list_report_acceptable(#{report_cb := Cb}) -> Cb =:= fun logger:format_otp_report/1 orelse Cb =:= fun logger:format_report/1; is_list_report_acceptable(_) -> false. enrich_report(ReportRaw, Meta) -> clientid and peername always in emqx_conn 's process metadata . Topic = case maps:get(topic, Meta, undefined) of undefined -> maps:get(topic, ReportRaw, undefined); Topic0 -> Topic0 end, ClientId = maps:get(clientid, Meta, undefined), Peer = maps:get(peername, Meta, undefined), MFA = maps:get(mfa, Meta, undefined), Line = maps:get(line, Meta, undefined), Msg = maps:get(msg, ReportRaw, undefined), lists:foldl( fun ({_, undefined}, Acc) -> Acc; (Item, Acc) -> [Item | Acc] end, maps:to_list(maps:without([topic, msg, clientid], ReportRaw)), [ {topic, try_format_unicode(Topic)}, {clientid, try_format_unicode(ClientId)}, {peername, Peer}, {line, Line}, {mfa, mfa(MFA)}, {msg, Msg} ] ). try_format_unicode(undefined) -> undefined; try_format_unicode(Char) -> List = try case unicode:characters_to_list(Char) of {error, _, _} -> error; {incomplete, _, _} -> error; Binary -> Binary end catch _:_ -> error end, case List of error -> io_lib:format("~0p", [Char]); _ -> List end. enrich_mfa({Fmt, Args}, #{mfa := Mfa, line := Line}) when is_list(Fmt) -> {Fmt ++ " mfa: ~ts line: ~w", Args ++ [mfa(Mfa), Line]}; enrich_mfa(Msg, _) -> Msg. enrich_client_info({Fmt, Args}, #{clientid := ClientId, peername := Peer}) when is_list(Fmt) -> {" ~ts@~ts " ++ Fmt, [ClientId, Peer | Args]}; enrich_client_info({Fmt, Args}, #{clientid := ClientId}) when is_list(Fmt) -> {" ~ts " ++ Fmt, [ClientId | Args]}; enrich_client_info({Fmt, Args}, #{peername := Peer}) when is_list(Fmt) -> {" ~ts " ++ Fmt, [Peer | Args]}; enrich_client_info(Msg, _) -> Msg. enrich_topic({Fmt, Args}, #{topic := Topic}) when is_list(Fmt) -> {" topic: ~ts" ++ Fmt, [Topic | Args]}; enrich_topic(Msg, _) -> Msg. mfa(undefined) -> undefined; mfa({M, F, A}) -> [atom_to_list(M), ":", atom_to_list(F), "/" ++ integer_to_list(A)].
7477158b3dfda5f2fe3c3e6a36482526a3f9384bda6a113e00823ca772cfea29
zhongwencool/mipush
mipush.erl
%%%------------------------------------------------------------------- %%%------------------------------------------------------------------- -module(mipush). -author(''). -include("mipush.hrl"). -define(MAX_TOPIC_LEN, 5). %% API -export([connect/1]). -export([disconnect/1]). %% 推送单条消息 -export([push_to_regid/4]). -export([push_to_alias/4]). -export([push_to_account/4]). -export([push_to_topic/4]). -export([push_to_multi_topic/5]). -export([push_to_all/3]). %%推送多条消息 -export([multi_msg_to_regids/5]). -export([multi_msg_to_alias/5]). -export([multi_msg_to_account/5]). -export([get_msg_count_info/5]). -export([get_msg_status/4]). -export([get_msgs_status/4]). -export([get_invalid_regids/2]). -export([subscribe_topic/6]). -export([unsubscribe_topic/5]). -export([get_all_topic/4]). -export([unsubscribe_alias/6]). -export([subscribe_alias/6]). -export([get_all_alias/4]). %% Job 操作 -export([check_schedule_job_exist/3]). -export([del_schedule_job/3]). %% Util -export([milliseconds_utc_since_1970/1]). -type url() :: nonempty_string(). -type year() ::2000..10000. -type month() :: 1..12. -type day() :: 1..31. -type hour() :: 1..24. -type minute() :: 0..59. -type second() :: 0..59. -type milliseconds() :: non_neg_integer(). -type date() :: {year(), month(), day()}. -export_type([hour/0, minute/0, second/0, milliseconds/0, date/0]). -type registration_id() :: binary()| string(). -type alias() :: string()| binary(). -type account() :: string()| binary(). -export_type([account/0, alias/0]). -export_type([registration_id/0]). -type push_msg() :: android_push_msg() | ios_push_msg(). -export_type([push_msg/0]). -type android_push_msg() :: #{payload => nonempty_string(), %%消息的内容.(注意:需要对payload字符串做urlencode处理) , packageName必须和开发者网站上申请的结果一致 0 表示通知栏消息 1 表示透传消息 description => string(), %%通知栏展示的通知的描述 notify_type => string(), %%可以是DEFAULT_ALL或者以下其他几种的OR组合 以上为必填项 , 以下为可选项 可选项 , 如果用户离线 , 设置消息在服务器保存的时间 , 单位 : ms . 服务器默认最长保留两周:1209600000 time_to_live => 1..1209600000, 可选项 , 定时发送消息 . , 用自1970年1月1日以来00:00:00.0 UTC时间表示(毫秒 ) time_to_send => pos_integer(), 可选项 , 默认情况下 , 通知栏只显示一条推送消息 . 如果通知栏要显示多条推送消息 , 需要针对不同的消息设置不同的notify_id %%相同notify_id的通知栏消息会覆盖之前的 notify_id => pos_integer(), 可选项 , 自定义通知栏消息铃声 . extra.sound_uri的值设置为铃声的URI , , %%如:"android.resource"铃声只能使用当前app内的资源, URI格式满足 android.resource packagename / XXX / XXX , 铃声文件放在Android app的raw目录下 'extra.sound_uri' => nonempty_string(), 可选项 , , 如 : " 我是滚动的文字 " 'extra.ticker' => string(), %%可选项, 开启/关闭app在前台时的通知弹出. %%当extra.notify_foreground值为”1″时, app会弹出通知栏消息; %%当extra.notify_foreground值为”0″时, app不会弹出通知栏消息。注: 默认情况下会弹出通知栏消息 'extra.notify_foreground' => string(), 可选项 , . 通过设置extra.notify_effect的值以得到不同的预定义点击行为 %%"1"通知栏点击后打开app的Launcher Activity %%"2":通知栏点击后打开app的任一Activity(还需要传入extra.intent_uri) " 3":通知栏点击后打开网页(还需要传入extra.web_uri ) 'extra.notify_effect' => string(), %% 可选项"intent:#Intent;component=com.yourpackage/.YourActivity;end" 'extra.intent_uri' => string(), %%可选项 "" 'extra.web_uri' => url(), 可选项 , 控制是否需要进行平缓发送(qps less 1000 / second)默认不支持 0 表示不支持平缓发送 1 表示支持平缓发送 'extra.flow_control' => integer(), 可选项 , 自定义通知栏样式 , 如"custom_notify " 'extra.layout_name' => nonempty_string(), 可选项 , 自定义通知栏样式 , 必须与layout_name一同使用 , %%指定layout中各控件展示的内容 如"{\"text\": {\"titleText\":\"标题\"}, \"image\": {\"iconImage\": \"icon\"}" 'extra.layout_value' => nonempty_string(), 可选项 , 使用推送批次(JobKey)功能聚合消息 . , 即相同jobkey的消息只展示第一条 , . 合法的jobkey由数字([0 - 9 ] ) %%大小写字母([a-zA-Z]), 下划线(_)和中划线(-)组成, 长度不大于8个字符 'extra.jobkey' => nonempty_string(), 可选项 , 开启消息送达和点击回执 . 将extra.callback的值设置为第三方接收回执的http接口 %%小米推送服务器每隔1s将已送达或已点击的消息ID和对应设备的regid或alias %%通过调用第三方http接口传给开发者. %%每次调用后, 小米推送服务器会清空这些数据. %%下次传给开发者将是新一拨数据。注:消息的送达回执只支持单发消息. 'extra.callback' => url(), 可选项 , 可以接收消息的设备的语言范围 , 用逗号分隔 , 如 : 中国大陆用"zh_CN " 'extra.locale' => nonempty_string(), 可选项 , , 逗号分隔 'extra.locale_not_in' => nonempty_string(), %%可选项, 对应不同品牌的手机或手机价格范畴 'extra.model' => nonempty_string(), 可选项 , 无法收到消息的设备的机型范围 , 逗号分隔 'extra.model_not_in' => nonempty_string(), 可选项 , 可以接收消息的app版本号 , 用逗号分割 , %%安卓app版本号来源于manifest文件中的”android:versionName”的值. %%注: 目前支持MiPush_SDK_Client_2_2_12_sdk.jar(及以后)的版本. 'extra.app_version' => nonempty_string(), 可选项 , 无法接收消息的app版本号 , 用逗号分割 'extra.app_version_not_in' => nonempty_string(), %%可选项, 指定在特定的网络环境下才能接收到消息 目前仅支持指定”wifi” 'extra.connpt' => nonempty_string() }. -type ios_push_msg() :: #{description => nonempty_string(), %%通知栏展示的通知的 以上为必填项 , 以下为可选项 可选项 , 如果用户离线 , 设置消息在服务器保存的时间 , 单位 : ms . time_to_live => non_neg_integer(), 可选项 , 定时发送消息 . 用自1970年1月1日以来00:00:00.0 UTC时间表示(以毫秒为单位的时间 ) . 注 : time_to_send => non_neg_integer(), 可选项 , 自定义消息铃声 . , default为系统默认声音 'extra.sound_url' => string(), %%可选项.通知角标 'extra.badge' => non_neg_integer(), 可选项 . 'extra.category' => non_neg_integer() }. -type connection() :: #{host => nonempty_string(), port => pos_integer(), ssl_opts => list(), timeout => pos_integer(), expires => pos_integer(), expires_conn => pos_integer(), socket => any(), err_callback => fun((binary()) -> stop | _) }. -export_type([connection/0]). %% <<"code">>|<<"data">>|<<"description">>|<<"info">>|<<"result">>|<<"trace_id">> -type result() :: #{binary() => any()}. -export_type([result/0]). -spec connect(connection()) -> {ok, pid()} | {error, {already_started, pid()}} | {error, Reason::term()}. connect(Connection = #{}) -> mipush_sup:start_connection(merge_connection(Connection)). -spec disconnect(pid()) -> ok|result(). disconnect(ConnId) -> mipush_connection:stop(ConnId). %% =================================================================== %%推送单条消息 %% =================================================================== %% @doc 向某个regid或一组regid列表推送某条消息 -spec push_to_regid(pid(), [registration_id(), ...], push_msg(), return|no_return)-> ok|result(). push_to_regid(ConnID, RegIDs = [_|_], PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{registration_id => join(RegIDs, ", ")}, Req = {"POST", MsgType, mipush_connection:build_request(?REGID_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 向某个alias或一组alias列表推送某条消息 -spec push_to_alias(pid(), [alias(), ...], push_msg(), return|no_return) -> ok|result(). push_to_alias(ConnID, Alias = [_|_], PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{alias => join(Alias, ", ")}, Req = {"POST", MsgType, mipush_connection:build_request(?ALIAS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 向某个account或一组account列表推送某条消息 restapi没有提供设置account的接口,所以只能通过客户端做 -spec push_to_account(pid(), [account(), ...], push_msg(), return|no_return) -> ok|result(). push_to_account(ConnID, Accounts = [_|_], PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{user_account => join(Accounts, ", ")}, Req = {"POST", MsgType, mipush_connection:build_request(?ACCOUNTS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 向某个topic推送某条消息 -spec push_to_topic(pid(), nonempty_string(), push_msg(), return|no_return) -> ok|result(). push_to_topic(ConnID, Topic, PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{topic => Topic}, Req = {"POST", MsgType, mipush_connection:build_request(?TOPIC_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 向所有设备推送某条消息 -spec push_to_all(pid(), push_msg(), return|no_return) -> ok|result(). push_to_all(ConnID, PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Req = {"POST", MsgType, mipush_connection:build_request(?ALL_PUSH_URL, NewPushMsg)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 向多个topic推送单条消息 -spec push_to_multi_topic(pid(), [string(), ...], string(), push_msg(), return|no_return) -> ok|{error, any()}. push_to_multi_topic(ConnID, Topics, OP, PushMsg, ReturnType)-> case check_topic(Topics, OP) of ok -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{topics => join(Topics, ":$")}, Req = {"POST", MsgType, mipush_connection:build_request(?MULTI_TOPIC_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result); {error, Reason} -> {error, Reason} end. %% =================================================================== %%推送多条消息 %% =================================================================== %% @doc 针对不同的regid推送不同的消息 -spec multi_msg_to_regids(pid(), ios|android, [{registration_id(), push_msg()}, ...], non_neg_integer(), return|no_return) -> ok|result(). multi_msg_to_regids(ConnID, MsgType, Msgs, TimeToSend, ReturnType)when is_integer(TimeToSend) -> Query = case TimeToSend == 0 of true -> #{messages => jsx:encode(transform_extra(Msgs))}; false -> #{messages => jsx:encode(transform_extra(Msgs)), time_to_send => TimeToSend} end, Req = {"POST", MsgType, mipush_connection:build_request(?REGIDS_MSGS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). @doc 针对不同的alias推送不同的消息 -spec multi_msg_to_alias(pid(), ios|android, [{alias(), push_msg()}, ...], non_neg_integer(), return|no_return) -> ok|result(). multi_msg_to_alias(ConnID, MsgType, Msgs, TimeToSend, ReturnType) when is_integer(TimeToSend) -> Query = case TimeToSend == 0 of true -> #{messages => jsx:encode(transform_extra(Msgs))}; false -> #{messages => jsx:encode(transform_extra(Msgs)), time_to_send => TimeToSend} end, Req = {"POST", MsgType, mipush_connection:build_request(?ALIAS_MSGS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 针对不同的userAccount推送不同的消息 -spec multi_msg_to_account(pid(), ios|android, [{account(), push_msg()}, ...], non_neg_integer(), return|no_return) -> ok|result(). multi_msg_to_account(ConnID, MsgType, Msgs, TimeToSend, ReturnType)when is_integer(TimeToSend) -> Query = case TimeToSend == 0 of true -> #{message => jsx:encode(transform_extra(Msgs))}; false -> #{message => jsx:encode(transform_extra(Msgs)), time_to_send => TimeToSend} end, Req = {"POST", MsgType, mipush_connection:build_request(?ACCOUNT_MSGS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% =================================================================== %% =================================================================== %% @doc 获取消息的统计数据 -spec get_msg_count_info(pid(), ios|android, date(), date(), string()) -> result(). get_msg_count_info(ConnID, MsgType, StartDate, EndDate, APPName) -> Query = #{start_date => format_date(StartDate), end_date => format_date(EndDate), restricted_package_name => APPName}, Req = {"GET", MsgType, mipush_connection:build_request(?MSG_COUNTER_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). %% @doc 追踪消息的状态 -spec get_msg_status(pid(), ios|android, 'msg_id'|'job_key', string()) -> result(). get_msg_status(ConnID, MsgType, Type, Value) -> Query = maps:put(Type, Value, #{}), Req = {"GET", MsgType, mipush_connection:build_request(?MSG_STATUS, Query)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). -spec get_msgs_status(pid(), ios|android, non_neg_integer(), non_neg_integer()) -> result(). get_msgs_status(ConnID, MsgType, BeginTime, EndTime) -> Query = #{begin_time => BeginTime, end_time => EndTime}, Req = {"GET", MsgType, mipush_connection:build_request(?MSGS_STATUS, Query)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). %% @doc 获取失效的regId列表 获取失效的regId列表,每次请求最多返回1000个regId 。 每次请求之后,成功返回的失效的regId将会从MiPush数据库删除 。 -spec get_invalid_regids(pid(), ios|android) -> list(). get_invalid_regids(ConnID, MsgType) -> Req = {"GET", MsgType, mipush_connection:build_request(?INVALID_REGIDS_URL, [])}, mipush_connection:send_message(ConnID, Req, return). %% =================================================================== %%订阅 topic/alias %% =================================================================== @doc 订阅RegId的标签 -spec subscribe_topic(pid(), ios|android, registration_id(), string(), 'undefined'|string(), return|no_return) -> ok|result(). subscribe_topic(ConnID, MsgType, RegisterID, Topic, Category, ReturnType) -> Querys = case Category of undefined -> #{registration_id => RegisterID, topic => Topic}; _ -> #{registration_id => RegisterID, topic => Topic, category => Category} end, Req = {"POST", MsgType, mipush_connection:build_request(?SUB_TOPIC_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). @doc , -spec unsubscribe_topic(pid(), ios|android, registration_id(), string(), return|no_return) -> ok|result(). unsubscribe_topic(ConnID, MsgType, RegisterID, Topic, ReturnType) -> Querys = #{registration_id => RegisterID, topic => Topic}, Req = {"POST", MsgType, mipush_connection:build_request(?UNSUB_TOPIC_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 获取一个应用的某个用户目前订阅的所有Topic -spec get_all_topic(pid(), ios|android, registration_id(), string()) -> ok|result(). get_all_topic(ConnID, MsgType, RegisterID, APPName) -> Querys = #{registration_id => RegisterID, regestricted_package_name => APPName}, Req = {"GET", MsgType, mipush_connection:build_request(?TOPIC_ALL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). @doc 订阅Regid的Aliases restapi没有提供设置alias的接口,所以只能通过客户端做 -spec subscribe_alias(pid(), ios|android, registration_id(), string(), [alias()], return|no_return) -> ok|result(). subscribe_alias(ConnID, MsgType, RegisterID, Topic, Aliases, ReturnType) -> Querys = #{registration_id => RegisterID, topic => Topic, aliases => Aliases}, Req = {"POST", MsgType, mipush_connection:build_request(?SUB_ALIAS_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 取消订阅RegId的Aliases -spec unsubscribe_alias(pid(), ios|android, registration_id(), string(), [alias()], return|no_return) -> ok|result(). unsubscribe_alias(ConnID, MsgType, RegisterID, Topic, Aliases, ReturnType) -> Querys = #{registration_id => RegisterID, topic => Topic, aliases => Aliases}, Req = {"POST", MsgType, mipush_connection:build_request(?UNSUB_ALIAS_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). %% @doc 获取一个应用的某个用户目前设置的所有Alias -spec get_all_alias(pid(), ios|android, registration_id(), string()) -> result(). get_all_alias(ConnID, MsgType, RegID, APPName) -> Querys = #{registration_id => RegID, regestricted_package_name => APPName}, Req = {"GET", MsgType, mipush_connection:build_request(?ALIAS_ALL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). %% =================================================================== %%JOB 操作 %% =================================================================== %% @doc 检测定时任务是否存在 -spec check_schedule_job_exist(pid(), ios|android, string()) -> result(). check_schedule_job_exist(ConnID, MsgType, JobID) -> Querys = #{job_id => JobID}, Req = {"GET", MsgType, mipush_connection:build_request(?JOB_EXIST, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). %% @doc 删除定时任务 -spec del_schedule_job(pid(), ios|android, string()) -> result(). del_schedule_job(ConnID, MsgType, JobID) -> Querys = #{job_id => JobID}, Req = {"GET", MsgType, mipush_connection:build_request(?JOB_DELETE, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). @doc 自1970年来的UTC毫秒数(国际时间 : : local_time中国区比universal_time快8小时 ) -spec milliseconds_utc_since_1970({{year(), month(), day()}, {hour(), minute(), second()}}) -> milliseconds(). milliseconds_utc_since_1970({{_Year, _Month, _Day}, {_Hour, _Min, _Sec}} = Time) -> [UTCTime] = calendar:local_time_to_universal_time_dst(Time), (calendar:datetime_to_gregorian_seconds(UTCTime) - calendar:datetime_to_gregorian_seconds({{1970, 01, 01}, {0, 0, 0 }})) * 1000. %% =================================================================== %% INTERNAL FUNCTION %% =================================================================== merge_connection(Connection) -> Default = #{host => "sandbox.xmpush.xiaomi.com", name => undefined, port => 443, android_auth_key => "please_config_android_api_key", android_reg_package_name => "please_config_android_package_name", ios_auth_key => "please_config_ios_api_key", ios_bundle_id => "please_config_ios_bundle_id", ssl_opts => [{nodelay, true}, {reuseaddr, true}], timeout => 30000, %% ms expires => 300, %% s expires_conn => 0, socket => undefined, err_callback => fun(T) -> io:format("~p~n", [T]) end }, maps:merge(Default, Connection). %% EXCEPT 差集 INTERSECTION 交集 UNION 并集 check_topic(Topics, OP)when OP == "UNION" orelse OP == "INTERSECTION" orelse OP == "EXCEPT" -> case erlang:length(Topics) > ?MAX_TOPIC_LEN of true -> {error, {"topic should =<", ?MAX_TOPIC_LEN}}; false -> ok end; check_topic(Topic, OP) -> {error, {"topic operation can't be", {Topic, OP}}}. join([ID| _RestIDs] = IDs, Sep) when is_binary(ID) -> join([binary:bin_to_list(IDtmp) ||IDtmp <- IDs], Sep); join([ID| RestIDs], Sep) -> ID ++ lists:append([Sep ++ X || X <- RestIDs]). transform_extra([]) -> []; transform_extra([{Target, Message}|RestMsgs]) -> [#{target => list_to_binary(Target), message => transform_message(Message)}|transform_extra(RestMsgs)]. transform_message(Message) -> NewMessage = maps:without(?EXTRA_LIST, Message), ExtraList = lists:foldl(fun(Key, Acc) -> case maps:get(Key, Message, undefined) of undefined -> Acc; Value -> maps:put(list_to_binary(atom_to_list(Key) -- "extra."), to_binary(Value), Acc) end end, #{}, ?EXTRA_LIST), NewMessage#{extra => ExtraList}. simplify_to_result(ok) -> ok; simplify_to_result([First|Rest]) -> jsx:decode(lists:foldl(fun(B, Acc) -> <<Acc/binary, ", ", B/binary>> end, First, Rest), [return_maps]). format_date({Year, Month, Day})-> MonthStr = case Month < 10 of false -> erlang:integer_to_list(Month); true -> "0" ++ erlang:integer_to_list(Month) end, DayStr = case Day < 10 of true -> "0" ++ erlang:integer_to_list(Day); false -> erlang:integer_to_list(Day) end, erlang:integer_to_list(Year) ++ MonthStr ++ DayStr. to_binary(Value)when is_list(Value) -> list_to_binary(Value); to_binary(Value)when is_integer(Value) -> integer_to_binary(Value); to_binary(Value)when is_atom(Value) -> atom_to_binary(Value, latin1); to_binary(Value)when is_binary(Value) -> Value.
null
https://raw.githubusercontent.com/zhongwencool/mipush/c69e6c15f3f36f2b4a157bbf393b261bc641f89c/src/mipush.erl
erlang
------------------------------------------------------------------- ------------------------------------------------------------------- API 推送单条消息 推送多条消息 Job 操作 Util 消息的内容.(注意:需要对payload字符串做urlencode处理) 通知栏展示的通知的描述 可以是DEFAULT_ALL或者以下其他几种的OR组合 相同notify_id的通知栏消息会覆盖之前的 如:"android.resource"铃声只能使用当前app内的资源, 可选项, 开启/关闭app在前台时的通知弹出. 当extra.notify_foreground值为”1″时, app会弹出通知栏消息; 当extra.notify_foreground值为”0″时, app不会弹出通知栏消息。注: 默认情况下会弹出通知栏消息 "1"通知栏点击后打开app的Launcher Activity "2":通知栏点击后打开app的任一Activity(还需要传入extra.intent_uri) 可选项"intent:#Intent;component=com.yourpackage/.YourActivity;end" 可选项 "" 指定layout中各控件展示的内容 如"{\"text\": {\"titleText\":\"标题\"}, \"image\": {\"iconImage\": \"icon\"}" 大小写字母([a-zA-Z]), 下划线(_)和中划线(-)组成, 长度不大于8个字符 小米推送服务器每隔1s将已送达或已点击的消息ID和对应设备的regid或alias 通过调用第三方http接口传给开发者. 每次调用后, 小米推送服务器会清空这些数据. 下次传给开发者将是新一拨数据。注:消息的送达回执只支持单发消息. 可选项, 对应不同品牌的手机或手机价格范畴 安卓app版本号来源于manifest文件中的”android:versionName”的值. 注: 目前支持MiPush_SDK_Client_2_2_12_sdk.jar(及以后)的版本. 可选项, 指定在特定的网络环境下才能接收到消息 目前仅支持指定”wifi” 通知栏展示的通知的 可选项.通知角标 <<"code">>|<<"data">>|<<"description">>|<<"info">>|<<"result">>|<<"trace_id">> =================================================================== 推送单条消息 =================================================================== @doc 向某个regid或一组regid列表推送某条消息 @doc 向某个alias或一组alias列表推送某条消息 @doc 向某个account或一组account列表推送某条消息 restapi没有提供设置account的接口,所以只能通过客户端做 @doc 向某个topic推送某条消息 @doc 向所有设备推送某条消息 @doc 向多个topic推送单条消息 =================================================================== 推送多条消息 =================================================================== @doc 针对不同的regid推送不同的消息 @doc 针对不同的userAccount推送不同的消息 =================================================================== =================================================================== @doc 获取消息的统计数据 @doc 追踪消息的状态 @doc 获取失效的regId列表 =================================================================== 订阅 topic/alias =================================================================== @doc 获取一个应用的某个用户目前订阅的所有Topic @doc 取消订阅RegId的Aliases @doc 获取一个应用的某个用户目前设置的所有Alias =================================================================== JOB 操作 =================================================================== @doc 检测定时任务是否存在 @doc 删除定时任务 =================================================================== INTERNAL FUNCTION =================================================================== ms s EXCEPT 差集 INTERSECTION 交集 UNION 并集
-module(mipush). -author(''). -include("mipush.hrl"). -define(MAX_TOPIC_LEN, 5). -export([connect/1]). -export([disconnect/1]). -export([push_to_regid/4]). -export([push_to_alias/4]). -export([push_to_account/4]). -export([push_to_topic/4]). -export([push_to_multi_topic/5]). -export([push_to_all/3]). -export([multi_msg_to_regids/5]). -export([multi_msg_to_alias/5]). -export([multi_msg_to_account/5]). -export([get_msg_count_info/5]). -export([get_msg_status/4]). -export([get_msgs_status/4]). -export([get_invalid_regids/2]). -export([subscribe_topic/6]). -export([unsubscribe_topic/5]). -export([get_all_topic/4]). -export([unsubscribe_alias/6]). -export([subscribe_alias/6]). -export([get_all_alias/4]). -export([check_schedule_job_exist/3]). -export([del_schedule_job/3]). -export([milliseconds_utc_since_1970/1]). -type url() :: nonempty_string(). -type year() ::2000..10000. -type month() :: 1..12. -type day() :: 1..31. -type hour() :: 1..24. -type minute() :: 0..59. -type second() :: 0..59. -type milliseconds() :: non_neg_integer(). -type date() :: {year(), month(), day()}. -export_type([hour/0, minute/0, second/0, milliseconds/0, date/0]). -type registration_id() :: binary()| string(). -type alias() :: string()| binary(). -type account() :: string()| binary(). -export_type([account/0, alias/0]). -export_type([registration_id/0]). -type push_msg() :: android_push_msg() | ios_push_msg(). -export_type([push_msg/0]). -type android_push_msg() :: , packageName必须和开发者网站上申请的结果一致 0 表示通知栏消息 1 表示透传消息 以上为必填项 , 以下为可选项 可选项 , 如果用户离线 , 设置消息在服务器保存的时间 , 单位 : ms . 服务器默认最长保留两周:1209600000 time_to_live => 1..1209600000, 可选项 , 定时发送消息 . , 用自1970年1月1日以来00:00:00.0 UTC时间表示(毫秒 ) time_to_send => pos_integer(), 可选项 , 默认情况下 , 通知栏只显示一条推送消息 . 如果通知栏要显示多条推送消息 , 需要针对不同的消息设置不同的notify_id notify_id => pos_integer(), 可选项 , 自定义通知栏消息铃声 . extra.sound_uri的值设置为铃声的URI , , URI格式满足 android.resource packagename / XXX / XXX , 铃声文件放在Android app的raw目录下 'extra.sound_uri' => nonempty_string(), 可选项 , , 如 : " 我是滚动的文字 " 'extra.ticker' => string(), 'extra.notify_foreground' => string(), 可选项 , . 通过设置extra.notify_effect的值以得到不同的预定义点击行为 " 3":通知栏点击后打开网页(还需要传入extra.web_uri ) 'extra.notify_effect' => string(), 'extra.intent_uri' => string(), 'extra.web_uri' => url(), 可选项 , 控制是否需要进行平缓发送(qps less 1000 / second)默认不支持 0 表示不支持平缓发送 1 表示支持平缓发送 'extra.flow_control' => integer(), 可选项 , 自定义通知栏样式 , 如"custom_notify " 'extra.layout_name' => nonempty_string(), 可选项 , 自定义通知栏样式 , 必须与layout_name一同使用 , 'extra.layout_value' => nonempty_string(), 可选项 , 使用推送批次(JobKey)功能聚合消息 . , 即相同jobkey的消息只展示第一条 , . 合法的jobkey由数字([0 - 9 ] ) 'extra.jobkey' => nonempty_string(), 可选项 , 开启消息送达和点击回执 . 将extra.callback的值设置为第三方接收回执的http接口 'extra.callback' => url(), 可选项 , 可以接收消息的设备的语言范围 , 用逗号分隔 , 如 : 中国大陆用"zh_CN " 'extra.locale' => nonempty_string(), 可选项 , , 逗号分隔 'extra.locale_not_in' => nonempty_string(), 'extra.model' => nonempty_string(), 可选项 , 无法收到消息的设备的机型范围 , 逗号分隔 'extra.model_not_in' => nonempty_string(), 可选项 , 可以接收消息的app版本号 , 用逗号分割 , 'extra.app_version' => nonempty_string(), 可选项 , 无法接收消息的app版本号 , 用逗号分割 'extra.app_version_not_in' => nonempty_string(), 'extra.connpt' => nonempty_string() }. -type ios_push_msg() :: 以上为必填项 , 以下为可选项 可选项 , 如果用户离线 , 设置消息在服务器保存的时间 , 单位 : ms . time_to_live => non_neg_integer(), 可选项 , 定时发送消息 . 用自1970年1月1日以来00:00:00.0 UTC时间表示(以毫秒为单位的时间 ) . 注 : time_to_send => non_neg_integer(), 可选项 , 自定义消息铃声 . , default为系统默认声音 'extra.sound_url' => string(), 'extra.badge' => non_neg_integer(), 可选项 . 'extra.category' => non_neg_integer() }. -type connection() :: #{host => nonempty_string(), port => pos_integer(), ssl_opts => list(), timeout => pos_integer(), expires => pos_integer(), expires_conn => pos_integer(), socket => any(), err_callback => fun((binary()) -> stop | _) }. -export_type([connection/0]). -type result() :: #{binary() => any()}. -export_type([result/0]). -spec connect(connection()) -> {ok, pid()} | {error, {already_started, pid()}} | {error, Reason::term()}. connect(Connection = #{}) -> mipush_sup:start_connection(merge_connection(Connection)). -spec disconnect(pid()) -> ok|result(). disconnect(ConnId) -> mipush_connection:stop(ConnId). -spec push_to_regid(pid(), [registration_id(), ...], push_msg(), return|no_return)-> ok|result(). push_to_regid(ConnID, RegIDs = [_|_], PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{registration_id => join(RegIDs, ", ")}, Req = {"POST", MsgType, mipush_connection:build_request(?REGID_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec push_to_alias(pid(), [alias(), ...], push_msg(), return|no_return) -> ok|result(). push_to_alias(ConnID, Alias = [_|_], PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{alias => join(Alias, ", ")}, Req = {"POST", MsgType, mipush_connection:build_request(?ALIAS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec push_to_account(pid(), [account(), ...], push_msg(), return|no_return) -> ok|result(). push_to_account(ConnID, Accounts = [_|_], PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{user_account => join(Accounts, ", ")}, Req = {"POST", MsgType, mipush_connection:build_request(?ACCOUNTS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec push_to_topic(pid(), nonempty_string(), push_msg(), return|no_return) -> ok|result(). push_to_topic(ConnID, Topic, PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{topic => Topic}, Req = {"POST", MsgType, mipush_connection:build_request(?TOPIC_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec push_to_all(pid(), push_msg(), return|no_return) -> ok|result(). push_to_all(ConnID, PushMsg, ReturnType) -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Req = {"POST", MsgType, mipush_connection:build_request(?ALL_PUSH_URL, NewPushMsg)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec push_to_multi_topic(pid(), [string(), ...], string(), push_msg(), return|no_return) -> ok|{error, any()}. push_to_multi_topic(ConnID, Topics, OP, PushMsg, ReturnType)-> case check_topic(Topics, OP) of ok -> NewPushMsg = maps:remove(type, PushMsg), MsgType = maps:get(type, PushMsg), Query = NewPushMsg#{topics => join(Topics, ":$")}, Req = {"POST", MsgType, mipush_connection:build_request(?MULTI_TOPIC_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result); {error, Reason} -> {error, Reason} end. -spec multi_msg_to_regids(pid(), ios|android, [{registration_id(), push_msg()}, ...], non_neg_integer(), return|no_return) -> ok|result(). multi_msg_to_regids(ConnID, MsgType, Msgs, TimeToSend, ReturnType)when is_integer(TimeToSend) -> Query = case TimeToSend == 0 of true -> #{messages => jsx:encode(transform_extra(Msgs))}; false -> #{messages => jsx:encode(transform_extra(Msgs)), time_to_send => TimeToSend} end, Req = {"POST", MsgType, mipush_connection:build_request(?REGIDS_MSGS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). @doc 针对不同的alias推送不同的消息 -spec multi_msg_to_alias(pid(), ios|android, [{alias(), push_msg()}, ...], non_neg_integer(), return|no_return) -> ok|result(). multi_msg_to_alias(ConnID, MsgType, Msgs, TimeToSend, ReturnType) when is_integer(TimeToSend) -> Query = case TimeToSend == 0 of true -> #{messages => jsx:encode(transform_extra(Msgs))}; false -> #{messages => jsx:encode(transform_extra(Msgs)), time_to_send => TimeToSend} end, Req = {"POST", MsgType, mipush_connection:build_request(?ALIAS_MSGS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec multi_msg_to_account(pid(), ios|android, [{account(), push_msg()}, ...], non_neg_integer(), return|no_return) -> ok|result(). multi_msg_to_account(ConnID, MsgType, Msgs, TimeToSend, ReturnType)when is_integer(TimeToSend) -> Query = case TimeToSend == 0 of true -> #{message => jsx:encode(transform_extra(Msgs))}; false -> #{message => jsx:encode(transform_extra(Msgs)), time_to_send => TimeToSend} end, Req = {"POST", MsgType, mipush_connection:build_request(?ACCOUNT_MSGS_PUSH_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec get_msg_count_info(pid(), ios|android, date(), date(), string()) -> result(). get_msg_count_info(ConnID, MsgType, StartDate, EndDate, APPName) -> Query = #{start_date => format_date(StartDate), end_date => format_date(EndDate), restricted_package_name => APPName}, Req = {"GET", MsgType, mipush_connection:build_request(?MSG_COUNTER_URL, Query)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). -spec get_msg_status(pid(), ios|android, 'msg_id'|'job_key', string()) -> result(). get_msg_status(ConnID, MsgType, Type, Value) -> Query = maps:put(Type, Value, #{}), Req = {"GET", MsgType, mipush_connection:build_request(?MSG_STATUS, Query)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). -spec get_msgs_status(pid(), ios|android, non_neg_integer(), non_neg_integer()) -> result(). get_msgs_status(ConnID, MsgType, BeginTime, EndTime) -> Query = #{begin_time => BeginTime, end_time => EndTime}, Req = {"GET", MsgType, mipush_connection:build_request(?MSGS_STATUS, Query)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). 获取失效的regId列表,每次请求最多返回1000个regId 。 每次请求之后,成功返回的失效的regId将会从MiPush数据库删除 。 -spec get_invalid_regids(pid(), ios|android) -> list(). get_invalid_regids(ConnID, MsgType) -> Req = {"GET", MsgType, mipush_connection:build_request(?INVALID_REGIDS_URL, [])}, mipush_connection:send_message(ConnID, Req, return). @doc 订阅RegId的标签 -spec subscribe_topic(pid(), ios|android, registration_id(), string(), 'undefined'|string(), return|no_return) -> ok|result(). subscribe_topic(ConnID, MsgType, RegisterID, Topic, Category, ReturnType) -> Querys = case Category of undefined -> #{registration_id => RegisterID, topic => Topic}; _ -> #{registration_id => RegisterID, topic => Topic, category => Category} end, Req = {"POST", MsgType, mipush_connection:build_request(?SUB_TOPIC_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). @doc , -spec unsubscribe_topic(pid(), ios|android, registration_id(), string(), return|no_return) -> ok|result(). unsubscribe_topic(ConnID, MsgType, RegisterID, Topic, ReturnType) -> Querys = #{registration_id => RegisterID, topic => Topic}, Req = {"POST", MsgType, mipush_connection:build_request(?UNSUB_TOPIC_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec get_all_topic(pid(), ios|android, registration_id(), string()) -> ok|result(). get_all_topic(ConnID, MsgType, RegisterID, APPName) -> Querys = #{registration_id => RegisterID, regestricted_package_name => APPName}, Req = {"GET", MsgType, mipush_connection:build_request(?TOPIC_ALL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). @doc 订阅Regid的Aliases restapi没有提供设置alias的接口,所以只能通过客户端做 -spec subscribe_alias(pid(), ios|android, registration_id(), string(), [alias()], return|no_return) -> ok|result(). subscribe_alias(ConnID, MsgType, RegisterID, Topic, Aliases, ReturnType) -> Querys = #{registration_id => RegisterID, topic => Topic, aliases => Aliases}, Req = {"POST", MsgType, mipush_connection:build_request(?SUB_ALIAS_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec unsubscribe_alias(pid(), ios|android, registration_id(), string(), [alias()], return|no_return) -> ok|result(). unsubscribe_alias(ConnID, MsgType, RegisterID, Topic, Aliases, ReturnType) -> Querys = #{registration_id => RegisterID, topic => Topic, aliases => Aliases}, Req = {"POST", MsgType, mipush_connection:build_request(?UNSUB_ALIAS_URL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, ReturnType), simplify_to_result(Result). -spec get_all_alias(pid(), ios|android, registration_id(), string()) -> result(). get_all_alias(ConnID, MsgType, RegID, APPName) -> Querys = #{registration_id => RegID, regestricted_package_name => APPName}, Req = {"GET", MsgType, mipush_connection:build_request(?ALIAS_ALL, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). -spec check_schedule_job_exist(pid(), ios|android, string()) -> result(). check_schedule_job_exist(ConnID, MsgType, JobID) -> Querys = #{job_id => JobID}, Req = {"GET", MsgType, mipush_connection:build_request(?JOB_EXIST, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). -spec del_schedule_job(pid(), ios|android, string()) -> result(). del_schedule_job(ConnID, MsgType, JobID) -> Querys = #{job_id => JobID}, Req = {"GET", MsgType, mipush_connection:build_request(?JOB_DELETE, Querys)}, Result = mipush_connection:send_message(ConnID, Req, return), simplify_to_result(Result). @doc 自1970年来的UTC毫秒数(国际时间 : : local_time中国区比universal_time快8小时 ) -spec milliseconds_utc_since_1970({{year(), month(), day()}, {hour(), minute(), second()}}) -> milliseconds(). milliseconds_utc_since_1970({{_Year, _Month, _Day}, {_Hour, _Min, _Sec}} = Time) -> [UTCTime] = calendar:local_time_to_universal_time_dst(Time), (calendar:datetime_to_gregorian_seconds(UTCTime) - calendar:datetime_to_gregorian_seconds({{1970, 01, 01}, {0, 0, 0 }})) * 1000. merge_connection(Connection) -> Default = #{host => "sandbox.xmpush.xiaomi.com", name => undefined, port => 443, android_auth_key => "please_config_android_api_key", android_reg_package_name => "please_config_android_package_name", ios_auth_key => "please_config_ios_api_key", ios_bundle_id => "please_config_ios_bundle_id", ssl_opts => [{nodelay, true}, {reuseaddr, true}], expires_conn => 0, socket => undefined, err_callback => fun(T) -> io:format("~p~n", [T]) end }, maps:merge(Default, Connection). check_topic(Topics, OP)when OP == "UNION" orelse OP == "INTERSECTION" orelse OP == "EXCEPT" -> case erlang:length(Topics) > ?MAX_TOPIC_LEN of true -> {error, {"topic should =<", ?MAX_TOPIC_LEN}}; false -> ok end; check_topic(Topic, OP) -> {error, {"topic operation can't be", {Topic, OP}}}. join([ID| _RestIDs] = IDs, Sep) when is_binary(ID) -> join([binary:bin_to_list(IDtmp) ||IDtmp <- IDs], Sep); join([ID| RestIDs], Sep) -> ID ++ lists:append([Sep ++ X || X <- RestIDs]). transform_extra([]) -> []; transform_extra([{Target, Message}|RestMsgs]) -> [#{target => list_to_binary(Target), message => transform_message(Message)}|transform_extra(RestMsgs)]. transform_message(Message) -> NewMessage = maps:without(?EXTRA_LIST, Message), ExtraList = lists:foldl(fun(Key, Acc) -> case maps:get(Key, Message, undefined) of undefined -> Acc; Value -> maps:put(list_to_binary(atom_to_list(Key) -- "extra."), to_binary(Value), Acc) end end, #{}, ?EXTRA_LIST), NewMessage#{extra => ExtraList}. simplify_to_result(ok) -> ok; simplify_to_result([First|Rest]) -> jsx:decode(lists:foldl(fun(B, Acc) -> <<Acc/binary, ", ", B/binary>> end, First, Rest), [return_maps]). format_date({Year, Month, Day})-> MonthStr = case Month < 10 of false -> erlang:integer_to_list(Month); true -> "0" ++ erlang:integer_to_list(Month) end, DayStr = case Day < 10 of true -> "0" ++ erlang:integer_to_list(Day); false -> erlang:integer_to_list(Day) end, erlang:integer_to_list(Year) ++ MonthStr ++ DayStr. to_binary(Value)when is_list(Value) -> list_to_binary(Value); to_binary(Value)when is_integer(Value) -> integer_to_binary(Value); to_binary(Value)when is_atom(Value) -> atom_to_binary(Value, latin1); to_binary(Value)when is_binary(Value) -> Value.
7c6f1d1f08e999b8aa6198a44e832dd5c4bf5f03adf498e16ebf7102c6d4f387
Tclv/HaskellBook
Hangman.hs
module Hangman where import Data.List (intersperse) data Puzzle = Puzzle String [Maybe Char] [Char] Int instance Show Puzzle where show (Puzzle _ discovered guessed guessesLeft) = (intersperse ' ' $ fmap renderPuzzleChar discovered) ++ " Guessed so far: " ++ guessed ++ " Guesses left: " ++ show guessesLeft numberOfGuessesInit :: Int numberOfGuessesInit = 7 renderPuzzleChar :: Maybe Char -> Char renderPuzzleChar Nothing = '_' renderPuzzleChar (Just a) = a charInWord :: Puzzle -> Char -> Bool charInWord (Puzzle word _ _ _) guess = guess `elem` word missedGuess :: Puzzle -> Char -> Puzzle missedGuess puzzle guess = Puzzle w f m (noG - 1) where (Puzzle w f m noG) = fillInCharacter puzzle guess alreadyGuessed :: Puzzle -> Char -> Bool alreadyGuessed (Puzzle _ _ guessedSoFar _) guess = guess `elem` guessedSoFar freshPuzzle :: String -> Puzzle freshPuzzle word = Puzzle word (map (const Nothing) word) [] numberOfGuessesInit fillInCharacter :: Puzzle -> Char -> Puzzle fillInCharacter (Puzzle word filledInSoFar s noG) c = Puzzle word newFilledInSoFar (c : s) noG where zipper guessed wordChar guessChar = if wordChar == guessed then Just wordChar else guessChar newFilledInSoFar = zipWith (zipper c) word filledInSoFar handleGuess :: Puzzle -> Char -> IO Puzzle handleGuess puzzle guess = do putStrLn $ "Your guess was: " ++ [guess] case (charInWord puzzle guess, alreadyGuessed puzzle guess) of (_, True) -> do putStrLn "Your already guessed that character, pick something else" return puzzle (True, _) -> do putStrLn "This character was in the word, filling in the word accordingly" return (fillInCharacter puzzle guess) (False, _) -> do putStrLn "This character wasn't in the word, try again" return (missedGuess puzzle guess)
null
https://raw.githubusercontent.com/Tclv/HaskellBook/78eaa5c67579526b0f00f85a10be3156bc304c14/ch14/hangman/src/Hangman.hs
haskell
module Hangman where import Data.List (intersperse) data Puzzle = Puzzle String [Maybe Char] [Char] Int instance Show Puzzle where show (Puzzle _ discovered guessed guessesLeft) = (intersperse ' ' $ fmap renderPuzzleChar discovered) ++ " Guessed so far: " ++ guessed ++ " Guesses left: " ++ show guessesLeft numberOfGuessesInit :: Int numberOfGuessesInit = 7 renderPuzzleChar :: Maybe Char -> Char renderPuzzleChar Nothing = '_' renderPuzzleChar (Just a) = a charInWord :: Puzzle -> Char -> Bool charInWord (Puzzle word _ _ _) guess = guess `elem` word missedGuess :: Puzzle -> Char -> Puzzle missedGuess puzzle guess = Puzzle w f m (noG - 1) where (Puzzle w f m noG) = fillInCharacter puzzle guess alreadyGuessed :: Puzzle -> Char -> Bool alreadyGuessed (Puzzle _ _ guessedSoFar _) guess = guess `elem` guessedSoFar freshPuzzle :: String -> Puzzle freshPuzzle word = Puzzle word (map (const Nothing) word) [] numberOfGuessesInit fillInCharacter :: Puzzle -> Char -> Puzzle fillInCharacter (Puzzle word filledInSoFar s noG) c = Puzzle word newFilledInSoFar (c : s) noG where zipper guessed wordChar guessChar = if wordChar == guessed then Just wordChar else guessChar newFilledInSoFar = zipWith (zipper c) word filledInSoFar handleGuess :: Puzzle -> Char -> IO Puzzle handleGuess puzzle guess = do putStrLn $ "Your guess was: " ++ [guess] case (charInWord puzzle guess, alreadyGuessed puzzle guess) of (_, True) -> do putStrLn "Your already guessed that character, pick something else" return puzzle (True, _) -> do putStrLn "This character was in the word, filling in the word accordingly" return (fillInCharacter puzzle guess) (False, _) -> do putStrLn "This character wasn't in the word, try again" return (missedGuess puzzle guess)
897ebe869888aef36eb20747ecea61b07bfc62b0a44336c593df30351fd43cf5
input-output-hk/project-icarus-importer
Types.hs
-- | Auxiliary types. module Bench.Cardano.Wallet.Types ( CompleteConfig (..) , EndpointConfig (..) , WalletAccount (..) , Wallet (..) , WalletsConfig (..) , CLOptions (..) , BenchEndpoint (..) , EndpointClient , Response , ResponseReport (..) ) where import Universum import Pos.Wallet.Web.ClientTypes (Addr, CId (..), CAccountId (..), Wal) import Pos.Wallet.Web.Error.Types (WalletError (..)) -- | Complete configuration for benchmarking. data CompleteConfig = CompleteConfig { endpointsConfig :: !(NonEmpty EndpointConfig) , walletsConfig :: !WalletsConfig , tlsPubCert :: !ByteString , tlsPrivKey :: !ByteString , needResponseAnalysis :: !Bool } -- | Endpoint configuration, obtained from the .csv-file. data EndpointConfig = EndpointConfig { -- | Name of the benchmark, used in the report file. benchName :: !String -- | Number of measures in benchmark. , numberOfMeasures :: !Int | Minimal value for the random delay generation , in seconds . -- This delay will be used as a pause between calls of a client. , minDelayForCalls :: !Double | Maximal value for the random delay generation , in seconds . -- This delay will be used as a pause between calls of a client. , maxDelayForCalls :: !Double -- | Path to report file (if doesn't exist, it will be created). , pathToReportFile :: !FilePath -- | Path to response reports file (if doesn't exist, it will be created). , pathToResponseReports :: !FilePath } -- | @WalletAccount@, for Wallets configuration, obtained from the .yaml-file. data WalletAccount = WalletAccount { accountId :: !CAccountId , addresses :: !(NonEmpty (CId Addr)) } -- | @Wallet@, for Wallets configuration, obtained from the .yaml-file. data Wallet = Wallet { walletId :: !(CId Wal) , accounts :: !(NonEmpty WalletAccount) } -- | @WalletsConfig@, for Wallets configuration, obtained from the .yaml-file. data WalletsConfig = WalletsConfig { wallets :: !(NonEmpty Wallet) } -- | Command-line options for benchmarks. data CLOptions = CLOptions { -- | Path to endpoints configuration file. pathToEndpointsConfig :: !FilePath -- | Path to wallets configuration file. , pathToWalletsConfig :: !FilePath -- | Path to TLS public certificate. , pathToTLSPubCert :: !FilePath -- | Path to TLS private key. , pathToTLSPrivKey :: !FilePath -- | If True, run benchmarks concurrently. , runConcurrently :: !Bool -- | If True, we must analyze responses from server. , analyzeResponse :: !Bool } -- | Clarification which benchmark we want to use. -- We need it for extracting particular configuration. data BenchEndpoint = GetAccountsBench | GetHistoryBench | GetSyncProgressBench | GetWalletBench | GetWalletsBench | IsValidAddressBench | NewAddressBench | NewPaymentBench | NewWalletBench deriving (Show) -- | Type synonym for client function: this function sends requests to particular endpoint of the Wallet Web API . type EndpointClient = CompleteConfig -> IO () -- | Response from the server. All endpoints return this type. type Response dataWeNeed = Either Text (Either WalletError dataWeNeed) -- | Report about correctness of response from the server. newtype ResponseReport = ResponseReport Text deriving Show
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/bench/Bench/Cardano/Wallet/Types.hs
haskell
| Auxiliary types. | Complete configuration for benchmarking. | Endpoint configuration, obtained from the .csv-file. | Name of the benchmark, used in the report file. | Number of measures in benchmark. This delay will be used as a pause between calls of a client. This delay will be used as a pause between calls of a client. | Path to report file (if doesn't exist, it will be created). | Path to response reports file (if doesn't exist, it will be created). | @WalletAccount@, for Wallets configuration, obtained from the .yaml-file. | @Wallet@, for Wallets configuration, obtained from the .yaml-file. | @WalletsConfig@, for Wallets configuration, obtained from the .yaml-file. | Command-line options for benchmarks. | Path to endpoints configuration file. | Path to wallets configuration file. | Path to TLS public certificate. | Path to TLS private key. | If True, run benchmarks concurrently. | If True, we must analyze responses from server. | Clarification which benchmark we want to use. We need it for extracting particular configuration. | Type synonym for client function: this function sends | Response from the server. All endpoints return this type. | Report about correctness of response from the server.
module Bench.Cardano.Wallet.Types ( CompleteConfig (..) , EndpointConfig (..) , WalletAccount (..) , Wallet (..) , WalletsConfig (..) , CLOptions (..) , BenchEndpoint (..) , EndpointClient , Response , ResponseReport (..) ) where import Universum import Pos.Wallet.Web.ClientTypes (Addr, CId (..), CAccountId (..), Wal) import Pos.Wallet.Web.Error.Types (WalletError (..)) data CompleteConfig = CompleteConfig { endpointsConfig :: !(NonEmpty EndpointConfig) , walletsConfig :: !WalletsConfig , tlsPubCert :: !ByteString , tlsPrivKey :: !ByteString , needResponseAnalysis :: !Bool } data EndpointConfig = EndpointConfig benchName :: !String , numberOfMeasures :: !Int | Minimal value for the random delay generation , in seconds . , minDelayForCalls :: !Double | Maximal value for the random delay generation , in seconds . , maxDelayForCalls :: !Double , pathToReportFile :: !FilePath , pathToResponseReports :: !FilePath } data WalletAccount = WalletAccount { accountId :: !CAccountId , addresses :: !(NonEmpty (CId Addr)) } data Wallet = Wallet { walletId :: !(CId Wal) , accounts :: !(NonEmpty WalletAccount) } data WalletsConfig = WalletsConfig { wallets :: !(NonEmpty Wallet) } data CLOptions = CLOptions pathToEndpointsConfig :: !FilePath , pathToWalletsConfig :: !FilePath , pathToTLSPubCert :: !FilePath , pathToTLSPrivKey :: !FilePath , runConcurrently :: !Bool , analyzeResponse :: !Bool } data BenchEndpoint = GetAccountsBench | GetHistoryBench | GetSyncProgressBench | GetWalletBench | GetWalletsBench | IsValidAddressBench | NewAddressBench | NewPaymentBench | NewWalletBench deriving (Show) requests to particular endpoint of the Wallet Web API . type EndpointClient = CompleteConfig -> IO () type Response dataWeNeed = Either Text (Either WalletError dataWeNeed) newtype ResponseReport = ResponseReport Text deriving Show
c1774bd00be454f9cd59e9c5d2b1430c164ba0c78f5d6ee394eb746f91bf7989
patrikja/AFPcourse
Promotion.hs
# LANGUAGE TypeFamilies , GADTs , DataKinds # module Promotion where data Nat = Zero | Suc Nat With the extension " DataKinds " data - definitions are " promoted " : So we get a new _ kind _ with ( empty ) datatypes Zero : : Suc : : The family is unchanged from Families.hs data Vec a n where Nil :: Vec a Zero Cons :: a -> Vec a n -> Vec a (Suc n) -- Some simple functions head :: Vec a (Suc n) -> a head (Cons x _) = x -- Providing a Nil case would be a type error -- Does the definition look familiar? vmap :: (a -> b) -> Vec a n -> Vec b n vmap _ Nil = Nil vmap f (Cons x xs) = Cons (f x) (vmap f xs) (+++) :: Vec a n -> Vec a m -> Vec a (Add n m) Nil +++ ys = ys (Cons x xs) +++ ys = Cons x (xs +++ ys) -- The type family now has a stronger "type" type family Add (m :: Nat) (n :: Nat) :: Nat type instance Add Zero m = m type instance Add (Suc n) m = Suc (Add n m) -- Now we are "protected" from "kind-incorrect" cases: type instance Add = Float {- Exercise: implement Fin and vector indexing. -} data Fin (n :: Nat) where FZ :: Fin (Suc n) FS :: Fin n -> Fin (Suc n) -- no constructor for Fin Zero type Fin0 = Fin Zero type Fin1 = Fin (Suc Zero) type Fin2 = Fin (Suc (Suc Zero)) type Fin3 = Fin (Suc (Suc (Suc Zero))) -- Some example values zer1 :: Fin1 zer1 = FZ zer2, one2 :: Fin2 zer2 = FZ one2 = FS zer1 zer3, one3, two3 :: Fin3 zer3 = FZ one3 = FS zer2 two3 = FS one2 ---------------- -- Vector indexing: index :: Vec a n -> Fin n -> a index (Cons x _) (FZ) = x index (Cons _ xs) (FS m) = index xs m index Nil _ = error "index: an empty vector has no elements" type Four = Suc (Suc (Suc (Suc Zero))) testVec :: Vec Int Four testVec = Cons 1 $ Cons 7 $ Cons 3 $ Cons 8 $ Nil test1 :: Int test1 = index testVec (FS FZ) -- Mention "Promotion": /~ghc/latest/docs/html/users_guide/promotion.html
null
https://raw.githubusercontent.com/patrikja/AFPcourse/1a079ae80ba2dbb36f3f79f0fc96a502c0f670b6/L13/src/Promotion.hs
haskell
Some simple functions Providing a Nil case would be a type error Does the definition look familiar? The type family now has a stronger "type" Now we are "protected" from "kind-incorrect" cases: Exercise: implement Fin and vector indexing. no constructor for Fin Zero Some example values -------------- Vector indexing: Mention "Promotion": /~ghc/latest/docs/html/users_guide/promotion.html
# LANGUAGE TypeFamilies , GADTs , DataKinds # module Promotion where data Nat = Zero | Suc Nat With the extension " DataKinds " data - definitions are " promoted " : So we get a new _ kind _ with ( empty ) datatypes Zero : : Suc : : The family is unchanged from Families.hs data Vec a n where Nil :: Vec a Zero Cons :: a -> Vec a n -> Vec a (Suc n) head :: Vec a (Suc n) -> a vmap :: (a -> b) -> Vec a n -> Vec b n vmap _ Nil = Nil vmap f (Cons x xs) = Cons (f x) (vmap f xs) (+++) :: Vec a n -> Vec a m -> Vec a (Add n m) Nil +++ ys = ys (Cons x xs) +++ ys = Cons x (xs +++ ys) type family Add (m :: Nat) (n :: Nat) :: Nat type instance Add Zero m = m type instance Add (Suc n) m = Suc (Add n m) type instance Add = Float data Fin (n :: Nat) where FZ :: Fin (Suc n) FS :: Fin n -> Fin (Suc n) type Fin0 = Fin Zero type Fin1 = Fin (Suc Zero) type Fin2 = Fin (Suc (Suc Zero)) type Fin3 = Fin (Suc (Suc (Suc Zero))) zer1 :: Fin1 zer1 = FZ zer2, one2 :: Fin2 zer2 = FZ one2 = FS zer1 zer3, one3, two3 :: Fin3 zer3 = FZ one3 = FS zer2 two3 = FS one2 index :: Vec a n -> Fin n -> a index (Cons x _) (FZ) = x index (Cons _ xs) (FS m) = index xs m index Nil _ = error "index: an empty vector has no elements" type Four = Suc (Suc (Suc (Suc Zero))) testVec :: Vec Int Four testVec = Cons 1 $ Cons 7 $ Cons 3 $ Cons 8 $ Nil test1 :: Int test1 = index testVec (FS FZ)
734c5d0a3e8c54f058074904f0ab6f6ccf4efc07c5bde101e542adffebf32fab
EasyCrypt/easycrypt
ecPhlRnd.ml
(* -------------------------------------------------------------------- *) open EcUtils open EcParsetree open EcTypes open EcModules open EcFol open EcPV open EcCoreGoal open EcLowGoal open EcLowPhlGoal module TTC = EcProofTyping (* -------------------------------------------------------------------- *) type chl_infos_t = (form, form option, form) rnd_tac_info type bhl_infos_t = (form, ty -> form option, ty -> form) rnd_tac_info type rnd_infos_t = (pformula, pformula option, pformula) rnd_tac_info type mkbij_t = EcTypes.ty -> EcTypes.ty -> EcFol.form (* -------------------------------------------------------------------- *) module Core = struct (* -------------------------------------------------------------------- *) let t_hoare_rnd_r tc = let env = FApi.tc1_env tc in let hs = tc1_as_hoareS tc in let (lv, distr), s = tc1_last_rnd tc hs.hs_s in let ty_distr = proj_distr_ty env (e_ty distr) in let x_id = EcIdent.create (symbol_of_lv lv) in let x = f_local x_id ty_distr in let distr = EcFol.form_of_expr (EcMemory.memory hs.hs_m) distr in let post = subst_form_lv env (EcMemory.memory hs.hs_m) lv x hs.hs_po in let post = f_imp (f_in_supp x distr) post in let post = f_forall_simpl [(x_id,GTty ty_distr)] post in let concl = f_hoareS_r {hs with hs_s=s; hs_po=post} in FApi.xmutate1 tc `Rnd [concl] (* -------------------------------------------------------------------- *) let t_choare_rnd_r (tac_info : chl_infos_t) tc = let env = FApi.tc1_env tc in let chs = tc1_as_choareS tc in let (lv, distr_e), s = tc1_last_rnd tc chs.chs_s in let ty_distr = proj_distr_ty env (e_ty distr_e) in let x_id = EcIdent.create (symbol_of_lv lv) in let x = f_local x_id ty_distr in let distr = EcFol.form_of_expr (EcMemory.memory chs.chs_m) distr_e in let post = subst_form_lv env (EcMemory.memory chs.chs_m) lv x chs.chs_po in let post = f_imp (f_in_supp x distr) post in let post = f_forall_simpl [(x_id,GTty ty_distr)] post in let post = f_anda (f_lossless ty_distr distr) post in let cost_pre = match tac_info with | PNoRndParams -> f_true | PSingleRndParam p -> p | _ -> assert false in let cond, cost = EcCHoare.cost_sub_self chs.chs_co (EcCHoare.cost_of_expr cost_pre chs.chs_m distr_e) in let concl = f_cHoareS_r { chs with chs_s = s; chs_po = f_and_simpl cost_pre post; chs_co = cost} in FApi.xmutate1 tc `Rnd [cond; concl] (* -------------------------------------------------------------------- *) let wp_equiv_disj_rnd_r side tc = let env = FApi.tc1_env tc in let es = tc1_as_equivS tc in let m,s = match side with | `Left -> es.es_ml, es.es_sl | `Right -> es.es_mr, es.es_sr in (* FIXME: exception when not rnds found *) let (lv, distr), s = tc1_last_rnd tc s in let ty_distr = proj_distr_ty env (e_ty distr) in let x_id = EcIdent.create (symbol_of_lv lv) in let x = f_local x_id ty_distr in let distr = EcFol.form_of_expr (EcMemory.memory m) distr in let post = subst_form_lv env (EcMemory.memory m) lv x es.es_po in let post = f_imp (f_in_supp x distr) post in let post = f_forall_simpl [(x_id,GTty ty_distr)] post in let post = f_anda (f_lossless ty_distr distr) post in let concl = match side with | `Left -> f_equivS_r { es with es_sl=s; es_po=post; } | `Right -> f_equivS_r { es with es_sr=s; es_po=post; } in FApi.xmutate1 tc `Rnd [concl] (* -------------------------------------------------------------------- *) let wp_equiv_rnd_r bij tc = let env = FApi.tc1_env tc in let es = tc1_as_equivS tc in let (lvL, muL), sl' = tc1_last_rnd tc es.es_sl in let (lvR, muR), sr' = tc1_last_rnd tc es.es_sr in let tyL = proj_distr_ty env (e_ty muL) in let tyR = proj_distr_ty env (e_ty muR) in let xL_id = EcIdent.create (symbol_of_lv lvL ^ "L") and xR_id = EcIdent.create (symbol_of_lv lvR ^ "R") in let xL = f_local xL_id tyL in let xR = f_local xR_id tyR in let muL = EcFol.form_of_expr (EcMemory.memory es.es_ml) muL in let muR = EcFol.form_of_expr (EcMemory.memory es.es_mr) muR in let tf, tfinv = match bij with | Some (f, finv) -> (f tyL tyR, finv tyR tyL) | None -> if not (EcReduction.EqTest.for_type env tyL tyR) then tc_error !!tc "%s, %s" "support are not compatible" "an explicit bijection is required"; (EcFol.f_identity ~name:"z" tyL, EcFol.f_identity ~name:"z" tyR) in ( ∀ x₂ , x₂ ∈ ℑ(D₂ ) ⇒ x₂ = ) ) * & & ( ∀ x₂ , x₂ ∈ ℑ(D₂ ) ⇒ μ(x₂ , ) = μ(f⁻¹(x₂ ) , D₁ ) ) * & & ( ∀ x₁ , x₁ ∈ ) ⇒ f(x₁ ) ∈ ℑ(D₂ ) & & x₁ = f⁻¹(f(x₁ ) ) & & φ(x₁ , f(x₁ ) ) ) * && (∀ x₂, x₂ ∈ ℑ(D₂) ⇒ μ(x₂, D₂) = μ(f⁻¹(x₂), D₁)) * && (∀ x₁, x₁ ∈ ℑ(D₁) ⇒ f(x₁) ∈ ℑ(D₂) && x₁ = f⁻¹(f(x₁)) && φ(x₁, f(x₁))) *) let f t = f_app_simpl tf [t] tyR in let finv t = f_app_simpl tfinv [t] tyL in let cond_fbij = f_eq xL (finv (f xL)) in let cond_fbij_inv = f_eq xR (f (finv xR)) in let post = es.es_po in let post = subst_form_lv env (EcMemory.memory es.es_ml) lvL xL post in let post = subst_form_lv env (EcMemory.memory es.es_mr) lvR (f xL) post in let cond1 = f_imp (f_in_supp xR muR) cond_fbij_inv in let cond2 = f_imp (f_in_supp xR muR) (f_eq (f_mu_x muR xR) (f_mu_x muL (finv xR))) in let cond3 = f_andas [f_in_supp (f xL) muR; cond_fbij; post] in let cond3 = f_imp (f_in_supp xL muL) cond3 in let concl = f_andas [f_forall_simpl [(xR_id, GTty tyR)] cond1; f_forall_simpl [(xR_id, GTty tyR)] cond2; f_forall_simpl [(xL_id, GTty tyL)] cond3] in let concl = f_equivS_r { es with es_sl=sl'; es_sr=sr'; es_po=concl; } in FApi.xmutate1 tc `Rnd [concl] (* -------------------------------------------------------------------- *) let t_bdhoare_rnd_r tac_info tc = let env = FApi.tc1_env tc in let bhs = tc1_as_bdhoareS tc in let (lv,distr),s = tc1_last_rnd tc bhs.bhs_s in let ty_distr = proj_distr_ty env (e_ty distr) in let distr = EcFol.form_of_expr (EcMemory.memory bhs.bhs_m) distr in let m = fst bhs.bhs_m in let mk_event_cond event = let v_id = EcIdent.create "v" in let v = f_local v_id ty_distr in let post_v = subst_form_lv env (EcMemory.memory bhs.bhs_m) lv v bhs.bhs_po in let event_v = f_app event [v] tbool in let v_in_supp = f_in_supp v distr in f_forall_simpl [v_id,GTty ty_distr] begin match bhs.bhs_cmp with | FHle -> f_imps_simpl [v_in_supp;post_v] event_v | FHge -> f_imps_simpl [v_in_supp;event_v] post_v | FHeq -> f_imp_simpl v_in_supp (f_iff_simpl event_v post_v) end in let f_cmp = match bhs.bhs_cmp with | FHle -> f_real_le | FHge -> fun x y -> f_real_le y x | FHeq -> f_eq in let is_post_indep = let fv = EcPV.PV.fv env m bhs.bhs_po in match lv with | LvVar (x,_) -> not (EcPV.PV.mem_pv env x fv) | LvTuple pvs -> List.for_all (fun (x,_) -> not (EcPV.PV.mem_pv env x fv)) pvs in let is_bd_indep = let fv_bd = PV.fv env mhr bhs.bhs_bd in let modif_s = s_write env s in PV.indep env modif_s fv_bd in let mk_event ?(simpl=true) ty = let x = EcIdent.create "x" in if is_post_indep && simpl then f_predT ty else match lv with | LvVar (pv,_) -> f_lambda [x,GTty ty] (EcPV.PVM.subst1 env pv m (f_local x ty) bhs.bhs_po) | _ -> tc_error !!tc "cannot infer a valid event, it must be provided" in let bound,pre_bound,binders = if is_bd_indep then bhs.bhs_bd, f_true, [] else let bd_id = EcIdent.create "bd" in let bd = f_local bd_id treal in bd, f_eq bhs.bhs_bd bd, [(bd_id,GTty treal)] in let subgoals = match tac_info, bhs.bhs_cmp with | PNoRndParams, FHle -> if is_post_indep then (* event is true *) let concl = f_bdHoareS_r {bhs with bhs_s=s} in [concl] else let event = mk_event ty_distr in let bounded_distr = f_real_le (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_hoareS bhs.bhs_m pre s post in let concl = f_forall_simpl binders concl in [concl] | PNoRndParams, _ -> if is_post_indep then (* event is true *) let event = mk_event ty_distr in let bounded_distr = f_eq (f_mu env distr event) f_r1 in let concl = f_bdHoareS_r {bhs with bhs_s=s; bhs_po=f_and bhs.bhs_po bounded_distr} in [concl] else let event = mk_event ty_distr in let bounded_distr = f_cmp (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_bdHoareS_r {bhs with bhs_s=s; bhs_pr=pre; bhs_po=post; bhs_bd=f_r1} in let concl = f_forall_simpl binders concl in [concl] | PSingleRndParam event, FHle -> let event = event ty_distr in let bounded_distr = f_real_le (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_hoareS bhs.bhs_m pre s post in let concl = f_forall_simpl binders concl in [concl] | PSingleRndParam event, _ -> let event = event ty_distr in let bounded_distr = f_cmp (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_bdHoareS_r {bhs with bhs_s=s; bhs_pr=pre; bhs_po=post; bhs_cmp=FHeq; bhs_bd=f_r1} in let concl = f_forall_simpl binders concl in [concl] | PMultRndParams ((phi,d1,d2,d3,d4),event), _ -> let event = match event ty_distr with | None -> mk_event ~simpl:false ty_distr | Some event -> event in let bd_sgoal = f_cmp (f_real_add (f_real_mul d1 d2) (f_real_mul d3 d4)) bhs.bhs_bd in let sgoal1 = f_bdHoareS_r {bhs with bhs_s=s; bhs_po=phi; bhs_bd=d1} in let sgoal2 = let bounded_distr = f_cmp (f_mu env distr event) d2 in let post = f_anda bounded_distr (mk_event_cond event) in f_forall_mems [bhs.bhs_m] (f_imp phi post) in let sgoal3 = f_bdHoareS_r {bhs with bhs_s=s; bhs_po=f_not phi; bhs_bd=d3} in let sgoal4 = let bounded_distr = f_cmp (f_mu env distr event) d4 in let post = f_anda bounded_distr (mk_event_cond event) in f_forall_mems [bhs.bhs_m] (f_imp (f_not phi) post) in let sgoal5 = let f_inbound x = f_anda (f_real_le f_r0 x) (f_real_le x f_r1) in f_ands (List.map f_inbound [d1; d2; d3; d4]) in [bd_sgoal;sgoal1;sgoal2;sgoal3;sgoal4;sgoal5] | _, _ -> tc_error !!tc "invalid arguments" in FApi.xmutate1 tc `Rnd subgoals (* -------------------------------------------------------------------- *) let semrnd tc mem used (s : instr list) : EcMemory.memenv * instr list = let error () = tc_error !!tc "semrnd" in let env = FApi.tc1_env tc in let wr, gwr = PV.elements (is_write env s) in let wr = match used with | None -> wr | Some used -> List.filter (fun (pv, _) -> PV.mem_pv env pv used) wr in if not (List.is_empty gwr) then error (); let open EcPV in let wr = let add (m, idx) pv = if is_some (PVMap.find pv m) then (m, idx) else (PVMap.add pv idx m, idx+1) in let m, idx = List.fold_left (fun (m, idx) { i_node = i } -> match i with | Sasgn (lv, _) | Srnd (lv, _) -> List.fold_left add (m, idx) (lv_to_list lv) | _ -> (m, idx) ) (PVMap.create env, 0) s in let m, _ = List.fold_left (fun (m, idx) (pv, _) -> add (m, idx) pv) (m, idx) wr in List.sort (fun (pv1, _) (pv2, _) -> compare (PVMap.find pv1 m) (PVMap.find pv2 m)) wr in let rec do1 (subst : PVM.subst) (s : instr list) = match s with | [] -> let tuple = List.map (fun (pv, _) -> PVM.find env pv mhr subst) wr in f_dunit (f_tuple tuple) | { i_node = Sasgn (lv, e) } :: s -> let e = form_of_expr mhr e in let e = PVM.subst env subst e in let subst = match lv with | LvVar (pv, _) -> PVM.add env pv mhr e subst | LvTuple pvs -> List.fold_lefti (fun subst i (pv, ty) -> PVM.add env pv mhr (f_proj e i ty) subst ) subst pvs in do1 subst s | { i_node = Srnd (lv, d) } :: s -> let d = form_of_expr mhr d in let d = PVM.subst env subst d in let x = EcIdent.create (name_of_lv lv) in let subst, xty = match lv with | LvVar (pv, ty) -> let x = f_local x ty in (PVM.add env pv mhr x subst, ty) | LvTuple pvs -> let ty = ttuple (List.snd pvs) in let x = f_local x ty in let subst = List.fold_lefti (fun subst i (pv, ty) -> PVM.add env pv mhr (f_proj x i ty) subst ) subst pvs in (subst, ty) in let body = do1 subst s in f_dlet_simpl xty (ttuple (List.snd wr)) d (f_lambda [(x, GTty xty)] body) | _ :: _ -> error () in let distr = do1 PVM.empty s in let distr = expr_of_form mhr distr in match lv_of_list wr with | None -> let x = { ov_name = Some "x"; ov_type = tunit; } in let mem, x = EcMemory.bind_fresh x mem in let x, xty = pv_loc (oget x.ov_name), x.ov_type in (mem, [i_rnd (LvVar (x, xty), distr)]) | Some wr -> (mem, [i_rnd (wr, distr)]) (* -------------------------------------------------------------------- *) let t_hoare_rndsem_r reduce pos tc = let hs = tc1_as_hoareS tc in let s1, s2 = o_split (Some pos) hs.hs_s in let fv = if reduce then Some (PV.fv (FApi.tc1_env tc) (fst hs.hs_m) hs.hs_po) else None in let m, s2 = semrnd tc hs.hs_m fv s2 in let concl = { hs with hs_s = stmt (s1 @ s2); hs_m = m; } in FApi.xmutate1 tc (`RndSem pos) [f_hoareS_r concl] (* -------------------------------------------------------------------- *) let t_bdhoare_rndsem_r reduce pos tc = let bhs = tc1_as_bdhoareS tc in let s1, s2 = o_split (Some pos) bhs.bhs_s in let fv = if reduce then Some (PV.fv (FApi.tc1_env tc) (fst bhs.bhs_m) bhs.bhs_po) else None in let m, s2 = semrnd tc bhs.bhs_m fv s2 in let concl = { bhs with bhs_s = stmt (s1 @ s2); bhs_m = m; } in FApi.xmutate1 tc (`RndSem pos) [f_bdHoareS_r concl] (* -------------------------------------------------------------------- *) let t_equiv_rndsem_r reduce side pos tc = let es = tc1_as_equivS tc in let s, m = match side with | `Left -> es.es_sl, es.es_ml | `Right -> es.es_sr, es.es_mr in let s1, s2 = o_split (Some pos) s in let fv = if reduce then Some (PV.fv (FApi.tc1_env tc) (fst m) es.es_po) else None in let m, s2 = semrnd tc m fv s2 in let s = stmt (s1 @ s2) in let concl = match side with | `Left -> { es with es_sl = s; es_ml = m; } | `Right -> { es with es_sr = s; es_mr = m; } in FApi.xmutate1 tc (`RndSem pos) [f_equivS_r concl] Core (* -------------------------------------------------------------------- *) module E = struct exception Abort end let solve n f tc = let tt = FApi.t_seqs [EcLowGoal.t_intros_n n; EcLowGoal.t_solve ~bases:["random"] ~depth:2; EcLowGoal.t_fail] in let subtc, hd = FApi.newgoal tc f in try let subtc = FApi.t_last (fun tc1 -> match FApi.t_try_base tt tc1 with | `Failure _ -> raise E.Abort | `Success tc -> tc) subtc in (subtc, Some hd) with E.Abort -> tc, None let t_apply_prept pt tc = Apply.t_apply_bwd_r (EcProofTerm.pt_of_prept tc pt) tc (* -------------------------------------------------------------------- *) let wp_equiv_disj_rnd_r side tc = let tc = Core.wp_equiv_disj_rnd_r side tc in let es = tc1_as_equivS (FApi.as_tcenv1 tc) in let c1, c2 = destr_and es.es_po in let newc1 = EcFol.f_forall_mems [es.es_ml; es.es_mr] c1 in let subtc = tc in let subtc, hdc1 = solve 2 newc1 subtc in match hdc1 with | None -> tc | Some hd -> let po = c2 in FApi.t_onalli (function | 0 -> fun tc -> EcLowGoal.t_trivial tc | 1 -> let open EcProofTerm.Prept in let m1 = EcIdent.create "_" in let m2 = EcIdent.create "_" in let h = EcIdent.create "_" in let h1 = EcIdent.create "_" in (t_intros_i [m1; m2; h] @! (t_split @+ [ t_apply_prept (hdl hd @ [amem m1; amem m2]); t_intros_i [h1] @! t_apply_hyp h])) | _ -> EcLowGoal.t_id) (FApi.t_first (EcPhlConseq.t_equivS_conseq es.es_pr po) subtc) (* -------------------------------------------------------------------- *) let wp_equiv_rnd_r bij tc = let tc = Core.wp_equiv_rnd_r bij tc in let es = tc1_as_equivS (FApi.as_tcenv1 tc) in let c1, c2, c3 = destr_and3 es.es_po in let (x, xty, c3) = destr_forall1 c3 in let ind, (c3, c4) = snd_map destr_and (destr_imp c3) in let newc2 = EcFol.f_forall_mems [es.es_ml; es.es_mr] c2 in let newc3 = EcFol.f_forall_mems [es.es_ml; es.es_mr] (f_forall [x, xty] (f_imp ind c3)) in let subtc = tc in let subtc, hdc2 = solve 4 newc2 subtc in let subtc, hdc3 = solve 4 newc3 subtc in let po = match hdc2, hdc3 with | None , None -> None | Some _, Some _ -> Some (f_anda c1 (f_forall [x, xty] (f_imp ind c4))) | Some _, None -> Some (f_anda c1 (f_forall [x, xty] (f_imp ind (f_anda c3 c4)))) | None , Some _ -> Some (f_andas [c1; c2; f_forall [x, xty] (f_imp ind c4)]) in match po with None -> tc | Some po -> let m1 = EcIdent.create "_" in let m2 = EcIdent.create "_" in let h = EcIdent.create "_" in let h1 = EcIdent.create "_" in let h2 = EcIdent.create "_" in let x = EcIdent.create "_" in let hin = EcIdent.create "_" in FApi.t_onalli (function | 0 -> fun tc -> EcLowGoal.t_trivial tc | 1 -> let open EcProofTerm.Prept in let t_c2 = let pt = match hdc2 with | None -> hyp h2 | Some hd -> hdl hd @ [amem m1; amem m2] in t_apply_prept pt in let t_c3_c4 = match hdc3 with | None -> t_apply_prept (hyp h) | Some hd -> let fx = f_local x (gty_as_ty xty) in t_intros_i [x; hin] @! t_split @+ [ t_apply_prept (hdl hd @ [amem m1; amem m2; aform fx; ahyp hin]); t_intros_n 1 @! t_apply_prept ((hyp h) @ [aform fx; ahyp hin])] in let t_case_c2 = match hdc2 with | None -> t_elim_and @! t_intros_i [h2; h] | Some _ -> t_intros_i [h] in t_intros_i [m1; m2] @! t_elim_and @! t_intros_i [h1] @! t_case_c2 @! t_split @+ [ t_apply_prept (hyp h1); t_intros_n 1 @! t_split @+ [ t_c2; t_intros_n 1 @! t_c3_c4 ] ] | _ -> EcLowGoal.t_id) (FApi.t_first (EcPhlConseq.t_equivS_conseq es.es_pr po) subtc) (* -------------------------------------------------------------------- *) let t_equiv_rnd_r side pos bij_info tc = match side, pos with | Some side, None -> wp_equiv_disj_rnd_r side tc | None, _ -> begin let pos = match pos with | None -> None | Some (Single i) -> Some (i, i) | Some (Double (il, ir)) -> Some (il, ir) in let tc = match pos with | None -> t_id tc | Some ((bl, il), (br, ir)) -> FApi.t_seq (Core.t_equiv_rndsem_r bl `Left il) (Core.t_equiv_rndsem_r br `Right ir) tc in let bij = match bij_info with | Some f, Some finv -> Some (f, finv) | Some bij, None | None, Some bij -> Some (bij, bij) | None, None -> None in FApi.t_first (wp_equiv_rnd_r bij) tc end | _ -> tc_error !!tc "invalid argument" (* -------------------------------------------------------------------- *) let wp_equiv_disj_rnd = FApi.t_low1 "wp-equiv-disj-rnd" wp_equiv_disj_rnd_r let wp_equiv_rnd = FApi.t_low1 "wp-equiv-rnd" wp_equiv_rnd_r (* -------------------------------------------------------------------- *) let t_hoare_rnd = FApi.t_low0 "hoare-rnd" Core.t_hoare_rnd_r let t_choare_rnd = FApi.t_low1 "choare-rnd" Core.t_choare_rnd_r let t_bdhoare_rnd = FApi.t_low1 "bdhoare-rnd" Core.t_bdhoare_rnd_r let t_equiv_rnd ?pos side bij_info = (FApi.t_low3 "equiv-rnd" t_equiv_rnd_r) side pos bij_info (* -------------------------------------------------------------------- *) let process_rnd side pos tac_info tc = let concl = FApi.tc1_goal tc in match side, pos, tac_info with | None, None, PNoRndParams when is_hoareS concl -> t_hoare_rnd tc | None, None, _ when is_cHoareS concl -> let tac_info = match tac_info with | PNoRndParams -> PNoRndParams | PSingleRndParam fp -> PSingleRndParam (TTC.tc1_process_Xhl_form tc tbool fp) | _ -> tc_error !!tc "invalid arguments" in FApi.t_seqsub (t_choare_rnd tac_info) [EcLowGoal.t_trivial; EcLowGoal.t_id] tc | None, None, _ when is_bdHoareS concl -> let tac_info = match tac_info with | PNoRndParams -> PNoRndParams | PSingleRndParam fp -> PSingleRndParam (fun t -> TTC.tc1_process_Xhl_form tc (tfun t tbool) fp) | PMultRndParams ((phi, d1, d2, d3, d4), p) -> let p t = p |> omap (TTC.tc1_process_Xhl_form tc (tfun t tbool)) in let phi = TTC.tc1_process_Xhl_form tc tbool phi in let d1 = TTC.tc1_process_Xhl_form tc treal d1 in let d2 = TTC.tc1_process_Xhl_form tc treal d2 in let d3 = TTC.tc1_process_Xhl_form tc treal d3 in let d4 = TTC.tc1_process_Xhl_form tc treal d4 in PMultRndParams ((phi, d1, d2, d3, d4), p) | _ -> tc_error !!tc "invalid arguments" in t_bdhoare_rnd tac_info tc | _, _, _ when is_equivS concl -> let process_form f ty1 ty2 = TTC.tc1_process_prhl_form tc (tfun ty1 ty2) f in let bij_info = match tac_info with | PNoRndParams -> None, None | PSingleRndParam f -> Some (process_form f), None | PTwoRndParams (f, finv) -> Some (process_form f), Some (process_form finv) | _ -> tc_error !!tc "invalid arguments" in t_equiv_rnd side ?pos bij_info tc | _ -> tc_error !!tc "invalid arguments" (* -------------------------------------------------------------------- *) let t_hoare_rndsem = FApi.t_low1 "hoare-rndsem" (Core.t_hoare_rndsem_r false) let t_bdhoare_rndsem = FApi.t_low1 "bdhoare-rndsem" (Core.t_bdhoare_rndsem_r false) let t_equiv_rndsem = FApi.t_low2 "equiv-rndsem" (Core.t_equiv_rndsem_r false) (* -------------------------------------------------------------------- *) let process_rndsem side pos tc = let concl = FApi.tc1_goal tc in match side with | None when is_hoareS concl -> t_hoare_rndsem pos tc | None when is_bdHoareS concl -> t_bdhoare_rndsem pos tc | Some side when is_equivS concl -> t_equiv_rndsem side pos tc | _ -> tc_error !!tc "invalid arguments"
null
https://raw.githubusercontent.com/EasyCrypt/easycrypt/5524b72dcb5c8404e686b74628647d881063785c/src/phl/ecPhlRnd.ml
ocaml
-------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- FIXME: exception when not rnds found -------------------------------------------------------------------- -------------------------------------------------------------------- event is true event is true -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
open EcUtils open EcParsetree open EcTypes open EcModules open EcFol open EcPV open EcCoreGoal open EcLowGoal open EcLowPhlGoal module TTC = EcProofTyping type chl_infos_t = (form, form option, form) rnd_tac_info type bhl_infos_t = (form, ty -> form option, ty -> form) rnd_tac_info type rnd_infos_t = (pformula, pformula option, pformula) rnd_tac_info type mkbij_t = EcTypes.ty -> EcTypes.ty -> EcFol.form module Core = struct let t_hoare_rnd_r tc = let env = FApi.tc1_env tc in let hs = tc1_as_hoareS tc in let (lv, distr), s = tc1_last_rnd tc hs.hs_s in let ty_distr = proj_distr_ty env (e_ty distr) in let x_id = EcIdent.create (symbol_of_lv lv) in let x = f_local x_id ty_distr in let distr = EcFol.form_of_expr (EcMemory.memory hs.hs_m) distr in let post = subst_form_lv env (EcMemory.memory hs.hs_m) lv x hs.hs_po in let post = f_imp (f_in_supp x distr) post in let post = f_forall_simpl [(x_id,GTty ty_distr)] post in let concl = f_hoareS_r {hs with hs_s=s; hs_po=post} in FApi.xmutate1 tc `Rnd [concl] let t_choare_rnd_r (tac_info : chl_infos_t) tc = let env = FApi.tc1_env tc in let chs = tc1_as_choareS tc in let (lv, distr_e), s = tc1_last_rnd tc chs.chs_s in let ty_distr = proj_distr_ty env (e_ty distr_e) in let x_id = EcIdent.create (symbol_of_lv lv) in let x = f_local x_id ty_distr in let distr = EcFol.form_of_expr (EcMemory.memory chs.chs_m) distr_e in let post = subst_form_lv env (EcMemory.memory chs.chs_m) lv x chs.chs_po in let post = f_imp (f_in_supp x distr) post in let post = f_forall_simpl [(x_id,GTty ty_distr)] post in let post = f_anda (f_lossless ty_distr distr) post in let cost_pre = match tac_info with | PNoRndParams -> f_true | PSingleRndParam p -> p | _ -> assert false in let cond, cost = EcCHoare.cost_sub_self chs.chs_co (EcCHoare.cost_of_expr cost_pre chs.chs_m distr_e) in let concl = f_cHoareS_r { chs with chs_s = s; chs_po = f_and_simpl cost_pre post; chs_co = cost} in FApi.xmutate1 tc `Rnd [cond; concl] let wp_equiv_disj_rnd_r side tc = let env = FApi.tc1_env tc in let es = tc1_as_equivS tc in let m,s = match side with | `Left -> es.es_ml, es.es_sl | `Right -> es.es_mr, es.es_sr in let (lv, distr), s = tc1_last_rnd tc s in let ty_distr = proj_distr_ty env (e_ty distr) in let x_id = EcIdent.create (symbol_of_lv lv) in let x = f_local x_id ty_distr in let distr = EcFol.form_of_expr (EcMemory.memory m) distr in let post = subst_form_lv env (EcMemory.memory m) lv x es.es_po in let post = f_imp (f_in_supp x distr) post in let post = f_forall_simpl [(x_id,GTty ty_distr)] post in let post = f_anda (f_lossless ty_distr distr) post in let concl = match side with | `Left -> f_equivS_r { es with es_sl=s; es_po=post; } | `Right -> f_equivS_r { es with es_sr=s; es_po=post; } in FApi.xmutate1 tc `Rnd [concl] let wp_equiv_rnd_r bij tc = let env = FApi.tc1_env tc in let es = tc1_as_equivS tc in let (lvL, muL), sl' = tc1_last_rnd tc es.es_sl in let (lvR, muR), sr' = tc1_last_rnd tc es.es_sr in let tyL = proj_distr_ty env (e_ty muL) in let tyR = proj_distr_ty env (e_ty muR) in let xL_id = EcIdent.create (symbol_of_lv lvL ^ "L") and xR_id = EcIdent.create (symbol_of_lv lvR ^ "R") in let xL = f_local xL_id tyL in let xR = f_local xR_id tyR in let muL = EcFol.form_of_expr (EcMemory.memory es.es_ml) muL in let muR = EcFol.form_of_expr (EcMemory.memory es.es_mr) muR in let tf, tfinv = match bij with | Some (f, finv) -> (f tyL tyR, finv tyR tyL) | None -> if not (EcReduction.EqTest.for_type env tyL tyR) then tc_error !!tc "%s, %s" "support are not compatible" "an explicit bijection is required"; (EcFol.f_identity ~name:"z" tyL, EcFol.f_identity ~name:"z" tyR) in ( ∀ x₂ , x₂ ∈ ℑ(D₂ ) ⇒ x₂ = ) ) * & & ( ∀ x₂ , x₂ ∈ ℑ(D₂ ) ⇒ μ(x₂ , ) = μ(f⁻¹(x₂ ) , D₁ ) ) * & & ( ∀ x₁ , x₁ ∈ ) ⇒ f(x₁ ) ∈ ℑ(D₂ ) & & x₁ = f⁻¹(f(x₁ ) ) & & φ(x₁ , f(x₁ ) ) ) * && (∀ x₂, x₂ ∈ ℑ(D₂) ⇒ μ(x₂, D₂) = μ(f⁻¹(x₂), D₁)) * && (∀ x₁, x₁ ∈ ℑ(D₁) ⇒ f(x₁) ∈ ℑ(D₂) && x₁ = f⁻¹(f(x₁)) && φ(x₁, f(x₁))) *) let f t = f_app_simpl tf [t] tyR in let finv t = f_app_simpl tfinv [t] tyL in let cond_fbij = f_eq xL (finv (f xL)) in let cond_fbij_inv = f_eq xR (f (finv xR)) in let post = es.es_po in let post = subst_form_lv env (EcMemory.memory es.es_ml) lvL xL post in let post = subst_form_lv env (EcMemory.memory es.es_mr) lvR (f xL) post in let cond1 = f_imp (f_in_supp xR muR) cond_fbij_inv in let cond2 = f_imp (f_in_supp xR muR) (f_eq (f_mu_x muR xR) (f_mu_x muL (finv xR))) in let cond3 = f_andas [f_in_supp (f xL) muR; cond_fbij; post] in let cond3 = f_imp (f_in_supp xL muL) cond3 in let concl = f_andas [f_forall_simpl [(xR_id, GTty tyR)] cond1; f_forall_simpl [(xR_id, GTty tyR)] cond2; f_forall_simpl [(xL_id, GTty tyL)] cond3] in let concl = f_equivS_r { es with es_sl=sl'; es_sr=sr'; es_po=concl; } in FApi.xmutate1 tc `Rnd [concl] let t_bdhoare_rnd_r tac_info tc = let env = FApi.tc1_env tc in let bhs = tc1_as_bdhoareS tc in let (lv,distr),s = tc1_last_rnd tc bhs.bhs_s in let ty_distr = proj_distr_ty env (e_ty distr) in let distr = EcFol.form_of_expr (EcMemory.memory bhs.bhs_m) distr in let m = fst bhs.bhs_m in let mk_event_cond event = let v_id = EcIdent.create "v" in let v = f_local v_id ty_distr in let post_v = subst_form_lv env (EcMemory.memory bhs.bhs_m) lv v bhs.bhs_po in let event_v = f_app event [v] tbool in let v_in_supp = f_in_supp v distr in f_forall_simpl [v_id,GTty ty_distr] begin match bhs.bhs_cmp with | FHle -> f_imps_simpl [v_in_supp;post_v] event_v | FHge -> f_imps_simpl [v_in_supp;event_v] post_v | FHeq -> f_imp_simpl v_in_supp (f_iff_simpl event_v post_v) end in let f_cmp = match bhs.bhs_cmp with | FHle -> f_real_le | FHge -> fun x y -> f_real_le y x | FHeq -> f_eq in let is_post_indep = let fv = EcPV.PV.fv env m bhs.bhs_po in match lv with | LvVar (x,_) -> not (EcPV.PV.mem_pv env x fv) | LvTuple pvs -> List.for_all (fun (x,_) -> not (EcPV.PV.mem_pv env x fv)) pvs in let is_bd_indep = let fv_bd = PV.fv env mhr bhs.bhs_bd in let modif_s = s_write env s in PV.indep env modif_s fv_bd in let mk_event ?(simpl=true) ty = let x = EcIdent.create "x" in if is_post_indep && simpl then f_predT ty else match lv with | LvVar (pv,_) -> f_lambda [x,GTty ty] (EcPV.PVM.subst1 env pv m (f_local x ty) bhs.bhs_po) | _ -> tc_error !!tc "cannot infer a valid event, it must be provided" in let bound,pre_bound,binders = if is_bd_indep then bhs.bhs_bd, f_true, [] else let bd_id = EcIdent.create "bd" in let bd = f_local bd_id treal in bd, f_eq bhs.bhs_bd bd, [(bd_id,GTty treal)] in let subgoals = match tac_info, bhs.bhs_cmp with | PNoRndParams, FHle -> if is_post_indep then let concl = f_bdHoareS_r {bhs with bhs_s=s} in [concl] else let event = mk_event ty_distr in let bounded_distr = f_real_le (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_hoareS bhs.bhs_m pre s post in let concl = f_forall_simpl binders concl in [concl] | PNoRndParams, _ -> if is_post_indep then let event = mk_event ty_distr in let bounded_distr = f_eq (f_mu env distr event) f_r1 in let concl = f_bdHoareS_r {bhs with bhs_s=s; bhs_po=f_and bhs.bhs_po bounded_distr} in [concl] else let event = mk_event ty_distr in let bounded_distr = f_cmp (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_bdHoareS_r {bhs with bhs_s=s; bhs_pr=pre; bhs_po=post; bhs_bd=f_r1} in let concl = f_forall_simpl binders concl in [concl] | PSingleRndParam event, FHle -> let event = event ty_distr in let bounded_distr = f_real_le (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_hoareS bhs.bhs_m pre s post in let concl = f_forall_simpl binders concl in [concl] | PSingleRndParam event, _ -> let event = event ty_distr in let bounded_distr = f_cmp (f_mu env distr event) bound in let pre = f_and bhs.bhs_pr pre_bound in let post = f_anda bounded_distr (mk_event_cond event) in let concl = f_bdHoareS_r {bhs with bhs_s=s; bhs_pr=pre; bhs_po=post; bhs_cmp=FHeq; bhs_bd=f_r1} in let concl = f_forall_simpl binders concl in [concl] | PMultRndParams ((phi,d1,d2,d3,d4),event), _ -> let event = match event ty_distr with | None -> mk_event ~simpl:false ty_distr | Some event -> event in let bd_sgoal = f_cmp (f_real_add (f_real_mul d1 d2) (f_real_mul d3 d4)) bhs.bhs_bd in let sgoal1 = f_bdHoareS_r {bhs with bhs_s=s; bhs_po=phi; bhs_bd=d1} in let sgoal2 = let bounded_distr = f_cmp (f_mu env distr event) d2 in let post = f_anda bounded_distr (mk_event_cond event) in f_forall_mems [bhs.bhs_m] (f_imp phi post) in let sgoal3 = f_bdHoareS_r {bhs with bhs_s=s; bhs_po=f_not phi; bhs_bd=d3} in let sgoal4 = let bounded_distr = f_cmp (f_mu env distr event) d4 in let post = f_anda bounded_distr (mk_event_cond event) in f_forall_mems [bhs.bhs_m] (f_imp (f_not phi) post) in let sgoal5 = let f_inbound x = f_anda (f_real_le f_r0 x) (f_real_le x f_r1) in f_ands (List.map f_inbound [d1; d2; d3; d4]) in [bd_sgoal;sgoal1;sgoal2;sgoal3;sgoal4;sgoal5] | _, _ -> tc_error !!tc "invalid arguments" in FApi.xmutate1 tc `Rnd subgoals let semrnd tc mem used (s : instr list) : EcMemory.memenv * instr list = let error () = tc_error !!tc "semrnd" in let env = FApi.tc1_env tc in let wr, gwr = PV.elements (is_write env s) in let wr = match used with | None -> wr | Some used -> List.filter (fun (pv, _) -> PV.mem_pv env pv used) wr in if not (List.is_empty gwr) then error (); let open EcPV in let wr = let add (m, idx) pv = if is_some (PVMap.find pv m) then (m, idx) else (PVMap.add pv idx m, idx+1) in let m, idx = List.fold_left (fun (m, idx) { i_node = i } -> match i with | Sasgn (lv, _) | Srnd (lv, _) -> List.fold_left add (m, idx) (lv_to_list lv) | _ -> (m, idx) ) (PVMap.create env, 0) s in let m, _ = List.fold_left (fun (m, idx) (pv, _) -> add (m, idx) pv) (m, idx) wr in List.sort (fun (pv1, _) (pv2, _) -> compare (PVMap.find pv1 m) (PVMap.find pv2 m)) wr in let rec do1 (subst : PVM.subst) (s : instr list) = match s with | [] -> let tuple = List.map (fun (pv, _) -> PVM.find env pv mhr subst) wr in f_dunit (f_tuple tuple) | { i_node = Sasgn (lv, e) } :: s -> let e = form_of_expr mhr e in let e = PVM.subst env subst e in let subst = match lv with | LvVar (pv, _) -> PVM.add env pv mhr e subst | LvTuple pvs -> List.fold_lefti (fun subst i (pv, ty) -> PVM.add env pv mhr (f_proj e i ty) subst ) subst pvs in do1 subst s | { i_node = Srnd (lv, d) } :: s -> let d = form_of_expr mhr d in let d = PVM.subst env subst d in let x = EcIdent.create (name_of_lv lv) in let subst, xty = match lv with | LvVar (pv, ty) -> let x = f_local x ty in (PVM.add env pv mhr x subst, ty) | LvTuple pvs -> let ty = ttuple (List.snd pvs) in let x = f_local x ty in let subst = List.fold_lefti (fun subst i (pv, ty) -> PVM.add env pv mhr (f_proj x i ty) subst ) subst pvs in (subst, ty) in let body = do1 subst s in f_dlet_simpl xty (ttuple (List.snd wr)) d (f_lambda [(x, GTty xty)] body) | _ :: _ -> error () in let distr = do1 PVM.empty s in let distr = expr_of_form mhr distr in match lv_of_list wr with | None -> let x = { ov_name = Some "x"; ov_type = tunit; } in let mem, x = EcMemory.bind_fresh x mem in let x, xty = pv_loc (oget x.ov_name), x.ov_type in (mem, [i_rnd (LvVar (x, xty), distr)]) | Some wr -> (mem, [i_rnd (wr, distr)]) let t_hoare_rndsem_r reduce pos tc = let hs = tc1_as_hoareS tc in let s1, s2 = o_split (Some pos) hs.hs_s in let fv = if reduce then Some (PV.fv (FApi.tc1_env tc) (fst hs.hs_m) hs.hs_po) else None in let m, s2 = semrnd tc hs.hs_m fv s2 in let concl = { hs with hs_s = stmt (s1 @ s2); hs_m = m; } in FApi.xmutate1 tc (`RndSem pos) [f_hoareS_r concl] let t_bdhoare_rndsem_r reduce pos tc = let bhs = tc1_as_bdhoareS tc in let s1, s2 = o_split (Some pos) bhs.bhs_s in let fv = if reduce then Some (PV.fv (FApi.tc1_env tc) (fst bhs.bhs_m) bhs.bhs_po) else None in let m, s2 = semrnd tc bhs.bhs_m fv s2 in let concl = { bhs with bhs_s = stmt (s1 @ s2); bhs_m = m; } in FApi.xmutate1 tc (`RndSem pos) [f_bdHoareS_r concl] let t_equiv_rndsem_r reduce side pos tc = let es = tc1_as_equivS tc in let s, m = match side with | `Left -> es.es_sl, es.es_ml | `Right -> es.es_sr, es.es_mr in let s1, s2 = o_split (Some pos) s in let fv = if reduce then Some (PV.fv (FApi.tc1_env tc) (fst m) es.es_po) else None in let m, s2 = semrnd tc m fv s2 in let s = stmt (s1 @ s2) in let concl = match side with | `Left -> { es with es_sl = s; es_ml = m; } | `Right -> { es with es_sr = s; es_mr = m; } in FApi.xmutate1 tc (`RndSem pos) [f_equivS_r concl] Core module E = struct exception Abort end let solve n f tc = let tt = FApi.t_seqs [EcLowGoal.t_intros_n n; EcLowGoal.t_solve ~bases:["random"] ~depth:2; EcLowGoal.t_fail] in let subtc, hd = FApi.newgoal tc f in try let subtc = FApi.t_last (fun tc1 -> match FApi.t_try_base tt tc1 with | `Failure _ -> raise E.Abort | `Success tc -> tc) subtc in (subtc, Some hd) with E.Abort -> tc, None let t_apply_prept pt tc = Apply.t_apply_bwd_r (EcProofTerm.pt_of_prept tc pt) tc let wp_equiv_disj_rnd_r side tc = let tc = Core.wp_equiv_disj_rnd_r side tc in let es = tc1_as_equivS (FApi.as_tcenv1 tc) in let c1, c2 = destr_and es.es_po in let newc1 = EcFol.f_forall_mems [es.es_ml; es.es_mr] c1 in let subtc = tc in let subtc, hdc1 = solve 2 newc1 subtc in match hdc1 with | None -> tc | Some hd -> let po = c2 in FApi.t_onalli (function | 0 -> fun tc -> EcLowGoal.t_trivial tc | 1 -> let open EcProofTerm.Prept in let m1 = EcIdent.create "_" in let m2 = EcIdent.create "_" in let h = EcIdent.create "_" in let h1 = EcIdent.create "_" in (t_intros_i [m1; m2; h] @! (t_split @+ [ t_apply_prept (hdl hd @ [amem m1; amem m2]); t_intros_i [h1] @! t_apply_hyp h])) | _ -> EcLowGoal.t_id) (FApi.t_first (EcPhlConseq.t_equivS_conseq es.es_pr po) subtc) let wp_equiv_rnd_r bij tc = let tc = Core.wp_equiv_rnd_r bij tc in let es = tc1_as_equivS (FApi.as_tcenv1 tc) in let c1, c2, c3 = destr_and3 es.es_po in let (x, xty, c3) = destr_forall1 c3 in let ind, (c3, c4) = snd_map destr_and (destr_imp c3) in let newc2 = EcFol.f_forall_mems [es.es_ml; es.es_mr] c2 in let newc3 = EcFol.f_forall_mems [es.es_ml; es.es_mr] (f_forall [x, xty] (f_imp ind c3)) in let subtc = tc in let subtc, hdc2 = solve 4 newc2 subtc in let subtc, hdc3 = solve 4 newc3 subtc in let po = match hdc2, hdc3 with | None , None -> None | Some _, Some _ -> Some (f_anda c1 (f_forall [x, xty] (f_imp ind c4))) | Some _, None -> Some (f_anda c1 (f_forall [x, xty] (f_imp ind (f_anda c3 c4)))) | None , Some _ -> Some (f_andas [c1; c2; f_forall [x, xty] (f_imp ind c4)]) in match po with None -> tc | Some po -> let m1 = EcIdent.create "_" in let m2 = EcIdent.create "_" in let h = EcIdent.create "_" in let h1 = EcIdent.create "_" in let h2 = EcIdent.create "_" in let x = EcIdent.create "_" in let hin = EcIdent.create "_" in FApi.t_onalli (function | 0 -> fun tc -> EcLowGoal.t_trivial tc | 1 -> let open EcProofTerm.Prept in let t_c2 = let pt = match hdc2 with | None -> hyp h2 | Some hd -> hdl hd @ [amem m1; amem m2] in t_apply_prept pt in let t_c3_c4 = match hdc3 with | None -> t_apply_prept (hyp h) | Some hd -> let fx = f_local x (gty_as_ty xty) in t_intros_i [x; hin] @! t_split @+ [ t_apply_prept (hdl hd @ [amem m1; amem m2; aform fx; ahyp hin]); t_intros_n 1 @! t_apply_prept ((hyp h) @ [aform fx; ahyp hin])] in let t_case_c2 = match hdc2 with | None -> t_elim_and @! t_intros_i [h2; h] | Some _ -> t_intros_i [h] in t_intros_i [m1; m2] @! t_elim_and @! t_intros_i [h1] @! t_case_c2 @! t_split @+ [ t_apply_prept (hyp h1); t_intros_n 1 @! t_split @+ [ t_c2; t_intros_n 1 @! t_c3_c4 ] ] | _ -> EcLowGoal.t_id) (FApi.t_first (EcPhlConseq.t_equivS_conseq es.es_pr po) subtc) let t_equiv_rnd_r side pos bij_info tc = match side, pos with | Some side, None -> wp_equiv_disj_rnd_r side tc | None, _ -> begin let pos = match pos with | None -> None | Some (Single i) -> Some (i, i) | Some (Double (il, ir)) -> Some (il, ir) in let tc = match pos with | None -> t_id tc | Some ((bl, il), (br, ir)) -> FApi.t_seq (Core.t_equiv_rndsem_r bl `Left il) (Core.t_equiv_rndsem_r br `Right ir) tc in let bij = match bij_info with | Some f, Some finv -> Some (f, finv) | Some bij, None | None, Some bij -> Some (bij, bij) | None, None -> None in FApi.t_first (wp_equiv_rnd_r bij) tc end | _ -> tc_error !!tc "invalid argument" let wp_equiv_disj_rnd = FApi.t_low1 "wp-equiv-disj-rnd" wp_equiv_disj_rnd_r let wp_equiv_rnd = FApi.t_low1 "wp-equiv-rnd" wp_equiv_rnd_r let t_hoare_rnd = FApi.t_low0 "hoare-rnd" Core.t_hoare_rnd_r let t_choare_rnd = FApi.t_low1 "choare-rnd" Core.t_choare_rnd_r let t_bdhoare_rnd = FApi.t_low1 "bdhoare-rnd" Core.t_bdhoare_rnd_r let t_equiv_rnd ?pos side bij_info = (FApi.t_low3 "equiv-rnd" t_equiv_rnd_r) side pos bij_info let process_rnd side pos tac_info tc = let concl = FApi.tc1_goal tc in match side, pos, tac_info with | None, None, PNoRndParams when is_hoareS concl -> t_hoare_rnd tc | None, None, _ when is_cHoareS concl -> let tac_info = match tac_info with | PNoRndParams -> PNoRndParams | PSingleRndParam fp -> PSingleRndParam (TTC.tc1_process_Xhl_form tc tbool fp) | _ -> tc_error !!tc "invalid arguments" in FApi.t_seqsub (t_choare_rnd tac_info) [EcLowGoal.t_trivial; EcLowGoal.t_id] tc | None, None, _ when is_bdHoareS concl -> let tac_info = match tac_info with | PNoRndParams -> PNoRndParams | PSingleRndParam fp -> PSingleRndParam (fun t -> TTC.tc1_process_Xhl_form tc (tfun t tbool) fp) | PMultRndParams ((phi, d1, d2, d3, d4), p) -> let p t = p |> omap (TTC.tc1_process_Xhl_form tc (tfun t tbool)) in let phi = TTC.tc1_process_Xhl_form tc tbool phi in let d1 = TTC.tc1_process_Xhl_form tc treal d1 in let d2 = TTC.tc1_process_Xhl_form tc treal d2 in let d3 = TTC.tc1_process_Xhl_form tc treal d3 in let d4 = TTC.tc1_process_Xhl_form tc treal d4 in PMultRndParams ((phi, d1, d2, d3, d4), p) | _ -> tc_error !!tc "invalid arguments" in t_bdhoare_rnd tac_info tc | _, _, _ when is_equivS concl -> let process_form f ty1 ty2 = TTC.tc1_process_prhl_form tc (tfun ty1 ty2) f in let bij_info = match tac_info with | PNoRndParams -> None, None | PSingleRndParam f -> Some (process_form f), None | PTwoRndParams (f, finv) -> Some (process_form f), Some (process_form finv) | _ -> tc_error !!tc "invalid arguments" in t_equiv_rnd side ?pos bij_info tc | _ -> tc_error !!tc "invalid arguments" let t_hoare_rndsem = FApi.t_low1 "hoare-rndsem" (Core.t_hoare_rndsem_r false) let t_bdhoare_rndsem = FApi.t_low1 "bdhoare-rndsem" (Core.t_bdhoare_rndsem_r false) let t_equiv_rndsem = FApi.t_low2 "equiv-rndsem" (Core.t_equiv_rndsem_r false) let process_rndsem side pos tc = let concl = FApi.tc1_goal tc in match side with | None when is_hoareS concl -> t_hoare_rndsem pos tc | None when is_bdHoareS concl -> t_bdhoare_rndsem pos tc | Some side when is_equivS concl -> t_equiv_rndsem side pos tc | _ -> tc_error !!tc "invalid arguments"
4416a534e8c10c31dbd29163fa79fafb33ebb90bcdb1ee53bfcadbb02ea44f1e
BIMSBbioinfo/guix-bimsb-nonfree
juicer.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2019 < > ;;; ;;; This file is NOT part of GNU Guix, but is supposed to be used with GNU ;;; Guix and thus has the same license. ;;; 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 (non-free juicer) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix gexp) #:use-module (guix git-download) #:use-module (guix utils) #:use-module (guix build-system ant) #:use-module (guix build-system gnu) #:use-module (gnu packages) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages bioinformatics) #:use-module (gnu packages gawk) #:use-module (gnu packages java) #:use-module (gnu packages perl)) ;; This depends on jCUDA, which depends on the non-free CUDA ;; libraries. ;; ;; TODO: unbundle all those jars in the lib directory. (define-public java-juicebox (package (name "java-juicebox") (version "1.9.9") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "00nz7g9raj1nwdd6vcpq85kc88p7d4266knglf80sc8kjbwpv120")))) (build-system ant-build-system) (arguments (list #:jdk icedtea-8 #:build-target "build.all.artifacts" #:tests? #f ; there are no tests #:make-flags #~(list (string-append "-Djdk.home.1.8=" (ungexp (this-package-native-input "jdk") "jdk"))) #:phases '(modify-phases %standard-phases (replace 'install (install-jars "out/artifacts/"))))) (native-inputs `(("jdk" ,icedtea-8 "jdk"))) (home-page "") (synopsis "Visualization and analysis software for Hi-C data") (description "Juicebox is visualization software for Hi-C data. Juicebox can now be used to visualize and interactively (re)assemble genomes.") (license license:expat))) (define-public juicer (let ((commit "43cc35ff546d33839b89ca3949c2e1f848077eb1") (revision "1")) (package (name "juicer") (version (git-version "1.6.2" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "0gcq9klgwwyq4y0pr0w6a2vfsf8v5a16zqpgqfks5yh6dyrj2ha9")))) (build-system gnu-build-system) (arguments `(#:tests? #f ; there are none! #:phases (modify-phases %standard-phases (replace 'configure (lambda* (#:key inputs outputs #:allow-other-keys) (substitute* "UGER/scripts/juicer.sh" (("^export TMPDIR.*") "") ; why would you even do that? (("java -") (string-append (which "java") " -")) (("#!/bin/bash") (string-append "#!" (which "bash"))) ;; This assumes the use of environment modules. ;; Disable this. (("^usePath=/broad/software/scripts/useuse") "usePath=echo") (("source \\$usePath") "") (("\\$load_cluster") "") (("^load_bwa=.*") "load_bwa=echo\n") (("^load_java=.*") "load_java=echo\n") (("^load_cluster=.*") "load_cluster=echo\n") (("^load_coreutils=.*") "load_coreutils=echo\n") (("^juiceDir=\"/broad/aidenlab\"") "juiceDir=\"/tmp\"") (("\\$\\{juiceDir\\}/scripts") (string-append (assoc-ref outputs "out") "/share/juicer/UGER/scripts"))) (substitute* "UGER/scripts/juicer_tools" Use this particular variant of Java . (("^java ") (string-append (which "java") " ")) ;; Don't try to find juicer_tools in the same ;; directory as the script. (("`dirname \\$0`/juicer_tools.jar") (string-append (assoc-ref inputs "java-juicebox") "/share/java/juicer_tools.jar"))))) (delete 'build) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin")) (share (string-append out "/share/juicer"))) (copy-recursively "." share) (mkdir-p bin) ;; Simple script to launch the selected pipeline ;; script. Default to UGER (grid engine) scripts. (with-output-to-file (string-append bin "/juicer") (lambda () (format #t "#!~a~%dir=\"$1\"; test -z \"$dir\" && dir=UGER; shift;~%~a \"~a/$dir/scripts/juicer.sh\" $@~%" (which "bash") (which "bash") share))) (chmod (string-append bin "/juicer") #o555))))))) (inputs (list bash java-juicebox icedtea-8 perl)) (propagated-inputs (list bwa coreutils gawk)) (home-page "") (synopsis "Visualization and analysis software for Hi-C data") (description "Juicebox is visualization software for Hi-C data. Juicebox can now be used to visualize and interactively (re)assemble genomes.") (license license:expat))))
null
https://raw.githubusercontent.com/BIMSBbioinfo/guix-bimsb-nonfree/78e3316d58b91f94b3052f6fc8fd5ec2df6e0843/non-free/juicer.scm
scheme
GNU Guix --- Functional package management for GNU This file is NOT part of GNU Guix, but is supposed to be used with GNU Guix and thus has the same license. 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. This depends on jCUDA, which depends on the non-free CUDA libraries. TODO: unbundle all those jars in the lib directory. there are no tests there are none! why would you even do that? This assumes the use of environment modules. Disable this. Don't try to find juicer_tools in the same directory as the script. Simple script to launch the selected pipeline script. Default to UGER (grid engine) scripts.
Copyright © 2019 < > 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 (non-free juicer) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix gexp) #:use-module (guix git-download) #:use-module (guix utils) #:use-module (guix build-system ant) #:use-module (guix build-system gnu) #:use-module (gnu packages) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages bioinformatics) #:use-module (gnu packages gawk) #:use-module (gnu packages java) #:use-module (gnu packages perl)) (define-public java-juicebox (package (name "java-juicebox") (version "1.9.9") (source (origin (method git-fetch) (uri (git-reference (url "") (commit version))) (file-name (git-file-name name version)) (sha256 (base32 "00nz7g9raj1nwdd6vcpq85kc88p7d4266knglf80sc8kjbwpv120")))) (build-system ant-build-system) (arguments (list #:jdk icedtea-8 #:build-target "build.all.artifacts" #:make-flags #~(list (string-append "-Djdk.home.1.8=" (ungexp (this-package-native-input "jdk") "jdk"))) #:phases '(modify-phases %standard-phases (replace 'install (install-jars "out/artifacts/"))))) (native-inputs `(("jdk" ,icedtea-8 "jdk"))) (home-page "") (synopsis "Visualization and analysis software for Hi-C data") (description "Juicebox is visualization software for Hi-C data. Juicebox can now be used to visualize and interactively (re)assemble genomes.") (license license:expat))) (define-public juicer (let ((commit "43cc35ff546d33839b89ca3949c2e1f848077eb1") (revision "1")) (package (name "juicer") (version (git-version "1.6.2" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "0gcq9klgwwyq4y0pr0w6a2vfsf8v5a16zqpgqfks5yh6dyrj2ha9")))) (build-system gnu-build-system) (arguments #:phases (modify-phases %standard-phases (replace 'configure (lambda* (#:key inputs outputs #:allow-other-keys) (substitute* "UGER/scripts/juicer.sh" (("java -") (string-append (which "java") " -")) (("#!/bin/bash") (string-append "#!" (which "bash"))) (("^usePath=/broad/software/scripts/useuse") "usePath=echo") (("source \\$usePath") "") (("\\$load_cluster") "") (("^load_bwa=.*") "load_bwa=echo\n") (("^load_java=.*") "load_java=echo\n") (("^load_cluster=.*") "load_cluster=echo\n") (("^load_coreutils=.*") "load_coreutils=echo\n") (("^juiceDir=\"/broad/aidenlab\"") "juiceDir=\"/tmp\"") (("\\$\\{juiceDir\\}/scripts") (string-append (assoc-ref outputs "out") "/share/juicer/UGER/scripts"))) (substitute* "UGER/scripts/juicer_tools" Use this particular variant of Java . (("^java ") (string-append (which "java") " ")) (("`dirname \\$0`/juicer_tools.jar") (string-append (assoc-ref inputs "java-juicebox") "/share/java/juicer_tools.jar"))))) (delete 'build) (replace 'install (lambda* (#:key outputs #:allow-other-keys) (let* ((out (assoc-ref outputs "out")) (bin (string-append out "/bin")) (share (string-append out "/share/juicer"))) (copy-recursively "." share) (mkdir-p bin) (with-output-to-file (string-append bin "/juicer") (lambda () (format #t "#!~a~%dir=\"$1\"; test -z \"$dir\" && dir=UGER; shift;~%~a \"~a/$dir/scripts/juicer.sh\" $@~%" (which "bash") (which "bash") share))) (chmod (string-append bin "/juicer") #o555))))))) (inputs (list bash java-juicebox icedtea-8 perl)) (propagated-inputs (list bwa coreutils gawk)) (home-page "") (synopsis "Visualization and analysis software for Hi-C data") (description "Juicebox is visualization software for Hi-C data. Juicebox can now be used to visualize and interactively (re)assemble genomes.") (license license:expat))))
672862b18f4f4045416eda7f54fe7699758ae29aed6d328c45cf8255c72f4c4a
ygmpkk/house
StdMenuReceiver.hs
module StdMenuReceiver(MenuElements(..)) where Clean Object I / O library , version 1.2 import CommonDef import StdIOCommon import StdReceiverAttribute import StdMenuElementClass import StdMenuDef import MenuHandle import ReceiverAccess(newReceiverHandle, newReceiver2Handle) instance MenuElements (Receiver m) where menuElementToHandles (Receiver rid f atts) = return [menuElementHandleToMenuElementState (MenuReceiverHandle (newReceiverHandle rid (getSelectState atts) f) (MenuId (rIdtoId rid):map receiverAttToMenuAtt atts)) ] instance MenuElements (Receiver2 m r) where menuElementToHandles (Receiver2 rid f atts) = return [menuElementHandleToMenuElementState (MenuReceiverHandle (newReceiver2Handle rid (getSelectState atts) f) (MenuId (r2IdtoId rid):map receiverAttToMenuAtt atts)) ] getSelectState :: [ReceiverAttribute ls ps] -> SelectState getSelectState rAtts = getReceiverSelectStateAtt (snd (cselect isReceiverSelectState (ReceiverSelectState Able) rAtts)) receiverAttToMenuAtt :: ReceiverAttribute ls ps -> MenuAttribute ls ps receiverAttToMenuAtt (ReceiverSelectState s) = MenuSelectState s
null
https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/hslibs/object-io/ObjectIO/StdMenuReceiver.hs
haskell
module StdMenuReceiver(MenuElements(..)) where Clean Object I / O library , version 1.2 import CommonDef import StdIOCommon import StdReceiverAttribute import StdMenuElementClass import StdMenuDef import MenuHandle import ReceiverAccess(newReceiverHandle, newReceiver2Handle) instance MenuElements (Receiver m) where menuElementToHandles (Receiver rid f atts) = return [menuElementHandleToMenuElementState (MenuReceiverHandle (newReceiverHandle rid (getSelectState atts) f) (MenuId (rIdtoId rid):map receiverAttToMenuAtt atts)) ] instance MenuElements (Receiver2 m r) where menuElementToHandles (Receiver2 rid f atts) = return [menuElementHandleToMenuElementState (MenuReceiverHandle (newReceiver2Handle rid (getSelectState atts) f) (MenuId (r2IdtoId rid):map receiverAttToMenuAtt atts)) ] getSelectState :: [ReceiverAttribute ls ps] -> SelectState getSelectState rAtts = getReceiverSelectStateAtt (snd (cselect isReceiverSelectState (ReceiverSelectState Able) rAtts)) receiverAttToMenuAtt :: ReceiverAttribute ls ps -> MenuAttribute ls ps receiverAttToMenuAtt (ReceiverSelectState s) = MenuSelectState s
02bd419c36900bcdbe49e854ea25f2024bf01717909325d42d0e97c51214b0ff
helium/helium-packet-router
hpr_http_roaming_utils.erl
%%%------------------------------------------------------------------- @author jonathanruttenberg ( C ) 2022 , Nova Labs %%% @doc %%% %%% @end Created : 17 . Sep 2022 10:56 AM %%%------------------------------------------------------------------- -module(hpr_http_roaming_utils). -author("jonathanruttenberg"). -define(RESPONSE_STREAM_ETS, hpr_http_response_stream_ets). %% API -export([ hexstring/1, binary_to_hexstring/1, format_time/1, uint32/1, hexstring_to_binary/1, hexstring_to_int/1, hexstring/2 ]). -spec binary_to_hexstring(binary()) -> binary(). binary_to_hexstring(ID) -> <<"0x", (binary:encode_hex(ID))/binary>>. -spec hexstring(number() | binary()) -> binary(). hexstring(Bin) when erlang:is_binary(Bin) -> binary_to_hexstring(Bin); hexstring(Num) when erlang:is_number(Num) -> hexstring(Num, 6); hexstring(Other) -> throw({unknown_hexstring_conversion, Other}). -spec hexstring(non_neg_integer(), non_neg_integer()) -> binary(). hexstring(Bin, Length) when erlang:is_binary(Bin) -> Inter0 = binary:encode_hex(Bin), Inter1 = string:pad(Inter0, Length, leading, $0), erlang:iolist_to_binary([<<"0x">>, Inter1]); hexstring(Num, Length) -> Inter0 = erlang:integer_to_binary(Num, 16), Inter1 = string:pad(Inter0, Length, leading, $0), erlang:iolist_to_binary([<<"0x">>, Inter1]). -spec format_time(integer()) -> binary(). format_time(Time) -> iso8601:format(calendar:system_time_to_universal_time(Time, millisecond)). -spec uint32(number()) -> 0..4294967295. uint32(Num) -> Num band 16#FFFF_FFFF. -spec hexstring_to_binary(binary()) -> binary(). hexstring_to_binary(<<"0x", Bin/binary>>) -> binary:decode_hex(Bin); hexstring_to_binary(Bin) when erlang:is_binary(Bin) -> binary:decode_hex(Bin); hexstring_to_binary(_Invalid) -> throw({invalid_hexstring_binary, _Invalid}). -spec hexstring_to_int(binary()) -> integer(). hexstring_to_int(<<"0x", Num/binary>>) -> erlang:binary_to_integer(Num, 16); hexstring_to_int(Bin) -> erlang:binary_to_integer(Bin, 16). %% ------------------------------------------------------------------ EUnit tests %% ------------------------------------------------------------------ -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). hexstring_test() -> Number = 7, EncodedNumber = <<"0x000007">>, ResultNumber = hexstring(Number), ?assertEqual(EncodedNumber, ResultNumber), Binary = <<"f">>, EncodedBinary = <<"0x66">>, ResultBinary = hexstring(Binary), ?assertEqual(EncodedBinary, ResultBinary), NotSupported = [1, 5], ?assertThrow({unknown_hexstring_conversion, _}, hexstring(NotSupported)). binary_to_hexstring_test() -> Binary = <<"join_accept_payload">>, EncodedBinary = <<"0x6A6F696E5F6163636570745F7061796C6F6164">>, ?assertEqual(EncodedBinary, binary_to_hexstring(Binary)). format_time_test() -> Now = 1667507573316, Formatted = <<"2022-11-03T20:32:53Z">>, ?assertEqual(Formatted, format_time(Now)). uint32_test() -> ?assertEqual(16#ffffffff, uint32(16#1ffffffff)). hexstring_to_binary_test() -> ZeroX = <<"0x66">>, DecodedBinary = <<"f">>, EncodedBinary = <<"0x6A6F696E5F6163636570745F7061796C6F6164">>, Binary = <<"join_accept_payload">>, NotSupported = [1, 5], ?assertEqual(DecodedBinary, hexstring_to_binary(ZeroX)), ?assertEqual(Binary, hexstring_to_binary(EncodedBinary)), ?assertThrow({invalid_hexstring_binary, _}, hexstring_to_binary(NotSupported)). hexstring_to_int_test() -> ZeroX = <<"0x66">>, ZXInt = 16#66, Encoded = <<"66">>, Integer = ZXInt, ?assertEqual(ZXInt, hexstring_to_int(ZeroX)), ?assertEqual(Integer, hexstring_to_int(Encoded)). hexstring_2_test() -> DevEUI = 0, Encoded = <<"0x0000000000000000">>, ?assertEqual(Encoded, hexstring(DevEUI, 16)). -endif.
null
https://raw.githubusercontent.com/helium/helium-packet-router/d6458e1a7e6460d4e95ad3a08b3c67030702f360/src/protocols/http/hpr_http_roaming_utils.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API ------------------------------------------------------------------ ------------------------------------------------------------------
@author jonathanruttenberg ( C ) 2022 , Nova Labs Created : 17 . Sep 2022 10:56 AM -module(hpr_http_roaming_utils). -author("jonathanruttenberg"). -define(RESPONSE_STREAM_ETS, hpr_http_response_stream_ets). -export([ hexstring/1, binary_to_hexstring/1, format_time/1, uint32/1, hexstring_to_binary/1, hexstring_to_int/1, hexstring/2 ]). -spec binary_to_hexstring(binary()) -> binary(). binary_to_hexstring(ID) -> <<"0x", (binary:encode_hex(ID))/binary>>. -spec hexstring(number() | binary()) -> binary(). hexstring(Bin) when erlang:is_binary(Bin) -> binary_to_hexstring(Bin); hexstring(Num) when erlang:is_number(Num) -> hexstring(Num, 6); hexstring(Other) -> throw({unknown_hexstring_conversion, Other}). -spec hexstring(non_neg_integer(), non_neg_integer()) -> binary(). hexstring(Bin, Length) when erlang:is_binary(Bin) -> Inter0 = binary:encode_hex(Bin), Inter1 = string:pad(Inter0, Length, leading, $0), erlang:iolist_to_binary([<<"0x">>, Inter1]); hexstring(Num, Length) -> Inter0 = erlang:integer_to_binary(Num, 16), Inter1 = string:pad(Inter0, Length, leading, $0), erlang:iolist_to_binary([<<"0x">>, Inter1]). -spec format_time(integer()) -> binary(). format_time(Time) -> iso8601:format(calendar:system_time_to_universal_time(Time, millisecond)). -spec uint32(number()) -> 0..4294967295. uint32(Num) -> Num band 16#FFFF_FFFF. -spec hexstring_to_binary(binary()) -> binary(). hexstring_to_binary(<<"0x", Bin/binary>>) -> binary:decode_hex(Bin); hexstring_to_binary(Bin) when erlang:is_binary(Bin) -> binary:decode_hex(Bin); hexstring_to_binary(_Invalid) -> throw({invalid_hexstring_binary, _Invalid}). -spec hexstring_to_int(binary()) -> integer(). hexstring_to_int(<<"0x", Num/binary>>) -> erlang:binary_to_integer(Num, 16); hexstring_to_int(Bin) -> erlang:binary_to_integer(Bin, 16). EUnit tests -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). hexstring_test() -> Number = 7, EncodedNumber = <<"0x000007">>, ResultNumber = hexstring(Number), ?assertEqual(EncodedNumber, ResultNumber), Binary = <<"f">>, EncodedBinary = <<"0x66">>, ResultBinary = hexstring(Binary), ?assertEqual(EncodedBinary, ResultBinary), NotSupported = [1, 5], ?assertThrow({unknown_hexstring_conversion, _}, hexstring(NotSupported)). binary_to_hexstring_test() -> Binary = <<"join_accept_payload">>, EncodedBinary = <<"0x6A6F696E5F6163636570745F7061796C6F6164">>, ?assertEqual(EncodedBinary, binary_to_hexstring(Binary)). format_time_test() -> Now = 1667507573316, Formatted = <<"2022-11-03T20:32:53Z">>, ?assertEqual(Formatted, format_time(Now)). uint32_test() -> ?assertEqual(16#ffffffff, uint32(16#1ffffffff)). hexstring_to_binary_test() -> ZeroX = <<"0x66">>, DecodedBinary = <<"f">>, EncodedBinary = <<"0x6A6F696E5F6163636570745F7061796C6F6164">>, Binary = <<"join_accept_payload">>, NotSupported = [1, 5], ?assertEqual(DecodedBinary, hexstring_to_binary(ZeroX)), ?assertEqual(Binary, hexstring_to_binary(EncodedBinary)), ?assertThrow({invalid_hexstring_binary, _}, hexstring_to_binary(NotSupported)). hexstring_to_int_test() -> ZeroX = <<"0x66">>, ZXInt = 16#66, Encoded = <<"66">>, Integer = ZXInt, ?assertEqual(ZXInt, hexstring_to_int(ZeroX)), ?assertEqual(Integer, hexstring_to_int(Encoded)). hexstring_2_test() -> DevEUI = 0, Encoded = <<"0x0000000000000000">>, ?assertEqual(Encoded, hexstring(DevEUI, 16)). -endif.
d66babc031cae1a86eb533bc115623fc01eef060d2f1d148be1019a6a9c7a121
serokell/blockchain-util
Validate.hs
# LANGUAGE AllowAmbiguousTypes # module Snowdrop.Core.Validate ( valid , validateIff , validateAll , StructuralValidationException (..) , structuralPreValidator , StructuralConstr ) where import Control.Monad.Except (MonadError (..)) import Universum import qualified Data.Map.Strict as M import qualified Data.Text.Buildable import Data.Vinyl.Core (Rec (..)) import Data.Vinyl.TypeLevel (AllConstrained) import Formatting (bprint, build, (%)) import Snowdrop.Core.ChangeSet (HChangeSet, csNew, csRemove) import Snowdrop.Core.ERoComp (ERoComp, HasBException, QueryERo, query) import Snowdrop.Hetero (ExnHKey) import Snowdrop.Util (HasReview (..), throwLocalError) --------------------------- -- Helpers for validation --------------------------- -- | Helper, which can be used for a validator to specify success case. valid :: (Monoid a, Monad m) => m a valid = pure mempty -- | Helper, which can be used for a validator to specify conditional success case. -- Error will be returned iff the given boolean is 'False'. validateIff :: forall e e1 m a . (Monoid a, MonadError e m, HasReview e e1) => e1 -> Bool -> m a validateIff e1 = bool (throwLocalError e1) valid -- | Helper, which can be used for a validator to specify conditional success case. -- Error value is determined for a given element of container and is returned only -- if check for the element results in 'False'. validateAll :: (Foldable f, MonadError e m, Container (f a)) => (Element (f a) -> e) -> (Element (f a) -> Bool) -> f a -> m () validateAll ex p ls = maybe (pure ()) (throwError . ex) (find (not . p) ls) --------------------------- -- Structural validator --------------------------- -- | Exception type for structural validation ('structuralPreValidator'). data StructuralValidationException = forall id . (Show id, Buildable id) => DpRemoveDoesntExist id -- ^ Id is expected to exist in state, but doesn't. | forall id . (Show id, Buildable id) => DpAddExist id -- ^ Id is expected to be absent in state, but exists. deriving instance Show StructuralValidationException instance Buildable StructuralValidationException where build = \case DpRemoveDoesntExist i -> bprint ("Removing entry associated with key "%build% ", which isn't present in store") i DpAddExist i -> bprint ("Adding entry associated with key "%build% ", which is already present in store") i -- this is an error as soon as we have separated 'New' and 'Upd' ' 's . type StructuralConstr components xs = ( AllConstrained (QueryERo components) xs , AllConstrained ExnHKey xs ) csRemoveExist :: forall xs components conf . ( HasBException conf StructuralValidationException , StructuralConstr components xs ) => HChangeSet xs -> ERoComp conf components () csRemoveExist = checkBody where checkBody :: forall rs . StructuralConstr components rs => HChangeSet rs -> ERoComp conf components () checkBody RNil = pure () checkBody gs'@(_ :& _) = checkBody' gs' checkBody' :: forall t xs' . StructuralConstr components (t ': xs') => HChangeSet (t ': xs') -> ERoComp conf components () checkBody' (cs :& gs) = do let inRefs = csRemove cs ins <- query @t @_ @conf inRefs validateAll (inj . DpRemoveDoesntExist) (flip M.member ins) inRefs checkBody gs csNewNotExist :: forall xs components conf . ( HasBException conf StructuralValidationException , StructuralConstr components xs ) => HChangeSet xs -> ERoComp conf components () csNewNotExist = checkBody where checkBody :: forall rs . StructuralConstr components rs => HChangeSet rs -> ERoComp conf components () checkBody RNil = pure () checkBody gs'@(_ :& _) = checkBody' gs' checkBody' :: forall t xs' . StructuralConstr components (t ': xs') => HChangeSet (t ': xs') -> ERoComp conf components () checkBody' (cs :& gs) = do let ks = M.keysSet (csNew cs) mp <- query @t @_ @conf ks validateAll (inj . DpAddExist) (not . flip M.member mp) ks checkBody gs -- | Structural validation checks whether the ids which are to be removed -- (or to be modified) exist in state and vice versa. structuralPreValidator :: forall xs components conf . ( HasBException conf StructuralValidationException , StructuralConstr components xs ) => HChangeSet xs -> ERoComp conf components () structuralPreValidator xs = csRemoveExist @xs @components @conf xs <> csNewNotExist @xs @components @conf xs
null
https://raw.githubusercontent.com/serokell/blockchain-util/a6428c6841e7002605a115002f58eff78ff9f128/snowdrop-core/src/Snowdrop/Core/Validate.hs
haskell
------------------------- Helpers for validation ------------------------- | Helper, which can be used for a validator to specify success case. | Helper, which can be used for a validator to specify conditional success case. Error will be returned iff the given boolean is 'False'. | Helper, which can be used for a validator to specify conditional success case. Error value is determined for a given element of container and is returned only if check for the element results in 'False'. ------------------------- Structural validator ------------------------- | Exception type for structural validation ('structuralPreValidator'). ^ Id is expected to exist in state, but doesn't. ^ Id is expected to be absent in state, but exists. this is an error as soon as we have separated 'New' and 'Upd' | Structural validation checks whether the ids which are to be removed (or to be modified) exist in state and vice versa.
# LANGUAGE AllowAmbiguousTypes # module Snowdrop.Core.Validate ( valid , validateIff , validateAll , StructuralValidationException (..) , structuralPreValidator , StructuralConstr ) where import Control.Monad.Except (MonadError (..)) import Universum import qualified Data.Map.Strict as M import qualified Data.Text.Buildable import Data.Vinyl.Core (Rec (..)) import Data.Vinyl.TypeLevel (AllConstrained) import Formatting (bprint, build, (%)) import Snowdrop.Core.ChangeSet (HChangeSet, csNew, csRemove) import Snowdrop.Core.ERoComp (ERoComp, HasBException, QueryERo, query) import Snowdrop.Hetero (ExnHKey) import Snowdrop.Util (HasReview (..), throwLocalError) valid :: (Monoid a, Monad m) => m a valid = pure mempty validateIff :: forall e e1 m a . (Monoid a, MonadError e m, HasReview e e1) => e1 -> Bool -> m a validateIff e1 = bool (throwLocalError e1) valid validateAll :: (Foldable f, MonadError e m, Container (f a)) => (Element (f a) -> e) -> (Element (f a) -> Bool) -> f a -> m () validateAll ex p ls = maybe (pure ()) (throwError . ex) (find (not . p) ls) data StructuralValidationException = forall id . (Show id, Buildable id) => DpRemoveDoesntExist id | forall id . (Show id, Buildable id) => DpAddExist id deriving instance Show StructuralValidationException instance Buildable StructuralValidationException where build = \case DpRemoveDoesntExist i -> bprint ("Removing entry associated with key "%build% ", which isn't present in store") i DpAddExist i -> bprint ("Adding entry associated with key "%build% ", which is already present in store") i ' 's . type StructuralConstr components xs = ( AllConstrained (QueryERo components) xs , AllConstrained ExnHKey xs ) csRemoveExist :: forall xs components conf . ( HasBException conf StructuralValidationException , StructuralConstr components xs ) => HChangeSet xs -> ERoComp conf components () csRemoveExist = checkBody where checkBody :: forall rs . StructuralConstr components rs => HChangeSet rs -> ERoComp conf components () checkBody RNil = pure () checkBody gs'@(_ :& _) = checkBody' gs' checkBody' :: forall t xs' . StructuralConstr components (t ': xs') => HChangeSet (t ': xs') -> ERoComp conf components () checkBody' (cs :& gs) = do let inRefs = csRemove cs ins <- query @t @_ @conf inRefs validateAll (inj . DpRemoveDoesntExist) (flip M.member ins) inRefs checkBody gs csNewNotExist :: forall xs components conf . ( HasBException conf StructuralValidationException , StructuralConstr components xs ) => HChangeSet xs -> ERoComp conf components () csNewNotExist = checkBody where checkBody :: forall rs . StructuralConstr components rs => HChangeSet rs -> ERoComp conf components () checkBody RNil = pure () checkBody gs'@(_ :& _) = checkBody' gs' checkBody' :: forall t xs' . StructuralConstr components (t ': xs') => HChangeSet (t ': xs') -> ERoComp conf components () checkBody' (cs :& gs) = do let ks = M.keysSet (csNew cs) mp <- query @t @_ @conf ks validateAll (inj . DpAddExist) (not . flip M.member mp) ks checkBody gs structuralPreValidator :: forall xs components conf . ( HasBException conf StructuralValidationException , StructuralConstr components xs ) => HChangeSet xs -> ERoComp conf components () structuralPreValidator xs = csRemoveExist @xs @components @conf xs <> csNewNotExist @xs @components @conf xs
318a2d4132c1252afdf7489eb3da2c4f0c6a786548908794df790ad7a5b6a264
ocaml/oasis-db
MyAccount.ml
* Web services to manage account @author @author Sylvain Le Gall *) open Lwt open XHTML.M open Eliom_services open Eliom_parameters open Eliom_sessions open Eliom_predefmod.Xhtml open CalendarLib open ODBGettext open Lwt open Template open Context open OCAAccount open Lwt_log let () = Sqlexpr.register "account" 1 (fun db -> Sqlexpr.execute db sqlinit"CREATE TABLE IF NOT EXISTS account\ (id INTEGER PRIMARY KEY NOT NULL)") (fun _ _ -> return ()) let account_settings = register_new_service ~path:["account"; "settings"] ~get_params:unit (fun sp () () -> Context.get_user ~sp () >>= fun (ctxt, accnt) -> Distro.user_settings_box ~sp ~ctxt () >>= fun distro_user_settings_box -> Monitor.user_settings_box ~sp ~ctxt () >>= fun monitor_user_settings_box -> Account.user_settings_box ~ctxt sp >>= fun account_ext_user_settings_box -> template ~ctxt ~sp ~title:(OneTitle (s_ "Account settings")) ~div_id:"account_settings" [ p [pcdata (s_ "OASIS-DB use two kinds of information: the one stored \ in its own database and the one coming from OCaml forge. \ You can edit the first one here but you need to go to \ OCaml forge to edit the later.")]; h2 [pcdata (s_ "OCaml forge information")]; account_ext_user_settings_box; h2 [pcdata (s_ "Local information")]; monitor_user_settings_box; distro_user_settings_box; ]) let admin = register_new_service ~path:["admin"; "oasis-db"] ~get_params:unit (fun sp () () -> Context.get_admin ~sp () >>= fun (ctxt, accnt) -> Cron.box ~ctxt ~sp () >>= fun cron_box -> template ~ctxt ~sp ~title:(OneTitle (s_ "Administration")) ~div_id:"admin" [ p [pcdata (s_ "This page let you access operation that requires 'admin' privileges."); em [pcdata (s_ "Use with caution.")]]; cron_box; ]) let my_account_with_offset = new_service ["my_account"] (opt (string "redirect") ** int "offset") () let my_account_handler sp redirect_opt log_offset = TODO : use redirect_opt let log_per_page = 20 in Context.get_user ~sp () >>= fun (ctxt, accnt) -> Monitor.account_box ~sp ~ctxt (fun offset -> (preapply my_account_with_offset (redirect_opt, offset))) log_per_page log_offset >>= fun (extra_headers, monitor_box) -> begin template ~ctxt ~sp ?extra_headers ~title:(OneTitle (s_ "My account")) ~div_id:"my_account" [ p [pcdata (Printf.sprintf (f_ "Hello %s!") accnt.accnt_real_name)]; monitor_box; ul (li [a account_settings sp [pcdata (s_ "Settings")] ()]) TODO [li [a admin sp [pcdata (s_ "Administration")] ()]]; ] end let () = register Common.my_account (fun sp redirect_opt () -> my_account_handler sp redirect_opt 0); register my_account_with_offset (fun sp (redirect_opt, offset) () -> my_account_handler sp redirect_opt offset)
null
https://raw.githubusercontent.com/ocaml/oasis-db/f8b19d431102b5c5b7dced00a5242a5366ad263f/src/web/MyAccount.ml
ocaml
* Web services to manage account @author @author Sylvain Le Gall *) open Lwt open XHTML.M open Eliom_services open Eliom_parameters open Eliom_sessions open Eliom_predefmod.Xhtml open CalendarLib open ODBGettext open Lwt open Template open Context open OCAAccount open Lwt_log let () = Sqlexpr.register "account" 1 (fun db -> Sqlexpr.execute db sqlinit"CREATE TABLE IF NOT EXISTS account\ (id INTEGER PRIMARY KEY NOT NULL)") (fun _ _ -> return ()) let account_settings = register_new_service ~path:["account"; "settings"] ~get_params:unit (fun sp () () -> Context.get_user ~sp () >>= fun (ctxt, accnt) -> Distro.user_settings_box ~sp ~ctxt () >>= fun distro_user_settings_box -> Monitor.user_settings_box ~sp ~ctxt () >>= fun monitor_user_settings_box -> Account.user_settings_box ~ctxt sp >>= fun account_ext_user_settings_box -> template ~ctxt ~sp ~title:(OneTitle (s_ "Account settings")) ~div_id:"account_settings" [ p [pcdata (s_ "OASIS-DB use two kinds of information: the one stored \ in its own database and the one coming from OCaml forge. \ You can edit the first one here but you need to go to \ OCaml forge to edit the later.")]; h2 [pcdata (s_ "OCaml forge information")]; account_ext_user_settings_box; h2 [pcdata (s_ "Local information")]; monitor_user_settings_box; distro_user_settings_box; ]) let admin = register_new_service ~path:["admin"; "oasis-db"] ~get_params:unit (fun sp () () -> Context.get_admin ~sp () >>= fun (ctxt, accnt) -> Cron.box ~ctxt ~sp () >>= fun cron_box -> template ~ctxt ~sp ~title:(OneTitle (s_ "Administration")) ~div_id:"admin" [ p [pcdata (s_ "This page let you access operation that requires 'admin' privileges."); em [pcdata (s_ "Use with caution.")]]; cron_box; ]) let my_account_with_offset = new_service ["my_account"] (opt (string "redirect") ** int "offset") () let my_account_handler sp redirect_opt log_offset = TODO : use redirect_opt let log_per_page = 20 in Context.get_user ~sp () >>= fun (ctxt, accnt) -> Monitor.account_box ~sp ~ctxt (fun offset -> (preapply my_account_with_offset (redirect_opt, offset))) log_per_page log_offset >>= fun (extra_headers, monitor_box) -> begin template ~ctxt ~sp ?extra_headers ~title:(OneTitle (s_ "My account")) ~div_id:"my_account" [ p [pcdata (Printf.sprintf (f_ "Hello %s!") accnt.accnt_real_name)]; monitor_box; ul (li [a account_settings sp [pcdata (s_ "Settings")] ()]) TODO [li [a admin sp [pcdata (s_ "Administration")] ()]]; ] end let () = register Common.my_account (fun sp redirect_opt () -> my_account_handler sp redirect_opt 0); register my_account_with_offset (fun sp (redirect_opt, offset) () -> my_account_handler sp redirect_opt offset)
b113a85eb83a3b99366959a50113545e12a003512bf56890bea73eb7ace99f32
ChrisPenner/proton
Kaleidoscope.hs
# LANGUAGE TypeFamilies # # LANGUAGE ScopedTypeVariables # module Proton.Kaleidoscope (Reflector(..), Kaleidoscope, Kaleidoscope', pointWise) where -- ala -syco5/slides/roman.pdf -- import Data.Profunctor import Control.Applicative import Data.Profunctor.Reflector type Kaleidoscope s t a b = forall p. Reflector p => p a b -> p s t type Kaleidoscope' s a = Kaleidoscope s s a a pointWise :: Kaleidoscope [a] [b] a b pointWise = dimap ZipList getZipList . reflected collapse : : forall p f a b c g. ( , Applicative g , Alternative f , , Corep p ~ g ) -- => Optic' p (f a) a -- collapse p = cotabulate done -- where -- func :: g (f a) -> (f a) -- func = cosieve (convolving p) -- done :: g (f a) -> f a done = func . pure @g . asum
null
https://raw.githubusercontent.com/ChrisPenner/proton/4ce22d473ce5bece8322c841bd2cf7f18673d57d/src/Proton/Kaleidoscope.hs
haskell
ala -syco5/slides/roman.pdf => Optic' p (f a) a collapse p = cotabulate done where func :: g (f a) -> (f a) func = cosieve (convolving p) done :: g (f a) -> f a
# LANGUAGE TypeFamilies # # LANGUAGE ScopedTypeVariables # module Proton.Kaleidoscope (Reflector(..), Kaleidoscope, Kaleidoscope', pointWise) where import Data.Profunctor import Control.Applicative import Data.Profunctor.Reflector type Kaleidoscope s t a b = forall p. Reflector p => p a b -> p s t type Kaleidoscope' s a = Kaleidoscope s s a a pointWise :: Kaleidoscope [a] [b] a b pointWise = dimap ZipList getZipList . reflected collapse : : forall p f a b c g. ( , Applicative g , Alternative f , , Corep p ~ g ) done = func . pure @g . asum
c8d85b99eee1f36315da3322610289ad7dc15b33ae2e43b6c0155ae83ed19a5f
felipereigosa/mock-mechanics
mechanical-tree.clj
(ns mockmechanics.core (:require [mockmechanics.library.vector :as vector])) (declare compute-subtree-transforms) (defn compute-children-transforms [world part-name transform key] (reduce (fn [w [child-name relative-transform]] (let [new-transform (combine-transforms relative-transform transform)] (compute-subtree-transforms w child-name new-transform key))) world (get-in world [key part-name :children]))) (defn compute-translated-loop-fn [loop-fn] (let [offset (second (first loop-fn))] (map (fn [[t p]] [t (vector/subtract p offset)]) loop-fn))) (defn block-compute-subtree-transforms [world name transform key] (-> world (assoc-in [key name :transform] transform) (compute-children-transforms name transform key))) (defn track-compute-subtree-transforms [world name transform key] (let [track (get-in world [:parts name]) angle (map-between-ranges (:value track) 0.0 1.0 0.0 360.0) angle-transform (make-transform [0 0 0] [0 1 0 angle]) transform (combine-transforms angle-transform transform) world (assoc-in world [key name :transform] transform)] (reduce (fn [w [child-name relative-transform]] (let [new-transform (combine-transforms relative-transform transform)] (compute-subtree-transforms w child-name new-transform key))) world (get-in world [key name :children])))) (defn wagon-compute-subtree-transforms [world name transform key] (let [wagon (get-in world [:parts name]) rotation (get-transform-rotation transform) loop-fn (if (= key :weld-groups) (compute-translated-loop-fn (:loop-fn wagon)) (:loop-fn wagon)) loop-fn (map (fn [[t v]] [t (apply-transform transform v)]) loop-fn) value (within (:value wagon) 0.0 1.0) position (get-function-value loop-fn value vector/interpolate) transform (make-transform position rotation)] (-> world (assoc-in [key name :transform] transform) (compute-children-transforms name transform key)))) (defn compute-subtree-transforms [world name transform key] (case (get-in world [:parts name :type]) :track (track-compute-subtree-transforms world name transform key) :wagon (wagon-compute-subtree-transforms world name transform key) (block-compute-subtree-transforms world name transform key))) (defn compute-transforms [world key] (let [ground (get-in world [:parts :ground-part]) transform (:transform ground)] (compute-subtree-transforms world :ground-part transform key)))
null
https://raw.githubusercontent.com/felipereigosa/mock-mechanics/93070a789f5b24a7b34643bc11f47f8cf6112f8d/src/mockmechanics/mechanical-tree.clj
clojure
(ns mockmechanics.core (:require [mockmechanics.library.vector :as vector])) (declare compute-subtree-transforms) (defn compute-children-transforms [world part-name transform key] (reduce (fn [w [child-name relative-transform]] (let [new-transform (combine-transforms relative-transform transform)] (compute-subtree-transforms w child-name new-transform key))) world (get-in world [key part-name :children]))) (defn compute-translated-loop-fn [loop-fn] (let [offset (second (first loop-fn))] (map (fn [[t p]] [t (vector/subtract p offset)]) loop-fn))) (defn block-compute-subtree-transforms [world name transform key] (-> world (assoc-in [key name :transform] transform) (compute-children-transforms name transform key))) (defn track-compute-subtree-transforms [world name transform key] (let [track (get-in world [:parts name]) angle (map-between-ranges (:value track) 0.0 1.0 0.0 360.0) angle-transform (make-transform [0 0 0] [0 1 0 angle]) transform (combine-transforms angle-transform transform) world (assoc-in world [key name :transform] transform)] (reduce (fn [w [child-name relative-transform]] (let [new-transform (combine-transforms relative-transform transform)] (compute-subtree-transforms w child-name new-transform key))) world (get-in world [key name :children])))) (defn wagon-compute-subtree-transforms [world name transform key] (let [wagon (get-in world [:parts name]) rotation (get-transform-rotation transform) loop-fn (if (= key :weld-groups) (compute-translated-loop-fn (:loop-fn wagon)) (:loop-fn wagon)) loop-fn (map (fn [[t v]] [t (apply-transform transform v)]) loop-fn) value (within (:value wagon) 0.0 1.0) position (get-function-value loop-fn value vector/interpolate) transform (make-transform position rotation)] (-> world (assoc-in [key name :transform] transform) (compute-children-transforms name transform key)))) (defn compute-subtree-transforms [world name transform key] (case (get-in world [:parts name :type]) :track (track-compute-subtree-transforms world name transform key) :wagon (wagon-compute-subtree-transforms world name transform key) (block-compute-subtree-transforms world name transform key))) (defn compute-transforms [world key] (let [ground (get-in world [:parts :ground-part]) transform (:transform ground)] (compute-subtree-transforms world :ground-part transform key)))
b3b222e9bef5fa806d21431541c34b84d82cc199572554d2758a289c8dd8e5d4
Phaetec/pogo-cruncher
utils.cljs
(ns cruncher.communication.utils (:require [cruncher.config :as config] [clojure.walk :refer [keywordize-keys]] [cognitect.transit :as transit])) (defn make-url "Prefix url with host." [url] (str (:host config/api) url)) ;;;; Conversions (defn clj->json "Convert CLJS to valid JSON." [col] (.stringify js/JSON (clj->js col))) (defn json->clj "Use cognitec's transit reader for json to convert it to proper Clojure datastructures." [response] (keywordize-keys response) #_(let [r (transit/reader :json)] (keywordize-keys (transit/read r response))))
null
https://raw.githubusercontent.com/Phaetec/pogo-cruncher/a93bd16cc4d118d2ec57c2a641bd1b11be0d133d/frontend/src/cruncher/communication/utils.cljs
clojure
Conversions
(ns cruncher.communication.utils (:require [cruncher.config :as config] [clojure.walk :refer [keywordize-keys]] [cognitect.transit :as transit])) (defn make-url "Prefix url with host." [url] (str (:host config/api) url)) (defn clj->json "Convert CLJS to valid JSON." [col] (.stringify js/JSON (clj->js col))) (defn json->clj "Use cognitec's transit reader for json to convert it to proper Clojure datastructures." [response] (keywordize-keys response) #_(let [r (transit/reader :json)] (keywordize-keys (transit/read r response))))
5d47de8cc797c4ef01055d3d4395a288a8d1937f55c03322c4d86f899465d312
mput/sicp-solutions
2_04.test.rkt
#lang racket (require rackunit/text-ui) (require rackunit "custom-checks.rkt") (require rackunit "../solutions/2_04.rkt") (define tests (test-suite "Test for exercise 2_04" (test-case "Test for piculiar pair realisation" (define testpair (n-cons 5 10)) (check-equal? (n-car testpair) 5) (check-equal? (n-cdr testpair) 10)))) (run-tests tests 'verbose)
null
https://raw.githubusercontent.com/mput/sicp-solutions/fe12ad2b6f17c99978c8fe04b2495005986b8496/tests/2_04.test.rkt
racket
#lang racket (require rackunit/text-ui) (require rackunit "custom-checks.rkt") (require rackunit "../solutions/2_04.rkt") (define tests (test-suite "Test for exercise 2_04" (test-case "Test for piculiar pair realisation" (define testpair (n-cons 5 10)) (check-equal? (n-car testpair) 5) (check-equal? (n-cdr testpair) 10)))) (run-tests tests 'verbose)
f4ee4a49b0c510d86de8b7ec62dda973a3412720f27fef8427565ad6f961167a
rcherrueau/APE
surface-lang3.rkt
#lang racket/base ;; @InProceedings{CPN98, author = { and and } , ;; title = {Ownership Types for Flexible Alias Protection}, booktitle = { Proceedings of the 1998 { ACM } { SIGPLAN } Conference on Object - Oriented Programming Systems , Languages { \ & } Applications { ( OOPSLA } ' 98 ) , Vancouver , British Columbia , Canada , October 18 - 22 , 1998 . } , pages = { 48 - -64 } , year = { 1998 } , ;; url = {}, ;; doi = {10.1145/286936.286947} ;; } (require (for-meta 2 racket/base syntax/parse syntax/transformer syntax/parse/define racket/syntax racket/match racket/list racket/stxparam "type-checker.rkt" "utils.rkt" ) (for-syntax racket/base syntax/parse syntax/parse/define syntax/transformer syntax/free-vars racket/syntax racket/match racket/list racket/stxparam "type-checker.rkt" "utils.rkt" ) syntax/parse syntax/parse/define racket/match racket/stxparam ;; "type-checker.rkt" ) ;; Naming conventions: - X , Y , FOO ( ie , uppercase variables ) and ` stx ' are syntax objects Utils (begin-for-syntax ;; -- Syntax checker in the form of ;; -lang.org/syntax/syntax-helpers.html#%28part._stxkeyword%29 ;; A check procedure consumes the syntax to check and a context ;; syntax object for error reporting and either raises an error to ;; reject the syntax or returns a value as its parsed ;; representation. Returns the first duplicate class in the program or # f if there ;; are no duplicate. (define (check-class clss-stx) (define (get-class-name cls-stx) (syntax-case cls-stx (class) [(class name) #'name] [(class name _ ...) #'name] [_ (raise-syntax-error #f "Bad syntax for class" cls-stx)])) (let* ([classes (syntax->list clss-stx)] [class-names (map get-class-name classes)]) (check-duplicate-identifier class-names))) Returns the first duplicate field in the class or # f if there are ;; no duplicate. (define (field-twice? cls-stx) (define (get-field-name field/def-stx) (syntax-case field/def-stx (field :) ;; (field [NAME : TYPE]) [(field [name : _]) #'name] [_ #f])) (let* ([fields/defs (syntax->list cls-stx)] [field-names (filter-map get-field-name fields/defs)]) (check-duplicate-identifier field-names))) Returns the first duplicate def in the class or # f if there are ;; no duplicate. (define (def-twice? cls-stx) (define (get-def-name field/def-stx) (syntax-case field/def-stx (def : →) ;; (def (NAME [ARG:NAME : ARG:TYPE] ... → RET:TYPE) E) [(def (name _ ...) _) #'name] [_ #f])) (let* ([fields/defs (syntax->list cls-stx)] [def-names (filter-map get-def-name fields/defs)]) (check-duplicate-identifier def-names))) (define (forall p l) (for/and ([i l]) (p i))) (define-literal-set keyword-lits ;; Note: I have to define new, send, ... as datum otherwise they ;; are going to be interpreted as identifier during macro ;; expansion and may risk an evaluation with new, send from ;; racket/class. #:datum-literals (new send get-field set-field! this) ;; I have no literals that should be interpreted. ()) Check ` # % app F ARG ... ` is one of defined keywords (define is-keyword? (literal-set->predicate keyword-lits)) ;; (define (is-expr? E) ;; ;; Check `E` is an expression ;; (define expr (syntax-e E)) ;; (cond ;; [(symbol? expr) #t] ;; variable ;; [(number? expr) #t] ;; [else ;; (let ([expr (syntax-e (car expr))]) ;; (member expr '(new let send get-field set-field!)))])) ;; -- Syntax class for type and arg (define-syntax-class type #:description "class' type with ownership and context parameters" #:attributes [TYPE OWNER CPARAMS] #:datum-literals (/) ;; Don't consider '/' as a pattern (pattern (O:id / T:id) #:with OWNER #'O #:with TYPE #'T #:with CPARAMS #''()) (pattern (O:id / (T:id PARAMS:id ...+)) #:with OWNER #'O #:with TYPE #'T #:with CPARAMS #''(PARAMS ...)) (pattern T:id #:with OWNER #''Θ #:with TYPE #'T #:with CPARAMS #''()) (pattern (T:id PARAMS:id ...+) #:with OWNER #''Θ #:with TYPE #'T #:with CPARAMS #''(PARAMS ...)) ) (define-syntax-class arg #:description "argument with its type" #:datum-literals (:) (pattern (NAME:id : T:type) #:attr OWNER #'T.OWNER #:attr TYPE #'T.TYPE #:attr CPARAMS #'T.CPARAMS)) ;; Format TYPE ;; (define (fTYPE TYPE) ;; (syntax-parse TYPE [ ( t : type ) # ' ( t. TYPE t. OWNER t. CPARAMS ) ] ;; [(a:arg) #'(a.TYPE a.OWNER a.CPARAMS)])) ) ;; Syntax parameters, as racket `parameter`, but at transformer level ;; - #syntax-parameters ;; - -of-macros/Syntax_parameters.html ;; ;; These parameters can be accessed inside a syntax object and give the binded stx object in return . E.g. , in the following , ` # ' my - param ` syntax object is , actually , a binder for the ` # ' 42 ` ;; syntax object. ;; > ( define - syntax - parameter my - param ( λ ( stx ) # ' 42 ) ) ;; > ... > # ' ( my - param ) ; 42 ;; ;; And I can later rebind it to another value with ;; `syntax-parameterize`, analogously to `parameterize` . ;; ;; These parameters should take place in a syntax-object for phase 0 ;; (runtime). However, in the following, I use these parameters to track information during phase 1 ( macro expansion ) . Thus , I bind ;; them to a syntax error if someone try to use it a runtime. (define-syntax-parameter current-class-type ;; Syntax object that is ;; the type of the ;; current class. (λ (stx) (raise-syntax-error #f "Should only be used during macro expansion" stx))) (define-syntax-parameter field-types ;; Map of `(class-τ . field-name) -> field-τ` (λ (stx) (raise-syntax-error #f "Should only be used during macro expansion" stx))) Accessing it at phase 1 needs resort to ` syntax - parameter - value ` (define-for-syntax (class-τ) (syntax-parameter-value #'current-class-type)) (define-for-syntax (check-∈f class-τ field-name [context-stx #f]) (let ([fields-τ (syntax-parameter-value #'field-types)] [field-key (cons class-τ field-name)]) (unless (hash-has-key? fields-τ field-key) (raise-syntax-error #f "Field not it class" context-stx field-name)) (hash-ref fields-τ field-key))) (define-for-syntax (field-τ class-τ field-name) (let ([fields-τ (syntax-parameter-value #'field-types)]) (hash-ref fields-τ (cons class-τ field-name)))) (define-for-syntax (stx=? a b) (cond [(and (identifier? a) (identifier? b)) (bound-identifier=? a b)] [(and (syntax? a) (syntax? b)) (and (bound-identifier=? (datum->syntax a '||) (datum->syntax b '||)) (stx=? (syntax-e a) (syntax-e b)))] [else (equal?/recur a b stx=?)])) (define-for-syntax (add-τ e τ) (syntax-property e 'type τ)) (define-for-syntax (get-τ e) (syntax-property e 'type)) (define-for-syntax (compute-τ e) (get-τ (local-expand e 'expression null))) (define-for-syntax (erase-τ e) (local-expand e 'expression null)) (define-for-syntax (comp+erase-τ e) (let* ([e- (local-expand e 'expression null)] [τ (get-τ e-)]) (values e- τ))) (define-for-syntax (check-τ τ1 τ2) (stx=? τ1 τ2)) ;; Expander ;; ----- Class ;; CLASS := (class NAME (C-PARAMS ...) FIELD ... DEF ...) ;; ~> (class O-SCHEME NAME FIELD ... DEF ...) (define-syntax-parser class ;; The `~!` eliminate backtracking. Hence, if the next `fail-when` failed , it will not backtrack to the second pattern , which would ;; create an infinite loop. [(_ NAME:id [CPARAM:id ...] ~! FIELD/DEF:expr ...) #:fail-when (field-twice? #'(FIELD/DEF ...)) "Duplicated field" #:fail-when (def-twice? #'(FIELD/DEF ...)) "Duplicated def" #'(syntax-parameterize ([current-class-type #'NAME] [field-types (hash)]) `(#%class NAME [CPARAM ...] ,FIELD/DEF ...))] # ' ` ( # % class NAME [ CPARAM ... ] B ) ] [(_ NAME:id FIELD/DEF:expr ...) #'(class NAME [] FIELD/DEF ...)] ) ;; ;; FIELD := (field [NAME : TYPE]) ;; ;; ~> (field O-SCHEME NAME) (define-syntax-parser field [(_ ARG:arg) #:with F-ARG (syntax->datum #'ARG) #'`(#%field F-ARG)]) ;; DEF := (def (NAME [ARG:NAME : ARG:TYPE] ... → RET:TYPE) E) ;; ~> (def RET:O-SCHEME NAME (ARG:O-SCHEME ...) E) (define-syntax-parser def #:datum-literals (→) [(_ (DNAME ARG:arg ... → RET:type) BODY:expr) #:with D-ARGs (syntax->datum #'(DNAME ARG ... → RET)) #'`(#%def D-ARGs ,BODY)]) ;; (define-for-syntax (add-τ e τ) (syntax-property e 'type τ)) ;; (define-for-syntax (get-τ e τ) (syntax-property e 'type)) ;; (define-for-syntax (compute-τ e) (get-τ (local-expand e 'expression null))) ( define - for - syntax ( check - τ τ1 τ2 ) ( stx= ? τ1 τ2 ) ) ;; (define-for-syntax (erase-τ e) (local-expand e 'expression null)) ;; (define-for-syntax (comp+erase-τ e) ;; (let* ([e- (local-expand e 'expression null)] ;; [τ (get-τ e-)]) ;; (values e- τ))) (define-syntax-parser @%app #:literal-sets ([keyword-lits]) [(_ new CLASS:type) (add-τ #'`(#%new CLASS) #'CLASS.TYPE)] [(_ get-field E:expr FNAME:id) ;; #:with Cτ (compute-τ #'E) #:with Cτ #''Main ;; (compute-τ #'E) ;; #:when (unless (∈f #'Cτ #'FNAME) ;; (raise-syntax-error #f ( format " Class ~s does n't contains field ~s " # ' Cτ # ' FNAME ) ;; this-syntax)) ;; (printf "~s:~s~n" this-syntax #'Cτ) # : with Fτ ; ; TODO : look into a store such as A for ( Cτ . FNAME ) ; ; then add - τ Fτ #'`(#%get-field ,E FNAME)] [(_ set-field! E1:expr FNAME:id E2:expr) #'`(#%set-field! ,E1 FNAME ,E2)] [(_ send E:expr DNAME:id ARG:expr ...) #'`(#%send ,E DNAME ,ARG ...)] ) ;; `(@%top . id)` refers to a top-level variable. In my lang, every ;; var is considered as a top-level variable since no racket `let` binds it . There is two kind of var : (define-syntax-parser @%top #:literal-sets ([keyword-lits]) ;; - The var is `this`, e.g., `(get-field (@%top . this) my-field)` -#% I rebind it to the core # % this . [(_ . this) (add-τ #''#%this (class-τ))] ;; - The var is presumably a local field of the current class, that ;; is, a sort of shortcut for (get-field this var) -- `var` instead of ` this.var ` in terms of Java . E.g. , ;; > (class C ;; > (field [var : D]) ;; > (def (get-f → D) (@%top . var))) ;; -#% I expand it to the normal form with `this`: ;; > (get-field (@%top . this) var) [(_ . ID:id) #'(@%app get-field (@%top . this) ID)]) (define-syntax-parser @let #:datum-literals (:) [(_ ((ANAME:id : ATYPE:type E:expr) BINDING ...) BODY:expr) A ` @let ` with multiple binding into multiple successive ` @let`s with one unique binding . The first binding of ` @let ` Remaining bindings of ` @let ` ;; #:with bind-name (syntax-local-lift-expression #'ANAME) (syntax-case #'BS () ;; FIXME: my ANAME should bind ANAME in BODY so that every (@%top ;; . var) if BODY refers to a top variable. ;; (define-syntax my-or (make-rename-transformer #'ANAME)) [() #'`(#%let (ANAME : ATYPE ,E) ,BODY)] [_ #'(@let (B1) (@let BS BODY))])]) (define-syntax-parser @%module-begin [(_ CLASS:expr ... E:expr) #:fail-when (check-class #'(CLASS ...)) "Duplicated class name" ;; Check `CLASS ...` is a list of class definition ;; #:when (forall is-class? (syntax->list #'(CLASS ...))) ;; #:with PROG (syntax-local-expand-expression #'(CLASS ... E) ;; #f ;; ) #'(#%module-begin (writeln `(#%prog ,CLASS ... ,E))) ;; (syntax-case #'PROG () [ ( module ( # % plain - module - begin . body ) ) # ` ( # % plain - module - begin ( # % require ) ;; . #,((make-syntax-introducer) #'body)) ;; ]) # ' ( # % module - begin ;; (module surface-module "surface-desugar-lang.rkt" ;; prog)) ]) (provide (rename-out [@%module-begin #%module-begin] [@%top #%top] ;; wrapped unbound variables [@let let] [@%app #%app] ) class field def ownership-scheme ;; current-class #%top-interaction ) ;; ;; ---- Value ; ; ( define - syntax - parser @%datum ; ; [ ( _ . N : ) # '' ( ) ] )
null
https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/CPN98/attic/surface-lang3.rkt
racket
@InProceedings{CPN98, title = {Ownership Types for Flexible Alias Protection}, url = {}, doi = {10.1145/286936.286947} } Naming conventions: -- Syntax checker in the form of -lang.org/syntax/syntax-helpers.html#%28part._stxkeyword%29 A check procedure consumes the syntax to check and a context syntax object for error reporting and either raises an error to reject the syntax or returns a value as its parsed representation. are no duplicate. no duplicate. (field [NAME : TYPE]) no duplicate. (def (NAME [ARG:NAME : ARG:TYPE] ... → RET:TYPE) E) Note: I have to define new, send, ... as datum otherwise they are going to be interpreted as identifier during macro expansion and may risk an evaluation with new, send from racket/class. I have no literals that should be interpreted. (define (is-expr? E) ;; Check `E` is an expression (define expr (syntax-e E)) (cond [(symbol? expr) #t] ;; variable [(number? expr) #t] [else (let ([expr (syntax-e (car expr))]) (member expr '(new let send get-field set-field!)))])) -- Syntax class for type and arg Don't consider '/' as a pattern Format TYPE (define (fTYPE TYPE) (syntax-parse TYPE [(a:arg) #'(a.TYPE a.OWNER a.CPARAMS)])) Syntax parameters, as racket `parameter`, but at transformer level - #syntax-parameters - -of-macros/Syntax_parameters.html These parameters can be accessed inside a syntax object and give syntax object. > ... 42 And I can later rebind it to another value with `syntax-parameterize`, analogously to `parameterize` . These parameters should take place in a syntax-object for phase 0 (runtime). However, in the following, I use these parameters to them to a syntax error if someone try to use it a runtime. Syntax object that is the type of the current class. Map of `(class-τ . field-name) -> field-τ` Expander ----- Class CLASS := (class NAME (C-PARAMS ...) FIELD ... DEF ...) ~> (class O-SCHEME NAME FIELD ... DEF ...) The `~!` eliminate backtracking. Hence, if the next `fail-when` create an infinite loop. ;; FIELD := (field [NAME : TYPE]) ;; ~> (field O-SCHEME NAME) DEF := (def (NAME [ARG:NAME : ARG:TYPE] ... → RET:TYPE) E) ~> (def RET:O-SCHEME NAME (ARG:O-SCHEME ...) E) (define-for-syntax (add-τ e τ) (syntax-property e 'type τ)) (define-for-syntax (get-τ e τ) (syntax-property e 'type)) (define-for-syntax (compute-τ e) (get-τ (local-expand e 'expression null))) (define-for-syntax (erase-τ e) (local-expand e 'expression null)) (define-for-syntax (comp+erase-τ e) (let* ([e- (local-expand e 'expression null)] [τ (get-τ e-)]) (values e- τ))) #:with Cτ (compute-τ #'E) (compute-τ #'E) #:when (unless (∈f #'Cτ #'FNAME) (raise-syntax-error #f this-syntax)) (printf "~s:~s~n" this-syntax #'Cτ) ; TODO : look into a store such as A for ( Cτ . FNAME ) ; then add - τ Fτ `(@%top . id)` refers to a top-level variable. In my lang, every var is considered as a top-level variable since no racket `let` - The var is `this`, e.g., `(get-field (@%top . this) my-field)` - The var is presumably a local field of the current class, that is, a sort of shortcut for (get-field this var) -- `var` instead of > (class C > (field [var : D]) > (def (get-f → D) (@%top . var))) -#% I expand it to the normal form with `this`: > (get-field (@%top . this) var) #:with bind-name (syntax-local-lift-expression #'ANAME) FIXME: my ANAME should bind ANAME in BODY so that every (@%top . var) if BODY refers to a top variable. (define-syntax my-or (make-rename-transformer #'ANAME)) Check `CLASS ...` is a list of class definition #:when (forall is-class? (syntax->list #'(CLASS ...))) #:with PROG (syntax-local-expand-expression #'(CLASS ... E) #f ) (syntax-case #'PROG () . #,((make-syntax-introducer) #'body)) ]) (module surface-module "surface-desugar-lang.rkt" prog)) wrapped unbound variables current-class ;; ---- Value ; ( define - syntax - parser @%datum ; [ ( _ . N : ) # '' ( ) ] )
#lang racket/base author = { and and } , booktitle = { Proceedings of the 1998 { ACM } { SIGPLAN } Conference on Object - Oriented Programming Systems , Languages { \ & } Applications { ( OOPSLA } ' 98 ) , Vancouver , British Columbia , Canada , October 18 - 22 , 1998 . } , pages = { 48 - -64 } , year = { 1998 } , (require (for-meta 2 racket/base syntax/parse syntax/transformer syntax/parse/define racket/syntax racket/match racket/list racket/stxparam "type-checker.rkt" "utils.rkt" ) (for-syntax racket/base syntax/parse syntax/parse/define syntax/transformer syntax/free-vars racket/syntax racket/match racket/list racket/stxparam "type-checker.rkt" "utils.rkt" ) syntax/parse syntax/parse/define racket/match racket/stxparam "type-checker.rkt" ) - X , Y , FOO ( ie , uppercase variables ) and ` stx ' are syntax objects Utils (begin-for-syntax Returns the first duplicate class in the program or # f if there (define (check-class clss-stx) (define (get-class-name cls-stx) (syntax-case cls-stx (class) [(class name) #'name] [(class name _ ...) #'name] [_ (raise-syntax-error #f "Bad syntax for class" cls-stx)])) (let* ([classes (syntax->list clss-stx)] [class-names (map get-class-name classes)]) (check-duplicate-identifier class-names))) Returns the first duplicate field in the class or # f if there are (define (field-twice? cls-stx) (define (get-field-name field/def-stx) (syntax-case field/def-stx (field :) [(field [name : _]) #'name] [_ #f])) (let* ([fields/defs (syntax->list cls-stx)] [field-names (filter-map get-field-name fields/defs)]) (check-duplicate-identifier field-names))) Returns the first duplicate def in the class or # f if there are (define (def-twice? cls-stx) (define (get-def-name field/def-stx) (syntax-case field/def-stx (def : →) [(def (name _ ...) _) #'name] [_ #f])) (let* ([fields/defs (syntax->list cls-stx)] [def-names (filter-map get-def-name fields/defs)]) (check-duplicate-identifier def-names))) (define (forall p l) (for/and ([i l]) (p i))) (define-literal-set keyword-lits #:datum-literals (new send get-field set-field! this) ()) Check ` # % app F ARG ... ` is one of defined keywords (define is-keyword? (literal-set->predicate keyword-lits)) (define-syntax-class type #:description "class' type with ownership and context parameters" #:attributes [TYPE OWNER CPARAMS] (pattern (O:id / T:id) #:with OWNER #'O #:with TYPE #'T #:with CPARAMS #''()) (pattern (O:id / (T:id PARAMS:id ...+)) #:with OWNER #'O #:with TYPE #'T #:with CPARAMS #''(PARAMS ...)) (pattern T:id #:with OWNER #''Θ #:with TYPE #'T #:with CPARAMS #''()) (pattern (T:id PARAMS:id ...+) #:with OWNER #''Θ #:with TYPE #'T #:with CPARAMS #''(PARAMS ...)) ) (define-syntax-class arg #:description "argument with its type" #:datum-literals (:) (pattern (NAME:id : T:type) #:attr OWNER #'T.OWNER #:attr TYPE #'T.TYPE #:attr CPARAMS #'T.CPARAMS)) [ ( t : type ) # ' ( t. TYPE t. OWNER t. CPARAMS ) ] ) the binded stx object in return . E.g. , in the following , ` # ' my - param ` syntax object is , actually , a binder for the ` # ' 42 ` > ( define - syntax - parameter my - param ( λ ( stx ) # ' 42 ) ) track information during phase 1 ( macro expansion ) . Thus , I bind (λ (stx) (raise-syntax-error #f "Should only be used during macro expansion" stx))) (λ (stx) (raise-syntax-error #f "Should only be used during macro expansion" stx))) Accessing it at phase 1 needs resort to ` syntax - parameter - value ` (define-for-syntax (class-τ) (syntax-parameter-value #'current-class-type)) (define-for-syntax (check-∈f class-τ field-name [context-stx #f]) (let ([fields-τ (syntax-parameter-value #'field-types)] [field-key (cons class-τ field-name)]) (unless (hash-has-key? fields-τ field-key) (raise-syntax-error #f "Field not it class" context-stx field-name)) (hash-ref fields-τ field-key))) (define-for-syntax (field-τ class-τ field-name) (let ([fields-τ (syntax-parameter-value #'field-types)]) (hash-ref fields-τ (cons class-τ field-name)))) (define-for-syntax (stx=? a b) (cond [(and (identifier? a) (identifier? b)) (bound-identifier=? a b)] [(and (syntax? a) (syntax? b)) (and (bound-identifier=? (datum->syntax a '||) (datum->syntax b '||)) (stx=? (syntax-e a) (syntax-e b)))] [else (equal?/recur a b stx=?)])) (define-for-syntax (add-τ e τ) (syntax-property e 'type τ)) (define-for-syntax (get-τ e) (syntax-property e 'type)) (define-for-syntax (compute-τ e) (get-τ (local-expand e 'expression null))) (define-for-syntax (erase-τ e) (local-expand e 'expression null)) (define-for-syntax (comp+erase-τ e) (let* ([e- (local-expand e 'expression null)] [τ (get-τ e-)]) (values e- τ))) (define-for-syntax (check-τ τ1 τ2) (stx=? τ1 τ2)) (define-syntax-parser class failed , it will not backtrack to the second pattern , which would [(_ NAME:id [CPARAM:id ...] ~! FIELD/DEF:expr ...) #:fail-when (field-twice? #'(FIELD/DEF ...)) "Duplicated field" #:fail-when (def-twice? #'(FIELD/DEF ...)) "Duplicated def" #'(syntax-parameterize ([current-class-type #'NAME] [field-types (hash)]) `(#%class NAME [CPARAM ...] ,FIELD/DEF ...))] # ' ` ( # % class NAME [ CPARAM ... ] B ) ] [(_ NAME:id FIELD/DEF:expr ...) #'(class NAME [] FIELD/DEF ...)] ) (define-syntax-parser field [(_ ARG:arg) #:with F-ARG (syntax->datum #'ARG) #'`(#%field F-ARG)]) (define-syntax-parser def #:datum-literals (→) [(_ (DNAME ARG:arg ... → RET:type) BODY:expr) #:with D-ARGs (syntax->datum #'(DNAME ARG ... → RET)) #'`(#%def D-ARGs ,BODY)]) ( define - for - syntax ( check - τ τ1 τ2 ) ( stx= ? τ1 τ2 ) ) (define-syntax-parser @%app #:literal-sets ([keyword-lits]) [(_ new CLASS:type) (add-τ #'`(#%new CLASS) #'CLASS.TYPE)] [(_ get-field E:expr FNAME:id) ( format " Class ~s does n't contains field ~s " # ' Cτ # ' FNAME ) #'`(#%get-field ,E FNAME)] [(_ set-field! E1:expr FNAME:id E2:expr) #'`(#%set-field! ,E1 FNAME ,E2)] [(_ send E:expr DNAME:id ARG:expr ...) #'`(#%send ,E DNAME ,ARG ...)] ) binds it . There is two kind of var : (define-syntax-parser @%top #:literal-sets ([keyword-lits]) -#% I rebind it to the core # % this . [(_ . this) (add-τ #''#%this (class-τ))] ` this.var ` in terms of Java . E.g. , [(_ . ID:id) #'(@%app get-field (@%top . this) ID)]) (define-syntax-parser @let #:datum-literals (:) [(_ ((ANAME:id : ATYPE:type E:expr) BINDING ...) BODY:expr) A ` @let ` with multiple binding into multiple successive ` @let`s with one unique binding . The first binding of ` @let ` Remaining bindings of ` @let ` (syntax-case #'BS () [() #'`(#%let (ANAME : ATYPE ,E) ,BODY)] [_ #'(@let (B1) (@let BS BODY))])]) (define-syntax-parser @%module-begin [(_ CLASS:expr ... E:expr) #:fail-when (check-class #'(CLASS ...)) "Duplicated class name" #'(#%module-begin (writeln `(#%prog ,CLASS ... ,E))) [ ( module ( # % plain - module - begin . body ) ) # ` ( # % plain - module - begin ( # % require ) # ' ( # % module - begin ]) (provide (rename-out [@%module-begin #%module-begin] [@let let] [@%app #%app] ) class field def ownership-scheme #%top-interaction )
422792b523e9829856ee9f5c2b639c03709125f3bf4bfb782b0a103c12b07e98
zack-bitcoin/amoveo
governance.erl
-module(governance). -export([tree_number_to_value/1, max/1, is_locked/1, genesis_state/0, name2number/1, number2name/1,%custom for this tree get_value/2, get/2, write/2,%update tree stuff dict_get/2,dict_get/3,dict_write/2, dict_get_value/2, dict_lock/2, dict_unlock/2, dict_change/3, %update dict stuff verify_proof/4,make_leaf/3,key_to_int/1, serialize/1,deserialize/1, new/2, test/0]).%common tree stuff -define(name, governance). -define(fee, constants:encoded_fee()). -include("../../records.hrl"). genesis_state() -> {MinimumOracleTime, MaximumOracleTime, BlockPeriod} = case application:get_env(amoveo_core, test_mode, false) of true - > { 1 , 1 , 100 } ; true -> {1, 1, 5}; false -> {352, 505, 550} end, G = [[block_reward, 1620], [developer_reward, 429], [time_gas, 1113], [space_gas, 1113], [max_block_size, 940], [block_period, BlockPeriod], [fun_limit, 350], [var_limit, 600], [oracle_initial_liquidity, 1500], [minimum_oracle_time, MinimumOracleTime], [maximum_oracle_time, MaximumOracleTime], [maximum_question_size, 352], [governance_change_limit, 51], [create_acc_tx, ?fee], [spend, ?fee], [delete_acc_tx, 0], [nc, ?fee], [ctc, ?fee], [csc, ?fee], [timeout, ?fee], [cs, ?fee], [ex, ?fee], [oracle_new, ?fee], [oracle_bet, ?fee], [oracle_close, ?fee], [unmatched, ?fee], [oracle_winnings, ?fee]], R = trees:empty_tree(governance), {ok, GenesisTree} = genesis_state(G, R), GenesisTree. genesis_state([], Tree) -> {ok, Tree}; genesis_state([[Name, Value] | Rest], Tree0) -> Id = name2number(Name), NewGovernance = new(Id, Value), Tree = write(NewGovernance, Tree0), genesis_state(Rest, Tree). dict_change(Name, Amount, Dict) -> Gov0 = dict_get(Name, Dict), Value0 = Gov0#gov.value + Amount, Value = max(Value0, 1), Gov = Gov0#gov{value = Value, lock = 0}, dict_write(Gov, Dict). dict_lock(Name, Dict) -> Gov0 = dict_get(Name, Dict), Gov = Gov0#gov{lock = 1}, dict_write(Gov, Dict). dict_unlock(Name, Dict) -> Gov0 = dict_get(Name, Dict), Gov = Gov0#gov{lock = 0}, dict_write(Gov, Dict). is_locked(Gov) -> case Gov#gov.lock of 0 -> false; 1 -> true end. tree_number_to_value(T) when T < 101 -> T; tree_number_to_value(T) -> tree_number_to_value_exponential(T - 100). tree_number_to_value_exponential(T) -> Top = 101, Bottom = 100, det_power(Top, Bottom, T). det_power(Top, Bottom, T) -> det_power(10000, Top, Bottom, T) div 100. det_power(Base, Top, Bottom, 1) -> (Base * Top) div Bottom; det_power(Base, Top, Bottom, T) -> R = T rem 2, case R of 1 -> B2 = (Base * Top) div Bottom, det_power(B2, Top, Bottom, T-1); 0 -> det_power(Base, (Top*Top) div Bottom, Bottom, T div 2) end. serialize(Gov) -> <<(Gov#gov.id):8, (Gov#gov.value):16, (Gov#gov.lock):8>>. get_value(coinbase, _) -> 0; get_value(Name, Tree) -> {_, Gov, _} = get(Name, Tree), tree_number_to_value(Gov#gov.value). key_to_int(X) when is_atom (X) -> name2number(X); key_to_int(X) -> X. get(Name, Tree) when is_atom(Name) -> case name2number(Name) of bad -> {error, unknown_name}; Key -> get(Key, Tree) end; get(Key, Tree) when is_integer(Key) -> {X, Leaf, Proof} = trie:get(Key, Tree, ?name), V = case Leaf of empty -> {error, empty_leaf}; L -> LeafValue = leaf:value(L), deserialize(LeafValue) end, {X, V, Proof}. %Blockchain variables name2number(block_reward) -> 1; name2number(developer_reward) -> 2; name2number(max_block_size) -> 3; name2number(block_period) -> 4; %VM variables name2number(time_gas) -> 5; name2number(space_gas) -> 6; name2number(fun_limit) -> 7;%how many functions can the vm make name2number(var_limit) -> 8;%how many variables can the vm store Oracle variables name2number(governance_change_limit) -> 9; name2number(oracle_initial_liquidity) -> 10; name2number(minimum_oracle_time) -> 11; name2number(maximum_oracle_time) -> 12; name2number(maximum_question_size) -> 13; %Transaction fees name2number(create_acc_tx) -> 14;%these store the minimum fee for each transaction type. "create_acc_tx" is the name of the record of the create_account_tx. name2number(spend) -> 15; name2number(delete_acc_tx) -> 16; name2number(nc) -> 17; name2number(nc_accept) -> 17; name2number(ctc) -> 18; name2number(ctc2) -> 18; name2number(csc) -> 19; name2number(timeout) -> 20; name2number(cs) -> 21; name2number(ex) -> 22; name2number(oracle_new) -> 23; name2number(oracle_bet) -> 24; name2number(oracle_close) -> 25; name2number(unmatched) -> 26; name2number(oracle_winnings) -> 27; name2number(oracle_question_liquidity) -> 28; name2number(contract_new_tx) -> 29; name2number(contract_use_tx) -> 30; name2number(sub_spend_tx) -> 31; name2number(contract_evidence_tx) -> 32; name2number(contract_timeout_tx) -> 33; name2number(contract_winnings_tx) -> 34; name2number(contract_simplify_tx) -> 35; name2number(max_contract_flavors) -> 36; name2number(swap_tx) -> 37; name2number(market_new_tx) -> 38; name2number(market_liquidity_tx) -> 39; name2number(market_swap_tx) -> 40; name2number(market_trading_fee) -> 41; name2number(swap_tx2) -> 42; name2number(trade_cancel_tx) -> 43; name2number(stablecoin_new_tx) -> 44; name2number(X) -> io:fwrite(X), 1=2, throw(invalid_governance_atom). number2name(1) -> block_reward; number2name(2) -> developer_reward; number2name(3) -> max_block_size; number2name(4) -> block_period; number2name(5) -> time_gas; number2name(6) -> space_gas; number2name(7) -> fun_limit; number2name(8) -> var_limit; number2name(9) -> governance_change_limit; number2name(10) -> oracle_initial_liquidity; number2name(11) -> minimum_oracle_time; number2name(12) -> maximum_oracle_time; number2name(13) -> maximum_question_size; number2name(14) -> create_acc_tx; number2name(15) -> spend; number2name(16) -> delete_acc_tx; number2name(17) -> nc; number2name(18) -> ctc; number2name(19) -> csc; number2name(20) -> timeout; number2name(21) -> cs; number2name(22) -> ex; number2name(23) -> oracle_new; number2name(24) -> oracle_bet; number2name(25) -> oracle_close; number2name(26) -> unmatched; number2name(27) -> oracle_winnings; number2name(28) -> oracle_question_liquidity; number2name(29) -> contract_new_tx; number2name(30) -> contract_use_tx; number2name(31) -> sub_spend_tx; number2name(32) -> contract_evidence_tx; number2name(33) -> contract_timeout_tx; number2name(34) -> contract_winnings_tx; number2name(35) -> contract_simplify_tx; number2name(36) -> max_contract_flavors; number2name(37) -> swap_tx; number2name(38) -> market_new_tx; number2name(39) -> market_liquidity_tx; number2name(40) -> market_swap_tx; number2name(41) -> market_trading_fee; number2name(42) -> swap_tx2; number2name(43) -> trade_cancel_tx; number2name(44) -> stablecoin_new_tx; number2name(X) -> io:fwrite(X), 1=2, error. max(Height) -> B = Height > forks:get(5), if B -> 29; true -> 28 end. make_leaf(Key, V, CFG) -> Key2 = if is_integer(Key) -> Key; true -> name2number(Key) end, leaf:new(Key2, V, 0, CFG). verify_proof(RootHash, Key, Value, Proof) -> trees:verify_proof(?MODULE, RootHash, Key, Value, Proof). %% Internals Everything fits into 32 - bit values new(Id, Value) -> new(Id, Value, 0). new(Id, Value, Lock) -> #gov{id = Id, value = Value, lock = Lock}. dict_write(Gov, Dict) -> Key = Gov#gov.id, dict:store({governance, Key}, serialize(Gov), Dict). write(Gov, Tree) -> Key = Gov#gov.id, Serialized = serialize(Gov), trie:put(Key, Serialized, 0, Tree, ?name). deserialize(SerializedGov) -> <<Id:8, Value:16, Lock:8>> = SerializedGov, #gov{id = Id, value = Value, lock = Lock}. dict_get_value(Key, Dict) when ((Key == timeout) or (Key == delete_acc_tx)) -> case dict_get(Key, Dict) of error -> error; empty -> empty; Gov -> V = Gov#gov.value, -tree_number_to_value(V) end; dict_get_value(Key, Dict) -> case dict_get(Key, Dict) of error -> error; empty -> empty; Gov -> V = Gov#gov.value, tree_number_to_value(V) end. dict_get(Key0, Dict) -> dict_get(Key0, Dict, 0). dict_get(Key0, Dict, Height) -> Key = if is_integer(Key0) -> Key0; true -> name2number(Key0) end, case dict:find({governance, Key}, Dict) of error -> empty; {ok, X} -> deserialize(X) end. %% Tests test() -> Num = name2number(fun_limit), C = new(Num, 1, 0), Trees = (tx_pool:get())#tx_pool.block_trees, Governance = trees:governance(Trees), Leaf = {gov, Num, 350, 0}, Leaf = deserialize(serialize(Leaf)), {_, Leaf, _} = get(fun_limit, Governance), G2 = write(C, Governance), {_, C2, _} = get(fun_limit, G2), io:fwrite(packer:pack([C, C2])), C = C2, {Root, Leaf, Proof} = get(fun_limit, Governance), true = verify_proof(Root, fun_limit, serialize(Leaf), Proof), success.
null
https://raw.githubusercontent.com/zack-bitcoin/amoveo/257f3e8cc07f1bae9df1a7252b8bc67a0dad3262/apps/amoveo_core/src/consensus/trees/governance.erl
erlang
custom for this tree update tree stuff update dict stuff common tree stuff Blockchain variables VM variables how many functions can the vm make how many variables can the vm store Transaction fees these store the minimum fee for each transaction type. "create_acc_tx" is the name of the record of the create_account_tx. Internals Tests
-module(governance). verify_proof/4,make_leaf/3,key_to_int/1, serialize/1,deserialize/1, new/2, -define(name, governance). -define(fee, constants:encoded_fee()). -include("../../records.hrl"). genesis_state() -> {MinimumOracleTime, MaximumOracleTime, BlockPeriod} = case application:get_env(amoveo_core, test_mode, false) of true - > { 1 , 1 , 100 } ; true -> {1, 1, 5}; false -> {352, 505, 550} end, G = [[block_reward, 1620], [developer_reward, 429], [time_gas, 1113], [space_gas, 1113], [max_block_size, 940], [block_period, BlockPeriod], [fun_limit, 350], [var_limit, 600], [oracle_initial_liquidity, 1500], [minimum_oracle_time, MinimumOracleTime], [maximum_oracle_time, MaximumOracleTime], [maximum_question_size, 352], [governance_change_limit, 51], [create_acc_tx, ?fee], [spend, ?fee], [delete_acc_tx, 0], [nc, ?fee], [ctc, ?fee], [csc, ?fee], [timeout, ?fee], [cs, ?fee], [ex, ?fee], [oracle_new, ?fee], [oracle_bet, ?fee], [oracle_close, ?fee], [unmatched, ?fee], [oracle_winnings, ?fee]], R = trees:empty_tree(governance), {ok, GenesisTree} = genesis_state(G, R), GenesisTree. genesis_state([], Tree) -> {ok, Tree}; genesis_state([[Name, Value] | Rest], Tree0) -> Id = name2number(Name), NewGovernance = new(Id, Value), Tree = write(NewGovernance, Tree0), genesis_state(Rest, Tree). dict_change(Name, Amount, Dict) -> Gov0 = dict_get(Name, Dict), Value0 = Gov0#gov.value + Amount, Value = max(Value0, 1), Gov = Gov0#gov{value = Value, lock = 0}, dict_write(Gov, Dict). dict_lock(Name, Dict) -> Gov0 = dict_get(Name, Dict), Gov = Gov0#gov{lock = 1}, dict_write(Gov, Dict). dict_unlock(Name, Dict) -> Gov0 = dict_get(Name, Dict), Gov = Gov0#gov{lock = 0}, dict_write(Gov, Dict). is_locked(Gov) -> case Gov#gov.lock of 0 -> false; 1 -> true end. tree_number_to_value(T) when T < 101 -> T; tree_number_to_value(T) -> tree_number_to_value_exponential(T - 100). tree_number_to_value_exponential(T) -> Top = 101, Bottom = 100, det_power(Top, Bottom, T). det_power(Top, Bottom, T) -> det_power(10000, Top, Bottom, T) div 100. det_power(Base, Top, Bottom, 1) -> (Base * Top) div Bottom; det_power(Base, Top, Bottom, T) -> R = T rem 2, case R of 1 -> B2 = (Base * Top) div Bottom, det_power(B2, Top, Bottom, T-1); 0 -> det_power(Base, (Top*Top) div Bottom, Bottom, T div 2) end. serialize(Gov) -> <<(Gov#gov.id):8, (Gov#gov.value):16, (Gov#gov.lock):8>>. get_value(coinbase, _) -> 0; get_value(Name, Tree) -> {_, Gov, _} = get(Name, Tree), tree_number_to_value(Gov#gov.value). key_to_int(X) when is_atom (X) -> name2number(X); key_to_int(X) -> X. get(Name, Tree) when is_atom(Name) -> case name2number(Name) of bad -> {error, unknown_name}; Key -> get(Key, Tree) end; get(Key, Tree) when is_integer(Key) -> {X, Leaf, Proof} = trie:get(Key, Tree, ?name), V = case Leaf of empty -> {error, empty_leaf}; L -> LeafValue = leaf:value(L), deserialize(LeafValue) end, {X, V, Proof}. name2number(block_reward) -> 1; name2number(developer_reward) -> 2; name2number(max_block_size) -> 3; name2number(block_period) -> 4; name2number(time_gas) -> 5; name2number(space_gas) -> 6; Oracle variables name2number(governance_change_limit) -> 9; name2number(oracle_initial_liquidity) -> 10; name2number(minimum_oracle_time) -> 11; name2number(maximum_oracle_time) -> 12; name2number(maximum_question_size) -> 13; name2number(spend) -> 15; name2number(delete_acc_tx) -> 16; name2number(nc) -> 17; name2number(nc_accept) -> 17; name2number(ctc) -> 18; name2number(ctc2) -> 18; name2number(csc) -> 19; name2number(timeout) -> 20; name2number(cs) -> 21; name2number(ex) -> 22; name2number(oracle_new) -> 23; name2number(oracle_bet) -> 24; name2number(oracle_close) -> 25; name2number(unmatched) -> 26; name2number(oracle_winnings) -> 27; name2number(oracle_question_liquidity) -> 28; name2number(contract_new_tx) -> 29; name2number(contract_use_tx) -> 30; name2number(sub_spend_tx) -> 31; name2number(contract_evidence_tx) -> 32; name2number(contract_timeout_tx) -> 33; name2number(contract_winnings_tx) -> 34; name2number(contract_simplify_tx) -> 35; name2number(max_contract_flavors) -> 36; name2number(swap_tx) -> 37; name2number(market_new_tx) -> 38; name2number(market_liquidity_tx) -> 39; name2number(market_swap_tx) -> 40; name2number(market_trading_fee) -> 41; name2number(swap_tx2) -> 42; name2number(trade_cancel_tx) -> 43; name2number(stablecoin_new_tx) -> 44; name2number(X) -> io:fwrite(X), 1=2, throw(invalid_governance_atom). number2name(1) -> block_reward; number2name(2) -> developer_reward; number2name(3) -> max_block_size; number2name(4) -> block_period; number2name(5) -> time_gas; number2name(6) -> space_gas; number2name(7) -> fun_limit; number2name(8) -> var_limit; number2name(9) -> governance_change_limit; number2name(10) -> oracle_initial_liquidity; number2name(11) -> minimum_oracle_time; number2name(12) -> maximum_oracle_time; number2name(13) -> maximum_question_size; number2name(14) -> create_acc_tx; number2name(15) -> spend; number2name(16) -> delete_acc_tx; number2name(17) -> nc; number2name(18) -> ctc; number2name(19) -> csc; number2name(20) -> timeout; number2name(21) -> cs; number2name(22) -> ex; number2name(23) -> oracle_new; number2name(24) -> oracle_bet; number2name(25) -> oracle_close; number2name(26) -> unmatched; number2name(27) -> oracle_winnings; number2name(28) -> oracle_question_liquidity; number2name(29) -> contract_new_tx; number2name(30) -> contract_use_tx; number2name(31) -> sub_spend_tx; number2name(32) -> contract_evidence_tx; number2name(33) -> contract_timeout_tx; number2name(34) -> contract_winnings_tx; number2name(35) -> contract_simplify_tx; number2name(36) -> max_contract_flavors; number2name(37) -> swap_tx; number2name(38) -> market_new_tx; number2name(39) -> market_liquidity_tx; number2name(40) -> market_swap_tx; number2name(41) -> market_trading_fee; number2name(42) -> swap_tx2; number2name(43) -> trade_cancel_tx; number2name(44) -> stablecoin_new_tx; number2name(X) -> io:fwrite(X), 1=2, error. max(Height) -> B = Height > forks:get(5), if B -> 29; true -> 28 end. make_leaf(Key, V, CFG) -> Key2 = if is_integer(Key) -> Key; true -> name2number(Key) end, leaf:new(Key2, V, 0, CFG). verify_proof(RootHash, Key, Value, Proof) -> trees:verify_proof(?MODULE, RootHash, Key, Value, Proof). Everything fits into 32 - bit values new(Id, Value) -> new(Id, Value, 0). new(Id, Value, Lock) -> #gov{id = Id, value = Value, lock = Lock}. dict_write(Gov, Dict) -> Key = Gov#gov.id, dict:store({governance, Key}, serialize(Gov), Dict). write(Gov, Tree) -> Key = Gov#gov.id, Serialized = serialize(Gov), trie:put(Key, Serialized, 0, Tree, ?name). deserialize(SerializedGov) -> <<Id:8, Value:16, Lock:8>> = SerializedGov, #gov{id = Id, value = Value, lock = Lock}. dict_get_value(Key, Dict) when ((Key == timeout) or (Key == delete_acc_tx)) -> case dict_get(Key, Dict) of error -> error; empty -> empty; Gov -> V = Gov#gov.value, -tree_number_to_value(V) end; dict_get_value(Key, Dict) -> case dict_get(Key, Dict) of error -> error; empty -> empty; Gov -> V = Gov#gov.value, tree_number_to_value(V) end. dict_get(Key0, Dict) -> dict_get(Key0, Dict, 0). dict_get(Key0, Dict, Height) -> Key = if is_integer(Key0) -> Key0; true -> name2number(Key0) end, case dict:find({governance, Key}, Dict) of error -> empty; {ok, X} -> deserialize(X) end. test() -> Num = name2number(fun_limit), C = new(Num, 1, 0), Trees = (tx_pool:get())#tx_pool.block_trees, Governance = trees:governance(Trees), Leaf = {gov, Num, 350, 0}, Leaf = deserialize(serialize(Leaf)), {_, Leaf, _} = get(fun_limit, Governance), G2 = write(C, Governance), {_, C2, _} = get(fun_limit, G2), io:fwrite(packer:pack([C, C2])), C = C2, {Root, Leaf, Proof} = get(fun_limit, Governance), true = verify_proof(Root, fun_limit, serialize(Leaf), Proof), success.
54d6107e41c1c2f7f9ac99049043d3e161b752b8a48ff7b580a681f4edfc8d5c
appleshan/cl-http
report.lisp
-*- Mode : LISP ; Syntax : ANSI - Common - Lisp ; Package : http ; Base : 10 ; Default - character - style : ( : fix : : normal ) -*- ( C ) Copyright 1994 - 99 , 2003 , 2005 - 2006 , ;;; All Rights Reserved. ;;; (in-package :http) ;;;------------------------------------------------------------------- ;;; ;;; REPORTING RELATED TO HTTP CONDITIONS ;;; (defmacro server-supports-chunking-p (server) `(and #+disable-chunking nil (client-http-version-meets-p ,server :http/1.1))) (defgeneric report-status-line (http-condition stream) (:documentation "Primitive that sends a status line over an HTTP connection.")) (defmethod report-status-line ((condition http-condition) stream) (declare (ignore stream)) (error "The condition, ~S, cannot be reported to the client." condition)) (defmethod report-status-line ((condition reportable-condition) stream) (let* ((status-code (status-code condition)) (reason (or (http-reason condition) (get-string-for-status-code status-code)))) (send-status-line stream status-code reason))) (defgeneric report-status-message (http-condition stream &optional format-string format-args) (:documentation "Primitive that sends a status body message over an HTTP connection.")) (defmethod report-status-message ((condition http-condition) stream &optional format-string format-args) (declare (ignore stream format-string format-args)) (error "The condition, ~S, cannot be reported to the client." condition)) (define cl-http-signature (&optional (stream *output-stream*)) "Writes the server signature as an address on STREAM." (with-emphasis (:address :stream stream) (note-anchor *server-version* :reference *cl-http-home-page-url-string* :stream stream))) (defun %report-status-message (url reason stream &optional reporter) (with-cl-http-html-document (:declare-dtd-version-p :strict :stream stream) (with-document-look-preamble (:stream stream) (declare-title reason :stream stream)) (with-document-look-body (:heading reason :header-class "header.cl-http" :body-class "body.cl-http" :footer-class "footer.cl-http" :stream stream) (with-paragraph (:stream stream) (cond (reporter (with-verbatim-text (:fresh-line nil :stream stream) (etypecase reporter (string (html:write-string-quoting-specials reporter stream)) ((or symbol function) (funcall reporter url stream))))) (url (fast-format stream "~A for URI ~A" reason (url:relative-name-string-for-locally-served-url url))) (t (fast-format stream "~&HTTP Status Code ~D not properly reported.~I~ ~&Please advise the server maintainer at: ~I" (server-status *server*) (break-line :stream stream)) (note-anchor (server-mail-address) :reference #'write-server-mail-address :stream stream))))))) (defmethod report-status-message ((condition reportable-condition) stream &optional format-string format-args) (let ((reason (or (http-reason condition) (get-string-for-status-code (status-code condition)))) (url (http-url condition))) (unless format-string (setq format-string (format-string condition))) (unless format-args (setq format-args (format-args condition))) (cond (format-string (let ((report (apply #'format nil format-string format-args))) (declare (dynamic-extent report)) (%report-status-message url reason stream report))) (t (%report-status-message url reason stream (http-reporter condition)))))) (defmethod report-status-message ((condition document-moved) stream &optional format-string format-args) (declare (ignore format-string format-args)) (let ((new-urls (new-urls condition)) (reason (http-reason condition))) (with-cl-http-html-document (:declare-dtd-version-p :strict :stream stream) (with-document-look-preamble (:stream stream) (declare-title reason :stream stream)) (with-document-look-body (:heading reason :header-class "header.cl-http" :body-class "body.cl-http" :footer-class "footer.cl-http" :stream stream) (with-paragraph (:stream stream) (write-string "This document has moved " stream) (typecase new-urls (cons (cond ((cdr new-urls) (loop for urls = new-urls then (cdr urls) for num upfrom 1 while urls do (with-anchor-noted (:reference (car new-urls) :stream stream) (fast-format stream "here ~D" num)) while (cdr urls) do (write ", "))) (t (note-anchor "here" :reference (car new-urls) :stream stream)))) (t (note-anchor "here" :reference new-urls :stream stream))) (write-char #\. stream)))))) (defmethod report-status-message ((condition inconsistent-digest-authorization-uri) stream &optional format-string format-args) (flet ((report-inconsistent-authorization-uri (request-uri stream) (let ((authorization (http-authorization condition)) (method (http-method condition)) (proxy-p (http-proxy-p condition))) (destructuring-bind (scheme &key uri &allow-other-keys) authorization (format stream "~&The REQUEST URI for the HTTP method, ~A, is not equal to the URI~&provided in the ~A ~:[~;PROXY-~]AUTHORIZATION header.~ ~2%~5TREQUEST-URL: ~S~&~13TURI: ~S~2%~5T~:[~;PROXY-~]AUTHORIZATION: ~{~&~10T~A: ~S~}" method scheme proxy-p request-uri uri proxy-p (cdr authorization)))))) (declare (dynamic-extent #'report-inconsistent-authorization-uri)) (let ((format (or format-string (format-string condition)))) (if format (call-next-method condition stream format (or format-args (format-args condition))) (%report-status-message (http-url condition) (http-reason condition) stream #'report-inconsistent-authorization-uri))))) (defun report-proxy-access-forbidden (url stream) (declare (ignore url)) (let ((server *server*)) (if server (fast-format stream "Proxy Access via ~A on port ~D is not available for your host at ~A." (server-local-host-domain-name server) (SERVER-HOST-LOCAL-PORT server) (server-host-ip-address server)) (fast-format stream "Proxy Access is not available for your host.")))) (defun report-proxy-connect-method-forbidden (authority stream) (let ((server *server*)) (if server (fast-format stream "Proxy CONNECT to ~A on port ~D is not allowed via ~A on port ~D." (host-string authority) (host-port authority) (server-local-host-domain-name server) (server-host-local-port server)) (fast-format stream "Proxy CONNECT to ~A on port ~D is not allowed." (host-string authority) (host-port authority))))) (define-generic http-url-string (reportable-condition) (:documentation "Returns the URL string for REPORTABLE-CONDITION, or null is a URL is unavailable.")) (defmethod http-url-string ((condition reportable-condition)) (let ((url (http-url condition))) (etypecase url (null nil) (string url) (url:url (url:name-string url))))) ;;;------------------------------------------------------------------- ;;; ;;; REPORT STATUS ;;; (define-generic report-http-headers (http-condition stream &optional termination-line-p header-plist content-type) (:documentation "Top-level methods for sending HTTP headers accompanying REPORT-STATUS.")) #+ignore (progn (defparameter count 0) (defmethod report-http-headers ((condition null) stream &optional (termination-line-p t) header-plist content-type) (when (< count 1) (incf count) (tv:notify nil "REPORT-HTTP-HEADERS error is in a break. Go debug it.") (break "Lost with null condition."))) ) (defmethod report-http-headers ((condition condition) stream &optional (termination-line-p t) header-plist (content-type :html)) (let ((headers `(:date ,(server-request-time *server*) :server ,*server-version* :connection (:close) ,.(when content-type `(:content-type ,(%mime-content-type-spec content-type))) ,@header-plist))) (declare (dynamic-extent headers)) (write-headers stream headers termination-line-p))) (defmethod report-http-headers ((condition reportable-condition) stream &optional (termination-line-p t) header-plist (content-type :html) &aux (server *server*)) (when (http-close-connection-p condition) (setf (server-close-connection-p server) t)) (%write-document-mime-headers stream content-type nil nil nil nil nil nil nil nil nil nil nil termination-line-p nil header-plist)) (defmethod report-http-headers :around ((condition method-not-allowed) stream &optional (termination-line-p t) header-plist content-type) (let* ((url (http-url condition)) (server *server*) ;; If the url is an uninterned search URL, we just default to the standard methods on the server 8/7/96 -- JCMa . (more-headers `(:allow ,(http-methods (or (and url (intern-url url :if-does-not-exist :soft)) server) (server-http-version server)) ,@header-plist))) (declare (dynamic-extent more-headers)) (case (http-method condition) close connection because the 1.0 servers will try to blast put data at us , and we do n't know that the connection is syncrhonizable (unless (server-supports-chunking-p server) (setf (server-close-connection-p server) t)))) (call-next-method condition stream termination-line-p more-headers content-type))) (defmethod report-http-headers ((condition cacheable-condition-mixin) stream &optional (termination-line-p t) header-plist (content-type :html)) (let ((server *server*) (url (http-url condition)) cache-control expires) (when (http-close-connection-p condition) (setf (server-close-connection-p server) t)) (if (server-supports-chunking-p server) (setq cache-control (url:response-cache-control-directives url)) (setq expires (url:expiration-universal-time url))) (%write-document-mime-headers stream content-type nil nil nil nil expires nil nil nil nil nil cache-control termination-line-p nil header-plist))) (define-generic report-status (http-condition stream) (:documentation "Top-level function for reporting a condition over an HTTP connection.")) (defmethod report-status ((condition http-condition) stream) (declare (ignore stream)) (error "The condition, ~S, cannot be reported to the client." condition)) (defmethod report-status ((condition reportable-condition) stream) (let* ((server *server*) (method (or (server-method server) (http-method condition)))) (case method (:head ;; head never sends a body (report-status-line condition stream) (report-http-headers condition stream t)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil)) (report-status-message condition stream))) (t (report-status-line condition stream) (report-http-headers condition stream t) (report-status-message condition stream))))))) ;; Don't bother reporting to dead TCP streams. (defmethod report-status :around ((condition reportable-condition) stream) (when (www-utils:live-connection-p stream) (call-next-method))) (defmethod report-status ((error url:parsing-error) stream) (let* ((url (url:url-string error)) (reason (get-string-for-status-code 400)) (server *server*) (method (server-method server))) (case method (:head ;; head never sends a body (send-status-line stream 400 reason) (report-http-headers error stream t nil nil)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (send-status-line stream 400 reason) (report-http-headers error stream nil)) (%report-status-message url reason stream))) (t (send-status-line stream 400 reason) (report-http-headers error stream t) (%report-status-message url reason stream))))))) ;; Doesn't inherit from reportable condition (defmethod report-status :around ((condition url:parsing-error) stream) (when (www-utils:live-connection-p stream) (call-next-method))) (defvar *report-status-condition* nil "Current condition being reported by REPORT-STATUS.") ;; Move this up to the highest condition to catch anything -- JCMa 12/1/2003 ( defmethod report - status : around ( ( condition condition ) stream ) ; (flet ((report-rentrant-error (primary-error secondary-error) ; (let ((secondary-error-type (type-of secondary-error))) ; (report-bug *bug-http-server* ; (format nil "REPORT-STATUS Re-entrant Error: ~S" secondary-error-type) ; "~:[~;~&Log: ~:*~S~]~&Primary Error: ~S~:[~;~&Primary Error Report: ~:*~A~]~ ; ~&Secondary Error: ~S~:[~;~&Secondary Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" ; (when http:*server* (write-extended-common-logfile-entry http:*server* nil)) ; (type-of primary-error) (report-string primary-error) (type-of secondary-error) (report-string secondary-error) ; (when *stack-backtraces-in-bug-reports* (stack-backtrace-string condition)))))) ; (cond (*report-status-condition* ; (report-rentrant-error *report-status-condition* condition)) ; (t (let ((*report-status-condition* condition)) ; (handler-case-if (not *debug-server*) ; (with-text-stream (stream :output) ;in case we're in binary mode ; (call-next-method condition stream)) ; (network-error () nil) ;no need to report errors telling the user he lost ; (condition (cond) (bug-report-error cond)))))))) ;; Catch any errors reporting errors. Errors that re-enter this code ;; are sure losers attempting to resignal within the process of ;; signalling the original error. These cases are detected and handled in a safe manner . 9/22/99 -- JCMa . Use handler - bind so that stack backtraces are visible in , inter alia , LW -- JCMa 10/3/2006 (defmethod report-status :around ((condition condition) stream) (labels ((report-rentrant-error (primary-error secondary-error) (let ((secondary-error-type (type-of secondary-error))) (report-bug *bug-http-server* (format nil "REPORT-STATUS Re-entrant Error: ~S" secondary-error-type) "~:[~;~&Log: ~:*~S~]~&Primary Error: ~S~:[~;~&Primary Error Report: ~:*~A~]~ ~&Secondary Error: ~S~:[~;~&Secondary Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (when http:*server* (write-extended-common-logfile-entry http:*server* nil)) (type-of primary-error) (report-string primary-error) (type-of secondary-error) (report-string secondary-error) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string condition))))) (handle-cond (error) (etypecase error (network-error nil) ; no need to report errors telling the user he lost (condition (bug-report-error error) t)))) (cond (*report-status-condition* (report-rentrant-error *report-status-condition* condition)) (t (let ((*report-status-condition* condition)) (handler-bind-if (not *debug-server*) ((error #'handle-cond)) (with-text-stream (stream :output) ;in case we're in binary mode (call-next-method condition stream)))))))) ;; Handles any residual errors not covered by other condition types. (defmethod report-status-unhandled-error ((error condition) stream request) (flet ((report-the-secondary-error (error stream reason) (let* ((report-string (report-string error)) (report (with-output-to-string (string) (with-paragraph (:stream string) (with-rendition (:bold :stream string) (write-string "Request: " string)) (if request (write-string request string) "{Not available}")) (with-paragraph (:stream string) (with-rendition (:bold :stream string) (write-string "Error: " string)) (with-verbatim-text (:fresh-line nil :stream stream) (write-string-quoting-specials report-string string)))))) (declare (dynamic-extent report-string report)) (%report-status-message nil reason stream report)))) (let ((reason (get-string-for-status-code 500))) (cond ((handler-case (server-supports-chunking-p *server*) (error () nil)) (%with-chunked-transfer-encoding (stream) (progn (send-status-line stream 500 reason) (report-http-headers error stream nil)) (report-the-secondary-error error stream reason))) (t (send-status-line stream 500 reason) (report-http-headers error stream t) (report-the-secondary-error error stream reason)))))) (defmethod report-status-unhandled-error :around ((error condition) stream request) (declare (ignore request)) (when (www-utils:live-connection-p stream) (call-next-method)) (bug-report-error error)) (defmethod report-status ((condition server-internal-error) stream) an internal error may be encapsulated or not ! 2/28/2001 -- JCMa . (error-report (and error (report-string error))) (server *server*) (method (or (server-method server) (http-method condition)))) (case method (:head ;; head redirects never send a body (report-status-line condition stream) (report-http-headers error stream t)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers error stream nil)) (report-status-message condition stream error-report))) (t (report-status-line condition stream) (report-http-headers error stream t) (report-status-message condition stream error-report))))))) (defmethod report-status :around ((condition server-internal-error) stream) stream ;ignore (when (www-utils:live-connection-p stream) (call-next-method)) (bug-report-error condition)) ;; This is quite inline so that it doesn't waste time when the server is on the edge. (defmethod report-status ((condition server-overloaded) stream) (flet ((report-the-message (stream reason) (with-html-document (:declare-dtd-version-p t :stream stream) (with-document-preamble (:stream stream) (declare-title reason :stream stream)) (with-standard-document-body (:stream stream) (with-section-heading (reason :stream stream) (horizontal-line :stream stream) (with-paragraph (:stream stream) (etypecase *overload-message* (null (write-string "This server is currently operating at capacity and cannot accept your request. Please try again later." stream)) (string (write-string *overload-message* stream)) (function (funcall *overload-message* condition stream)) (symbol (funcall (fdefinition *overload-message*) condition stream)))) (horizontal-line :stream stream) (cl-http-signature stream)))))) (let* ((status-code (status-code condition)) (reason (or (http-reason condition) (get-string-for-status-code status-code))) (server *server*) (method (or (server-method server) (http-method condition)))) (case method (:head ;; head redirects never send a body (send-status-line stream status-code reason) (report-http-headers condition stream t)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (send-status-line stream status-code reason) (report-http-headers condition stream nil)) (report-the-message stream reason))) (t (send-status-line stream status-code reason) (report-http-headers condition stream t) (report-the-message stream reason)))))))) (defmethod report-status ((condition access-control-condition) stream) (let* ((server *server*) (method (or (server-method server) (http-method condition)))) (case method (:head ;; head redirects never send a body (report-status-line condition stream) (report-http-headers condition stream t nil nil)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil)) (report-status-message condition stream))) close connection for 1.0 puts , or unsynchronizable posts ((:post :put) (setf (server-close-connection-p server) t))) (report-status-line condition stream) (report-http-headers condition stream t) (report-status-message condition stream))))))) (defmethod authentication-header-spec ((condition recoverable-unauthorized-client-access)) (www-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition))) (defmethod authentication-header-spec ((condition client-access-with-stale-nonce)) (www-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition) :stale t)) (defmethod authentication-header-spec ((condition recoverable-unauthorized-proxy-access)) (proxy-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition))) (defmethod authentication-header-spec ((condition proxy-access-with-stale-nonce)) (proxy-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition) :stale t)) (defmethod report-status ((condition recoverable-unauthorized-access) stream) (let* ((more-headers (authentication-header-spec condition)) (server *server*) (method (or (server-method server) (http-method condition)))) (declare (dynamic-extent more-headers)) (case method (:head ;; head redirects never send a body (report-status-line condition stream) (report-http-headers condition stream t more-headers nil)) close connection for 1.0 puts , or unsynchronizable posts ((:post :put) (setf (server-close-connection-p server) t))) (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil more-headers)) (report-status-message condition stream))) close connection for 1.0 puts ((:post :put) (setf (server-close-connection-p server) t))) (report-status-line condition stream) (report-http-headers condition stream t more-headers) (report-status-message condition stream))))))) (defmethod report-status ((condition unsupported-method) stream) (let* ((method (http-method condition)) (url (http-url-string condition)) (args (list method url))) (declare (dynamic-extent args)) (cond ((server-supports-chunking-p *server*) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil)) (report-status-message condition stream "The ~A method is not supported: ~S" args))) (t (report-status-line condition stream) (report-http-headers condition stream t) (report-status-message condition stream "The ~A method is not supported: ~S" args))))) ;; body section can be sent with MIME multi-part message. (defmethod report-status ((condition document-moved) stream) (let* ((target-window (http-target-window condition)) (more-headers `(,.(loop for url in (ensure-list (new-urls condition)) collect :location collect (url:name-string url)) ,.(when target-window `(:window-target ,target-window)))) (method (http-method condition))) (declare (dynamic-extent more-headers)) (case method (:head ;; head redirects never send a body (report-status-line condition stream) (report-http-headers condition stream t more-headers nil)) (t (cond ((server-supports-chunking-p *server*) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil more-headers)) (report-status-message condition stream))) close connection for 1.0 PUT (:put (setf (server-close-connection-p *server*) t))) (report-status-line condition stream) (report-http-headers condition stream t more-headers) (report-status-message condition stream))))))) Status codes 303 , 307 are not reliably understood by http 1.0 clients . ;; This method automatical downgrades the result. (defmethod report-status-line ((condition http/1.1-redirection-downgrade-mixin) stream) (let* ((status-code (status-code condition)) (reason (or (http-reason condition) (get-string-for-status-code status-code)))) (send-status-line stream (if (server-supports-chunking-p *server*) status-code 302) reason))) ;; original implementation by the spec. Use the forwarded stuff to redirect search GETS and POST ;(defun handle-url-redirection (url method &optional method-parameters) ; (let ((alternate-urls (url:alternate-urls url))) ; (cond ((null alternate-urls) ; (signal 'document-not-found :url url)) ; ((every #'(lambda (x) ; (host-equal (host-object x) (local-host))) ; alternate-urls) ; (signal (if (every #'url:cached-pathname alternate-urls) ; 'document-moved-temporarily ; 'document-moved-permanently) ; :url url ; :new-urls alternate-urls)) ; ((cdr alternate-urls) ; (error "Redirection off the local host can only use a single URL.")) ; (t (signal 'document-forwarded ; :url url ; :redirect-to-url (car alternate-urls) ; :method method ; :method-parameters method-parameters))))) Next implementation 9/19/2000 -- JCMa . ;(defun handle-url-standard-redirection (url temporary-p method &optional target-window) ; (check-type target-window (or null string)) ; (let ((alternate-urls (url:alternate-urls url))) ; (cond ; ((null alternate-urls) ; (signal 'document-not-found :url url)) ; (temporary-p ; (signal 'document-moved-temporarily :url url :method method :new-urls alternate-urls :target-window target-window)) ; (t (signal 'document-moved-permanently :url url :method method :new-urls alternate-urls :target-window target-window))))) (defun %standard-url-redirect (url target-url redirection-type method target-window) (check-type target-window (or null string)) (let ((alternate-urls (http::ensure-list target-url))) (unless alternate-urls (signal 'document-not-found :url url)) (ecase redirection-type (:temporary-redirect (case method (:get (signal 'document-found :url url :method method :new-urls alternate-urls :target-window target-window)) (t (signal 'document-moved-temporarily :url url :method method :new-urls alternate-urls :target-window target-window)))) (:permanent-redirect (signal 'document-moved-permanently :url url :method method :new-urls alternate-urls :target-window target-window)) (:forward (if (case method (:get (not (explicit-expiration-p url))) (:post t)) (signal 'document-forwarded :url url :method method :new-urls alternate-urls :target-window target-window) (signal 'document-moved-temporarily :url url :method method :new-urls alternate-urls :target-window target-window))) (:proxy (signal 'document-access-via-proxy :url url :method method :new-urls alternate-urls :target-window target-window)) (:multiple-choices (signal 'document-multiple-choices :url url :method method :new-urls alternate-urls :target-window target-window))))) (defun standard-url-redirect (url redirection-type method &optional target-window) "Signals a redirection to alternative resources URL according to METHOD and REDIRECTION-TYPE. METHOD is the http method of the request. REDIRECTION-TYPE is one of: :FORWARD Exists primarily to allow a POST to redirect the client to a URI. :MULTIPLE-CHOICES Redirects the client to a set of representations each with their own agent driven negotiation information. :PERMANENT-REDIRECT Redirects the client to a new URI where the resource permanently resides. All references can be permanently updated. :PROXY Indicates that the client should retry the request via a proxy. :TEMPORARY-REDIRECT Redirects the client to a new URI where the resource temporarily resides. TARGET-WINDOW is the name of the window to the display the result of the redirection." (%standard-url-redirect url (url:alternate-urls url) redirection-type method target-window)) (defmethod report-status ((condition precondition-failed) stream) (report-status-line condition stream) (report-http-headers condition stream t nil nil)) ;;;------------------------------------------------------------------- ;;; ;;; AUTOMATIC BUG REPORTING BY ERROR CLASS ;;; ;; report the bugs in general (defmethod bug-report-error ((error error)) (let ((error-type (type-of error))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) "~&Log: ~S~&Error: ~S~:[~;~&Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string error) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string error))))) (defmethod bug-report-error ((condition condition)) (let ((condition-type (type-of condition))) (report-bug *bug-http-server* (format nil "HTTP Condition: ~S" condition-type) "~&Log: ~S~&Condition: ~S~:[~;~&Condition Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") condition-type (report-string condition) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string condition))))) (defmethod bug-report-error ((error server-internal-error)) (let* ((err (or (server-error error) error)) (error-type (type-of err))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) "~&Log: ~S~&Error: ~A~:[~;~&Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string err) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string error))))) (defmethod bug-report-error ((error error-computing-response)) (let* ((headers (http-headers error)) (err (or (server-error error) error)) (error-type (type-of err)) (backtrace (http-stack-backtrace error))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) "~&Log: ~S~&Error: ~A~:[~;~&Error Report: ~:*~A~]~:[~;~&Headers: ~:*~S~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string err) headers backtrace))) (defmethod bug-report-error ((error error-handling-post-method)) (let* ((err (or (server-error error) error)) (error-type (type-of err)) (backtrace (http-stack-backtrace error)) (headers (http-headers error)) (form-alist (http-form-alist error))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) "~&Log: ~S~&Error: ~S~:[~;~&Error Report: ~:*~A~]~:[~;~&Headers: ~:*~S~]~ ~&Form - Alist : ~:*~S~]~:[~;~&Backtrace : ~:*~A~ ] " (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string err) headers form-alist backtrace)))
null
https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/server/report.lisp
lisp
Syntax : ANSI - Common - Lisp ; Package : http ; Base : 10 ; Default - character - style : ( : fix : : normal ) -*- All Rights Reserved. ------------------------------------------------------------------- REPORTING RELATED TO HTTP CONDITIONS PROXY-~]AUTHORIZATION header.~ PROXY-~]AUTHORIZATION: ~{~&~10T~A: ~S~}" ------------------------------------------------------------------- REPORT STATUS If the url is an uninterned search URL, we just default to the head never sends a body Don't bother reporting to dead TCP streams. head never sends a body Doesn't inherit from reportable condition Move this up to the highest condition to catch anything -- JCMa 12/1/2003 (flet ((report-rentrant-error (primary-error secondary-error) (let ((secondary-error-type (type-of secondary-error))) (report-bug *bug-http-server* (format nil "REPORT-STATUS Re-entrant Error: ~S" secondary-error-type) "~:[~;~&Log: ~:*~S~]~&Primary Error: ~S~:[~;~&Primary Error Report: ~:*~A~]~ ~&Secondary Error: ~S~:[~;~&Secondary Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (when http:*server* (write-extended-common-logfile-entry http:*server* nil)) (type-of primary-error) (report-string primary-error) (type-of secondary-error) (report-string secondary-error) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string condition)))))) (cond (*report-status-condition* (report-rentrant-error *report-status-condition* condition)) (t (let ((*report-status-condition* condition)) (handler-case-if (not *debug-server*) (with-text-stream (stream :output) ;in case we're in binary mode (call-next-method condition stream)) (network-error () nil) ;no need to report errors telling the user he lost (condition (cond) (bug-report-error cond)))))))) Catch any errors reporting errors. Errors that re-enter this code are sure losers attempting to resignal within the process of signalling the original error. These cases are detected and handled ~&Log: ~:*~S~]~&Primary Error: ~S~:[~;~&Primary Error Report: ~:*~A~]~ ~&Secondary Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" no need to report errors telling the user he lost in case we're in binary mode Handles any residual errors not covered by other condition types. head redirects never send a body ignore This is quite inline so that it doesn't waste time when the server is on the edge. head redirects never send a body head redirects never send a body head redirects never send a body body section can be sent with MIME multi-part message. head redirects never send a body This method automatical downgrades the result. original implementation by the spec. Use the forwarded stuff to redirect search GETS and POST (defun handle-url-redirection (url method &optional method-parameters) (let ((alternate-urls (url:alternate-urls url))) (cond ((null alternate-urls) (signal 'document-not-found :url url)) ((every #'(lambda (x) (host-equal (host-object x) (local-host))) alternate-urls) (signal (if (every #'url:cached-pathname alternate-urls) 'document-moved-temporarily 'document-moved-permanently) :url url :new-urls alternate-urls)) ((cdr alternate-urls) (error "Redirection off the local host can only use a single URL.")) (t (signal 'document-forwarded :url url :redirect-to-url (car alternate-urls) :method method :method-parameters method-parameters))))) (defun handle-url-standard-redirection (url temporary-p method &optional target-window) (check-type target-window (or null string)) (let ((alternate-urls (url:alternate-urls url))) (cond ((null alternate-urls) (signal 'document-not-found :url url)) (temporary-p (signal 'document-moved-temporarily :url url :method method :new-urls alternate-urls :target-window target-window)) (t (signal 'document-moved-permanently :url url :method method :new-urls alternate-urls :target-window target-window))))) ------------------------------------------------------------------- AUTOMATIC BUG REPORTING BY ERROR CLASS report the bugs in general ~&Error Report: ~:*~A~]~:[~;~&Headers: ~:*~S~]~ ~&Backtrace : ~:*~A~ ] "
( C ) Copyright 1994 - 99 , 2003 , 2005 - 2006 , (in-package :http) (defmacro server-supports-chunking-p (server) `(and #+disable-chunking nil (client-http-version-meets-p ,server :http/1.1))) (defgeneric report-status-line (http-condition stream) (:documentation "Primitive that sends a status line over an HTTP connection.")) (defmethod report-status-line ((condition http-condition) stream) (declare (ignore stream)) (error "The condition, ~S, cannot be reported to the client." condition)) (defmethod report-status-line ((condition reportable-condition) stream) (let* ((status-code (status-code condition)) (reason (or (http-reason condition) (get-string-for-status-code status-code)))) (send-status-line stream status-code reason))) (defgeneric report-status-message (http-condition stream &optional format-string format-args) (:documentation "Primitive that sends a status body message over an HTTP connection.")) (defmethod report-status-message ((condition http-condition) stream &optional format-string format-args) (declare (ignore stream format-string format-args)) (error "The condition, ~S, cannot be reported to the client." condition)) (define cl-http-signature (&optional (stream *output-stream*)) "Writes the server signature as an address on STREAM." (with-emphasis (:address :stream stream) (note-anchor *server-version* :reference *cl-http-home-page-url-string* :stream stream))) (defun %report-status-message (url reason stream &optional reporter) (with-cl-http-html-document (:declare-dtd-version-p :strict :stream stream) (with-document-look-preamble (:stream stream) (declare-title reason :stream stream)) (with-document-look-body (:heading reason :header-class "header.cl-http" :body-class "body.cl-http" :footer-class "footer.cl-http" :stream stream) (with-paragraph (:stream stream) (cond (reporter (with-verbatim-text (:fresh-line nil :stream stream) (etypecase reporter (string (html:write-string-quoting-specials reporter stream)) ((or symbol function) (funcall reporter url stream))))) (url (fast-format stream "~A for URI ~A" reason (url:relative-name-string-for-locally-served-url url))) (t (fast-format stream "~&HTTP Status Code ~D not properly reported.~I~ ~&Please advise the server maintainer at: ~I" (server-status *server*) (break-line :stream stream)) (note-anchor (server-mail-address) :reference #'write-server-mail-address :stream stream))))))) (defmethod report-status-message ((condition reportable-condition) stream &optional format-string format-args) (let ((reason (or (http-reason condition) (get-string-for-status-code (status-code condition)))) (url (http-url condition))) (unless format-string (setq format-string (format-string condition))) (unless format-args (setq format-args (format-args condition))) (cond (format-string (let ((report (apply #'format nil format-string format-args))) (declare (dynamic-extent report)) (%report-status-message url reason stream report))) (t (%report-status-message url reason stream (http-reporter condition)))))) (defmethod report-status-message ((condition document-moved) stream &optional format-string format-args) (declare (ignore format-string format-args)) (let ((new-urls (new-urls condition)) (reason (http-reason condition))) (with-cl-http-html-document (:declare-dtd-version-p :strict :stream stream) (with-document-look-preamble (:stream stream) (declare-title reason :stream stream)) (with-document-look-body (:heading reason :header-class "header.cl-http" :body-class "body.cl-http" :footer-class "footer.cl-http" :stream stream) (with-paragraph (:stream stream) (write-string "This document has moved " stream) (typecase new-urls (cons (cond ((cdr new-urls) (loop for urls = new-urls then (cdr urls) for num upfrom 1 while urls do (with-anchor-noted (:reference (car new-urls) :stream stream) (fast-format stream "here ~D" num)) while (cdr urls) do (write ", "))) (t (note-anchor "here" :reference (car new-urls) :stream stream)))) (t (note-anchor "here" :reference new-urls :stream stream))) (write-char #\. stream)))))) (defmethod report-status-message ((condition inconsistent-digest-authorization-uri) stream &optional format-string format-args) (flet ((report-inconsistent-authorization-uri (request-uri stream) (let ((authorization (http-authorization condition)) (method (http-method condition)) (proxy-p (http-proxy-p condition))) (destructuring-bind (scheme &key uri &allow-other-keys) authorization method scheme proxy-p request-uri uri proxy-p (cdr authorization)))))) (declare (dynamic-extent #'report-inconsistent-authorization-uri)) (let ((format (or format-string (format-string condition)))) (if format (call-next-method condition stream format (or format-args (format-args condition))) (%report-status-message (http-url condition) (http-reason condition) stream #'report-inconsistent-authorization-uri))))) (defun report-proxy-access-forbidden (url stream) (declare (ignore url)) (let ((server *server*)) (if server (fast-format stream "Proxy Access via ~A on port ~D is not available for your host at ~A." (server-local-host-domain-name server) (SERVER-HOST-LOCAL-PORT server) (server-host-ip-address server)) (fast-format stream "Proxy Access is not available for your host.")))) (defun report-proxy-connect-method-forbidden (authority stream) (let ((server *server*)) (if server (fast-format stream "Proxy CONNECT to ~A on port ~D is not allowed via ~A on port ~D." (host-string authority) (host-port authority) (server-local-host-domain-name server) (server-host-local-port server)) (fast-format stream "Proxy CONNECT to ~A on port ~D is not allowed." (host-string authority) (host-port authority))))) (define-generic http-url-string (reportable-condition) (:documentation "Returns the URL string for REPORTABLE-CONDITION, or null is a URL is unavailable.")) (defmethod http-url-string ((condition reportable-condition)) (let ((url (http-url condition))) (etypecase url (null nil) (string url) (url:url (url:name-string url))))) (define-generic report-http-headers (http-condition stream &optional termination-line-p header-plist content-type) (:documentation "Top-level methods for sending HTTP headers accompanying REPORT-STATUS.")) #+ignore (progn (defparameter count 0) (defmethod report-http-headers ((condition null) stream &optional (termination-line-p t) header-plist content-type) (when (< count 1) (incf count) (tv:notify nil "REPORT-HTTP-HEADERS error is in a break. Go debug it.") (break "Lost with null condition."))) ) (defmethod report-http-headers ((condition condition) stream &optional (termination-line-p t) header-plist (content-type :html)) (let ((headers `(:date ,(server-request-time *server*) :server ,*server-version* :connection (:close) ,.(when content-type `(:content-type ,(%mime-content-type-spec content-type))) ,@header-plist))) (declare (dynamic-extent headers)) (write-headers stream headers termination-line-p))) (defmethod report-http-headers ((condition reportable-condition) stream &optional (termination-line-p t) header-plist (content-type :html) &aux (server *server*)) (when (http-close-connection-p condition) (setf (server-close-connection-p server) t)) (%write-document-mime-headers stream content-type nil nil nil nil nil nil nil nil nil nil nil termination-line-p nil header-plist)) (defmethod report-http-headers :around ((condition method-not-allowed) stream &optional (termination-line-p t) header-plist content-type) (let* ((url (http-url condition)) (server *server*) standard methods on the server 8/7/96 -- JCMa . (more-headers `(:allow ,(http-methods (or (and url (intern-url url :if-does-not-exist :soft)) server) (server-http-version server)) ,@header-plist))) (declare (dynamic-extent more-headers)) (case (http-method condition) close connection because the 1.0 servers will try to blast put data at us , and we do n't know that the connection is syncrhonizable (unless (server-supports-chunking-p server) (setf (server-close-connection-p server) t)))) (call-next-method condition stream termination-line-p more-headers content-type))) (defmethod report-http-headers ((condition cacheable-condition-mixin) stream &optional (termination-line-p t) header-plist (content-type :html)) (let ((server *server*) (url (http-url condition)) cache-control expires) (when (http-close-connection-p condition) (setf (server-close-connection-p server) t)) (if (server-supports-chunking-p server) (setq cache-control (url:response-cache-control-directives url)) (setq expires (url:expiration-universal-time url))) (%write-document-mime-headers stream content-type nil nil nil nil expires nil nil nil nil nil cache-control termination-line-p nil header-plist))) (define-generic report-status (http-condition stream) (:documentation "Top-level function for reporting a condition over an HTTP connection.")) (defmethod report-status ((condition http-condition) stream) (declare (ignore stream)) (error "The condition, ~S, cannot be reported to the client." condition)) (defmethod report-status ((condition reportable-condition) stream) (let* ((server *server*) (method (or (server-method server) (http-method condition)))) (case method (report-status-line condition stream) (report-http-headers condition stream t)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil)) (report-status-message condition stream))) (t (report-status-line condition stream) (report-http-headers condition stream t) (report-status-message condition stream))))))) (defmethod report-status :around ((condition reportable-condition) stream) (when (www-utils:live-connection-p stream) (call-next-method))) (defmethod report-status ((error url:parsing-error) stream) (let* ((url (url:url-string error)) (reason (get-string-for-status-code 400)) (server *server*) (method (server-method server))) (case method (send-status-line stream 400 reason) (report-http-headers error stream t nil nil)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (send-status-line stream 400 reason) (report-http-headers error stream nil)) (%report-status-message url reason stream))) (t (send-status-line stream 400 reason) (report-http-headers error stream t) (%report-status-message url reason stream))))))) (defmethod report-status :around ((condition url:parsing-error) stream) (when (www-utils:live-connection-p stream) (call-next-method))) (defvar *report-status-condition* nil "Current condition being reported by REPORT-STATUS.") ( defmethod report - status : around ( ( condition condition ) stream ) in a safe manner . 9/22/99 -- JCMa . Use handler - bind so that stack backtraces are visible in , inter alia , LW -- JCMa 10/3/2006 (defmethod report-status :around ((condition condition) stream) (labels ((report-rentrant-error (primary-error secondary-error) (let ((secondary-error-type (type-of secondary-error))) (report-bug *bug-http-server* (format nil "REPORT-STATUS Re-entrant Error: ~S" secondary-error-type) (when http:*server* (write-extended-common-logfile-entry http:*server* nil)) (type-of primary-error) (report-string primary-error) (type-of secondary-error) (report-string secondary-error) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string condition))))) (handle-cond (error) (etypecase error (condition (bug-report-error error) t)))) (cond (*report-status-condition* (report-rentrant-error *report-status-condition* condition)) (t (let ((*report-status-condition* condition)) (handler-bind-if (not *debug-server*) ((error #'handle-cond)) (call-next-method condition stream)))))))) (defmethod report-status-unhandled-error ((error condition) stream request) (flet ((report-the-secondary-error (error stream reason) (let* ((report-string (report-string error)) (report (with-output-to-string (string) (with-paragraph (:stream string) (with-rendition (:bold :stream string) (write-string "Request: " string)) (if request (write-string request string) "{Not available}")) (with-paragraph (:stream string) (with-rendition (:bold :stream string) (write-string "Error: " string)) (with-verbatim-text (:fresh-line nil :stream stream) (write-string-quoting-specials report-string string)))))) (declare (dynamic-extent report-string report)) (%report-status-message nil reason stream report)))) (let ((reason (get-string-for-status-code 500))) (cond ((handler-case (server-supports-chunking-p *server*) (error () nil)) (%with-chunked-transfer-encoding (stream) (progn (send-status-line stream 500 reason) (report-http-headers error stream nil)) (report-the-secondary-error error stream reason))) (t (send-status-line stream 500 reason) (report-http-headers error stream t) (report-the-secondary-error error stream reason)))))) (defmethod report-status-unhandled-error :around ((error condition) stream request) (declare (ignore request)) (when (www-utils:live-connection-p stream) (call-next-method)) (bug-report-error error)) (defmethod report-status ((condition server-internal-error) stream) an internal error may be encapsulated or not ! 2/28/2001 -- JCMa . (error-report (and error (report-string error))) (server *server*) (method (or (server-method server) (http-method condition)))) (case method (report-status-line condition stream) (report-http-headers error stream t)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers error stream nil)) (report-status-message condition stream error-report))) (t (report-status-line condition stream) (report-http-headers error stream t) (report-status-message condition stream error-report))))))) (defmethod report-status :around ((condition server-internal-error) stream) (when (www-utils:live-connection-p stream) (call-next-method)) (bug-report-error condition)) (defmethod report-status ((condition server-overloaded) stream) (flet ((report-the-message (stream reason) (with-html-document (:declare-dtd-version-p t :stream stream) (with-document-preamble (:stream stream) (declare-title reason :stream stream)) (with-standard-document-body (:stream stream) (with-section-heading (reason :stream stream) (horizontal-line :stream stream) (with-paragraph (:stream stream) (etypecase *overload-message* (null (write-string "This server is currently operating at capacity and cannot accept your request. Please try again later." stream)) (string (write-string *overload-message* stream)) (function (funcall *overload-message* condition stream)) (symbol (funcall (fdefinition *overload-message*) condition stream)))) (horizontal-line :stream stream) (cl-http-signature stream)))))) (let* ((status-code (status-code condition)) (reason (or (http-reason condition) (get-string-for-status-code status-code))) (server *server*) (method (or (server-method server) (http-method condition)))) (case method (send-status-line stream status-code reason) (report-http-headers condition stream t)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (send-status-line stream status-code reason) (report-http-headers condition stream nil)) (report-the-message stream reason))) (t (send-status-line stream status-code reason) (report-http-headers condition stream t) (report-the-message stream reason)))))))) (defmethod report-status ((condition access-control-condition) stream) (let* ((server *server*) (method (or (server-method server) (http-method condition)))) (case method (report-status-line condition stream) (report-http-headers condition stream t nil nil)) (t (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil)) (report-status-message condition stream))) close connection for 1.0 puts , or unsynchronizable posts ((:post :put) (setf (server-close-connection-p server) t))) (report-status-line condition stream) (report-http-headers condition stream t) (report-status-message condition stream))))))) (defmethod authentication-header-spec ((condition recoverable-unauthorized-client-access)) (www-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition))) (defmethod authentication-header-spec ((condition client-access-with-stale-nonce)) (www-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition) :stale t)) (defmethod authentication-header-spec ((condition recoverable-unauthorized-proxy-access)) (proxy-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition))) (defmethod authentication-header-spec ((condition proxy-access-with-stale-nonce)) (proxy-authenticate-header-spec (http-authentication-realm condition) (http-authentication-method condition) :stale t)) (defmethod report-status ((condition recoverable-unauthorized-access) stream) (let* ((more-headers (authentication-header-spec condition)) (server *server*) (method (or (server-method server) (http-method condition)))) (declare (dynamic-extent more-headers)) (case method (report-status-line condition stream) (report-http-headers condition stream t more-headers nil)) close connection for 1.0 puts , or unsynchronizable posts ((:post :put) (setf (server-close-connection-p server) t))) (cond ((server-supports-chunking-p server) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil more-headers)) (report-status-message condition stream))) close connection for 1.0 puts ((:post :put) (setf (server-close-connection-p server) t))) (report-status-line condition stream) (report-http-headers condition stream t more-headers) (report-status-message condition stream))))))) (defmethod report-status ((condition unsupported-method) stream) (let* ((method (http-method condition)) (url (http-url-string condition)) (args (list method url))) (declare (dynamic-extent args)) (cond ((server-supports-chunking-p *server*) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil)) (report-status-message condition stream "The ~A method is not supported: ~S" args))) (t (report-status-line condition stream) (report-http-headers condition stream t) (report-status-message condition stream "The ~A method is not supported: ~S" args))))) (defmethod report-status ((condition document-moved) stream) (let* ((target-window (http-target-window condition)) (more-headers `(,.(loop for url in (ensure-list (new-urls condition)) collect :location collect (url:name-string url)) ,.(when target-window `(:window-target ,target-window)))) (method (http-method condition))) (declare (dynamic-extent more-headers)) (case method (report-status-line condition stream) (report-http-headers condition stream t more-headers nil)) (t (cond ((server-supports-chunking-p *server*) (%with-chunked-transfer-encoding (stream) (progn (report-status-line condition stream) (report-http-headers condition stream nil more-headers)) (report-status-message condition stream))) close connection for 1.0 PUT (:put (setf (server-close-connection-p *server*) t))) (report-status-line condition stream) (report-http-headers condition stream t more-headers) (report-status-message condition stream))))))) Status codes 303 , 307 are not reliably understood by http 1.0 clients . (defmethod report-status-line ((condition http/1.1-redirection-downgrade-mixin) stream) (let* ((status-code (status-code condition)) (reason (or (http-reason condition) (get-string-for-status-code status-code)))) (send-status-line stream (if (server-supports-chunking-p *server*) status-code 302) reason))) Next implementation 9/19/2000 -- JCMa . (defun %standard-url-redirect (url target-url redirection-type method target-window) (check-type target-window (or null string)) (let ((alternate-urls (http::ensure-list target-url))) (unless alternate-urls (signal 'document-not-found :url url)) (ecase redirection-type (:temporary-redirect (case method (:get (signal 'document-found :url url :method method :new-urls alternate-urls :target-window target-window)) (t (signal 'document-moved-temporarily :url url :method method :new-urls alternate-urls :target-window target-window)))) (:permanent-redirect (signal 'document-moved-permanently :url url :method method :new-urls alternate-urls :target-window target-window)) (:forward (if (case method (:get (not (explicit-expiration-p url))) (:post t)) (signal 'document-forwarded :url url :method method :new-urls alternate-urls :target-window target-window) (signal 'document-moved-temporarily :url url :method method :new-urls alternate-urls :target-window target-window))) (:proxy (signal 'document-access-via-proxy :url url :method method :new-urls alternate-urls :target-window target-window)) (:multiple-choices (signal 'document-multiple-choices :url url :method method :new-urls alternate-urls :target-window target-window))))) (defun standard-url-redirect (url redirection-type method &optional target-window) "Signals a redirection to alternative resources URL according to METHOD and REDIRECTION-TYPE. METHOD is the http method of the request. REDIRECTION-TYPE is one of: :FORWARD Exists primarily to allow a POST to redirect the client to a URI. :MULTIPLE-CHOICES Redirects the client to a set of representations each with their own agent driven negotiation information. :PERMANENT-REDIRECT Redirects the client to a new URI where the resource permanently resides. All references can be permanently updated. :PROXY Indicates that the client should retry the request via a proxy. :TEMPORARY-REDIRECT Redirects the client to a new URI where the resource temporarily resides. TARGET-WINDOW is the name of the window to the display the result of the redirection." (%standard-url-redirect url (url:alternate-urls url) redirection-type method target-window)) (defmethod report-status ((condition precondition-failed) stream) (report-status-line condition stream) (report-http-headers condition stream t nil nil)) (defmethod bug-report-error ((error error)) (let ((error-type (type-of error))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) "~&Log: ~S~&Error: ~S~:[~;~&Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string error) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string error))))) (defmethod bug-report-error ((condition condition)) (let ((condition-type (type-of condition))) (report-bug *bug-http-server* (format nil "HTTP Condition: ~S" condition-type) "~&Log: ~S~&Condition: ~S~:[~;~&Condition Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") condition-type (report-string condition) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string condition))))) (defmethod bug-report-error ((error server-internal-error)) (let* ((err (or (server-error error) error)) (error-type (type-of err))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) "~&Log: ~S~&Error: ~A~:[~;~&Error Report: ~:*~A~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string err) (when *stack-backtraces-in-bug-reports* (stack-backtrace-string error))))) (defmethod bug-report-error ((error error-computing-response)) (let* ((headers (http-headers error)) (err (or (server-error error) error)) (error-type (type-of err)) (backtrace (http-stack-backtrace error))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) "~&Log: ~S~&Error: ~A~:[~;~&Error Report: ~:*~A~]~:[~;~&Headers: ~:*~S~]~:[~;~&Backtrace: ~:*~A~]" (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string err) headers backtrace))) (defmethod bug-report-error ((error error-handling-post-method)) (let* ((err (or (server-error error) error)) (error-type (type-of err)) (backtrace (http-stack-backtrace error)) (headers (http-headers error)) (form-alist (http-form-alist error))) (report-bug *bug-http-server* (format nil "HTTP Error: ~S" error-type) (if http:*server* (write-extended-common-logfile-entry http:*server* nil) "NA") error-type (report-string err) headers form-alist backtrace)))
4eb422214874c4fe5e8ced4350bcbdfaec93b767a42ab983eaf8fee179e658af
emqx/ekka
ekka_cluster_etcd_SUITE.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2019 - 2022 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(ekka_cluster_etcd_SUITE). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(ETCD_PORT, 2379). -define(OPTIONS, [{server, [":" ++ integer_to_list(?ETCD_PORT)]}, {prefix, "emqxcl"}, {version, v2}, {node_ttl, 60} ]). all() -> ekka_ct:all(?MODULE). init_per_testcase(t_restart_process, Config) -> case ekka_ct:is_tcp_server_available("localhost", ?ETCD_PORT) of true -> application:ensure_all_started(eetcd), Config; false -> {skip, no_etcd} end; init_per_testcase(_TestCase, Config) -> ok = meck:new(httpc, [non_strict, passthrough, no_history]), Config. end_per_testcase(t_restart_process, _Config) -> application:stop(eetcd); end_per_testcase(TestCase, _Config) -> ok = meck:unload(httpc), ekka_ct:cleanup(TestCase). t_discover(_Config) -> Json = <<"{\"node\": {\"nodes\": [{\"key\": \"ekkacl/[email protected]\"}]}}">>, ok = meck:expect(httpc, request, fun(get, _Req, _Opts, _) -> {ok, 200, Json} end), {ok, ['[email protected]']} = ekka_cluster_strategy:discover(ekka_cluster_etcd, ?OPTIONS). t_lock(_Config) -> ok = meck:expect(httpc, request, fun(put, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = ekka_cluster_strategy:lock(ekka_cluster_etcd, ?OPTIONS). t_unlock(_) -> ok = meck:expect(httpc, request, fun(delete, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = ekka_cluster_strategy:unlock(ekka_cluster_etcd, ?OPTIONS). t_register(_) -> ok = meck:new(ekka_cluster_sup, [non_strict, passthrough, no_history]), ok = meck:expect(ekka_cluster_sup, start_child, fun(_, _) -> {ok, self()} end), ok = meck:expect(httpc, request, fun(put, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = ekka_cluster_strategy:register(ekka_cluster_etcd, ?OPTIONS), ok = meck:unload(ekka_cluster_sup). t_unregister(_) -> ok = meck:expect(httpc, request, fun(delete, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = meck:expect(ekka_cluster_sup, stop_child, fun(_) -> ok end), ok = ekka_cluster_strategy:unregister(ekka_cluster_etcd, ?OPTIONS), ok = meck:unload(ekka_cluster_sup). t_etcd_set_node_key(_) -> ok = meck:expect(httpc, request, fun(put, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), {ok, #{<<"errorCode">> := 0}} = ekka_cluster_etcd:etcd_set_node_key(?OPTIONS). t_restart_process(_) -> snabbkaffe:fix_ct_logging(), Options = lists:keyreplace(version, 1, ?OPTIONS, {version, v3}), Node = ekka_ct:start_slave(ekka, n1, [{ekka, cluster_discovery, {etcd, Options}}]), try ok = ekka_ct:wait_running(Node), Pid = erpc:call(Node, erlang, whereis, [ekka_cluster_etcd]), SupPid = erpc:call(Node, erlang, whereis, [ekka_sup]), Ref = monitor(process, Pid), SupRef = monitor(process, SupPid), exit(Pid, kill), receive {'DOWN', Ref, process, Pid, _} -> ok after 200 -> exit(proc_not_killed) end, receive {'DOWN', SupRef, process, SupPid, _} -> exit(supervisor_died) after 200 -> ok end, ok = ekka_ct:wait_running(Node, 2_000), ok after ok = ekka_ct:stop_slave(Node) end, ok.
null
https://raw.githubusercontent.com/emqx/ekka/2a2dec9b434855f0d5d507a19d5b8d05d5ff9ddb/test/ekka_cluster_etcd_SUITE.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. --------------------------------------------------------------------
Copyright ( c ) 2019 - 2022 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(ekka_cluster_etcd_SUITE). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(ETCD_PORT, 2379). -define(OPTIONS, [{server, [":" ++ integer_to_list(?ETCD_PORT)]}, {prefix, "emqxcl"}, {version, v2}, {node_ttl, 60} ]). all() -> ekka_ct:all(?MODULE). init_per_testcase(t_restart_process, Config) -> case ekka_ct:is_tcp_server_available("localhost", ?ETCD_PORT) of true -> application:ensure_all_started(eetcd), Config; false -> {skip, no_etcd} end; init_per_testcase(_TestCase, Config) -> ok = meck:new(httpc, [non_strict, passthrough, no_history]), Config. end_per_testcase(t_restart_process, _Config) -> application:stop(eetcd); end_per_testcase(TestCase, _Config) -> ok = meck:unload(httpc), ekka_ct:cleanup(TestCase). t_discover(_Config) -> Json = <<"{\"node\": {\"nodes\": [{\"key\": \"ekkacl/[email protected]\"}]}}">>, ok = meck:expect(httpc, request, fun(get, _Req, _Opts, _) -> {ok, 200, Json} end), {ok, ['[email protected]']} = ekka_cluster_strategy:discover(ekka_cluster_etcd, ?OPTIONS). t_lock(_Config) -> ok = meck:expect(httpc, request, fun(put, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = ekka_cluster_strategy:lock(ekka_cluster_etcd, ?OPTIONS). t_unlock(_) -> ok = meck:expect(httpc, request, fun(delete, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = ekka_cluster_strategy:unlock(ekka_cluster_etcd, ?OPTIONS). t_register(_) -> ok = meck:new(ekka_cluster_sup, [non_strict, passthrough, no_history]), ok = meck:expect(ekka_cluster_sup, start_child, fun(_, _) -> {ok, self()} end), ok = meck:expect(httpc, request, fun(put, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = ekka_cluster_strategy:register(ekka_cluster_etcd, ?OPTIONS), ok = meck:unload(ekka_cluster_sup). t_unregister(_) -> ok = meck:expect(httpc, request, fun(delete, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), ok = meck:expect(ekka_cluster_sup, stop_child, fun(_) -> ok end), ok = ekka_cluster_strategy:unregister(ekka_cluster_etcd, ?OPTIONS), ok = meck:unload(ekka_cluster_sup). t_etcd_set_node_key(_) -> ok = meck:expect(httpc, request, fun(put, _Req, _Opts, _) -> {ok, 200, <<"{\"errorCode\": 0}">>} end), {ok, #{<<"errorCode">> := 0}} = ekka_cluster_etcd:etcd_set_node_key(?OPTIONS). t_restart_process(_) -> snabbkaffe:fix_ct_logging(), Options = lists:keyreplace(version, 1, ?OPTIONS, {version, v3}), Node = ekka_ct:start_slave(ekka, n1, [{ekka, cluster_discovery, {etcd, Options}}]), try ok = ekka_ct:wait_running(Node), Pid = erpc:call(Node, erlang, whereis, [ekka_cluster_etcd]), SupPid = erpc:call(Node, erlang, whereis, [ekka_sup]), Ref = monitor(process, Pid), SupRef = monitor(process, SupPid), exit(Pid, kill), receive {'DOWN', Ref, process, Pid, _} -> ok after 200 -> exit(proc_not_killed) end, receive {'DOWN', SupRef, process, SupPid, _} -> exit(supervisor_died) after 200 -> ok end, ok = ekka_ct:wait_running(Node, 2_000), ok after ok = ekka_ct:stop_slave(Node) end, ok.
b6008636d80937d5c46183f7d7187e25a3b53c1483f8ec3a0aee7ab5f43a2827
godotclj/godotclj
context.clj
(ns godotclj.context (:gen-class :extends godotclj.context$Directives)) (defn -getHeaderFiles [_] ["<wrapper.h>"])
null
https://raw.githubusercontent.com/godotclj/godotclj/23e9c62e7083f7be9aff8bb205d2a270dd5b5e39/src/clojure/godotclj/context.clj
clojure
(ns godotclj.context (:gen-class :extends godotclj.context$Directives)) (defn -getHeaderFiles [_] ["<wrapper.h>"])
a443e5af4723f681da57eae198f9f1b755a644e542df0c83b766e367863dcd5d
janestreet/bonsai
multi_factor_intf.ml
open! Core open! Import * A [ Multi_factor.t ] is a collection of [ Single_factor.t]s ( referred to as a " subwidget " in this module ) , indexed by the [ Arg . Key ] type . This widget provides focus tracking among the different subwidgets . in this module), indexed by the [Arg.Key] type. This widget provides focus tracking among the different subwidgets. *) module type Key = sig type t [@@deriving equal, sexp] include Comparable.S with type t := t val to_string : t -> string (** The human-language name of your type. E.g. if [t] represents some attributes of a trade, you could use something like "trade property" here. *) val name_singular : string (** As above, but in the plural. *) val name_plural : string end module type S = sig open! Core open! Import module Item : Single_factor.Item module Key : Key module Single_factor : module type of Single_factor.Make (Item) module Action : sig type t = | Cycle_focused_subwidget of [ `Next | `Prev ] | Set_focused_subwidget of Key.t | Subwidget_action of Key.t * Single_factor.Action.t | Select_on_all_subwidgets of [ `All | `None ] end module Result : sig type t = { view : Vdom.Node.t ; view_for_testing : string Lazy.t ; key_handler : Vdom_keyboard.Keyboard_event_handler.t ; inject : Action.t -> unit Vdom.Effect.t (** [selection] is the set of all selected items, by key. *) ; selection : Item.Set.t Key.Map.t } [@@deriving fields] * A DOM node very similar to [ t.view ] , but with a handler attached to deal with keyboard events . We provide both this and [ view ] / [ key_handler ] separately , as the latter is required when embedding this component into an incr_dom app -- since incr_dom likes to always have the root node be in focus , it is required that one constructs one big overall Keyboard_event_handler.t for the entire page . with keyboard events. We provide both this and [view] / [key_handler] separately, as the latter is required when embedding this component into an incr_dom app -- since incr_dom likes to always have the root node be in focus, it is required that one constructs one big overall Keyboard_event_handler.t for the entire page. *) val view_with_keydown_handler : t -> Vdom.Node.t end type per_subwidget = { default_selection_status : Selection_status.t ; all_items : Item.Set.t } val bonsai : ?initial_model_settings:Single_factor.Initial_model_settings.t Key.Map.t -> all_keys:Key.Set.t -> id_prefix:string Value.t -> per_subwidget Key.Map.t Value.t -> Result.t Computation.t end module type Multi_factor = sig module type S = S module type Key = Key module Make (Item : Single_factor.Item) (Key : Key) : S with module Item := Item and module Key := Key end
null
https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/web_ui/multi_select/src/multi_factor_intf.ml
ocaml
* The human-language name of your type. E.g. if [t] represents some attributes of a trade, you could use something like "trade property" here. * As above, but in the plural. * [selection] is the set of all selected items, by key.
open! Core open! Import * A [ Multi_factor.t ] is a collection of [ Single_factor.t]s ( referred to as a " subwidget " in this module ) , indexed by the [ Arg . Key ] type . This widget provides focus tracking among the different subwidgets . in this module), indexed by the [Arg.Key] type. This widget provides focus tracking among the different subwidgets. *) module type Key = sig type t [@@deriving equal, sexp] include Comparable.S with type t := t val to_string : t -> string val name_singular : string val name_plural : string end module type S = sig open! Core open! Import module Item : Single_factor.Item module Key : Key module Single_factor : module type of Single_factor.Make (Item) module Action : sig type t = | Cycle_focused_subwidget of [ `Next | `Prev ] | Set_focused_subwidget of Key.t | Subwidget_action of Key.t * Single_factor.Action.t | Select_on_all_subwidgets of [ `All | `None ] end module Result : sig type t = { view : Vdom.Node.t ; view_for_testing : string Lazy.t ; key_handler : Vdom_keyboard.Keyboard_event_handler.t ; inject : Action.t -> unit Vdom.Effect.t ; selection : Item.Set.t Key.Map.t } [@@deriving fields] * A DOM node very similar to [ t.view ] , but with a handler attached to deal with keyboard events . We provide both this and [ view ] / [ key_handler ] separately , as the latter is required when embedding this component into an incr_dom app -- since incr_dom likes to always have the root node be in focus , it is required that one constructs one big overall Keyboard_event_handler.t for the entire page . with keyboard events. We provide both this and [view] / [key_handler] separately, as the latter is required when embedding this component into an incr_dom app -- since incr_dom likes to always have the root node be in focus, it is required that one constructs one big overall Keyboard_event_handler.t for the entire page. *) val view_with_keydown_handler : t -> Vdom.Node.t end type per_subwidget = { default_selection_status : Selection_status.t ; all_items : Item.Set.t } val bonsai : ?initial_model_settings:Single_factor.Initial_model_settings.t Key.Map.t -> all_keys:Key.Set.t -> id_prefix:string Value.t -> per_subwidget Key.Map.t Value.t -> Result.t Computation.t end module type Multi_factor = sig module type S = S module type Key = Key module Make (Item : Single_factor.Item) (Key : Key) : S with module Item := Item and module Key := Key end
bff5d77c2b9d1b6cdfab31eb4be9f8faa4cb265bb6201341b49827c53be9637e
VisionsGlobalEmpowerment/webchange
handler.clj
(ns webchange.secondary.handler (:require [compojure.core :refer [GET POST PUT DELETE defroutes routes]] [ring.util.response :refer [file-response bad-request response]] [webchange.secondary.core :as core] [webchange.common.handler :refer [current-user]] [webchange.auth.roles :refer [is-admin?]] [buddy.auth :refer [authenticated? throw-unauthorized]] [clojure.tools.logging :as log] [webchange.db.core :refer [*db*] :as db] [clojure.data.json :as json] [config.core :refer [env]] [webchange.secondary.updater :as updater] [webchange.school.core :as school] [webchange.common.hmac-sha256 :as sign])) (defn teacher? [request] (and (authenticated? request) (-> request :session :identity :teacher-id))) (defn handle-dump-full [id request] (response (core/get-dump-by-school id))) (defn handle-get-school-update [id request] (let [requested-courses (-> request :body :requested-courses)] (response (core/get-course-update id requested-courses)))) (defn handle-load-school-update [id request] (let [data (-> request :body slurp (json/read-str :key-fn keyword))] (core/import-secondary-data! (Integer/parseInt id) data) (response {}))) (defn handle-load-school-sync [id request] (if (env :secondary) (let [school-id (Integer/parseInt id) owner-id (current-user request)] (when-not (or (is-admin? owner-id) (school/school-admin? school-id owner-id)) (throw-unauthorized {:role :educator})) (updater/start-sync! school-id) (response {:result "Ok"})) (bad-request "not a secondary school"))) (defn handle-asset-difference [request] (let [school-id (-> request :body :school-id) school-hashes (-> request :body :hashes) requested-courses (-> request :body :course-slugs)] (response (core/calc-asset-update school-id school-hashes requested-courses)))) (defn handle-get-latest-version [] (let [file-path (env :latest-binary-path)] (if (nil? file-path) (bad-request "no update available") (file-response file-path)))) (defn handle-software-update [request] (when-not (teacher? request) (throw-unauthorized {:role :teacher})) (if (env :secondary) (updater/update-local-instance!) (bad-request "not a secondary school"))) (defn handle-sync-status [request] (-> (updater/get-sync-status) (response))) (defroutes local-sync-routes (POST "/api/school/sync/:id" [id :as request] (handle-load-school-sync id request)) (GET "/api/school/sync-status" request (handle-sync-status request)) (POST "/api/software/update" request (handle-software-update request))) (defroutes global-sync-routes (GET "/api/school/dump-full/:id" [id :as request] (handle-dump-full id request)) (PUT "/api/school/update/:id" [id :as request] (handle-load-school-update id request)) (GET "/api/school/courses-update/:id" [id :as request] (handle-get-school-update id request)) (POST "/api/school/courses-update/:id" [id :as request] (handle-get-school-update id request)) (POST "/api/school/asset/difference/" request (handle-asset-difference request)) (sign/wrap-api-with-signature (GET "/api/software/latest" _ (handle-get-latest-version))))
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/bfc1897e371c44aa9707b645f2f376558374f66e/src/clj/webchange/secondary/handler.clj
clojure
(ns webchange.secondary.handler (:require [compojure.core :refer [GET POST PUT DELETE defroutes routes]] [ring.util.response :refer [file-response bad-request response]] [webchange.secondary.core :as core] [webchange.common.handler :refer [current-user]] [webchange.auth.roles :refer [is-admin?]] [buddy.auth :refer [authenticated? throw-unauthorized]] [clojure.tools.logging :as log] [webchange.db.core :refer [*db*] :as db] [clojure.data.json :as json] [config.core :refer [env]] [webchange.secondary.updater :as updater] [webchange.school.core :as school] [webchange.common.hmac-sha256 :as sign])) (defn teacher? [request] (and (authenticated? request) (-> request :session :identity :teacher-id))) (defn handle-dump-full [id request] (response (core/get-dump-by-school id))) (defn handle-get-school-update [id request] (let [requested-courses (-> request :body :requested-courses)] (response (core/get-course-update id requested-courses)))) (defn handle-load-school-update [id request] (let [data (-> request :body slurp (json/read-str :key-fn keyword))] (core/import-secondary-data! (Integer/parseInt id) data) (response {}))) (defn handle-load-school-sync [id request] (if (env :secondary) (let [school-id (Integer/parseInt id) owner-id (current-user request)] (when-not (or (is-admin? owner-id) (school/school-admin? school-id owner-id)) (throw-unauthorized {:role :educator})) (updater/start-sync! school-id) (response {:result "Ok"})) (bad-request "not a secondary school"))) (defn handle-asset-difference [request] (let [school-id (-> request :body :school-id) school-hashes (-> request :body :hashes) requested-courses (-> request :body :course-slugs)] (response (core/calc-asset-update school-id school-hashes requested-courses)))) (defn handle-get-latest-version [] (let [file-path (env :latest-binary-path)] (if (nil? file-path) (bad-request "no update available") (file-response file-path)))) (defn handle-software-update [request] (when-not (teacher? request) (throw-unauthorized {:role :teacher})) (if (env :secondary) (updater/update-local-instance!) (bad-request "not a secondary school"))) (defn handle-sync-status [request] (-> (updater/get-sync-status) (response))) (defroutes local-sync-routes (POST "/api/school/sync/:id" [id :as request] (handle-load-school-sync id request)) (GET "/api/school/sync-status" request (handle-sync-status request)) (POST "/api/software/update" request (handle-software-update request))) (defroutes global-sync-routes (GET "/api/school/dump-full/:id" [id :as request] (handle-dump-full id request)) (PUT "/api/school/update/:id" [id :as request] (handle-load-school-update id request)) (GET "/api/school/courses-update/:id" [id :as request] (handle-get-school-update id request)) (POST "/api/school/courses-update/:id" [id :as request] (handle-get-school-update id request)) (POST "/api/school/asset/difference/" request (handle-asset-difference request)) (sign/wrap-api-with-signature (GET "/api/software/latest" _ (handle-get-latest-version))))