id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,212 | canvas.lisp | VitoVan_calm/docs/examples/mondrian/canvas.lisp | ;;
;; Random Mondrian © 2023 by Vito Van
;; is licensed under CC BY-NC-SA 4.0.
;; To view a copy of this license, visit
;; http://creativecommons.org/licenses/by-nc-sa/4.0/
;; To obtain a commercial license, visit:
;; https://www.buymeacoffee.com/vitovan/e/119065
;;
(in-package #:calm)
#-jscl
(unless (str:starts-with? "dist" (uiop:getenv "CALM_CMD")) (swank:create-server))
(defparameter *mondrian-version* "0.0.1")
(setf *calm-window-width* 600)
(setf *calm-window-height* 500)
(setf *calm-window-title* "Mondrian")
(defun on-mousebuttonup (&key button x y clicks)
(declare (ignore button x y clicks))
(setf *calm-redraw* t))
;; disable redraw when moving mosue
(defun on-mousemotion (&key x y)
(declare (ignore x y))
(setf *calm-redraw* nil))
(defun on-mousebuttondown (&key button x y clicks)
(declare (ignore button x y clicks))
(setf *calm-redraw* nil))
(defun on-windowenter () (setf *calm-redraw* nil))
(defun on-windowleave () (setf *calm-redraw* nil))
;; white, red, yellow, blue
(defparameter *mondrian-color-list* '((0.93 0.92 0.94) (0.89 0.12 0.17) (0.94 0.87 0.47) (0 0.35 0.59)))
(defun draw-rect (x y w h &optional color)
(c:set-source-rgb 0 0 0)
(c:rectangle x y w h)
(c:stroke-preserve)
(apply #'c:set-source-rgb (nth (if color (1+ (random 3)) 0) *mondrian-color-list*))
(c:fill-path))
#-jscl
(setf *random-state* (make-random-state t))
(defun draw ()
(c:set-line-width 20)
(loop with x = 0
for width = (+ 42 (random 300))
until (> x *calm-window-width*)
do (loop with y = 0
for height = (+ 42 (random 300))
until (> y *calm-window-height*)
do (draw-rect x y width height (= (random 3) 0))
do (incf y height))
do (incf x width)))
| 1,799 | Common Lisp | .lisp | 48 | 33.666667 | 104 | 0.641217 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | c23ac6cb149e8d288b50ff055f4acc76690d2c9925e41a0beeb1a9b441ef3e5b | 2,212 | [
-1
] |
2,213 | canvas.lisp | VitoVan_calm/docs/examples/circles/canvas.lisp | (in-package #:calm)
#-jscl
(unless (str:starts-with? "dist" (uiop:getenv "CALM_CMD")) (swank:create-server))
(defparameter *color-list* '((0.83 0.82 0.84) (0.89 0.12 0.17) (0.94 0.87 0.47) (0 0.35 0.59)))
(defun draw ()
(c:set-operator :darken)
(dotimes (i 7)
(c:arc (+ 72 (* (- (/ *calm-window-width* 5) 44) i)) 73 50 0 (* 2 pi))
(apply #'c:set-source-rgb (nth (if (>= i 4) (- i 4) i) *color-list*))
(c:fill-path)))
| 435 | Common Lisp | .lisp | 10 | 40.7 | 95 | 0.576832 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 97ff314ce1a55880e0db390ab7118a5cf7d98f2f95e2a005cfc7b174e8244ba5 | 2,213 | [
-1
] |
2,214 | bundle.lisp | VitoVan_calm/s/usr/macos/bundle.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(calm-config)
(defun make-bundle (app-name bundle-id app-version dist-dir app-icon)
(let* ((ori-plist (str:from-file (merge-pathnames "s/usr/macos/app-Info.plist" *calm-env-calm-home*)))
(app-dir (merge-pathnames (str:concat app-name ".app/") *calm-env-app-dir*))
(app-content-dir (merge-pathnames "Contents/" app-dir))
(app-receipt-dir (merge-pathnames "_MASReceipt/" app-content-dir))
(app-resources-dir (merge-pathnames "Resources/" app-content-dir))
(app-macos-dir (merge-pathnames "MacOS/" app-content-dir))
(dist-dir-abs (or (uiop:absolute-pathname-p dist-dir)
(uiop:merge-pathnames* dist-dir *calm-env-app-dir*)))
(app-icon-abs (or (uiop:absolute-pathname-p app-icon)
(uiop:merge-pathnames* app-icon *calm-env-app-dir*)))
(codesign-cmd "codesign --sign - --force --preserve-metadata=entitlements,requirements,flags,runtime "))
;; clean old bunlde
(uiop:delete-directory-tree app-dir :validate t :if-does-not-exist :ignore)
(ensure-directories-exist app-content-dir)
(ensure-directories-exist app-receipt-dir)
(ensure-directories-exist app-resources-dir)
;; touch receipt
;;https://notes.alinpanaitiu.com/Making%20macOS%20apps%20uninstallable
;; the following trick makes the app "uninstallable"
(u:touch-file (merge-pathnames "receipt" app-receipt-dir))
;; write Info.plist
(str:to-file (merge-pathnames "Info.plist" app-content-dir)
(str:replace-using
(list "_APP_NAME_" app-name
"_BUNDLE_ID_" bundle-id
"_APP_VERSION_" app-version)
ori-plist))
;; copy dist
(u:copy-dir
dist-dir-abs
app-macos-dir)
;; copy icon
(u:copy-file app-icon-abs (merge-pathnames "icon.icns" app-resources-dir))
(u:calm-log "signing everything... (some files need sudo permission)")
(u:exec (str:concat "find " app-name ".app/Contents/MacOS/ -type f | xargs -I _ sudo " codesign-cmd " _")
:ignore-error-status t)
(u:calm-log "signing calm launcher...")
(u:exec (str:concat "sudo " codesign-cmd app-name ".app/Contents/MacOS/calm")
:ignore-error-status t)
(u:calm-log "signing the application bundle itself...")
(u:exec (str:concat "sudo " codesign-cmd app-name ".app")
:ignore-error-status t))
(u:calm-log-fancy "~%Application Bundle created: ~A.app~%" app-name))
(make-bundle
(u:get-from-env-or-ask 'app-name "Hello")
(u:get-from-env-or-ask 'bundle-id "com.jack.hello")
(u:get-from-env-or-ask 'app-version "0.0.1")
(or (uiop:getenv "DIST_DIR") (uiop:native-namestring (uiop:merge-pathnames* "dist/" *calm-env-app-dir*)))
(u:get-from-env-or-ask 'app-icon (namestring (merge-pathnames "build/app.icns" *calm-env-calm-home*))))
| 2,928 | Common Lisp | .lisp | 54 | 46.314815 | 113 | 0.644576 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 971a280c2ee02d71b47dd457990a1874990159761c590fc3cd2ec436580f65ab | 2,214 | [
-1
] |
2,215 | dmg.lisp | VitoVan_calm/s/usr/macos/dmg.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(calm-config)
(defun make-dmg (app-name dmg-icon)
(uiop:chdir *calm-env-app-dir*)
;; clean old dmg
(uiop:delete-file-if-exists (merge-pathnames (str:concat app-name ".dmg") *calm-env-app-dir*))
(when (not (= (u:exec "command -v create-dmg" :ignore-error-status t) 0))
(when (not (= (u:exec "command -v brew" :ignore-error-status t) 0))
(u:exec "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""))
(u:exec "brew install create-dmg"))
(u:exec
(str:concat
;; https://github.com/actions/runner-images/issues/7522#issuecomment-1566746364
(if (uiop:getenv "CI") "sudo " "")
"create-dmg "
" --hdiutil-verbose --volname \"" app-name " - CALM\""
" --volicon \"" dmg-icon "\""
" --window-pos 200 120"
" --window-size 800 280"
" --icon-size 100"
" --icon \"" app-name ".app\" 200 90"
" --hide-extension \"" app-name ".app\""
" --app-drop-link 600 85"
" \"" app-name ".dmg\"" " \"" app-name ".app/\""))
(u:calm-log-fancy "~%DMG created: ~A.dmg~%" app-name))
(make-dmg
(u:get-from-env-or-ask 'app-name "Hello")
(u:get-from-env-or-ask 'dmg-icon (namestring (merge-pathnames "build/app-dmg.icns" *calm-env-calm-home*))))
| 1,287 | Common Lisp | .lisp | 30 | 39.066667 | 115 | 0.623501 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | aa4aeaf2064a6a323ea9cc4cd0346033e1c3f38eaa4823ba19d7ec2f0b83fd9c | 2,215 | [
-1
] |
2,216 | load-and-compile.lisp | VitoVan_calm/s/usr/web/load-and-compile.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(defun load-and-compile (lisp-files)
(let* ((app-web-dir (merge-pathnames "web/" *calm-env-app-dir*))
(app-output-file (merge-pathnames "canvas.js" app-web-dir))
(quicklisp-setup-file (merge-pathnames "quicklisp/setup.lisp" *calm-env-calm-home*))
(jscl-git-path (merge-pathnames "build/web/jscl/" *calm-env-calm-home*))
(jscl-git-url "https://github.com/jscl-project/jscl.git")
(jscl-lisp-file (merge-pathnames "build/web/jscl/jscl.lisp" *calm-env-calm-home*))
(jscl-compile-script-template (merge-pathnames "s/usr/web/jscl-compile-script-template.lisp" *calm-env-calm-home*))
(jscl-compile-script (merge-pathnames "build/web/jscl/jscl-compile-script.lisp" *calm-env-calm-home*)))
(ensure-directories-exist app-web-dir)
(unless (probe-file jscl-git-path)
(u:exec (str:concat "git clone " jscl-git-url " " (uiop:native-namestring jscl-git-path)))
(u:exec (str:concat
"cd " (uiop:native-namestring jscl-git-path)
" && git checkout 25e0341e95725f9d6bba991c3adeaa58ae885066")))
(u:calm-log "generating JSCL compile scripts ~A~%" jscl-compile-script)
(str:to-file
jscl-compile-script
(str:replace-using
(list "__LISP_FILES_LIST__" lisp-files
"__APP_OUTPUT_FILE__" (uiop:native-namestring app-output-file)
"__CALM_HOME__" *calm-env-calm-home*)
(str:from-file jscl-compile-script-template)))
(u:calm-log "load and compile with JSCL~%")
(u:exec (str:concat "CALM_NO_CORE=1 calm sbcl --load " (uiop:native-namestring quicklisp-setup-file)
" --load " (uiop:native-namestring jscl-lisp-file)
" --load " (uiop:native-namestring jscl-compile-script)))))
(load-and-compile
(u:get-from-env-or-ask 'lisp-files
(write-to-string (list (uiop:native-namestring (uiop:merge-pathnames* "canvas.lisp" *calm-env-app-dir*))))))
| 2,020 | Common Lisp | .lisp | 33 | 52.030303 | 132 | 0.643829 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | a46c3681cadc3d8bfcd0903c50b898e4d6e0a8545885a7860e745de4c5157bc1 | 2,216 | [
-1
] |
2,217 | wasm.lisp | VitoVan_calm/s/usr/web/wasm.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(defun make-wasm (rebuild-wasm-p)
(let* ((calm-version (slot-value (asdf:find-system 'calm) 'asdf:version))
(web-tar-url (str:concat "https://github.com/VitoVan/calm/releases/download/" calm-version "/calm.tar"))
(build-web-dir (merge-pathnames "build/web/" *calm-env-calm-home*))
(web-tar-file (merge-pathnames "calm.tar" build-web-dir))
(app-web-dir (merge-pathnames "web/" *calm-env-app-dir*))
(build-dir (merge-pathnames "build-web/" *calm-env-app-dir*))
(app-fonts-dir (merge-pathnames "fonts/" *calm-env-app-dir*))
(app-assets-dir (merge-pathnames "assets/" *calm-env-app-dir*))
(build-share-dir (merge-pathnames "share/" build-dir))
(build-fonts-dir (merge-pathnames "fonts/" build-share-dir))
(build-assets-dir (merge-pathnames "assets/" build-share-dir)))
(ensure-directories-exist build-web-dir)
(ensure-directories-exist app-web-dir)
(if (string= rebuild-wasm-p "no")
(progn
(format t "rebuild-wasm-p was set as NO, using cache, or download it? let's see...~%")
(if (probe-file web-tar-file)
(format t "Using cached web tar file: ~A~%" web-tar-file)
(progn
(format t "Downloading web tar file from ~A ... ~%" web-tar-url)
(u:exec (str:concat "curl -o " (uiop:native-namestring web-tar-file) " -L " web-tar-url))))
(format t "extract files to ~A...~%" app-web-dir)
(u:exec (str:concat "tar xvf " (uiop:native-namestring web-tar-file) " --strip-components=1 --directory=" (uiop:native-namestring app-web-dir))))
(progn
(format t "Building WASM ... ~%")
;; preparation and clean up
(ensure-directories-exist build-share-dir)
(u:touch-file (merge-pathnames "nothing" build-share-dir))
(when (probe-file build-fonts-dir) (uiop:delete-directory-tree build-fonts-dir :validate t))
(when (probe-file build-assets-dir) (uiop:delete-directory-tree build-assets-dir :validate t))
;; copy files
(when (probe-file app-fonts-dir) (u:copy-dir app-fonts-dir build-fonts-dir))
(when (probe-file app-assets-dir) (u:copy-dir app-assets-dir build-assets-dir))
(ensure-directories-exist (merge-pathnames "src/" build-dir))
(u:copy-dir (merge-pathnames "src/web" *calm-env-calm-home*) (merge-pathnames "src/web" build-dir))
(format t "~%~%compiling... this will take one year, please be patient.~%~%~%")
(u:exec
(str:concat
"docker run --rm --name pcwa -v "
(uiop:native-namestring build-dir)
":/app -w=/app vitovan/pango-cairo-wasm "
"emcc -Oz "
"-sALLOW_MEMORY_GROWTH "
"-sFULL_ES2 "
"-s USE_SDL=2 "
"-s USE_SDL_MIXER=2 "
"-s USE_PTHREADS=0 "
"--shell-file src/web/calm.html "
"--pre-js src/web/pre.js "
"--js-library src/web/bridge.js "
"--preload-file ./share@/usr/share/ "
"src/web/calm.c -o calm.html "
(uiop:run-program "docker run --rm --name pcwa vitovan/pango-cairo-wasm pkg-config --libs --cflags glib-2.0, gobject-2.0, cairo, pixman-1, freetype2, fontconfig, cairo, expat, harfbuzz" :output '(:string :stripped t))
"-s EXPORTED_RUNTIME_METHODS=ccall,cwrap,allocateUTF8,UTF8ToString "
"-s EXPORTED_FUNCTIONS=_main,"
"_cairo_create,"
"_cairo_reference,"
"_cairo_destroy,"
"_cairo_status,"
"_cairo_save,"
"_cairo_restore,"
"_cairo_get_target,"
"_cairo_push_group,"
"_cairo_push_group_with_content,"
"_cairo_pop_group,"
"_cairo_pop_group_to_source,"
"_cairo_get_group_target,"
"_cairo_set_source_rgb,"
"_cairo_set_source_rgba,"
"_cairo_set_source,"
"_cairo_set_source_surface,"
"_cairo_get_source,"
"_cairo_set_antialias,"
"_cairo_get_antialias,"
"_cairo_set_dash,"
"_cairo_get_dash_count,"
"_cairo_get_dash,"
"_cairo_set_fill_rule,"
"_cairo_get_fill_rule,"
"_cairo_set_line_cap,"
"_cairo_get_line_cap,"
"_cairo_set_line_join,"
"_cairo_get_line_join,"
"_cairo_set_line_width,"
"_cairo_get_line_width,"
"_cairo_set_miter_limit,"
"_cairo_get_miter_limit,"
"_cairo_set_operator,"
"_cairo_get_operator,"
"_cairo_set_tolerance,"
"_cairo_get_tolerance,"
"_cairo_clip,"
"_cairo_clip_preserve,"
"_cairo_clip_extents,"
"_cairo_in_clip,"
"_cairo_reset_clip,"
"_cairo_rectangle_list_destroy,"
"_cairo_copy_clip_rectangle_list,"
"_cairo_fill,"
"_cairo_fill_preserve,"
"_cairo_fill_extents,"
"_cairo_in_fill,"
"_cairo_mask,"
"_cairo_mask_surface,"
"_cairo_paint,"
"_cairo_paint_with_alpha,"
"_cairo_stroke,"
"_cairo_stroke_preserve,"
"_cairo_stroke_extents,"
"_cairo_in_stroke,"
"_cairo_copy_page,"
"_cairo_show_page,"
"_cairo_get_reference_count,"
"_cairo_set_user_data,"
"_cairo_get_user_data,"
"_cairo_copy_path,"
"_cairo_copy_path_flat,"
"_cairo_path_destroy,"
"_cairo_append_path,"
"_cairo_has_current_point,"
"_cairo_get_current_point,"
"_cairo_new_path,"
"_cairo_new_sub_path,"
"_cairo_close_path,"
"_cairo_arc,"
"_cairo_arc_negative,"
"_cairo_curve_to,"
"_cairo_line_to,"
"_cairo_move_to,"
"_cairo_rectangle,"
"_cairo_glyph_path,"
"_cairo_text_path,"
"_cairo_rel_curve_to,"
"_cairo_rel_line_to,"
"_cairo_rel_move_to,"
"_cairo_path_extents,"
"_cairo_pattern_add_color_stop_rgb,"
"_cairo_pattern_add_color_stop_rgba,"
"_cairo_pattern_get_color_stop_count,"
"_cairo_pattern_get_color_stop_rgba,"
"_cairo_pattern_create_rgb,"
"_cairo_pattern_create_rgba,"
"_cairo_pattern_get_rgba,"
"_cairo_pattern_create_for_surface,"
"_cairo_pattern_get_surface,"
"_cairo_pattern_create_linear,"
"_cairo_pattern_get_linear_points,"
"_cairo_pattern_create_radial,"
"_cairo_pattern_get_radial_circles,"
"_cairo_pattern_create_mesh,"
"_cairo_mesh_pattern_begin_patch,"
"_cairo_mesh_pattern_end_patch,"
"_cairo_mesh_pattern_move_to,"
"_cairo_mesh_pattern_line_to,"
"_cairo_mesh_pattern_curve_to,"
"_cairo_mesh_pattern_set_control_point,"
"_cairo_mesh_pattern_set_corner_color_rgb,"
"_cairo_mesh_pattern_set_corner_color_rgba,"
"_cairo_mesh_pattern_get_patch_count,"
"_cairo_mesh_pattern_get_path,"
"_cairo_mesh_pattern_get_control_point,"
"_cairo_mesh_pattern_get_corner_color_rgba,"
"_cairo_pattern_reference,"
"_cairo_pattern_destroy,"
"_cairo_pattern_status,"
"_cairo_pattern_set_extend,"
"_cairo_pattern_get_extend,"
"_cairo_pattern_set_filter,"
"_cairo_pattern_get_filter,"
"_cairo_pattern_set_matrix,"
"_cairo_pattern_get_matrix,"
"_cairo_pattern_get_type,"
"_cairo_pattern_get_reference_count,"
"_cairo_pattern_set_user_data,"
"_cairo_pattern_get_user_data,"
"_cairo_region_create,"
"_cairo_region_create_rectangle,"
"_cairo_region_create_rectangles,"
"_cairo_region_copy,"
"_cairo_region_reference,"
"_cairo_region_destroy,"
"_cairo_region_status,"
"_cairo_region_get_extents,"
"_cairo_region_num_rectangles,"
"_cairo_region_get_rectangle,"
"_cairo_region_is_empty,"
"_cairo_region_contains_point,"
"_cairo_region_contains_rectangle,"
"_cairo_region_equal,"
"_cairo_region_translate,"
"_cairo_region_intersect,"
"_cairo_region_intersect_rectangle,"
"_cairo_region_subtract,"
"_cairo_region_subtract_rectangle,"
"_cairo_region_union,"
"_cairo_region_union_rectangle,"
"_cairo_region_xor,"
"_cairo_region_xor_rectangle,"
"_cairo_translate,"
"_cairo_scale,"
"_cairo_rotate,"
"_cairo_transform,"
"_cairo_set_matrix,"
"_cairo_get_matrix,"
"_cairo_identity_matrix,"
"_cairo_user_to_device,"
"_cairo_user_to_device_distance,"
"_cairo_device_to_user,"
"_cairo_device_to_user_distance,"
"_cairo_select_font_face,"
"_cairo_set_font_size,"
"_cairo_set_font_matrix,"
"_cairo_get_font_matrix,"
"_cairo_set_font_options,"
"_cairo_get_font_options,"
"_cairo_set_font_face,"
"_cairo_get_font_face,"
"_cairo_set_scaled_font,"
"_cairo_get_scaled_font,"
"_cairo_show_text,"
"_cairo_show_glyphs,"
"_cairo_show_text_glyphs,"
"_cairo_font_extents,"
"_cairo_text_extents,"
"_cairo_glyph_extents,"
"_cairo_toy_font_face_create,"
"_cairo_toy_font_face_get_family,"
"_cairo_toy_font_face_get_slant,"
"_cairo_toy_font_face_get_weight,"
"_cairo_glyph_allocate,"
"_cairo_glyph_free,"
"_cairo_text_cluster_allocate,"
"_cairo_text_cluster_free,"
"_cairo_pattern_create_raster_source,"
"_cairo_raster_source_pattern_set_callback_data,"
"_cairo_raster_source_pattern_get_callback_data,"
"_cairo_raster_source_pattern_set_acquire,"
"_cairo_raster_source_pattern_get_acquire,"
"_cairo_raster_source_pattern_set_snapshot,"
"_cairo_raster_source_pattern_get_snapshot,"
"_cairo_raster_source_pattern_set_copy,"
"_cairo_raster_source_pattern_get_copy,"
"_cairo_raster_source_pattern_set_finish,"
"_cairo_raster_source_pattern_get_finish,"
"_cairo_tag_begin,"
"_cairo_tag_end,"
"_cairo_image_surface_get_width,"
"_cairo_image_surface_get_height,"
"_cairo_image_surface_create_from_png,"
"_cairo_surface_status,"
"_cairo_status,"
"_config,"
"_Mix_OpenAudio,"
"_Mix_CloseAudio,"
"_Mix_LoadMUS,"
"_Mix_LoadWAV_RW,"
"_SDL_RWFromFile,"
"_Mix_PlayMusic,"
"_Mix_HaltMusic,"
"_Mix_HaltChannel,"
"_Mix_Volume,"
"_Mix_VolumeMusic,"
"_Mix_PlayChannelTimed,"
"_Mix_Playing,"
"_Mix_AllocateChannels,"
"_SDL_GetTicks,"
"_SDL_GetError,"
"_free"))
(u:calm-log-fancy "~%WASM file compiled.")))))
(make-wasm
(u:get-from-env-or-ask 'rebuild-wasm-p "no"))
| 11,855 | Common Lisp | .lisp | 275 | 30.712727 | 229 | 0.532475 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | de357b910ef1d10bb7aae759503411c711ce2c53d964952de41d81a7d2016269 | 2,217 | [
-1
] |
2,218 | post-compile.lisp | VitoVan_calm/s/usr/web/post-compile.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(defun post-compile ()
(let* ((app-web-dir (merge-pathnames "web/" *calm-env-app-dir*))
(app-build-web-dir (merge-pathnames "build-web/" *calm-env-app-dir*))
(build-web-dir (merge-pathnames "build/web/" *calm-env-calm-home*))
(jscl-js-file (merge-pathnames "jscl/jscl.js" build-web-dir))
(jscl-output-file (merge-pathnames "jscl.js" app-web-dir)))
(format t "copying jscl.js~%")
(u:copy-file jscl-js-file jscl-output-file)
(format t "copying calm.js~%")
(u:copy-file (merge-pathnames "calm.js" app-build-web-dir) (merge-pathnames "calm.js" app-web-dir))
(format t "copying calm.worker.js~%")
(u:copy-file (merge-pathnames "calm.worker.js" app-build-web-dir) (merge-pathnames "calm.worker.js" app-web-dir))
(format t "copying calm.wasm~%")
(u:copy-file (merge-pathnames "calm.wasm" app-build-web-dir) (merge-pathnames "calm.wasm" app-web-dir))
(format t "copying calm.data~%")
(u:copy-file (merge-pathnames "calm.data" app-build-web-dir) (merge-pathnames "calm.data" app-web-dir))
(format t "copying calm.html~%")
(u:copy-file (merge-pathnames "calm.html" app-build-web-dir) (merge-pathnames "calm.html" app-web-dir))
(format t "copying favicon.ico~%")
(u:copy-file (merge-pathnames "build/app.ico" *calm-env-calm-home*) (merge-pathnames "favicon.ico" app-web-dir))
(when (probe-file app-build-web-dir)
(uiop:delete-directory-tree app-build-web-dir :validate t))
(u:calm-log-fancy "Web page generated: ~A~%" app-web-dir)
(u:exec (str:concat "ls -lah " (uiop:native-namestring app-web-dir)))))
(post-compile)
| 1,669 | Common Lisp | .lisp | 28 | 54.5 | 117 | 0.672161 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 0e3c47513254167fb4e4257adda277258118cc9e1a2fd00a6a9790d620b63034 | 2,218 | [
-1
] |
2,219 | jscl-compile-script-template.lisp | VitoVan_calm/s/usr/web/jscl-compile-script-template.lisp | (jscl:bootstrap)
;; track: https://github.com/jscl-project/jscl/issues/474
(pushnew :jscl *features*)
(jscl:compile-application
(concatenate 'list
(list "__CALM_HOME__src/web/package.lisp"
"__CALM_HOME__src/web/cairo.lisp"
"__CALM_HOME__src/c.lisp"
"__CALM_HOME__src/calm.lisp"
"__CALM_HOME__src/config.lisp"
"__CALM_HOME__src/events.lisp")
'__LISP_FILES_LIST__
(list "__CALM_HOME__src/web/post.lisp"))
"__APP_OUTPUT_FILE__")
(quit)
| 617 | Common Lisp | .lisp | 15 | 27.866667 | 59 | 0.493355 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 7b4db4bd8987577c19926cdf29ae3dd693135f0037abfbd3666b47316dd452aa | 2,219 | [
-1
] |
2,220 | installer.lisp | VitoVan_calm/s/usr/windows/installer.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(calm-config)
(defun make-installer (app-name dist-dir)
(uiop:chdir *calm-env-app-dir*)
(uiop:delete-directory-tree (merge-pathnames "calm-app-root/" *calm-env-app-dir*) :validate t :if-does-not-exist :ignore)
(uiop:delete-file-if-exists (merge-pathnames "installer.nsi" *calm-env-app-dir*))
(u:copy-dir
(or
(uiop:absolute-pathname-p dist-dir)
(uiop:merge-pathnames* dist-dir *calm-env-app-dir*))
(merge-pathnames "calm-app-root" *calm-env-app-dir*))
;; make installer script
(str:to-file (merge-pathnames "installer.nsi" *calm-env-app-dir*)
(str:replace-all
"_APP_NAME_" app-name
(str:from-file (merge-pathnames "s/usr/windows/installer.nsi" *calm-env-calm-home*))))
;; copy installer assets
(let* ((installer-assets-dir (merge-pathnames "calm-installer-assets/" *calm-env-app-dir*))
(calm-build-dir (merge-pathnames "build/" *calm-env-calm-home*)))
(unless (probe-file installer-assets-dir)
(ensure-directories-exist installer-assets-dir)
(mapcar
#'(lambda (filename)
(u:copy-file (merge-pathnames filename calm-build-dir) (merge-pathnames filename installer-assets-dir)))
'("app-installer.ico" "app-uninstaller.ico" "installer-header.bmp" "installer-page.bmp"))))
(setf (uiop:getenv "PATH") (str:concat "C:\\Program Files (x86)\\NSIS;" (uiop:getenv "PATH")))
(when (not (= (u:exec "where makensis" :ignore-error-status t) 0))
(when (not (= (u:exec "where winget" :ignore-error-status t) 0))
(u:exec "calm s usr windows winget.ps1"))
(u:exec "winget install nsis -s winget --accept-source-agreements --accept-package-agreements"))
(u:exec "makensis -V4 installer.nsi")
(u:calm-log-fancy "~%Installer created: ~A-Installer.exe~%" app-name))
(make-installer
(u:get-from-env-or-ask 'app-name "Hello")
(or (uiop:getenv "DIST_DIR") (uiop:native-namestring (uiop:merge-pathnames* "dist/" *calm-env-app-dir*))))
| 2,015 | Common Lisp | .lisp | 37 | 49.108108 | 123 | 0.677337 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 21a65edea0406cf1cc5201d9dc3f3fe250717f3600af069fe4118265442d92c7 | 2,220 | [
-1
] |
2,221 | icon.lisp | VitoVan_calm/s/usr/windows/icon.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(calm-config)
(defun set-icon (app-icon)
(let ((rcedit-bin (merge-pathnames "s/usr/windows/rcedit.exe" *calm-env-calm-home*))
(rcedit-url "https://github.com/electron/rcedit/releases/download/v2.0.0/rcedit-x64.exe")
(old-sbcl (merge-pathnames "sbcl/bin/sbcl.exe" *calm-env-calm-home*))
(new-sbcl (merge-pathnames "sbcl/bin/sbcl-with-icon.exe" *calm-env-calm-home*))
(calm-no-console (merge-pathnames "calmNoConsole.exe" *calm-env-calm-home*)))
(uiop:copy-file old-sbcl new-sbcl)
(unless (probe-file rcedit-bin)
(u:calm-log "downloading rcedit.exe from:~%~A~%" rcedit-url)
(u:exec (str:concat "curl.exe -L -o " (uiop:native-namestring rcedit-bin) " --url " rcedit-url)))
(u:exec (str:concat (uiop:native-namestring rcedit-bin)
" "
(uiop:native-namestring new-sbcl)
" --set-icon "
app-icon))
(u:exec (str:concat (uiop:native-namestring rcedit-bin)
" "
(uiop:native-namestring calm-no-console)
" --set-icon "
app-icon)))
(u:calm-log "~%ICON applied: ~A~%" app-icon))
(set-icon
(u:get-from-env-or-ask 'app-icon (namestring (merge-pathnames "build/app.ico" *calm-env-calm-home*))))
| 1,389 | Common Lisp | .lisp | 27 | 40.62963 | 103 | 0.586411 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 8f46376d4216b4c56bc2dedb9407625858a81f559320e18f3896daa732e55fdb | 2,221 | [
-1
] |
2,222 | appimage.lisp | VitoVan_calm/s/usr/linux/appimage.lisp | #-calm
(ql:quickload :calm)
(in-package :calm)
(calm-config)
(defun make-appimage (app-name app-icon dist-dir)
(uiop:chdir *calm-env-app-dir*)
(let ((appimage-tool-bin (merge-pathnames "s/usr/linux/appimagetool.AppImage" *calm-env-calm-home*))
(appimage-tool-url "https://github.com/AppImage/AppImageKit/releases/download/13/appimagetool-x86_64.AppImage")
(appimage-app-dir (merge-pathnames (str:concat app-name ".AppDir/") *calm-env-app-dir*))
(appimage-app-run (merge-pathnames "s/usr/linux/AppRun" *calm-env-calm-home*)))
(unless (probe-file appimage-tool-bin)
(u:calm-log "downloading appimagetool from:~%~A~%" appimage-tool-url)
(u:exec (str:concat "curl -o " (uiop:native-namestring appimage-tool-bin) " -L " appimage-tool-url))
(u:exec (str:concat "chmod +x " (uiop:native-namestring appimage-tool-bin))))
;; mkdir
(ensure-directories-exist appimage-app-dir)
;; copy dist-dir
(ensure-directories-exist (merge-pathnames "usr/" appimage-app-dir))
(u:copy-dir dist-dir (merge-pathnames "usr/bin/" appimage-app-dir))
;; copy AppRun
(u:copy-file appimage-app-run (merge-pathnames "AppRun" appimage-app-dir))
;; make it executable
(u:exec (str:concat "chmod +x " (uiop:native-namestring (merge-pathnames "AppRun" appimage-app-dir))))
;; copy AppImage ICON
(u:copy-file app-icon (merge-pathnames (str:concat "icon." (pathname-type app-icon)) appimage-app-dir))
;; copy SDL Window ICON, this is only needed by Linux system
(ensure-directories-exist (merge-pathnames "usr/bin/build/" appimage-app-dir))
(u:copy-file app-icon (merge-pathnames "usr/bin/build/app.png" appimage-app-dir))
;; generate desktop file
(str:to-file (merge-pathnames (str:concat app-name ".desktop") appimage-app-dir)
(str:replace-all
"_APP_NAME_" app-name
(str:from-file (merge-pathnames "s/usr/linux/app.desktop" *calm-env-calm-home*))))
(u:exec (str:concat
(uiop:native-namestring appimage-tool-bin)
" --appimage-extract-and-run "
"\"" (uiop:native-namestring appimage-app-dir) "\""
" \"" app-name ".AppImage\"")))
(u:calm-log-fancy "~%AppImage created: ~A.AppImage~%" app-name))
(make-appimage
(u:get-from-env-or-ask 'app-name "Hello")
(u:get-from-env-or-ask 'app-icon (namestring (merge-pathnames "build/app.png" *calm-env-calm-home*)))
(or (uiop:getenv "DIST_DIR") (uiop:native-namestring (uiop:merge-pathnames* "dist/" *calm-env-app-dir*))))
| 2,559 | Common Lisp | .lisp | 43 | 52.953488 | 119 | 0.671457 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 3dffa6c6c071482f408a68561fc86a16658fd0589e99f8b0634a1141cafee415 | 2,222 | [
-1
] |
2,223 | panic.lisp | VitoVan_calm/s/usr/all/panic.lisp | (in-package #:calm)
;;
;; CALM version check
;; version check won't work on JSCL, since the lack of ASDF
;;
#-jscl
(let ((required-version "1.3.2")
(calm-version (slot-value (asdf:find-system 'calm) 'asdf:version)))
(when (uiop:version< calm-version required-version)
(format t
"Sorry, this is built on CALM ~A, older version (current: ~A) of CALM won't work.~%"
required-version calm-version)
(uiop:quit)))
;; DEBUGGING, please uncomment the correspoding line
;;
;; for Emacs - SLIME
;; https://slime.common-lisp.dev/
;;
;; (unless (str:starts-with? "dist" (uiop:getenv "CALM_CMD")) (swank:create-server :dont-close t))
;;
;; for LEM - micros
;; https://github.com/lem-project/micros
;;
;; (unless (str:starts-with? "dist" (uiop:getenv "CALM_CMD")) (micros:create-server :dont-close t))
;;
;; for Alive - Visual Studio Code
;; https://github.com/nobody-famous/alive
;; please config `alive.lsp.startCommand':
;;
;; {
;; "alive.lsp.startCommand": [
;; "calm",
;; "alive"
;; ]
;; }
;;
;; by default, the screensaver is disabled,
;; if you want to enable screensaver,
;; please uncomment the following line
;;
;; (setf (uiop:getenv "SDL_VIDEO_ALLOW_SCREENSAVER") "1")
;;
;; setting window properties, for others, please check
;; https://github.com/VitoVan/calm/blob/main/src/config.lisp
;;
(setf *calm-window-width* 600)
(setf *calm-window-height* 150)
(setf *calm-window-title* "CALM")
(defun draw ()
(c:set-source-rgb (/ 12 255) (/ 55 255) (/ 132 255))
(c:paint)
(c:set-source-rgb 1 1 1)
(c:move-to 30 100)
(c:set-font-size 84)
(c:show-text "DON'T PANIC"))
| 1,709 | Common Lisp | .lisp | 55 | 28.981818 | 99 | 0.63791 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 2998776e802d13c5845889bfaf214d6d6d793890cbffcc114fe4650ae9cf6bf9 | 2,223 | [
-1
] |
2,224 | copy-lib.lisp | VitoVan_calm/s/dev/all/copy-lib.lisp | (mapcar
#'(lambda (lib)
(let* ((lib-pathname (cffi:foreign-library-pathname lib))
(lib-path-namestring (namestring lib-pathname)))
(unless (str:starts-with-p "/System" lib-path-namestring)
(uiop:run-program
;; this has to be done by `cp` because `uiop:copy-file` has some weird behaviours on MSYS2
(str:concat "cp "
(namestring
#+linux
(uiop:merge-pathnames* lib-pathname "/usr/lib64/")
#+darwin
(uiop:merge-pathnames* lib-pathname "/usr/local/lib/")
#+win32
(uiop:merge-pathnames* lib-pathname "/mingw64/bin/"))
" ./lib/" )))))
(cffi:list-foreign-libraries :loaded-only t))
(quit)
| 820 | Common Lisp | .lisp | 18 | 31.333333 | 100 | 0.518102 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 4e0baaf01b699cd0c4f91e5baaeed8ce4357f0d51242542d836afa9c32c8e993 | 2,224 | [
-1
] |
2,225 | load-calm.lisp | VitoVan_calm/s/dev/all/load-calm.lisp | ;; the existence of this file is to avoid the tricky shitty escaping of quotation marks
#-quicklisp
(load "./quicklisp/setup.lisp")
;; https://groups.google.com/g/quicklisp/c/wrULkRePVE4
#+win32
(quicklisp-client::make-system-index "./quicklisp/local-projects/")
#-calm
(load "./calm.asd")
#-calm
(ql:quickload :calm)
| 318 | Common Lisp | .lisp | 10 | 30.8 | 87 | 0.75974 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 9ed70e90ad7234b0614cae55ee525c26b03aa8654988b588167c4050b4a3bcce | 2,225 | [
-1
] |
2,226 | quicklisp-fix-old-packages.sh | VitoVan_calm/s/dev/all/quicklisp-fix-old-packages.sh | # these are waiting for the next (maybe) Quicklisp update
cd ./quicklisp/local-projects
git clone https://github.com/andy128k/cl-gobject-introspection.git
cd cl-gobject-introspection
git reset --hard 4908a84c16349929b309c50409815ff81fb9b3c4
cd ..
| 248 | Common Lisp | .lisp | 6 | 40.166667 | 66 | 0.838174 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 24d31c3e8e5dd0fb4a9cd579ade55d7b5fc2cd505469a82c9327eebecf3efa05 | 2,226 | [
-1
] |
2,227 | quicklisp.sh | VitoVan_calm/s/dev/all/quicklisp.sh | echo "Install Quicklisp ..."
if ! [ -d quicklisp ]; then
if ! [ -f quicklisp.lisp ]; then
set -x
curl -o ./quicklisp.lisp -L https://beta.quicklisp.org/quicklisp.lisp
set +x
fi
./calm sbcl \
--load quicklisp.lisp \
--load ./s/dev/all/install-quicklisp.lisp
fi
| 318 | Common Lisp | .lisp | 11 | 22.636364 | 77 | 0.576547 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 07f79973908af9be735c6738d36869e37b4052bad551a7e2fef83c619422ac5e | 2,227 | [
-1
] |
2,228 | quicklisp-fix-apple-silicon.sh | VitoVan_calm/s/dev/all/quicklisp-fix-apple-silicon.sh | # https://github.com/lispgames/cl-sdl2/issues/154#issuecomment-1280030566
# this path is made on 2024-08-06
# should be removed when the following PR merged:
# https://github.com/lispgames/cl-sdl2/pull/167
# https://github.com/lispgames/cl-sdl2-image/pull/11
# https://github.com/Failproofshark/cl-sdl2-ttf/pull/28
# and this issue closed:
# https://github.com/lispgames/cl-sdl2-mixer/issues/12
# Get the system architecture
arch=$(uname -m)
# Check if the architecture is arm64
if [ "$arch" == "arm64" ]; then
echo "This macOS system is ARM64. Applying SDL2 patch"
cd ./quicklisp/local-projects
git clone https://github.com/cffi/cffi.git
cd cffi
git reset --hard 13f21d5272d56e759d64895f670b428a63a16f01
cd ..
git clone https://github.com/rpav/cl-autowrap.git
cd cl-autowrap
git reset --hard 4bba9e37b59cd191dea150a89aef7245a40b1c9d
cd ..
git clone https://github.com/ellisvelo/cl-sdl2.git
cd cl-sdl2
git reset --hard fe8a1638dcadae3ea1e5627897cad3aa99f95635
cd ..
git clone https://github.com/ellisvelo/cl-sdl2-mixer.git
cd cl-sdl2-mixer
git reset --hard 8e20cbc06ab61413bdd0183da1d02bbb52fd7332
cd ..
git clone https://github.com/ellisvelo/cl-sdl2-image.git
cd cl-sdl2-image
git reset --hard 8734b0e24de9ca390c9f763d9d7cd501546d17d4
cd ..
else
echo "This macOS system is not ARM64. No need to apply patch."
exit 0
fi
| 1,432 | Common Lisp | .lisp | 38 | 33.947368 | 73 | 0.742424 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 0f9aeb5adc80117e80c9f121bb782e9b126ff2b0eae3d185e49946011be59b60 | 2,228 | [
-1
] |
2,229 | install-quicklisp.lisp | VitoVan_calm/s/dev/all/install-quicklisp.lisp | ;; the existence of this file is purely for the suckness of white-space / quotation escaping on different platforms.
(quicklisp-quickstart:install :path "./quicklisp")
(quit)
| 175 | Common Lisp | .lisp | 3 | 57.333333 | 116 | 0.790698 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 16fc67f5865620560b5d3863a4762b6b4d4770924b12381bf1e4ae94b6e74e84 | 2,229 | [
-1
] |
2,230 | calm.asd | VitoVan_calm/calm.asd | (asdf:defsystem #:calm
:description "CALM - Canvas Aided Lisp Magic"
:version "1.3.2"
:author "Vito Van"
:license "GNU General Public License, version 2"
:depends-on (
#:sdl2
#:sdl2-mixer
#:sdl2-image
#:str
#:swank
#:bt-semaphore
#:cl-cairo2
#:cl-gobject-introspection)
:pathname "./src/"
:serial t
:components ((:file "package")
(:file "config")
(:file "events")
(:file "utils")
(:file "c")
(:file "cairo")
(:file "fontconfig")
(:file "calm")))
| 687 | Common Lisp | .asd | 24 | 17.583333 | 50 | 0.447964 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 1123921b672d89394ad82a61229528ee14c0d0e140d14c0cd0ae72584593ff9d | 2,230 | [
-1
] |
2,231 | sbcl.yml | VitoVan_calm/.github/workflows/sbcl.yml | name: SBCL
on:
push:
tags:
- "sbcl-*"
- "test-sbcl-*"
jobs:
Ubuntu:
# The type of runner that the job will run on
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-20.04]
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v3
- name: install dependencies
run: |
sudo apt update -y
sudo apt install build-essential -y
sudo apt install libzstd-dev -y
- name: build
run: |
# use custom built sbcl for grandpa ubuntu
# otherwise, it won't build
curl -o install_root.zip -L https://github.com/VitoVan/calm/releases/download/sbcl-2.3.4/install_root-ubuntu-20.04.zip
unzip install_root.zip
rm install_root.zip
mv ./install_root ./sbcl
export PATH=$(pwd)/sbcl/bin:$PATH
# start building new sbcl
set -x
curl -OL http://downloads.sourceforge.net/project/sbcl/sbcl/2.4.7/sbcl-2.4.7-source.tar.bz2
set +x
bzip2 -cd sbcl-2.4.7-source.tar.bz2 | tar xvf -
cd sbcl-2.4.7
sh make.sh --with-sb-thread --with-sb-core-compression
- name: zip install_root
run: |
set -x
cd sbcl-2.4.7
export INSTALL_ROOT=$HOME/install_root
sh install.sh
cd ..
echo $INSTALL_ROOT
cp -r $INSTALL_ROOT ./install_root
zip -r -9 install_root-${{ matrix.os }}.zip ./install_root
- name: GH Release
uses: softprops/[email protected]
with:
draft: true
files: |
*.zip
macOS:
# The type of runner that the job will run on
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-12, macos-13, macos-14]
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v3
- name: install
shell: bash
run: |
brew update && brew install sbcl && brew fetch zstd && brew reinstall zstd
- name: build
run: |
# for newer version of homebrew, the location of files has changed
export CPATH=$(brew --prefix zstd)/include:/usr/local/include:$CPATH
export LIBRARY_PATH=$(brew --prefix zstd)/lib/:$LIBRARY_PATH
# start building
set -x
curl -OL http://downloads.sourceforge.net/project/sbcl/sbcl/2.4.7/sbcl-2.4.7-source.tar.bz2
set +x
bzip2 -cd sbcl-2.4.7-source.tar.bz2 | tar xvf -
cd sbcl-2.4.7
sh make.sh --with-sb-thread --with-sb-core-compression
- name: zip install_root
run: |
set -x
cd sbcl-2.4.7
export INSTALL_ROOT=$HOME/install_root
sh install.sh
cd ..
echo $INSTALL_ROOT
cp -r $INSTALL_ROOT ./install_root
zip -r -9 install_root-${{ matrix.os }}.zip ./install_root
- name: GH Release
uses: softprops/[email protected]
with:
draft: true
files: |
*.zip
Windows:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-2019]
defaults:
run:
shell: msys2 {0}
steps:
- uses: actions/checkout@v3
- uses: msys2/setup-msys2@v2
with:
location: D:\
release: true
update: false
install: >-
p7zip
zip
mingw-w64-x86_64-gcc
mingw-w64-x86_64-zstd
make
diffutils
wget
git
- name: build
run: |
wget http://prdownloads.sourceforge.net/sbcl/sbcl-2.2.7-x86-64-windows-binary.msi
7z x sbcl-2.2.7-x86-64-windows-binary.msi -Osbcl-2.2.7-bin && rm sbcl-2.2.7-x86-64-windows-binary.msi
wget http://downloads.sourceforge.net/project/sbcl/sbcl/2.4.7/sbcl-2.4.7-source.tar.bz2
bzip2 -cd sbcl-2.4.7-source.tar.bz2 | tar xvf -
cd sbcl-2.4.7
PATH=$PATH:"../sbcl-2.2.7-bin/" SBCL_HOME="../sbcl-2.2.7-bin/" sh make.sh --xc-host='sbcl --lose-on-corruption --disable-ldb --disable-debugger' --with-sb-thread --with-sb-core-compression
- name: zip install_root
run: |
set -x
cd sbcl-2.4.7
export INSTALL_ROOT=$HOME/install_root
sh install.sh
cd ..
echo $INSTALL_ROOT
cp -r $INSTALL_ROOT ./install_root
zip -r -9 install_root-${{ matrix.os }}.zip ./install_root
- name: GH Release
uses: softprops/[email protected]
with:
draft: true
files: |
*.zip
| 4,953 | Common Lisp | .cl | 144 | 25.083333 | 198 | 0.564718 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | c7db6ea1b266b4d4a785b8431e6db8f735684d70c0b8e3868f651f44f0b9e63c | 2,231 | [
-1
] |
2,233 | sbcl.sh | VitoVan_calm/s/dev/msys/sbcl.sh | echo "Install SBCL binary (with compression feature) ..."
if ! [ -d sbcl ]; then
if ! [ -f install_root.zip ]; then
set -x
curl -o install_root.zip -L https://github.com/VitoVan/calm/releases/download/sbcl-2.4.7/install_root-windows-2019.zip
set +x
fi
rm -rf ./install_root
rm -f calm.core
unzip install_root.zip
mv ./install_root ./sbcl
fi
| 389 | Common Lisp | .cl | 12 | 27.416667 | 126 | 0.64191 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 9e9851e8697939295c67bda9a54dba4e8e558c93742104fbe1929ae7bd0b2c17 | 2,233 | [
-1
] |
2,234 | sbcl.sh | VitoVan_calm/s/dev/darwin/sbcl.sh | echo "Install SBCL binary (with compression feature) ..."
if ! [ -d sbcl ]; then
if ! [ -f install_root.zip ]; then
set -x
if [[ -z "${CI_MATRIX_OS}" ]]; then
macos_version=$(sw_vers -productVersion | cut -d. -f1)
echo "macOS version: $macos_version"
curl -o install_root.zip -L https://github.com/VitoVan/calm/releases/download/sbcl-2.4.7/install_root-macos-${macos_version}.zip
else
curl -o install_root.zip -L https://github.com/VitoVan/calm/releases/download/sbcl-2.4.7/install_root-${CI_MATRIX_OS}.zip
fi
set +x
fi
rm -rf ./install_root
rm -f calm.core
unzip install_root.zip
mv ./install_root ./sbcl
fi
| 721 | Common Lisp | .cl | 18 | 32.833333 | 140 | 0.610242 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 2b7ae614ee52860a96c106dd2d242ecc67ca047738a703464abc697a142532c6 | 2,234 | [
-1
] |
2,235 | sbcl.sh | VitoVan_calm/s/dev/fedora/sbcl.sh | echo "Install SBCL binary (with compression feature) ..."
if ! [ -d sbcl ]; then
if ! [ -f install_root.zip ]; then
set -x
curl -o install_root.zip -L https://github.com/VitoVan/calm/releases/download/sbcl-2.4.7/install_root-ubuntu-20.04.zip
set +x
fi
rm -rf ./install_root
rm -f calm.core
unzip install_root.zip
mv ./install_root ./sbcl
fi
| 389 | Common Lisp | .cl | 12 | 27.416667 | 126 | 0.639257 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | db3045d17b4464fb66877c3e8c7d8cdec509878cd4f0d45499d9e4fd9d6f705c | 2,235 | [
-1
] |
2,239 | build.bat | VitoVan_calm/build/build.bat | echo "build launcher ..."
cl /Fe:calmNoConsole src\calm.c /link /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup
cl /Fe:calm src\calm.c /link /SUBSYSTEM:CONSOLE
echo "executing build.sh in MSYS2 ..."
C:\msys64\msys2_shell.cmd -defterm -here -no-start -mingw64 -c 'bash ./build/build.sh'
| 279 | Common Lisp | .l | 5 | 54.8 | 86 | 0.751825 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 63b85cd7a54668568b25f97039c1ace6206c13b837ce0ca91b551fcb075111f6 | 2,239 | [
-1
] |
2,240 | build.sh | VitoVan_calm/build/build.sh | export CALM_BUILDING=1
env
build_fedora () {
sudo dnf update -y
if ! [ -f calm ]; then
echo "build launcher ..."
sudo dnf install gcc -y
gcc src/calm.c -o calm
fi
echo "remove Windows fonts dir ..."
sed '/<dir>C:\\Windows\\Fonts<\/dir>/d' s/usr/all/fonts.conf > tmp-fonts.conf
mv tmp-fonts.conf s/usr/all/fonts.conf
echo "executing calm s ..."
./calm s dev fedora deps.sh && \
./calm s dev fedora sbcl.sh && \
./calm s dev all quicklisp.sh && \
./calm s dev all quicklisp-fix-old-packages.sh && \
./calm s dev all alive.sh && \
./calm s dev all copy-lib.sh && \
./calm s dev fedora config-lib.sh
# prepare appimage-tool
APPIMAGETOOL="./s/usr/linux/appimagetool.AppImage"
APPIMAGETOOL_LICENSE="./s/usr/linux/appimagetool-LICENSE"
if [ ! -f "$APPIMAGETOOL" ]; then
set -x
curl -o "$APPIMAGETOOL" -L https://github.com/AppImage/AppImageKit/releases/download/13/appimagetool-x86_64.AppImage
curl -o "$APPIMAGETOOL_LICENSE" -L https://raw.githubusercontent.com/AppImage/AppImageKit/master/LICENSE
chmod +x "$APPIMAGETOOL"
set +x
fi
./calm s dev fedora pack.sh
echo "DONE"
}
build_darwin () {
# don't do this, some stupid CI would take forever and then fail
# brew update
echo "build launcher ..."
brew install gcc
gcc src/calm.c -o calm
# codesign for macos-14 enhanced security
codesign --sign - --force --preserve-metadata=entitlements,requirements,flags,runtime calm
echo "remove Windows fonts dir ..."
sed '/<dir>C:\\Windows\\Fonts<\/dir>/d' s/usr/all/fonts.conf > tmp-fonts.conf
mv tmp-fonts.conf s/usr/all/fonts.conf
echo "executing calm s ..."
./calm s dev darwin deps.sh && \
./calm s dev darwin sbcl.sh && \
./calm s dev all quicklisp.sh && \
./calm s dev all quicklisp-fix-apple-silicon.sh && \
./calm s dev all quicklisp-fix-old-packages.sh && \
./calm s dev all alive.sh && \
./calm s dev all copy-lib.sh && \
./calm s dev darwin config-lib.sh && \
./calm s dev darwin pack.sh && \
echo "DONE"
}
build_msys () {
pacman -Suy
## The following should be ran on MSVC Shell
# echo "build launcher ..."
# cl /Fe:calmGUI src\calm.c /link /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup
# cl /Fe:calm src\calm.c /link /SUBSYSTEM:CONSOLE
./calm s dev msys deps.sh && \
./calm s dev msys sbcl.sh && \
./calm s dev all quicklisp.sh && \
./calm s dev all quicklisp-fix-old-packages.sh && \
./calm s dev all alive.sh && \
./calm s dev all copy-lib.sh && \
./calm s dev msys config-lib.sh
echo "setting icons ..."
RCEDIT="./s/usr/windows/rcedit.exe"
RCEDIT_LICENSE="./s/usr/windows/rcedit-LICENSE"
if [ ! -f "$RCEDIT" ]; then
set -x
curl -o "$RCEDIT" -L https://github.com/electron/rcedit/releases/download/v2.0.0/rcedit-x64.exe
curl -o "$RCEDIT_LICENSE" -L https://raw.githubusercontent.com/electron/rcedit/master/LICENSE
set +x
fi
"$RCEDIT" "./sbcl/bin/sbcl.exe" --set-icon "./build/app.ico"
#
# calmNoConsole.exe will be copied into dist folder,
# so let's make its icon the same as the app icon
#
"$RCEDIT" "./calmNoConsole.exe" --set-icon "./build/app.ico"
"$RCEDIT" "./calm.exe" --set-icon "./build/calm.ico"
echo "packing ..."
./calm s dev msys pack.sh
echo "DONE."
}
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
export DISTRO="$(awk -F= '/^NAME/{print $2}' /etc/os-release | sed 's/"//g')"
if [[ "$DISTRO" == "Fedora"* ]]; then
build_fedora
else
echo "Sorry, I only managed to build this on Fedora."
echo "If you don't mind, docker could fulfil this task:"
echo " docker run -v $PWD:/calm -w /calm fedora bash build/build.sh"
exit 42
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
build_darwin
elif [[ "$OSTYPE" == "msys" ]]; then
build_msys
else
echo "Unsupported platform, please try Fedora Linux / macOS / MSYS2"
exit 42
fi
if ./calm test; then
echo "DONE."
./calm s dev all clean.sh
exit 0
else
echo "Failed!"
./calm s dev all clean.sh
exit 42
fi
| 4,337 | Common Lisp | .l | 116 | 31.482759 | 124 | 0.609895 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | cae5c1f735d6e2f631f95da10ae39ba2fee2ee0a54120e674816fe3f7904fc62 | 2,240 | [
-1
] |
2,249 | calm.c | VitoVan_calm/src/calm.c | /*
* CAUTION:
*
* !!!! SHITTY CODE AHEAD !!!!
*
* I tried to replace Bash with C to get more compatibility
* on different OSes, but iSuck@C.
* Now the bright side is that it worked,
* the dark side is that the code is worse than the Bash scripts.
*
* Please forgive me, and improve the code if you don't mind.
*
* I am formatting this file with:
* clang-format --style=Google -i calm.c
* So, if you are editing this file, please format it afterwards
*
* Compile on Windows:
* GUI:
* cl /Fe:calmNoConsole calm.c /link /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup
* Console:
* cl /Fe:calm calm.c /link /SUBSYSTEM:CONSOLE
*
* Compile on *nix:
* gcc calm.c -o calm
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#define F_OK 0
#else
#include <libgen.h>
#include <unistd.h>
#endif
void apply_env(char const *variable, char const *value) {
#ifdef _WIN32
_putenv_s(variable, value);
#else
setenv(variable, value, 1);
#endif
}
const char *get_binary_path() {
static char path[FILENAME_MAX];
uint32_t size = sizeof(path);
#ifdef __APPLE__
_NSGetExecutablePath(path, &size);
#elif defined _WIN32
GetModuleFileName(NULL, path, size);
#elif defined __linux__
readlink("/proc/self/exe", path, size);
#endif
return path;
}
const char *get_binary_dir() {
#ifdef _WIN32
static char drive[FILENAME_MAX];
char dir[FILENAME_MAX];
_splitpath_s(get_binary_path(), drive, sizeof(drive), dir, sizeof(dir), NULL,
0, NULL, 0);
return strcat(drive, dir);
#else
return dirname((char *)get_binary_path());
#endif
}
const char *get_lib_path() {
static char lib_path[FILENAME_MAX];
#ifdef __APPLE__
/*
* add quotation mark, to avoid white-space problems
* this shit seems only work on macOS
*/
strcpy(lib_path, "\"");
#else
strcpy(lib_path, "");
#endif
strcat(lib_path, get_binary_dir());
#ifdef _WIN32
char *lib_rel = "lib";
#else
char *lib_rel = "/lib";
#endif
strcat(lib_path, lib_rel);
#ifdef __APPLE__
strcat(lib_path, "\"");
#endif
printf("LIB_PATH=%s\n", lib_path);
return lib_path;
}
const char *get_sbcl_path() {
char *calm_host_lisp = getenv("CALM_HOST_LISP");
if (calm_host_lisp) return calm_host_lisp;
static char sbcl_path[FILENAME_MAX];
strcpy(sbcl_path, " \""); // to escape white-space
strcat(sbcl_path, get_binary_dir());
#ifdef _WIN32
if (getenv("CALM_WITH_ICON") == NULL) {
strcat(sbcl_path, "sbcl\\bin\\sbcl");
} else {
strcat(sbcl_path, "sbcl\\bin\\sbcl-with-icon");
}
#else
strcat(sbcl_path, "/sbcl/bin/sbcl");
#endif
strcat(sbcl_path, "\""); // to escape white-space
if (access("calm.core", F_OK) == 0 && getenv("CALM_NO_CORE") == NULL) {
strcat(sbcl_path, " --core calm.core");
}
strcat(sbcl_path, " --noinform --no-sysinit --no-userinit");
return sbcl_path;
}
void prepend(char *s1, char *s2) {
int len1 = strlen(s1);
int len2 = strlen(s2);
// Make s1 big enough to hold both strings
s1 = realloc(s1, len1 + len2 + 1);
// Move s1's original contents to the end
memmove(s1 + len2, s1, len1 + 1);
// Copy s2 to the beginning of s1
memcpy(s1, s2, len2);
}
/*
* return the new value for
* Linux: LD_LIBRARY_PATH
* macOS: DYLD_LIBRARY_PATH
* Windows: PATH
*/
const char *get_lib_env() {
const char *lib_path = get_lib_path();
char *path_separator = ":";
#ifdef __APPLE__
char *ori_lib_env = getenv("DYLD_LIBRARY_PATH");
#elif defined __linux__
char *ori_lib_env = getenv("LD_LIBRARY_PATH");
#elif defined _WIN32
path_separator = ";";
char *ori_lib_env = getenv("PATH");
#endif
if (ori_lib_env == NULL) {
ori_lib_env = "";
}
char *lib_env =
malloc((strlen(ori_lib_env) + strlen(lib_path) + strlen(path_separator) +
1024 // I don't know what I'm doing
) *
sizeof(char));
strcpy(lib_env, ori_lib_env);
#if defined _WIN32
// on Windows, we need to prepend PATH to coexist (override) with other
// incompatible version of SDL2 under system env settings of PATH
if (strlen(ori_lib_env) > 0) {
prepend(lib_env, path_separator);
}
prepend(lib_env, lib_path);
#else
if (strlen(ori_lib_env) > 0) {
strcat(lib_env, path_separator);
}
strcat(lib_env, lib_path);
#endif
printf("LIB_ENV=%s\n", lib_env);
return lib_env;
}
int exec_calm_script(int argc, char *argv[], int wait) {
char entry_cmd[FILENAME_MAX];
char script_path[FILENAME_MAX];
char *cmd_ext;
strcpy(script_path, "s");
for (int i = 2; i < argc; i++) {
strcat(script_path, "/");
strcat(script_path, argv[i]);
if (i == (argc - 1)) {
cmd_ext = strrchr(argv[i], '.');
}
}
if (cmd_ext == NULL) {
printf("NO Extension, can't determine the executer %s\n", script_path);
return 42;
} else if (strcmp(cmd_ext, ".sh") == 0) {
strcpy(entry_cmd, "sh ");
} else if (strcmp(cmd_ext, ".bat") == 0) {
strcpy(entry_cmd, "cmd /c ");
} else if (strcmp(cmd_ext, ".ps1") == 0) {
strcpy(entry_cmd, "powershell -ExecutionPolicy Bypass -F ");
} else if (strcmp(cmd_ext, ".scpt") == 0) {
strcpy(entry_cmd, "osascript ");
} else if (strcmp(cmd_ext, ".lisp") == 0) {
strcpy(entry_cmd, get_sbcl_path());
strcat(entry_cmd, " --load calm.asd --eval '(ql:quickload :calm)' --load ");
} else {
printf("UNKNOWN SCRIPT: %s\n", script_path);
return 42;
}
strcat(entry_cmd, script_path);
if (wait == 0) {
strcat(entry_cmd, " &");
}
printf("EXECUTING CALM SCRIPT: %s\n", entry_cmd);
return system(entry_cmd) != 0 ? 42 : 0;
}
/*
* show an alert, for the first time long loading process
* only needed when running `calm` command
*/
void firstrun() {
if (getenv("CI") == NULL && getenv("CALM_BUILDING") == NULL) {
if (access(".calm-initialised", F_OK) != 0) {
char *argv[] = {NULL, NULL, "usr", "os", "file"};
#ifdef __APPLE__
argv[3] = "macos";
argv[4] = "init-msg.scpt";
#endif
#ifdef __linux__
argv[3] = "linux";
argv[4] = "init-msg.sh";
#endif
#ifdef _WIN32
argv[3] = "windows";
argv[4] = "init-msg.ps1";
#endif
exec_calm_script(5, argv, 0);
}
}
}
int main(int argc, char *argv[]) {
char calm_cmd[1024];
const char *lib_env = get_lib_env();
if (argc >= 2) {
strcpy(calm_cmd, argv[1]);
} else {
strcpy(calm_cmd, "show");
}
apply_env("CALM_CMD", calm_cmd);
printf("CALM_CMD=%s\n", getenv("CALM_CMD"));
#ifdef _WIN32
char backslash[] = "\\";
#else
char slash[] = "/";
#endif
/*
* applying CALM_APP_DIR
*/
if (getenv("CALM_APP_DIR") == NULL) {
char cwd[FILENAME_MAX];
getcwd(cwd, sizeof(cwd));
#ifdef _WIN32
strcat(cwd, backslash);
#else
strcat(cwd, slash);
#endif
apply_env("CALM_APP_DIR", cwd);
printf("CALM_APP_DIR=%s \n", getenv("CALM_APP_DIR"));
} else {
printf("inherited CALM_APP_DIR=%s \n", getenv("CALM_APP_DIR"));
}
/*
* applying CALM_HOME
*/
if (getenv("CALM_HOME") == NULL) {
char binarydir[FILENAME_MAX];
strcpy(binarydir, get_binary_dir());
#ifndef _WIN32
strcat(binarydir, slash);
#endif
apply_env("CALM_HOME", binarydir);
printf("CALM_HOME=%s \n", getenv("CALM_HOME"));
} else {
printf("inherited CALM_HOME=%s \n", getenv("CALM_HOME"));
}
/*
* applying SBCL_HOME
*/
#ifdef _WIN32
char *sbcl_home_rel = "sbcl\\lib\\sbcl";
#else
char *sbcl_home_rel = "/sbcl/lib/sbcl";
#endif
char sbcl_home[FILENAME_MAX];
strcpy(sbcl_home, get_binary_dir());
strcat(sbcl_home, sbcl_home_rel);
apply_env("SBCL_HOME", sbcl_home);
printf("SBCL_HOME=%s \n", getenv("SBCL_HOME"));
/*
* cd to CALM_HOME
*/
chdir(getenv("CALM_HOME"));
/*
* if it is not building CALM, and there is no calm.core
* then show tips and build core
*/
if (access("calm.asd", F_OK) == 0 && strcmp(calm_cmd, "core") != 0 &&
getenv("CALM_BUILDING") == NULL) {
firstrun();
if (access("calm.core", F_OK) != 0) {
#ifdef _WIN32
system("calm.exe core");
#else
system("./calm core");
#endif
if (access("calm.core", F_OK) != 0) {
// sleep 2 seconds for calm.core to be written to the disk
printf("waiting for calm.core to be written to the disk...\n");
#ifdef _WIN32
Sleep(2000);
#else
sleep(2);
#endif
}
}
}
/*
* ==============
* detecting SBCL path - START
* ==============
*/
char entry_cmd[FILENAME_MAX];
#ifdef __APPLE__
if (getenv("CALM_BUILDING") != NULL) { // Building, don't set lib env
strcpy(entry_cmd, get_sbcl_path());
} else {
/*
* Apple won't allow us to modify DYLD_LIBRARY_PATH:
* https://developer.apple.com/forums/thread/13161
* https://developer.apple.com/library/archive/documentation/Security/Conceptual/System_Integrity_Protection_Guide/RuntimeProtections/RuntimeProtections.html
* So the following won't work:
* apply_env("DYLD_LIBRARY_PATH", lib_path);
* We have to prepend this inside the command, like:
* DYLD_LIBRARY_PATH=/some/where/my/lib ./my-app
*/
strcpy(entry_cmd, "DYLD_LIBRARY_PATH=");
strcat(entry_cmd, lib_env);
strcat(entry_cmd, " ");
strcat(entry_cmd, get_sbcl_path());
}
#elif defined _WIN32
apply_env("PATH", lib_env);
printf("PATH=%s \n", getenv("PATH"));
strcpy(entry_cmd, get_sbcl_path());
#elif defined __linux__
apply_env("LD_LIBRARY_PATH", lib_env);
printf("LD_LIBRARY_PATH=%s \n", getenv("LD_LIBRARY_PATH"));
strcpy(entry_cmd, get_sbcl_path());
#endif
if (access("calm.asd", F_OK) == 0) {
/*
* ==============
* Running CALM
* ==============
*/
if (strcmp(calm_cmd, "sbcl") == 0) { // running CALM bundled SBCL
for (int i = 2; i < argc; i++) {
strcat(entry_cmd, " ");
strcat(entry_cmd, argv[i]);
}
} else if (strcmp(calm_cmd, "s") == 0) { // running CALM scripts
return exec_calm_script(argc, argv, 1);
} else { // load CALM normally
strcat(entry_cmd, " --load entry.lisp");
}
// Execute Entry Command
printf("EXECUTING: %s\n", entry_cmd);
if (system(entry_cmd) != 0) return 42;
} else {
/*
* ==============
* Running CALM Application
* ==============
*/
printf("EXECUTING: bin/calm-app\n");
#ifdef _WIN32
if (WinExec("bin\\calm-app.exe", SW_NORMAL) > 31) {
return 0;
} else {
return 42;
}
#elif defined __APPLE__
strcpy(entry_cmd, "DYLD_LIBRARY_PATH=");
strcat(entry_cmd, lib_env);
strcat(entry_cmd, " bin/calm-app");
if (system(entry_cmd) != 0) return 42;
#else
if (system("bin/calm-app") != 0) return 42;
#endif
}
return 0;
}
| 10,710 | Common Lisp | .l | 387 | 24.178295 | 161 | 0.617495 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | ed8577079cc941d26eb91ab94354e6fa77757ed67cc47cbd5c5037594d541ddf | 2,249 | [
-1
] |
2,252 | calm.c | VitoVan_calm/src/web/calm.c | #include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <cairo/cairo.h>
#include <emscripten.h>
#include <stdbool.h>
#include <stdio.h>
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *texture;
cairo_surface_t *cr_surface = NULL;
int fps = 0;
int window_width = 600;
int window_height = 150;
int renderer_width;
int renderer_height;
double cairo_x_multiplier;
double cairo_y_multiplier;
extern int js_on_keydown(int sym);
extern int js_on_keyup(int sym);
extern int js_on_mousemotion(int x, int y);
extern int js_on_mousebuttonup(int button, int x, int y, int clicks);
extern int js_on_mousebuttondown(int button, int x, int y, int clicks);
extern int js_on_fingermotion(float x, float y, float dx, float dy,
float pressure, int fingerId);
extern int js_on_fingerup(float x, float y, float dx, float dy, float pressure,
int fingerId);
extern int js_on_fingerdown(float x, float y, float dx, float dy,
float pressure, int fingerId);
extern int js_on_windowenter();
extern int js_on_windowleave();
extern int js_on_windowresized(int w, int h);
extern bool js_get_calm_redraw();
extern int js_draw();
extern int js_think();
EM_JS(void, set_cairo_context_to_js, (cairo_t * cr), { window._cr = cr; });
void config(const char *title) { SDL_SetWindowTitle(window, title); }
void draw(cairo_t *cr) {
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_paint(cr);
set_cairo_context_to_js(cr);
if (js_draw() == 42) {
return;
}
cairo_set_source_rgba(cr, 0.89, 0.12, 0.17, 1);
cairo_paint(cr);
cairo_set_source_rgba(cr, 1, 1, 1, 1);
cairo_move_to(cr, 30, 100);
cairo_set_font_size(cr, 84);
cairo_show_text(cr, "DON'T PANIC");
}
void idle_handler() {
if (cr_surface == NULL || js_get_calm_redraw()) {
int *pixels = NULL;
int pitch;
SDL_LockTexture(texture, NULL, (void **)&pixels, &pitch);
cr_surface = cairo_image_surface_create_for_data(
(unsigned char *)pixels, CAIRO_FORMAT_ARGB32, renderer_width,
renderer_height, pitch);
cairo_surface_set_device_scale(cr_surface, cairo_x_multiplier,
cairo_y_multiplier);
cairo_t *cr = cairo_create(cr_surface);
draw(cr);
SDL_UnlockTexture(texture);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
cairo_destroy(cr);
cairo_surface_destroy(cr_surface);
}
}
void resize_handler() {
SDL_GetRendererOutputSize(renderer, &renderer_width, &renderer_height);
cairo_x_multiplier = (double)renderer_width / (double)window_width;
cairo_y_multiplier = (double)renderer_height / (double)window_height;
SDL_DestroyTexture(texture);
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, renderer_width,
renderer_height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
void handler() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
js_on_keydown(event.key.keysym.scancode);
break;
case SDL_KEYUP:
js_on_keyup(event.key.keysym.scancode);
break;
case SDL_MOUSEMOTION:
js_on_mousemotion(event.motion.x, event.motion.y);
break;
case SDL_MOUSEBUTTONUP:
js_on_mousebuttonup(event.button.button, event.button.x, event.button.y,
event.button.clicks);
break;
case SDL_MOUSEBUTTONDOWN:
js_on_mousebuttondown(event.button.button, event.button.x,
event.button.y, event.button.clicks);
break;
case SDL_FINGERMOTION:
js_on_fingermotion(event.tfinger.x, event.tfinger.y, event.tfinger.dx,
event.tfinger.dy, event.tfinger.pressure,
event.tfinger.fingerId);
break;
case SDL_FINGERUP:
js_on_fingerup(event.tfinger.x, event.tfinger.y, event.tfinger.dx,
event.tfinger.dy, event.tfinger.pressure,
event.tfinger.fingerId);
break;
case SDL_FINGERDOWN:
js_on_fingerdown(event.tfinger.x, event.tfinger.y, event.tfinger.dx,
event.tfinger.dy, event.tfinger.pressure,
event.tfinger.fingerId);
break;
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_ENTER:
js_on_windowenter();
break;
case SDL_WINDOWEVENT_LEAVE:
js_on_windowleave();
break;
case SDL_WINDOWEVENT_RESIZED:
js_on_windowresized(event.window.data1, event.window.data2);
resize_handler();
break;
}
break;
case SDL_QUIT:
emscripten_cancel_main_loop();
break;
default:
break;
}
}
js_think();
idle_handler();
}
void run_main_loop() { emscripten_set_main_loop(handler, fps, true); }
int main(int argc, char *argv[]) {
// this is of course not useful if we are not using pango (yet)
setenv("PANGOCAIRO_BACKEND", "fontconfig", 1);
setenv("CALM_APP_DIR", "/usr/share/", 1);
char *env_calm_window_width = getenv("CALM_WINDOW_WIDTH");
char *env_calm_window_height = getenv("CALM_WINDOW_HEIGHT");
if (env_calm_window_width != NULL || env_calm_window_height != NULL) {
window_width = atoi(env_calm_window_width);
window_height = atoi(env_calm_window_height);
}
char *env_calm_fps = getenv("CALM_FPS");
if (env_calm_fps != NULL) {
fps = atoi(env_calm_fps);
}
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
window =
SDL_CreateWindow("CALM", 0, 0, window_width, window_height,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL |
// the following two must be present at the same time
// otherwise emscripten canvas will do weird things
SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengles2");
renderer =
SDL_CreateRenderer(window, -1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
SDL_RENDERER_TARGETTEXTURE);
SDL_RendererInfo rendererInfo;
SDL_GetRendererInfo(renderer, &rendererInfo);
printf("Renderer: %s\n", rendererInfo.name);
SDL_GetRendererOutputSize(renderer, &renderer_width, &renderer_height);
cairo_x_multiplier = (double)renderer_width / (double)window_width;
cairo_y_multiplier = (double)renderer_height / (double)window_height;
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, renderer_width,
renderer_height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
run_main_loop();
Mix_CloseAudio();
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
| 7,073 | Common Lisp | .l | 183 | 31.060109 | 80 | 0.640093 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | d4c6e1b9e6ed519bc644c9beea3725b053ea74f27d01b2b2969e8b6c1454d057 | 2,252 | [
-1
] |
2,253 | calm.html | VitoVan_calm/src/web/calm.html | <!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>CALM</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<style>
html, body {
height: 100%;
}
body {
font-family: arial;
margin: 0;
padding: none;
}
.emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; }
div.emscripten { text-align: center; }
div.emscripten_border {
height: 100%;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
background-color: #dfe1e5;
}
/* the canvas *must not* have any border or padding, or mouse coords will be wrong */
canvas.emscripten {
border: 0px none;
background-color: #0d3784;
border-radius: 8px;
box-shadow: rgba(0, 0, 0, 0.07) 0px 1px 2px, rgba(0, 0, 0, 0.07) 0px 2px 4px, rgba(0, 0, 0, 0.07) 0px 4px 8px, rgba(0, 0, 0, 0.07) 0px 8px 16px, rgba(0, 0, 0, 0.07) 0px 16px 32px, rgba(0, 0, 0, 0.07) 0px 32px 64px;
}
#emscripten_logo {
display: inline-block;
margin: 0;
}
.indicator {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-content: center;
align-items: center;
height: 100px;
position: absolute;
left: 0;
top: 0;
width: 100%;
background-color: white;
}
.indicator > .spinner, .indicator > div > #progress {
margin: 20px;
accent-color: #0d3784;
}
.spinner {
height: 30px;
width: 30px;
-webkit-animation: rotation .8s linear infinite;
-moz-animation: rotation .8s linear infinite;
-o-animation: rotation .8s linear infinite;
animation: rotation 0.8s linear infinite;
border-left: 5px solid rgb(235, 235, 235);
border-right: 5px solid rgb(235, 235, 235);
border-bottom: 5px solid rgb(235, 235, 235);
border-top: 5px solid rgb(120, 120, 120);
border-radius: 100%;
background-color: #0d3784;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(360deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(360deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
#status {
font-weight: bold;
color: rgb(120, 120, 120);
}
#progress {
height: 20px;
width: 300px;
}
#controls {
display: inline-block;
float: right;
vertical-align: top;
margin-top: 30px;
margin-right: 20px;
}
#output {
width: 100%;
height: 200px;
margin: 0 auto;
margin-top: 10px;
border-left: 0px;
border-right: 0px;
padding-left: 0px;
padding-right: 0px;
display: block;
background-color: black;
color: white;
font-family: 'Lucida Console', Monaco, monospace;
outline: none;
}
</style>
</head>
<body>
<div class="indicator" id='indicator'>
<div class="spinner" id='spinner'></div>
<div id="status">Downloading...</div>
<div>
<progress value="0" max="100" id="progress" hidden=1></progress>
</div>
</div>
<div class="emscripten_border">
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" tabindex=-1></canvas>
</div>
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.last.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Module.setStatus.last.time < 30) return; // if this is a progress update, skip it if too soon
Module.setStatus.last.time = now;
Module.setStatus.last.text = text;
if (m) {
text = m[1];
// if only 1 task, why do we need the progress bar?
console.log("setStatus text: ", text);
if (m[4] <= 2) {
progressElement.removeAttribute('value');
} else {
progressElement.setAttribute('value', parseInt(m[2])*100);
}
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) {
spinnerElement.style.display = 'none';
document.getElementById('indicator').style.display = 'none';
document.getElementById('canvas').style.backgroundColor = 'transparent';
}
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) console.error('[post-exception status] ' + text);
};
};
</script>
<script src="jscl.js" type="text/javascript"></script>
<script src="canvas.js" type="text/javascript"></script>
{{{ SCRIPT }}}
</body>
</html>
| 7,838 | Common Lisp | .l | 212 | 28.183962 | 223 | 0.571579 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 0839665e31dc09747ff297c8cc311db207bc9991d39188906866e71a0e329b5f | 2,253 | [
-1
] |
2,254 | installation_JA.md | VitoVan_calm/docs/installation_JA.md | # CALM インストール
## CALM の設定
もう[ダウンロード](https://github.com/VitoVan/calm#pre-built-binary)済みですよね?
では、使いやすい環境を整えてみましょう。
- Linux
```bash
tar xvf calm.tgz --directory=$HOME/
echo 'export PATH="$HOME/calm/:$PATH"'>> ~/.bashrc
```
- macOS
1. ダウンロードした DMG ファイルを開きます
2. .app をアプリケーションフォルダにドラッグします
3. 私を信じて、Calm.appの隔離を解除してください。
```bash
xattr -d com.apple.quarantine /Applications/Calm.app
```
4. DMG を取り出し、Calm.app を実行する
初回の実行には **時間がかかるかもしれません。**
5. コマンド `calm` を PATH 環境に追加する
```bash
echo 'export PATH="/Applications/Calm.app/Contents/MacOS/:$PATH"'>> ~/.bashrc
```
- Windows
1. 右クリックしてすべて展開します
2. 解凍したフォルダを C: に移動します
3. [PATH 環境変数](https://helpdeskgeek.com/windows-10/add-windows-path-environment-variable/)に `C:¥calm` を追加します
> MSYS2 または Git Bash を使用している場合は、以下のコードを実行してください:
>
> ```bash
> echo 'export PATH="/c/calm/:$PATH"' >> ~/.bashrc
> ```
> Windows の場合、マイクロソフト社によって検証されていないため、システムがソフトウェアの実行を停止する確率が非常に高いです。実行に問題がある場合は、[SmartScreen をバイパスする方法を見つけてください](https://www.google.com/search?q=how+to+bypass+smartscreen)。
これで準備万端、お楽しみください。
| 1,785 | Common Lisp | .l | 33 | 30.090909 | 176 | 0.694139 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 55c63b03e854c7051cfee1540e24d43ea4c7c608ad8a5b715c7d3245ac8c3728 | 2,254 | [
-1
] |
2,255 | installation.md | VitoVan_calm/docs/installation.md | # CALM Installation
## Setting Up CALM
You have [donwloaded](https://github.com/VitoVan/calm#pre-built-binary) it, right?
Now let's set up the environment for the ease of use.
- Linux
```bash
tar xvf calm.tgz --directory=$HOME/
echo 'export PATH="$HOME/calm/:$PATH"'>> ~/.bashrc
```
- macOS
1. Open the downloaded DMG file
2. Drag the .app to the Applications folder
3. Trust me and de-quarantine Calm.app
```bash
xattr -d com.apple.quarantine /Applications/Calm.app
```
4. Eject the DMG and run Calm.app
**It may take a while** for the first run.
5. Add command `calm` to the PATH environment
```bash
echo 'export PATH="/Applications/Calm.app/Contents/MacOS/:$PATH"'>> ~/.bashrc
```
- Windows
1. Right click to Extract All
2. Move the extracted folder to `C:\calm`
3. Add `C:\calm` to your [PATH environment variable](https://helpdeskgeek.com/windows-10/add-windows-path-environment-variable/)
> If you are using MSYS2 or Git Bash, run the following code:
>
> ```bash
> echo 'export PATH="/c/calm/:$PATH"' >> ~/.bashrc
> ```
> On Windows, it's very likely the system will stop you from running the software, since it's not verified by Microsoft. If you have problem to run it, please [find a way to bypass SmartScreen](https://www.google.com/search?q=how+to+get+around+windows+smartscreen).
Now you are all set, enjoy.
| 1,438 | Common Lisp | .l | 33 | 39 | 270 | 0.689033 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 215957d805b51135bf7e6a5de8e8b274e6542bd00ced9885a1d6d581ec9d107d | 2,255 | [
-1
] |
2,256 | changelog.org | VitoVan_calm/docs/changelog.org | * CALM
** 1.3.2
- better code signing for CALM made applications
Before this change:
1. CALM itself will be shown as a damaged application,
the user has to de-quarantine it with command line:
xattr -d com.apple.quarantine /Applications/Calm.app
2. CALM made applications, will also be shown as damaged,
the user also has to de-quarantine them.
After this change:
1. CALM itself still be shown as a damaged application.
2. CALM made applications, will shown as:
"cannot be opened because the developer cannot be verified."
which is better, since the user could open it with right click.
** 1.3.1
- fix macos-14 (arm64) codesign problem
https://apple.stackexchange.com/questions/258623/how-to-fix-killed-9-error-in-mac-os/470957#470957
** 1.3.0
- upgrade SBCL to 2.4.7
- add macos-14 (arm64) support
- fix: weird Quicklisp + Windows + SBCL bug
https://groups.google.com/g/quicklisp/c/wrULkRePVE4/m/DZHc0qVhAQAJ
- fix: weird Windows + plain old CMD bug
https://github.com/VitoVan/calm/issues/179
- ci: add macos-14 binary release
- ci: remove macos-11 binary release
** 1.2.0
- add documents:
- hacking_JA.md @eltociear
- installation_JA.md @eltociear
- CONTRIBUTING_JA.md @eltociear
- CONTRIBUTING.md
- add alive support
for Alive - Visual Studio Code
https://github.com/nobody-famous/alive
https://marketplace.visualstudio.com/items?itemName=rheller.alive
please config `alive.lsp.startCommand':
#+begin_src json
{
"alive.lsp.startCommand": [
"calm",
"alive"
]
}
#+end_src
- fix coexisting with other SDL2 on Windows
reported by @simmihugs at #170
- fix defect when publish-with-options + whitespaced app-name
- remove Windows fonts dir on *nix, to reduce fontconfig warnings
** 1.1.2
- add Japanese document: README_JA.md
by Ikko Eltociear Ashimine (安次嶺 一功) @eltociear
- fix macOS Ventura ugly DMG file on GitHub Workflow
- fix default font family in dev mode
use `c:select-font-family`
- fix ugly font on Windows
add `<dir>C:\Windows\Fonts</dir>` to fonts.conf
- fix aggressive font dir scanning
remove `<dir prefix="cwd">./</dir>` from fonts.conf
- remove unused command `dist-with-canvas`
- tidy up CI script - calm.yml
** 1.1.1
- add document for `c:select-font-family`
- reduce CALM first startup time
- fix first startup message (zenity) on Linux
- fix CL systems re-loading problem on recent Linux (tested on Fedora 36)
** 1.1.0
- expose `*calm-window*` variable
for SDL2 Window related control
- expose `*calm-redraw*` variable
for manual management of the canvas refreshing
** 1.0.1
- fix: audio won't play the second time
** 1.0.0
- stabilise CALM command and API
use Semantic Versioning from now on
- fix Windows publishing problem on 0.1.4
- fix audio problem on CI (just don't open it)
- create webpage
https://vitovan.com/calm/
** 0.1.4
- downgrade glibc version 2.33+ -> 2.31(for Linux)
now CALM applications could run on the old Ubuntu 20.04 LTS
- more elegant circles/canvas.lisp
** 0.1.3
- fix version check in command `calm hello`
- add `c:halt-wav`
i.e. SDL2_mixer/Mix_HaltChannel
- add `fc-init-reinitialize`
to load fonts while developing with `calm` command
- add volume controle `c:volume` and `c:volume-music`
i.e. SDL2_mixer/Mix_Volume, SDL2_mixer/Mix_VolumeMusic
- add `c:play-audio` and `c:halt-audio` on web
i.e. HTMLAudioElement: new Audio(url)
** 0.1.2
- add touch event support, mainly for mobile + web
should also work on all platforms
- zoom canvas on small screen (web only), i.e. mobile
- remove `*calm-version*`, use `asdf:version` insteadd
drop version check on JSCL
** 0.1.1
- downgrade glibc dependency to 2.33 (from 2.35)
- upgrade JSCL to 25e0341e95725f9d6bba991c3adeaa58ae885066
for more `setfable` operations and function `log`
- enhance `publish-web` experience, default to pre-built wasm
by downloading them while `calm publish-web` if were not present
** 0.1.0
- fix cairo_x/y_multiplier
it causes ugly canvas painting on some irregular devices (web only)
** 0.0.42
- fix macOS dylib conflict
- enhance performance: 0 % ~ 0.3 % CPU usage when idle
- add web support, with [[https://github.com/VitoVan/pango-cairo-wasm/][WebAssembly]] + [[https://github.com/jscl-project/jscl][JSCL]]
- add custom fonts directory support
you could just put your fonts into the fonts directory (alongside with canvas.lisp),
it will be picked up by fontconfig, select it with: `c:select-font-family`.
** 0.0.41
- add Pango
https://docs.gtk.org/Pango/
- add multi-threading
https://bordeaux-threads.common-lisp.dev/
- add Windows high-dpi / DPI scaling support
https://github.com/libsdl-org/SDL/pull/5778
- rearrange code layout, add file c.lisp
| 4,738 | Common Lisp | .l | 124 | 35.870968 | 134 | 0.745213 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 5765b82b194f87c2b27200c1a8d848cbaf575a081200877010340aa5ae084ef0 | 2,256 | [
-1
] |
2,263 | calm.yml | VitoVan_calm/.github/workflows/calm.yml | name: CI
on: push
jobs:
Linux:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Build for Linux
run: |
docker run --env CI=true -v $PWD:/calm -w /calm fedora:32 bash build/build.sh
ls -lah .
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: CALM Linux
if-no-files-found: error
path: |
*.tgz
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.tgz
Web:
needs: Linux
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Build for Web
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
calm hello
curl -o fonts/OpenSans-Regular.ttf -L https://github.com/googlefonts/opensans/raw/main/fonts/ttf/OpenSans-Regular.ttf
export REBUILD_WASM_P=yes
calm publish-web
tar cf calm.tar web/calm.*
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: CALM Web
if-no-files-found: error
path: |
*.tar
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.tar
macOS:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-12, macos-13, macos-14]
env:
CI_MATRIX_OS: ${{ matrix.os }}
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
steps:
- uses: actions/checkout@v3
- name: Setup AppleScript for macOS 13
if: ${{ matrix.os == 'macos-13' }}
run: |
sudo sqlite3 $HOME/Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
- name: Build
run: |
# install it before executing the script
# to work around resource busy thing
brew install create-dmg
bash build/build.sh
ls -lah .
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: CALM macOS
if-no-files-found: error
path: |
*.dmg
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.dmg
Windows:
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- uses: ilammy/msvc-dev-cmd@v1
- name: Build
shell: cmd
run: |
build\\build.bat
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: CALM Windows
if-no-files-found: error
path: |
*.zip
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.zip
# Circles Exmaple
Circles-Web:
needs: Web
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact Linux
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Download Artifact Web
uses: actions/download-artifact@v3
with:
name: CALM Web
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
mkdir -p ./calm/build/web/ && cp calm.tar ./calm/build/web/calm.tar
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Circles
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/circles/
calm publish-web
ls -lah .
zip -r -9 ${APP_NAME}-web.zip ./web
cp *.zip ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*-web.zip
Circles-Linux:
needs: Linux
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Circles
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/circles/
calm publish
ls -lah .
cp *.AppImage ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.AppImage
Circles-macOS:
needs: macOS
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-12, macos-13, macos-14]
env:
CI_MATRIX_OS: ${{ matrix.os }}
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
steps:
- uses: actions/checkout@v3
- name: Setup AppleScript for macOS 13
if: ${{ matrix.os == 'macos-13' }}
run: |
sudo sqlite3 $HOME/Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM macOS
- name: Build
run: |
set -x
ls -lah
export OS_SUBFIX=".${CI_MATRIX_OS}"
cp calm${OS_SUBFIX}.dmg calm.dmg
hdiutil attach calm.dmg
cp -R "/Volumes/Calm - CALM/Calm.app/Contents/MacOS/" calm
ls -lah calm
rm *.dmg
export PATH=$PATH:$(pwd)/calm/
export APP_VERSION=1.3.2
export APP_ID=com.vitovan.circles
export APP_NAME=Circles
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/circles/
calm publish
ls -lah .
mv *.dmg Circles${OS_SUBFIX}.dmg
cp *.dmg ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.dmg
Circles-Windows:
needs: Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- uses: msys2/setup-msys2@v2
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Windows
- name: Build
shell: msys2 {0}
run: |
set -x
ls -lah
pacman -S --noconfirm --needed unzip
unzip calm.zip
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Circles
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/circles/
calm publish
mv ./*-Installer.exe ./Circles.exe
ls -lah .
cp *.exe ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.exe
# Fan Exmaple
Fan-Web:
needs: Web
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact Linux
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Download Artifact - Web
uses: actions/download-artifact@v3
with:
name: CALM Web
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
mkdir -p ./calm/build/web/ && cp calm.tar ./calm/build/web/calm.tar
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Fan
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/fan/
calm publish-web
ls -lah .
zip -r -9 ${APP_NAME}-web.zip ./web
cp *.zip ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*-web.zip
Fan-Linux:
needs: Linux
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Fan
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/fan/
calm publish
ls -lah .
cp *.AppImage ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.AppImage
Fan-macOS:
needs: macOS
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-12, macos-13, macos-14]
env:
CI_MATRIX_OS: ${{ matrix.os }}
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
steps:
- uses: actions/checkout@v3
- name: Setup AppleScript for macOS 13
if: ${{ matrix.os == 'macos-13' }}
run: |
sudo sqlite3 $HOME/Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM macOS
- name: Build
run: |
set -x
ls -lah
export OS_SUBFIX=".${CI_MATRIX_OS}"
cp calm${OS_SUBFIX}.dmg calm.dmg
hdiutil attach calm.dmg
cp -R "/Volumes/Calm - CALM/Calm.app/Contents/MacOS/" calm
ls -lah calm
rm *.dmg
export PATH=$PATH:$(pwd)/calm/
export APP_VERSION=1.3.2
export APP_ID=com.vitovan.fan
export APP_NAME=Fan
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/fan/
calm publish
ls -lah .
mv *.dmg Fan${OS_SUBFIX}.dmg
cp *.dmg ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.dmg
Fan-Windows:
needs: Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- uses: msys2/setup-msys2@v2
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Windows
- name: Build
shell: msys2 {0}
run: |
set -x
ls -lah
pacman -S --noconfirm --needed unzip
unzip calm.zip
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Fan
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/fan/
calm publish
mv ./*-Installer.exe ./Fan.exe
ls -lah .
cp *.exe ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.exe
# Mondrian Exmaple
Mondrian-Web:
needs: Web
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Download Artifact - Web
uses: actions/download-artifact@v3
with:
name: CALM Web
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
mkdir -p ./calm/build/web/ && cp calm.tar ./calm/build/web/calm.tar
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Mondrian
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/mondrian/
calm publish-web
ls -lah .
zip -r -9 ${APP_NAME}-web.zip ./web
cp *.zip ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*-web.zip
Mondrian-Linux:
needs: Linux
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Mondrian
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/mondrian/
calm publish
ls -lah .
cp *.AppImage ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.AppImage
Mondrian-macOS:
needs: macOS
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-12, macos-13, macos-14]
env:
CI_MATRIX_OS: ${{ matrix.os }}
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
steps:
- uses: actions/checkout@v3
- name: Setup AppleScript for macOS 13
if: ${{ matrix.os == 'macos-13' }}
run: |
sudo sqlite3 $HOME/Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM macOS
- name: Build
run: |
set -x
ls -lah
export OS_SUBFIX=".${CI_MATRIX_OS}"
cp calm${OS_SUBFIX}.dmg calm.dmg
hdiutil attach calm.dmg
cp -R "/Volumes/Calm - CALM/Calm.app/Contents/MacOS/" calm
ls -lah calm
rm *.dmg
export PATH=$PATH:$(pwd)/calm/
export APP_VERSION=1.3.2
export APP_ID=com.vitovan.mondrian
export APP_NAME=Mondrian
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/mondrian/
calm publish
ls -lah .
mv *.dmg Mondrian${OS_SUBFIX}.dmg
cp *.dmg ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.dmg
Mondrian-Windows:
needs: Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- uses: msys2/setup-msys2@v2
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Windows
- name: Build
shell: msys2 {0}
run: |
set -x
ls -lah
pacman -S --noconfirm --needed unzip
unzip calm.zip
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Mondrian
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/mondrian/
calm publish
mv ./*-Installer.exe ./Mondrian.exe
ls -lah .
cp *.exe ../../../
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.exe
# Meditator Exmaple
Meditator-Web:
needs: Web
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Download Artifact - Web
uses: actions/download-artifact@v3
with:
name: CALM Web
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
mkdir -p ./calm/build/web/ && cp calm.tar ./calm/build/web/calm.tar
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Meditator
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/meditator/
# extra sound files need to be packed
export REBUILD_WASM_P=yes
calm publish-web
ls -lah .
zip -r -9 ${APP_NAME}-web.zip ./web
cp *.zip ../../../
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Meditator Web
if-no-files-found: error
path: |
*-web.zip
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*-web.zip
Meditator-Linux:
needs: Linux
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Linux
- name: Build
run: |
set -x
ls -lah
tar xvf calm.tgz
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Meditator
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/meditator/
calm publish
ls -lah .
cp *.AppImage ../../../
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Meditator Linux
if-no-files-found: error
path: |
*.AppImage
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.AppImage
Meditator-macOS:
needs: macOS
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-12, macos-13, macos-14]
env:
CI_MATRIX_OS: ${{ matrix.os }}
HOMEBREW_NO_AUTO_UPDATE: 1
HOMEBREW_NO_INSTALL_CLEANUP: 1
steps:
- uses: actions/checkout@v3
- name: Setup AppleScript for macOS 13
if: ${{ matrix.os == 'macos-13' }}
run: |
sudo sqlite3 $HOME/Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db "INSERT OR REPLACE INTO access VALUES('kTCCServiceAppleEvents','/usr/local/opt/runner/provisioner/provisioner',1,2,3,1,NULL,NULL,0,'com.apple.finder',X'fade0c000000002c00000001000000060000000200000010636f6d2e6170706c652e66696e64657200000003',NULL,1592919552);"
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM macOS
- name: Build
run: |
set -x
ls -lah
export OS_SUBFIX=".${CI_MATRIX_OS}"
cp calm${OS_SUBFIX}.dmg calm.dmg
hdiutil attach calm.dmg
cp -R "/Volumes/Calm - CALM/Calm.app/Contents/MacOS/" calm
ls -lah calm
rm *.dmg
export PATH=$PATH:$(pwd)/calm/
export APP_VERSION=1.3.2
export APP_ID=com.vitovan.meditator
export APP_NAME=Meditator
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/meditator/
calm publish
ls -lah .
mv *.dmg Meditator${OS_SUBFIX}.dmg
cp *.dmg ../../../
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Meditator macOS
if-no-files-found: error
path: |
*.dmg
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.dmg
Meditator-Windows:
needs: Windows
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- uses: msys2/setup-msys2@v2
- name: Download Artifact
uses: actions/download-artifact@v3
with:
name: CALM Windows
- name: Build
shell: msys2 {0}
run: |
set -x
ls -lah
pacman -S --noconfirm --needed unzip
unzip calm.zip
ls -lah calm
export PATH=$PATH:$(pwd)/calm/
export APP_NAME=Meditator
# switch dir, this is unnecessary if you are already at the same dir with canvas.lisp
cd docs/examples/meditator/
calm publish
mv ./*-Installer.exe ./Meditator.exe
ls -lah .
cp *.exe ../../../
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: Meditator Windows
if-no-files-found: error
path: |
*.exe
- name: GH Release
uses: softprops/[email protected]
if: startsWith(github.ref, 'refs/tags/')
with:
draft: true
files: |
*.exe
| 24,715 | Common Lisp | .l | 734 | 24.393733 | 339 | 0.579093 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 085a0e25dc5a9ee67d53a51c7a00d75c401fa4a3767ab33a701618b6b7ccf635 | 2,263 | [
-1
] |
2,264 | app-Info.plist | VitoVan_calm/s/usr/macos/app-Info.plist | <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleGetInfoString</key>
<string>_APP_NAME_</string>
<key>CFBundleExecutable</key>
<string>calm</string>
<key>CFBundleIdentifier</key>
<string>_BUNDLE_ID_</string>
<key>CFBundleName</key>
<string>_APP_NAME_</string>
<key>CFBundleIconFile</key>
<string>icon.icns</string>
<key>CFBundleShortVersionString</key>
<string>_APP_VERSION_</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>IFMajorVersion</key>
<integer>0</integer>
<key>IFMinorVersion</key>
<integer>1</integer>
<key>NSHighResolutionCapable</key><true/>
<key>NSSupportsAutomaticGraphicsSwitching</key><true/>
</dict>
</plist>
| 895 | Common Lisp | .l | 28 | 29.392857 | 111 | 0.72895 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 8ddfb81c6eae76d577279dc1f8d741c2dabf920f9c7a89d8e21f26154e3251ec | 2,264 | [
-1
] |
2,272 | installer.nsi | VitoVan_calm/s/usr/windows/installer.nsi | ;NSIS Modern User Interface
;Basic Example Script
;Written by Joost Verburg
;--------------------------------
;Include Modern UI
!include "MUI2.nsh"
;--------------------------------
;General
;Name and file
Name "_APP_NAME_"
OutFile "_APP_NAME_-Installer.exe"
Unicode True
;Default installation folder
InstallDir "$LOCALAPPDATA\_APP_NAME_"
InstallColors /windows
;Request application privileges for Windows Vista
RequestExecutionLevel user
;--------------------------------
;Interface Settings
!define MUI_ICON "calm-installer-assets\app-installer.ico"
!define MUI_UNICON "calm-installer-assets\app-uninstaller.ico"
!define MUI_ABORTWARNING
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_BITMAP calm-installer-assets\installer-header.bmp
!define MUI_WELCOMEFINISHPAGE_BITMAP calm-installer-assets\installer-page.bmp
;--------------------------------
;Pages
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!define MUI_FINISHPAGE_RUN
!define MUI_FINISHPAGE_RUN_FUNCTION "LaunchLink"
Function LaunchLink
ExecShell "" "$DESKTOP\_APP_NAME_.lnk"
FunctionEnd
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
;--------------------------------
;Languages
!insertmacro MUI_LANGUAGE "English"
;--------------------------------
;Installer Sections
Section "Installer Section"
SetOutPath "$INSTDIR"
File /r calm-app-root
WriteUninstaller "$INSTDIR\Uninstall.exe"
; Create application shortcut (first in calm-app-root to have the correct "start in" target)
SetOutPath "$INSTDIR\calm-app-root\"
CreateShortCut "$INSTDIR\calm-app-root\_APP_NAME_.lnk" "$INSTDIR\calm-app-root\calm.exe"
SetOutPath "$INSTDIR\"
CreateShortCut "$INSTDIR\uninstall-_APP_NAME_.lnk" "$INSTDIR\Uninstall.exe"
; Start menu entries
SetOutPath "$SMPROGRAMS\_APP_NAME_\"
CopyFiles "$INSTDIR\calm-app-root\_APP_NAME_.lnk" "$SMPROGRAMS\_APP_NAME_\"
CopyFiles "$INSTDIR\calm-app-root\_APP_NAME_.lnk" "$DESKTOP\"
CopyFiles "$INSTDIR\uninstall-_APP_NAME_.lnk" "$SMPROGRAMS\_APP_NAME_\"
Delete "$INSTDIR\calm-app-root\_APP_NAME_.lnk"
Delete "$INSTDIR\uninstall-_APP_NAME_.lnk"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\_APP_NAME_" "DisplayName" "_APP_NAME_"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\_APP_NAME_" "UninstallString" "$INSTDIR\Uninstall.exe"
WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\_APP_NAME_" "DisplayIcon" "$INSTDIR\calm-app-root\calm.exe"
SectionEnd
;--------------------------------
;Uninstaller Section
Section "Uninstall"
Delete "$SMPROGRAMS\_APP_NAME_\*.*"
RMDir "$SMPROGRAMS\_APP_NAME_\"
Delete "$DESKTOP\_APP_NAME_.lnk"
Delete "$INSTDIR\Uninstall.exe"
RMDir /r "$INSTDIR\calm-app-root"
RMDir "$INSTDIR"
DeleteRegKey HKCU "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\_APP_NAME_"
SectionEnd | 2,955 | Common Lisp | .l | 73 | 37.589041 | 131 | 0.714737 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | dfac2f8cb101cea889b95c609ee2e5fab1c8868d67072586beebe051c5d82f0c | 2,272 | [
-1
] |
2,277 | config-lib.sh | VitoVan_calm/s/dev/msys/config-lib.sh | echo "config all libraries (.dll) ..."
cd ./lib
cp /mingw64/bin/libzstd.dll ./
cp /mingw64/bin/libpangocairo*.dll ./
# copy all the DLLs required by *.dll
ldd *.dll | grep mingw | awk '{print $3}' | xargs -I _ cp _ .
# copy all typelibs
cp -R /mingw64/lib/girepository-1.0/*.typelib ./
| 290 | Common Lisp | .l | 8 | 34.875 | 62 | 0.673835 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | d00fee4f14e4d9c51ae5bd51199a3ecb87ca475aff178901ceaad2ce627407bc | 2,277 | [
-1
] |
2,279 | config-lib.sh | VitoVan_calm/s/dev/darwin/config-lib.sh | # debug
set -x
echo "config all libraries (.dylib) ..."
cd ./lib
cp $(brew --prefix)/lib/libzstd.dylib ./
cp $(brew --prefix)/lib/libpangocairo*.dylib ./
# copy all dependencies
# this should be ran for many times until no more dylib need to be copied
# loop 42 times to make sure every dependency's dependency's dependency's ... dependencies are all copied
for i in {1..42}
do
otool -L *.dylib | grep $(brew --prefix) | awk '{print $1}' | xargs -I _ cp -n _ .
# some fuckers had fucked up rpath, we need to consider that
otool -L *.dylib | grep "@rpath" | sed s,@rpath,"$(brew --prefix)/lib/", | awk '{print $1}' | xargs -I _ cp -n _ .
done
chmod +w *.dylib
# set LC_RPATH
# make all of them able to load dependencies from the @loader_path
for f in *.dylib; do install_name_tool -add_rpath @loader_path/. $f; done
# change LC_ID_DYLIB
for f in *.dylib; do install_name_tool -id @rpath/`basename $f` $f; done
# change LC_LOAD_DYLIB
# make all of them load dependencies from the @rpath
for f in *.dylib
do
for p in $(otool -L $f | grep $(brew --prefix) | awk '{print $1}')
do
install_name_tool -change $p @rpath/`basename $p` $f
done
done
rm libSDL2.dylib
ln -s libSDL2-2.0.0.dylib libSDL2.dylib
rm libSDL2_mixer.dylib
ln -s libSDL2_mixer-2.0.0.dylib libSDL2_mixer.dylib
rm libSDL2_image.dylib
ln -s libSDL2_image-2.0.0.dylib libSDL2_image.dylib
rm libcairo.dylib
ln -s libcairo.2.dylib libcairo.dylib
rm libpangocairo-1.0.dylib
ln -s libpangocairo-1.0.0.dylib libpangocairo-1.0.dylib
rm libgobject-2.0.dylib
ln -s libgobject-2.0.0.dylib libgobject-2.0.dylib
rm libgirepository-1.0.dylib
ln -s libgirepository-1.0.1.dylib libgirepository-1.0.dylib
rm libzstd.dylib
ln -s libzstd.1.dylib libzstd.dylib
ls -lah .
# copy all typelibs
cp -L -R $(brew --prefix)/lib/girepository-1.0/*.typelib ./
# codesign for macos-14 enhanced security
ls *.dylib | xargs -I _ codesign --sign - --force --preserve-metadata=entitlements,requirements,flags,runtime _
ls *.typelib | xargs -I _ sudo codesign --sign - --force --preserve-metadata=entitlements,requirements,flags,runtime _
| 2,113 | Common Lisp | .l | 52 | 38.673077 | 118 | 0.720999 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 95a3a20c728a4246aa1d67a4ed1def6f39eb986915a1e85b319238856d00e4db | 2,279 | [
-1
] |
2,281 | config-lib.sh | VitoVan_calm/s/dev/fedora/config-lib.sh | echo "config all libraries (.so) ..."
cd ./lib
cp /usr/lib64/libzstd.so* ./
cp /usr/lib64/libpangocairo-*.so* ./
chmod +x *.so*
ldd ./*.so* | grep '=> /lib64' | awk '{print $3}' | sort | uniq | xargs -I _ cp _ .
rm -f libc.so*
rm -f libm.so*
rm -f libstdc++.so*
rm -f libdl.so*
rm -f librt.so*
rm -f libpthread.so*
cp -R /usr/lib64/girepository-1.0/*.typelib ./
| 364 | Common Lisp | .l | 13 | 26.846154 | 83 | 0.621777 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 098b709e1e36f1b28a2df730c83d4fbdbe4864d2554249725a8ffa1803d7b57a | 2,281 | [
-1
] |
2,284 | copy-lib.sh | VitoVan_calm/s/dev/all/copy-lib.sh | echo "Copy all libraries (.so / .dll / .dylib) ..."
rm -rf ./lib
mkdir ./lib
./calm sbcl --load ./s/dev/all/load-calm.lisp --load ./s/dev/all/copy-lib.lisp
| 156 | Common Lisp | .l | 4 | 38 | 78 | 0.644737 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | a3318a103124dc7d78b5edef029ac4e3cbeaa22220a6391a5ab11b9f6d80c68d | 2,284 | [
-1
] |
2,285 | clean.sh | VitoVan_calm/s/dev/all/clean.sh | rm -rf ./lib
rm -rf ./sbcl
rm -rf ./quicklisp
rm -f ./install_root.zip
rm -f ./calm.core
rm -f ./calm.exe
rm -f ./calmNoConsole.exe
rm -f ./calm
rm -f ./quicklisp.lisp
| 168 | Common Lisp | .l | 9 | 17.666667 | 25 | 0.679245 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | bb86d1f2467040d45ae41db473baf886a2975343a8b7404653698838640367d0 | 2,285 | [
-1
] |
2,287 | alive.sh | VitoVan_calm/s/dev/all/alive.sh | echo "Downloading alive-lsp ..."
if ! [ -d quicklisp/local-projects/alive-lsp ]; then
git clone --depth 1 --branch v0.2.7 https://github.com/nobody-famous/alive-lsp.git quicklisp/local-projects/alive-lsp
./calm sbcl --load ./s/dev/all/load-calm.lisp --load ./s/dev/all/install-alive.lisp
fi
| 299 | Common Lisp | .l | 5 | 57.2 | 121 | 0.717687 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 68ba9b66be00306ef3d1e3dbbfeb235594112f1e715c1804f5229a92de84800a | 2,287 | [
-1
] |
2,289 | copy-lib-with-canvas.sh | VitoVan_calm/s/dev/all/copy-lib-with-canvas.sh | echo "Copy libraries with canvas.lisp (.so / .dll / .dylib) ..."
cd ./lib
../calm sbcl \
--load ./s/dev/all/load-calm.lisp \
--load "${CALM_APP_DIR}/canvas.lisp" \
--load ./s/dev/all/copy-lib.lisp
| 221 | Common Lisp | .l | 6 | 31.833333 | 64 | 0.572093 | VitoVan/calm | 101 | 3 | 8 | GPL-2.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | d12f7b028fab507db93321eefe71390683295d59a7adb71884b61967d4c9a0eb | 2,289 | [
-1
] |
2,306 | run-tests.lisp | fosskers_cl-transducers/run-tests.lisp | (ql:quickload :transducers/tests)
(in-package :transducers/tests)
(let ((status (parachute:status (parachute:test 'transducers/tests))))
(cond ((eq :PASSED status) (uiop:quit))
(t (uiop:quit 1))))
| 208 | Common Lisp | .lisp | 5 | 38.4 | 70 | 0.69802 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 490c796440472b2b222c0278540458d850deb728b8ade5f01f10b543e8d7810a | 2,306 | [
-1
] |
2,307 | jzon.lisp | fosskers_cl-transducers/jzon/jzon.lisp | (defpackage transducers/jzon
(:use :cl)
(:shadow #:read #:write)
(:import-from #:trivia #:match)
(:local-nicknames (#:t #:transducers)
(#:j #:com.inuoe.jzon))
(:export #:read #:write)
(:documentation "JSON extensions for Transducers."))
(in-package :transducers/jzon)
(defstruct (json (:copier nil) (:predicate nil))
"The source of some JSON data."
(source nil :read-only t :type (or pathname stream string)))
(declaim (ftype (function ((or pathname stream string)) json) read))
(defun read (source)
"Mark a data SOURCE as being some store of JSON data."
(make-json :source source))
(defmethod t:transduce (xform f (source json))
(json-transduce xform f (json-source source)))
(declaim (ftype (function (t t (or pathname stream string)) *) json-transduce))
(defun json-transduce (xform f source)
(let* ((init (funcall f))
(xf (funcall xform f)))
(etypecase source
(stream (funcall xf (json-reduce xf init source)))
(pathname (with-open-file (stream source)
(funcall xf (json-reduce xf init stream))))
(string (with-input-from-string (stream source)
(funcall xf (json-reduce xf init stream)))))))
(declaim (ftype (function (t t stream) *) json-reduce))
(defun json-reduce (f identity stream)
(j:with-parser (parser stream)
(multiple-value-bind (event value) (j:parse-next parser)
(declare (ignore value))
(when (not (eq :begin-array event))
(error "Given JSON data is not an Array."))
(labels ((recurse (acc)
(match (j:parse-next-element parser :max-depth t
:eof-error-p nil
:eof-value :done)
(:done acc)
(json (let ((acc (t::safe-call f acc json)))
(if (t:reduced-p acc)
(t:reduced-val acc)
(recurse acc)))))))
(recurse identity)))))
#+nil
(t:transduce #'t:pass #'t:cons (read "[{\"name\": \"A\"}, {\"name\": \"B\"}]"))
;; FIXME 2023-05-02 I suspect I'm missing some `unwind-protect' business here!
(declaim (ftype (function (stream &key (:pretty t)) *) write))
(defun write (stream &key (pretty nil))
"Serialize every value that passes through the transduction into JSON, and
output that JSON into the given STREAM."
(let ((writer (j:make-writer :stream stream :pretty pretty)))
(lambda (&optional (acc nil a-p) (input nil i-p))
(declare (ignore acc))
(cond ((and a-p i-p)
(j:write-value writer (if (and (listp input)
(keywordp (car input)))
(t:plist input)
input)))
((and a-p (not i-p))
(j:end-array writer)
(j:close-writer writer))
(t (j:begin-array writer))))))
#+nil
(with-output-to-string (stream)
(t:transduce #'t:pass (write stream) '((:name "Colin" :age 35) (:name "Jack" :age 10))))
#+nil
(with-output-to-string (stream)
(t:transduce #'t:pass (write stream) (read "[{\"name\": \"A\"}, {\"name\": \"B\"}]")))
#+nil
(with-open-file (stream #p"big.json" :direction :output :if-exists :supersede)
(t:transduce (t:take 100000000) (write stream :pretty t) (t:ints 0)))
#+nil
(time (t:transduce #'t:pass #'t:count (read #p"big.json")))
#+nil
(t:transduce (t:filter-map (lambda (ht) (gethash "age" ht)))
#'t:average
(read "[{\"age\": 34}, {\"age\": 25}]"))
(defmethod j:write-value ((writer j:writer) (value t:plist))
(j:with-object writer
(t:transduce (t:map (lambda (pair)
(j:write-key writer (car pair))
(j:write-value writer (cdr pair))))
#'t:for-each
value)))
| 3,911 | Common Lisp | .lisp | 86 | 35.848837 | 90 | 0.562582 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 7a71a8ccebf381e041f42212d06d53a2e645b7ebe9d91ac11e4863c2052f825d | 2,307 | [
-1
] |
2,308 | fset.lisp | fosskers_cl-transducers/fset/fset.lisp | (defpackage transducers/fset
(:use :cl)
(:shadow #:set #:map)
(:local-nicknames (#:t #:transducers)
(#:s #:fset))
(:export #:set #:map #:seq #:bag)
(:documentation "Fset extensions for Transducers."))
(in-package :transducers/fset)
;; --- Transducers --- ;;
(defmethod t:transduce (xform f (source s:set))
(set-transduce xform f source))
(defmethod t:transduce (xform f (source s:map))
(map-transduce xform f source))
(defmethod t:transduce (xform f (source s:seq))
(seq-transduce xform f source))
(defmethod t:transduce (xform f (source s:bag))
(bag-transduce xform f source))
(defun set-transduce (xform f coll)
(let* ((init (funcall f))
(xf (funcall xform f))
(result (set-reduce xf init coll)))
(funcall xf result)))
(defun set-reduce (f identity set)
(let ((iter (s:iterator set)))
(labels ((recurse (acc)
(if (funcall iter :done?)
acc
(let ((acc (t::safe-call f acc (funcall iter :get))))
(if (t:reduced-p acc)
(t:reduced-val acc)
(recurse acc))))))
(recurse identity))))
#+nil
(t:transduce #'t:pass #'t:cons (s:set 1 2 3 1))
(defun map-transduce (xform f coll)
(let* ((init (funcall f))
(xf (funcall xform f))
(result (map-reduce xf init coll)))
(funcall xf result)))
(defun map-reduce (f identity set)
(let ((iter (s:iterator set)))
(labels ((recurse (acc)
(if (funcall iter :done?)
acc
(multiple-value-bind (key val) (funcall iter :get)
(let ((acc (t::safe-call f acc (cl:cons key val))))
(if (t:reduced-p acc)
(t:reduced-val acc)
(recurse acc)))))))
(recurse identity))))
#+nil
(t:transduce (t:map #'car) #'t:cons (s:map (:a 1) (:b 2) (:c 3)))
(defun seq-transduce (xform f coll)
(let* ((init (funcall f))
(xf (funcall xform f))
(result (seq-reduce xf init coll)))
(funcall xf result)))
(defun seq-reduce (f identity set)
(let ((iter (s:iterator set)))
(labels ((recurse (acc)
(if (funcall iter :done?)
acc
(let ((acc (t::safe-call f acc (funcall iter :get))))
(if (t:reduced-p acc)
(t:reduced-val acc)
(recurse acc))))))
(recurse identity))))
#+nil
(t:transduce #'t:pass #'t:cons (s:seq 1 2 3 1))
(defun bag-transduce (xform f coll)
(let* ((init (funcall f))
(xf (funcall xform f))
(result (bag-reduce xf init coll)))
(funcall xf result)))
(defun bag-reduce (f identity set)
(let ((iter (s:iterator set)))
(labels ((recurse (acc)
(if (funcall iter :done?)
acc
(let ((acc (t::safe-call f acc (funcall iter :get))))
(if (t:reduced-p acc)
(t:reduced-val acc)
(recurse acc))))))
(recurse identity))))
#+nil
(t:transduce #'t:pass #'t:cons (s:bag 1 2 3 1))
;; --- Reducers --- ;;
(defun set (&optional (acc (s:empty-set) a-p) (input nil i-p))
"Reducer: Collect all results as an immutable Fset set."
(cond ((and a-p i-p) (s:with acc input))
((and a-p (not i-p)) acc)
(t (s:empty-set))))
#+nil
(t:transduce #'t:pass #'set '(1 2 3 1))
(defun map (&optional (acc (s:empty-map) a-p) (input nil i-p))
"Reducer: Collect all results as an immutable Fset map."
(cond ((and a-p i-p) (destructuring-bind (key . val) input
(s:with acc key val)))
((and a-p (not i-p)) acc)
(t (s:empty-map))))
#+nil
(t:transduce #'t:enumerate #'map "hello")
(defun seq (&optional (acc (s:empty-seq) a-p) (input nil i-p))
"Reducer: Collect all results as an immutable Fset seq."
(cond ((and a-p i-p) (s:with-last acc input))
((and a-p (not i-p)) acc)
(t (s:empty-seq))))
#+nil
(t:transduce #'t:pass #'seq '(1 2 3 1))
(defun bag (&optional (acc (s:empty-bag) a-p) (input nil i-p))
"Reducer: Collect all results as an immutable Fset bag."
(cond ((and a-p i-p) (s:with acc input))
((and a-p (not i-p)) acc)
(t (s:empty-bag))))
#+nil
(t:transduce #'t:pass #'bag '(1 2 1 3 1))
| 4,408 | Common Lisp | .lisp | 116 | 29.784483 | 72 | 0.537866 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | aa2aa6a59aa606e4e2e9e2a96011aa696cd086250f245ded311b96dc6580245b | 2,308 | [
-1
] |
2,309 | main.lisp | fosskers_cl-transducers/tests/main.lisp | (defpackage transducers/tests
(:use :cl :parachute)
(:local-nicknames (#:t #:transducers)
(#:j #:transducers/jzon)
(#:s #:transducers/fset)))
(in-package :transducers/tests)
(define-test reduction)
(define-test "Collecting"
:parent reduction
(is equal '() (t:transduce #'t:pass #'t:cons '()))
(is equalp #() (t:transduce #'t:pass #'t:vector #()))
(is equal "hello" (t:transduce #'t:pass #'t:string "hello")))
(define-test "Counting"
:parent reduction
(is = 0 (t:transduce #'t:pass #'t:count '()))
(is = 3 (t:transduce #'t:pass #'t:count '(1 2 3)))
(is = 0 (t:transduce #'t:pass #'t:count #()))
(is = 3 (t:transduce #'t:pass #'t:count #(1 2 3))))
(define-test "Predicates"
:parent reduction
(false (t:transduce #'t:pass (t:anyp #'evenp) '(1 3 5 7 9)))
(true (t:transduce #'t:pass (t:anyp #'evenp) '(1 3 5 7 9 2)))
(true (t:transduce #'t:pass (t:allp #'oddp) '(1 3 5 7 9)))
(false (t:transduce #'t:pass (t:allp #'oddp) '(1 3 5 7 9 2))))
(define-test "First and Last"
:parent reduction
(is = 7 (t:transduce (t:filter #'oddp) #'t:first '(2 4 6 7 10)))
(fail (t:transduce (t:filter #'oddp) #'t:first '(2 4 6 10)))
(is = 10 (t:transduce #'t:pass #'t:last '(2 4 6 7 10)))
(fail (t:transduce #'t:pass #'t:last '())))
(define-test "Folding and Finding"
:parent reduction
(fail (t:transduce #'t:pass (t:fold #'cl:max) '()))
(is = 1000 (t:transduce #'t:pass (t:fold #'cl:max 0) '(1 2 3 4 1000 5 6)))
(is = 1000 (t:transduce #'t:pass (t:fold #'cl:max) '(1 2 3 4 1000 5 6)))
(is = 6 (t:transduce #'t:pass (t:find #'evenp) '(1 3 5 6 9)))
(is = 1000 (t:transduce #'t:pass (t:find #'evenp :default 1000) '(1 3 5 9)))
(is = 7/2 (t:transduce #'t:pass #'t:average '(1 2 3 4 5 6)))
(fail (t:transduce (t:filter #'evenp) #'t:average '(1 3 5))))
(define-test transduction)
(define-test "Mapping"
:parent transduction
:depends-on (reduction)
(is equal '() (t:transduce (t:map #'1+) #'t:cons '()))
(is equal '(2 3 4) (t:transduce (t:map #'1+) #'t:cons '(1 2 3))))
(define-test "Filtering"
:parent transduction
:depends-on (reduction)
(is equal '(2 4) (t:transduce (t:filter #'evenp) #'t:cons '(1 2 3 4 5)))
(is equal '(2 5 8) (t:transduce (t:filter-map #'cl:first) #'t:cons '(() (2 3) () (5 6) () (8 9))))
(is equal '(1 2 3 "abc") (t:transduce #'t:unique #'t:cons '(1 2 1 3 2 1 2 "abc")))
(is equal '(1 2 3 4 3)
(t:transduce #'t:dedup #'t:cons '(1 1 1 2 2 2 3 3 3 4 3 3))))
(define-test "Taking and Dropping"
:parent transduction
:depends-on (reduction)
(is equal '() (t:transduce (t:drop 100) #'t:cons '(1 2 3 4 5)))
(is equal '(4 5) (t:transduce (t:drop 3) #'t:cons '(1 2 3 4 5)))
(is equal '(7 8 9) (t:transduce (t:drop-while #'evenp) #'t:cons '(2 4 6 7 8 9)))
(is equal '() (t:transduce (t:take 0) #'t:cons '(1 2 3 4 5)))
(is equal '(1 2 3) (t:transduce (t:take 3) #'t:cons '(1 2 3 4 5)))
(is equal '() (t:transduce (t:take-while #'evenp) #'t:cons '(1)))
(is equal '(2 4 6 8) (t:transduce (t:take-while #'evenp) #'t:cons '(2 4 6 8 9 2))))
(define-test "Flattening"
:parent transduction
:depends-on (reduction)
(is equal '(1 2 3 4 5 6 7 8 9)
(t:transduce #'t:concatenate #'t:cons '((1 2 3) (4 5 6) (7 8 9))))
(is equal '(1 2 3 0 4 5 6 0 7 8 9 0)
(t:transduce #'t:flatten #'t:cons '((1 2 3) 0 (4 (5) 6) 0 (7 8 9) 0)))
(is equal '(:a 1 :b 2 :c 3)
(t:transduce #'t:uncons #'t:cons (t:plist '(:a 1 :b 2 :c 3))))
(is equal '(:a 2 :b 3 :c 4)
(t:transduce (t:comp (t:map (lambda (pair) (cons (car pair) (1+ (cdr pair)))))
#'t:uncons)
#'t:cons (t:plist '(:a 1 :b 2 :c 3)))))
(define-test "Pairing"
:parent transduction
:depends-on (reduction)
(is equal '((1 2 3) (4 5)) (t:transduce (t:segment 3) #'t:cons '(1 2 3 4 5)))
(is equal '((1 2 3) (2 3 4) (3 4 5))
(t:transduce (t:window 3) #'t:cons '(1 2 3 4 5)))
(is equal '((2 4 6) (7 9 1) (2 4 6) (3))
(t:transduce (t:group-by #'evenp) #'t:cons '(2 4 6 7 9 1 2 4 6 3))))
(define-test "Hash Tables"
:parent transduction
:depends-on (reduction)
(let ((table (make-hash-table :test #'equal)))
(setf (gethash :a table) 1)
(setf (gethash :b table) 2)
(setf (gethash :c table) 3)
(is equal '(1 2 3) (sort (t:transduce (t:map #'cdr) #'t:cons table) #'<))
(is equal '(:a :b :c) (sort (t:transduce (t:map #'car) #'t:cons table) #'string<))))
(define-test "Other"
:parent transduction
:depends-on (reduction)
(is equal '(1 3 5 7 9)
(t:transduce (t:step 2) #'t:cons '(1 2 3 4 5 6 7 8 9)))
(is equal '(1 0 2 0 3) (t:transduce (t:intersperse 0) #'t:cons '(1 2 3)))
(is equal (list (cons 0 "a") (cons 1 "b") (cons 2 "c"))
(t:transduce #'t:enumerate #'t:cons '("a" "b" "c")))
(is equal '(0 1 3 6 10)
(t:transduce (t:scan #'+ 0) #'t:cons '(1 2 3 4)))
(is equal '(0 1)
(t:transduce (t:comp (t:scan #'+ 0) (t:take 2))
#'t:cons '(1 2 3 4)))
(is equal '(hi 11 12)
(t:transduce (t:comp (t:filter (lambda (n) (> n 10)))
(t:once 'hi)
(t:take 3))
#'t:cons (t:ints 1))))
(define-test "Composition"
:parent transduction
:depends-on (reduction
"Taking and Dropping"
"Filtering"
"Other")
(is equal '(12 20 30)
(t:transduce (t:comp
#'t:enumerate
(t:map (lambda (pair) (* (car pair) (cdr pair))))
(t:filter #'evenp)
(t:drop 3)
(t:take 3))
#'t:cons
'(1 2 3 4 5 6 7 8 9 10))))
#+nil
(t:transduce (t:comp (t:drop 3) (t:take 2)) #'t:cons '(1 2 3 4 5 6))
#+nil
(funcall (t:comp #'1+ (lambda (n) (* 2 n))) 7)
(define-test "Conditions"
:parent transduction
:depends-on (reduction)
(is equal '(0 2 3)
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:map (lambda (item) (if (= 1 item) (error "無念") item))) #'t:cons '(0 1 2 3))))
(is equal '(0 2 3)
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:map (lambda (item) (if (= 1 item) (error "無念") item))) #'t:cons #(0 1 2 3))))
(is string-equal "Bithday"
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:map (lambda (item) (if (eq #\r item) (error "無念") item))) #'t:string "Birthday")))
(let ((table (make-hash-table :test #'equal)))
(setf (gethash :a table) 1)
(setf (gethash :b table) 2)
(setf (gethash :c table) 3)
(is equal '(1 3)
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:map (lambda (item) (if (= 2 (cdr item)) (error "無念") (cdr item)))) #'t:cons table))))
(is = 4
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:map (lambda (line) (if (str:emptyp (str:trim line)) (error "Empty!") line))) #'t:count #p"tests/file.txt")))
(is equal '(0 2 3 4)
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:comp (t:take 4) (t:map (lambda (item) (if (= 1 item) (error "無念") item)))) #'t:cons (t:ints 0))))
(is equal '(0 2 3)
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:map (lambda (pair) (if (= 1 (cdr pair)) (error "無念") (cdr pair)))) #'t:cons (t:plist '(:a 0 :b 1 :c 2 :d 3)))))
(is equal '(0 2 3)
(handler-bind ((error #'(lambda (c) (declare (ignore c)) (invoke-restart 't:next-item))))
(t:transduce (t:map (lambda (item) (if (= 1 item) (error "無念") item))) #'t:cons (j:read "[0,1,2,3]")))))
(define-test "Sources"
:depends-on (reduction transduction)
(is equal '() (t:transduce (t:take 0) #'t:cons (t:ints 0)))
(is equal '(0 1 2 3) (t:transduce (t:take 4) #'t:cons (t:ints 0)))
(is equal '(0 -1 -2 -3) (t:transduce (t:take 4) #'t:cons (t:ints 0 :step -1)))
(is equal '(1 2 3 1 2 3 1) (t:transduce (t:take 7) #'t:cons (t:cycle '(1 2 3))))
(is equal '(1 2 3 1 2 3 1) (t:transduce (t:take 7) #'t:cons (t:cycle #(1 2 3))))
(is equal "hellohe" (t:transduce (t:take 7) #'t:string (t:cycle "hello")))
(is equal '() (t:transduce (t:take 7) #'t:cons (t:cycle '())))
(is equal (list (cons :a 1) (cons :b 2) (cons :c 3))
(t:transduce #'t:pass #'t:cons (t:plist '(:a 1 :b 2 :c 3))))
(fail (t:transduce #'t:pass #'t:cons 1)))
(define-test "Higher Order Transducers"
:depends-on (reduction transduction)
(is equal '(1 4 1 4 1)
(t:transduce (t:comp (t:take 5)
(t:map #'1+)
(t:branch #'evenp
(t:map (t:comp #'write-to-string #'1+))
(t:map (t:const "Odd!")))
(t:map #'length))
#'t:cons (t:ints 1)))
(is equal (cons '(1 2 3 4 5 6 7 8 9) 12)
(t:transduce (t:comp (t:take 9)
(t:map #'1+)
(t:split (t:comp (t:filter #'evenp) (t:take 3)) #'+)
(t:map #'1-))
#'t:cons (t:ints 1))))
(define-test "Tail-recursion"
:depends-on (reduction transduction)
(let ((huge (t:transduce (t:take 1000000) #'t:cons (t:ints 1))))
(is = 1000000 (t:transduce #'t:pass #'t:count huge)))
(is = 1000000
(labels ((recurse (acc)
(if (= acc 1000000)
acc
(recurse (1+ acc)))))
(recurse 1))))
(define-test "JSON: Reading and Writing"
(is equal "[{\"name\":\"A\"},{\"name\":\"B\"}]"
(with-output-to-string (stream)
(t:transduce #'t:pass (j:write stream) (j:read "[{\"name\": \"A\"}, {\"name\": \"B\"}]"))))
(is equal "[{\"name\":\"Colin\",\"age\":35},{\"name\":\"Jack\",\"age\":10}]"
(with-output-to-string (stream)
(t:transduce #'t:pass (j:write stream) '((:name "Colin" :age 35) (:name "Jack" :age 10))))))
(define-test "CSV: Reading and Writing"
(is equal '("Name,Age" "Colin,35" "Tamayo,26")
(t:transduce (t:comp #'t:from-csv (t:into-csv '("Name" "Age")))
#'t:cons '("Name,Age,Hair" "Colin,35,Blond" "Tamayo,26,Black"))))
(define-test "Fset: Immutable Collections"
(let ((set (fset:set 1 2 3 1)))
(is fset:equal? set (t:transduce #'t:pass #'s:set set)))
(let ((map (fset:map (:a 1) (:b 2) (:c 3))))
(is fset:equal? map (t:transduce #'t:pass #'s:map map)))
(let ((seq (fset:seq 1 2 3)))
(is fset:equal? seq (t:transduce #'t:pass #'s:seq seq)))
(let ((bag (fset:bag 1 2 3 1)))
(is fset:equal? bag (t:transduce #'t:pass #'s:bag bag))))
#+nil
(test 'transducers/tests)
#+nil
(test 'transducers/tests :report 'interactive)
| 11,023 | Common Lisp | .lisp | 223 | 42.627803 | 135 | 0.538755 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 35f27189a3cda21b38f1cca92a04dd195ca58345bcbd86fba6db679141283e79 | 2,309 | [
-1
] |
2,310 | sources.lisp | fosskers_cl-transducers/transducers/sources.lisp | (in-package :transducers)
(defstruct (generator (:copier nil) (:predicate nil))
"A wrapper around a function that can potentially yield endless values."
(func nil :read-only t :type (function () *)))
(defvar *done* 'done
"A value to signal the end of an unfolding process.")
(defstruct (plist (:copier nil) (:predicate nil))
(list nil :read-only t :type list))
(declaim (ftype (function (list) plist) plist))
(defun plist (plist)
"Source: Yield key-value pairs from a Property List, usually known as a 'plist'.
The pairs are passed as a cons cell."
(make-plist :list plist))
;; FIXME type signature, expecting `values' to be called within the given
;; function.
(declaim (ftype (function ((function (t) *) t) generator) unfold))
(defun unfold (f seed)
(let* ((curr seed)
(func (lambda ()
(multiple-value-bind (acc next) (funcall f curr)
(cond ((eq *done* next) *done*)
(t (setf curr acc)
next))))))
(make-generator :func func)))
(declaim (ftype (function (t) generator) repeat))
(defun repeat (item)
"Source: Endlessly yield a given ITEM."
(make-generator :func (constantly item)))
#+nil
(transduce (take 4) #'cons (repeat 9))
(declaim (ftype (function (integer &key (:step fixnum)) generator) ints))
(defun ints (start &key (step 1))
"Source: Yield all integers, beginning with START and advancing by an optional
STEP value which can be positive or negative. If you only want a specific range
within the transduction, then use `take-while' within your transducer chain."
(let* ((curr start)
(func (lambda ()
(let ((old curr))
(setf curr (+ curr step))
old))))
(make-generator :func func)))
#+nil
(transduce (take 10) #'cons (ints 0 :step 2))
(declaim (ftype (function ((or single-float double-float integer)) generator) random))
(defun random (limit)
"Source: Yield an endless stream of random numbers, based on a given LIMIT."
(make-generator :func (lambda () (cl:random limit))))
#+nil
(transduce (take 20) #'cons (random 10))
(declaim (ftype (function (cl:vector) generator) shuffle))
(defun shuffle (vec)
"Source: Endlessly yield random elements from a given vector. Recall also that
strings are vectors too, so:
(transduce (take 5) #'string (shuffle \"Númenor\"))
=> \"mNNrú\"
"
(let* ((len (length vec))
(func (lambda () (aref vec (cl:random len)))))
(make-generator :func func)))
#+nil
(transduce (take 5) #'cons (shuffle #("Colin" "Tamayo" "Natsume")))
(defgeneric cycle (seq)
(:documentation "Source: Yield the values of a given SEQ endlessly."))
(defmethod cycle ((seq list))
(if (null seq)
(make-generator :func (lambda () *done*))
(let* ((curr seq)
(func (lambda ()
(cond ((null curr)
(setf curr (cdr seq))
(car seq))
(t (let ((next (car curr)))
(setf curr (cdr curr))
next))))))
(make-generator :func func))))
(defmethod cycle ((seq cl:vector))
"This works for strings as well."
(if (zerop (length seq))
(make-generator :func (lambda () *done*))
(let* ((ix 0)
(len (length seq))
(func (lambda ()
(cond ((>= ix len)
(setf ix 1)
(aref seq 0))
(t (let ((next (aref seq ix)))
(setf ix (1+ ix))
next))))))
(make-generator :func func))))
#+nil
(transduce (take 10) #'cons (cycle '(1 2 3)))
| 3,754 | Common Lisp | .lisp | 91 | 33.043956 | 86 | 0.583036 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | d05a1adb2f5af249be425d60c0a2c9b9e4a7072d30d25ad6a51e9d3ae9fd07fb | 2,310 | [
-1
] |
2,311 | utils.lisp | fosskers_cl-transducers/transducers/utils.lisp | (in-package :transducers)
(defun ensure-function (arg)
(cond ((functionp arg) arg)
((symbolp arg) (ensure-function (symbol-function arg)))
(t (error "Argument is not a function: ~a" arg))))
;; TODO Make this a macro.
(defun comp (function &rest functions)
"Function composition.
(funcall (comp #'1+ #'length) \"foo\") == (1+ (length \"foo\"))"
(reduce (lambda (f g)
(let ((f (ensure-function f))
(g (ensure-function g)))
(lambda (&rest arguments)
(funcall f (apply g arguments)))))
functions
:initial-value function))
#+nil
(funcall (comp (const 1337) (lambda (n) (* 2 n)) #'1+) 1)
(defun const (item)
"Return a function that ignores its argument and returns ITEM instead."
(lambda (x)
(declare (ignore x))
item))
(declaim (ftype (function ((or t reduced)) reduced) ensure-reduced))
(defun ensure-reduced (x)
"Ensure that X is reduced."
(if (reduced-p x)
x
(make-reduced :val x)))
(declaim (ftype (function ((or t reduced)) *) ensure-unreduced))
(defun ensure-unreduced (x)
"Ensure that X is unreduced."
(if (reduced-p x)
(reduced-val x)
x))
(defun preserving-reduced (reducer)
"A helper function that wraps a reduced value twice since reducing
functions (like list-reduce) unwraps them. tconcatenate is a good example: it
re-uses its reducer on its input using list-reduce. If that reduction finishes
early and returns a reduced value, list-reduce would 'unreduce' that value and
try to continue the transducing process."
(lambda (a b)
(let ((result (funcall reducer a b)))
(if (reduced-p result)
(make-reduced :val result)
result))))
(defun zipmap (keys vals)
"Form a hashmap with the KEYS mapped to the corresponding VALS.
Borrowed from Clojure, thanks guys."
(let ((table (make-hash-table :test #'equal)))
(mapc (lambda (k v) (setf (gethash k table) v)) keys vals)
table))
| 1,980 | Common Lisp | .lisp | 52 | 33.173077 | 78 | 0.659364 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 7dddf577c9da9d66e27b51fc78a33feac867ddc57b5a2da5961c8e8960f56f95 | 2,311 | [
-1
] |
2,312 | entry.lisp | fosskers_cl-transducers/transducers/entry.lisp | (in-package :transducers)
(defgeneric transduce (xform f source)
(:documentation "The entry-point for processing some data source via transductions.
This requires three things:
- A transducer function, or a composed chain of them
- A reducing function
- A source
Note: `comp' can be used to chain transducers together.
When ran, `transduce' will pull values from the source, transform them via the
transducers, and reduce into some single value (likely some collection but not
necessarily). `transduce' will only pull as many values from the source as are
actually needed, and does so one at a time. This ensures that large
sources (like files) don't consume too much memory.
# Examples
Assuming that you've required this library with a local nickname of `t', here's
how we can filter an infinite source and reduce into a single sum:
(t:transduce (t:comp (t:filter #'oddp)
(t:take 1000)
(t:map (lambda (n) (* n n))))
#'+ (t:ints 1))
;; => 1333333000 (31 bits, #x4F790C08)
Note that due to how transducer and reducer functions are composed internally,
the order provided to `comp' gets applied from top to bottom. In the above
example, this means that `filter' is applied first, and `map' last.
There are a variety of functions to instead reduce into a collection:
(t:transduce (t:map #'1+) #'t:vector '(1 2 3))
;; => #(2 3 4)
Many standard collections can be easily \"sourced\", including those that aren't
normally so conveniently traversed like Hash Tables, Property Lists, and lines
of a file.
;; Read key-value pairs from a plist and recollect into a Hash Table.
(t:transduce #'t:pass #'t:hash-table (t:plist `(:a 1 :b 2 :c 3)))
# Custom Sources
Since `transduce' is generic, you can use `defmethod' to define your own custom
sources. See `sources.lisp' and `entry.lisp' for examples of how to do this.
"))
(defmethod transduce (xform f (source cl:string))
(string-transduce xform f source))
(defmethod transduce (xform f (source list))
"Transducing over an alist works automatically via this method, and the pairs are
streamed as-is as cons cells."
(list-transduce xform f source))
(defmethod transduce (xform f (source cl:vector))
(vector-transduce xform f source))
(defmethod transduce (xform f (source cl:hash-table))
"Yields key-value pairs as cons cells."
(hash-table-transduce xform f source))
(defmethod transduce (xform f (source pathname))
(file-transduce xform f source))
(defmethod transduce (xform f (source generator))
(generator-transduce xform f source))
(defmethod transduce (xform f (source stream))
(stream-transduce xform f source))
(defmethod transduce (xform f (source plist))
"Yields key-value pairs as cons cells.
# Conditions
- `imbalanced-pist': if the number of keys and values do not match."
(plist-transduce xform f source))
(defmethod transduce (xform f fallback)
"Fallback for types which don't implement this. Always errors.
# Conditions
- `no-transduce-implementation': an unsupported type was transduced over."
(error 'no-transduce-implementation :type (type-of fallback)))
#+nil
(transduce (map #'char-upcase) #'string "hello")
#+nil
(transduce (map #'1+) #'vector '(1 2 3 4))
#+nil
(transduce (map #'1+) #'+ #(1 2 3 4))
#+nil
(let ((hm (make-hash-table :test #'equal)))
(setf (gethash 'a hm) 1)
(setf (gethash 'b hm) 2)
(setf (gethash 'c hm) 3)
(transduce (filter #'evenp) (max 0) hm))
#+nil
(transduce (map #'1+) #'+ 1) ;; Expected to fail.
(declaim (ftype (function (t t list) *) list-transduce))
(defun list-transduce (xform f coll)
(let* ((init (funcall f))
(xf (funcall xform f))
(result (list-reduce xf init coll)))
(funcall xf result)))
(declaim (ftype (function ((function (&optional t t) *) t list) *) list-reduce))
(defun list-reduce (f identity lst)
(labels ((recurse (acc items)
(if (null items)
acc
(let ((v (safe-call f acc (car items))))
(if (reduced-p v)
(reduced-val v)
(recurse v (cdr items)))))))
(recurse identity lst)))
#+nil
(transduce (map (lambda (item) (if (= item 1) (error "無念") item)))
#'cons '(0 1 2 3))
(declaim (ftype (function (t t cl:vector) *) vector-transduce))
(defun vector-transduce (xform f coll)
(let* ((init (funcall f))
(xf (funcall xform f))
(result (vector-reduce xf init coll)))
(funcall xf result)))
(defun vector-reduce (f identity vec)
(let ((len (length vec)))
(labels ((recurse (acc i)
(if (= i len)
acc
(let ((acc (safe-call f acc (aref vec i))))
(if (reduced-p acc)
(reduced-val acc)
(recurse acc (1+ i)))))))
(recurse identity 0))))
#+nil
(vector-transduce (map #'1+) #'cons #(1 2 3 4 5))
(declaim (ftype (function (t t cl:string) *) string-transduce))
(defun string-transduce (xform f coll)
(vector-transduce xform f coll))
#+nil
(string-transduce (map #'char-upcase) #'cons "hello")
(declaim (ftype (function (t t cl:hash-table) *) hash-table-transduce))
(defun hash-table-transduce (xform f coll)
"Transduce over the contents of a given Hash Table."
(let* ((init (funcall f))
(xf (funcall xform f))
(result (hash-table-reduce xf init coll)))
(funcall xf result)))
(defun hash-table-reduce (f identity ht)
(with-hash-table-iterator (iter ht)
(labels ((recurse (acc)
(multiple-value-bind (entry-p key value) (iter)
(if (not entry-p)
acc
(let ((acc (safe-call f acc (cl:cons key value))))
(if (reduced-p acc)
(reduced-val acc)
(recurse acc)))))))
(recurse identity))))
#+nil
(let ((hm (make-hash-table :test #'equal)))
(setf (gethash 'a hm) 1)
(setf (gethash 'b hm) 2)
(setf (gethash 'c hm) 3)
(hash-table-transduce (comp (map #'cdr) (filter #'evenp)) (fold #'cl:max 0) hm))
(defun file-transduce (xform f filename)
"Transduce over the lines of the file named by a FILENAME."
(let* ((init (funcall f))
(xf (funcall xform f))
(result (file-reduce xf init filename)))
(funcall xf result)))
(defun file-reduce (f identity filename)
(with-open-file (stream filename)
(stream-reduce f identity stream)))
#+nil
(file-transduce #'pass #'count #p"/home/colin/history.txt")
(defun stream-transduce (xform f stream)
"Transduce over the lines of a given STREAM. Note: Closing the stream is the
responsiblity of the caller!"
(let* ((init (funcall f))
(xf (funcall xform f))
(result (stream-reduce xf init stream)))
(funcall xf result)))
(defun stream-reduce (f identity stream)
(labels ((recurse (acc)
(let ((line (read-line stream nil)))
(if (not line)
acc
(let ((acc (safe-call f acc line)))
(if (reduced-p acc)
(reduced-val acc)
(recurse acc)))))))
(recurse identity)))
#+nil
(with-open-file (stream #p"/home/colin/.sbclrc")
(transduce #'pass #'count stream))
(defun generator-transduce (xform f gen)
"Transduce over a potentially endless stream of values from a generator GEN."
(let* ((init (funcall f))
(xf (funcall xform f))
(result (generator-reduce xf init gen)))
(funcall xf result)))
(defun generator-reduce (f identity gen)
(labels ((recurse (acc)
(let ((val (funcall (generator-func gen))))
(cond ((eq *done* val) acc)
(t (let ((acc (safe-call f acc val)))
(if (reduced-p acc)
(reduced-val acc)
(recurse acc))))))))
(recurse identity)))
(declaim (ftype (function (t t plist) *) plist-transduce))
(defun plist-transduce (xform f coll)
(let* ((init (funcall f))
(xf (funcall xform f))
(result (plist-reduce xf init coll)))
(funcall xf result)))
(declaim (ftype (function ((function (&optional t t) *) t plist) *) plist-reduce))
(defun plist-reduce (f identity lst)
(labels ((recurse (acc items)
(cond ((null items) acc)
((null (cdr items))
(let ((key (car items)))
(restart-case (error 'imbalanced-plist :key key)
(use-value (value)
:report "Supply a value for the final key."
:interactive (lambda () (prompt-new-value (format nil "Value for key ~a: " key)))
(recurse acc (list key value))))))
(t (let ((v (safe-call f acc (cl:cons (car items) (second items)))))
(if (reduced-p v)
(reduced-val v)
(recurse v (cdr (cdr items)))))))))
(recurse identity (plist-list lst))))
#+nil
(transduce #'pass #'cons (plist `(:a 1 :b 2 :c 3)))
#+nil
(transduce (map #'car) #'cons (plist `(:a 1 :b 2 :c 3)))
#+nil
(transduce (map #'cdr) #'+ (plist `(:a 1 :b 2 :c))) ;; Imbalanced plist for testing.
#+nil
(transduce #'pass #'cons '((:a . 1) (:b . 2) (:c . 3)))
| 9,414 | Common Lisp | .lisp | 219 | 35.894977 | 107 | 0.613415 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | dcc1f7217d5f5dbecd8581f02660cbf273ceae38617bd35afccdcdb4f19ccc0d | 2,312 | [
-1
] |
2,313 | conditions.lisp | fosskers_cl-transducers/transducers/conditions.lisp | (in-package :transducers)
(define-condition imbalanced-plist (error)
((key :initarg :key :reader imbalanced-plist-key))
(:documentation "A given `plist' source had an uneven number of keys.")
(:report (lambda (condition stream)
(format stream "The final key ~a had no value."
(imbalanced-plist-key condition)))))
(define-condition empty-transduction (error)
((msg :initarg :msg :reader empty-transduction-msg))
(:documentation "A transduction was empty when it was expected not to be.")
(:report (lambda (condition stream)
(format stream "~a~&" (empty-transduction-msg condition)))))
(define-condition non-positive-integer (error)
((n :initarg :n :reader npi-n)
(fn :initarg :fn :reader npi-fn))
(:documentation "A non-positive integer was passed to a function that expected one.")
(:report (lambda (condition stream)
(format stream "Non-positive integer passed to `~a': ~d"
(npi-fn condition)
(npi-n condition)))))
(define-condition empty-argument (error)
((fn :initarg :fn :reader empty-argument-fn))
(:documentation "A non-empty sequence was expected, but that didn't stop the user.")
(:report (lambda (condition stream)
(format stream "Empty sequence passed to `~a'."
(empty-argument-fn condition)))))
(define-condition no-transduce-implementation (error)
((type :initarg :type :reader no-transduce-implementation-type))
(:documentation "The user attempted to call `transduce' on an unsupported type.")
(:report (lambda (condition stream)
(format stream "The type ~a cannot be transduced over. Did you mean to pass a list?"
(no-transduce-implementation-type condition)))))
(defun prompt-new-value (prompt)
(format *query-io* prompt)
(force-output *query-io*)
(list (read *query-io*)))
;; FIXME 2024-07-05 It's my birthday. Should this be a macro?
(defun safe-call (f acc item)
"Call a transduction chain with the given arguments, wrapping the possibilities
in various restart cases."
(labels ((recurse (acc item)
(restart-case (funcall f acc item)
(next-item ()
:report "Skip this item and continue the transduction."
acc)
(retry-item ()
:report "Put this item through the transduction chain once more."
(recurse acc item))
(alter-item (alter)
:report "Transform this item via a given function, then try the transduction again."
:interactive (lambda () (prompt-for-function-name))
(recurse acc (funcall alter item)))
(use-value (value)
:report "Supply a different value and reattempt the transduction."
:interactive (lambda () (prompt-new-value "Value: "))
(recurse acc value)))))
(recurse acc item)))
(defun prompt-for-function-name ()
"Prompt the user for a function name."
(format *query-io* "Function name: ")
(force-output *query-io*)
(let ((input (read *query-io*)))
(if (and (symbolp input) (fboundp input))
(list input)
(error "Not a known function: ~A" input))))
| 3,273 | Common Lisp | .lisp | 65 | 41.723077 | 101 | 0.638125 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | a8658db1eeecae7c8e26f9dc91b1510cc939733038113c0f3730e615ba1f4d6a | 2,313 | [
-1
] |
2,314 | reducers.lisp | fosskers_cl-transducers/transducers/reducers.lisp | (in-package :transducers)
(declaim (ftype (function (&optional list t) list) cons))
(defun cons (&optional (acc nil a-p) (input nil i-p))
"Reducer: Collect all results as a list."
(cond ((and a-p i-p) (cl:cons input acc))
((and a-p (not i-p)) (nreverse acc))
(t '())))
(declaim (ftype (function (&optional list t) list) snoc))
(defun snoc (&optional (acc nil a-p) (input nil i-p))
"Reducer: Collect all results as a list, but results are reversed.
In theory, slightly more performant than `cons' since it performs no final
reversal."
(cond ((and a-p i-p) (cl:cons input acc))
((and a-p (not i-p)) acc)
(t '())))
(defun string (&optional (acc nil a-p) (input #\z i-p))
"Reducer: Collect a stream of characters into to a single string."
(cond ((and a-p i-p) (cl:cons input acc))
((and a-p (not i-p)) (cl:concatenate 'cl:string (nreverse acc)))
(t '())))
#+nil
(string-transduce (map #'char-upcase) #'string "hello")
(defun vector (&optional (acc nil a-p) (input nil i-p))
"Reducer: Collect a stream of values into a vector."
(cond ((and a-p i-p) (cl:cons input acc))
((and a-p (not i-p)) (cl:concatenate 'cl:vector (nreverse acc)))
(t '())))
#+nil
(vector-transduce (map #'1+) #'vector #(1 2 3))
(declaim (ftype (function (&optional (or cl:hash-table null) t) cl:hash-table) hash-table))
(defun hash-table (&optional (acc nil a-p) (input nil i-p))
"Reducer: Collect a stream of key-value cons pairs into a hash table."
(cond ((and a-p i-p) (destructuring-bind (key . val) input
(setf (gethash key acc) val)
acc))
((and a-p (not i-p)) acc)
(t (make-hash-table :test #'equal))))
#+nil
(transduce #'enumerate #'hash-table '("a" "b" "c"))
(declaim (ftype (function (&optional fixnum t) fixnum) count))
(defun count (&optional (acc 0 a-p) (input nil i-p))
"Reducer: Count the number of elements that made it through the transduction."
(declare (ignore input))
(cond ((and a-p i-p) (1+ acc))
((and a-p (not i-p)) acc)
(t 0)))
#+nil
(transduce #'pass #'count '(1 2 3 4 5))
(defun average (&optional (acc nil a-p) (input nil i-p))
"Reducer: Calculate the average value of all numeric elements in a transduction."
(cond ((and a-p i-p)
(destructuring-bind (count . total) acc
(cl:cons (1+ count) (+ total input))))
((and a-p (not i-p))
(destructuring-bind (count . total) acc
(if (= 0 count)
(error 'empty-transduction :msg "`average' called on an empty transduction.")
(/ total count))))
(t (cl:cons 0 0))))
#+nil
(transduce #'pass #'average '(1 2 3 4 5 6))
#+nil
(transduce (filter #'evenp) #'average '(1 3 5))
(defmacro any (pred)
"Deprecated: Use `anyp'."
(warn "`any' is deprecated; use `anyp' instead.")
`(anyp ,pred))
(declaim (ftype (function ((function (t) *)) *) anyp))
(defun anyp (pred)
"Reducer: Yield t if any element in the transduction satisfies PRED.
Short-circuits the transduction as soon as the condition is met."
(lambda (&optional (acc nil a-p) (input nil i-p))
(cond ((and a-p i-p)
(let ((test (funcall pred input)))
(if test
(make-reduced :val t)
nil)))
((and a-p (not i-p)) acc)
(t nil))))
#+nil
(transduce #'pass (any #'evenp) '(1 3 5 7 9))
#+nil
(transduce #'pass (any #'evenp) '(1 3 5 7 9 2))
(defmacro all (pred)
"Deprecated: Use `allp'."
(warn "`all' is deprecated; use `allp' instead.")
`(allp ,pred))
(declaim (ftype (function ((function (t) *)) *) allp))
(defun allp (pred)
"Reducer: Yield t if all elements of the transduction satisfy PRED.
Short-circuits with NIL if any element fails the test."
(lambda (&optional (acc nil a-p) (input nil i-p))
(cond ((and a-p i-p)
(let ((test (funcall pred input)))
(if (and acc test)
t
(make-reduced :val nil))))
((and a-p (not i-p)) acc)
(t t))))
#+nil
(transduce #'pass (all #'oddp) '(1 3 5 7 9))
#+nil
(transduce #'pass (all #'oddp) '(1 3 5 7 9 2))
(defun first (&optional (acc 'transducers-none a-p) (input nil i-p))
"Reducer: Yield the first value of the transduction. As soon as this first value
is yielded, the entire transduction stops.
# Conditions
- `empty-transduction': when no values made it through the transduction.
"
(cond ((and a-p i-p) (make-reduced :val input))
((and a-p (not i-p))
(if (eq 'transducers-none acc)
(restart-case (error 'empty-transduction :msg "first: the transduction was empty.")
(use-value (value)
:report "Supply a fallback value and end the transduction."
:interactive (lambda () (prompt-new-value "Fallback: "))
value))
acc))
(t 'transducers-none)))
#+nil
(transduce (filter #'oddp) #'first '(2 4 6 7 10))
#+nil
(transduce (filter #'oddp) #'first '(2 4 6 10))
(defun last (&optional (acc 'transducers-none a-p) (input nil i-p))
"Reducer: Yield the last value of the transduction.
# Conditions
- `empty-transduction': when no values made it through the transduction.
"
(cond ((and a-p i-p) input)
((and a-p (not i-p))
(if (eq 'transducers-none acc)
(restart-case (error 'empty-transduction :msg "last: the transduction was empty.")
(use-value (value)
:report "Supply a fallback value and end the transduction."
:interactive (lambda () (prompt-new-value "Fallback: "))
value))
acc))
(t 'transducers-none)))
#+nil
(transduce #'pass #'last '(2 4 6 7 10))
#+nil
(transduce #'pass #'last '())
(declaim (ftype (function ((function (t t) *) &optional t) *) fold))
(defun fold (f &optional (seed nil seed-p))
"Reducer: The fundamental reducer. `fold' creates an ad-hoc reducer based on
a given 2-argument function. An optional SEED value can also be given as the
initial accumulator value, which also becomes the return value in case there
were no input left in the transduction.
Functions like `+' and `*' are automatically valid reducers, because they yield
sane values even when given 0 or 1 arguments. Other functions like `max' cannot
be used as-is as reducers since they can't be called without arguments. For
functions like this, `fold' is appropriate.
# Conditions
- `empty-transduction': if no SEED is given and the transduction is empty.
"
(if seed-p
(lambda (&optional (acc nil a-p) (input nil i-p))
(cond ((and a-p i-p) (funcall f acc input))
((and a-p (not i-p)) acc)
(t seed)))
(lambda (&optional (acc nil a-p) (input nil i-p))
(cond ((and a-p i-p)
(if (eq acc 'transducers-none)
input
(funcall f acc input)))
((and a-p (not i-p))
(if (eq acc 'transducers-none)
(restart-case (error 'empty-transduction :msg "fold was called without a seed, but the transduction was also empty.")
(use-value (value)
:report "Supply a default value and end the transduction."
:interactive (lambda () (prompt-new-value "Default value: "))
value))
acc))
(t 'transducers-none)))))
#+nil
(transduce #'pass (fold #'cl:max) '())
#+nil
(transduce #'pass (fold #'cl:max 0) '(1 2 3 4 1000 5 6))
#+nil
(transduce #'pass (fold #'cl:max) '(1 2 3 4 1000 5 6))
(defun max (default)
"Deprecated: Use `fold' and pass it `cl:max' instead."
(warn "`max' is deprecated; use `fold' instead.")
(fold #'cl:max default))
(defun min (default)
"Deprecated: Use `fold' and pass it `cl:min' instead."
(warn "`min' is deprecated; use `fold' instead.")
(fold #'cl:min default))
(declaim (ftype (function ((function (t) *) &key (:default t)) *) find))
(defun find (pred &key default)
"Reducer: Find the first element in the transduction that satisfies a given PRED.
Yields `nil' if no such element were found."
(lambda (&optional (acc nil a-p) (input nil i-p))
(cond ((and a-p i-p)
(if (funcall pred input)
(make-reduced :val input)
default))
((and a-p (not i-p)) acc)
(t default))))
#+nil
(transduce #'pass (find #'evenp) '(1 3 5 6 9))
#+nil
(transduce #'pass (find #'evenp :default 1000) '(1 3 5 9))
(defun for-each (&rest vargs)
"Reducer: Run through every item in a transduction for their side effects.
Throws away all results and yields t."
(declare (ignore vargs))
t)
#+nil
(transduce (map (lambda (n) (format t "~a~%" n))) #'for-each #(1 2 3 4))
| 8,807 | Common Lisp | .lisp | 210 | 35.719048 | 136 | 0.607009 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 5f254ccc24d3cc68f0b7556673c16404a669abd453b61dac79e70e8dfc066c6b | 2,314 | [
-1
] |
2,315 | transducers.asd | fosskers_cl-transducers/transducers.asd | (defsystem "transducers"
:version "1.2.0"
:author "Colin Woodbury <[email protected]>"
:license "LGPL-3.0-only"
:depends-on (:sycamore)
:components ((:module "transducers"
:components
((:file "transducers")
(:file "reducers")
(:file "sources")
(:file "entry")
(:file "conditions")
(:file "utils"))))
:description "Ergonomic, efficient data processing."
:in-order-to ((test-op (test-op :transducers/tests))))
(defsystem "transducers/tests"
:author "Colin Woodbury <[email protected]>"
:license "LGPL-3.0-only"
:depends-on (:transducers
:transducers/jzon
:transducers/fset
:fset
:parachute
:str)
:components ((:module "tests"
:components
((:file "main"))))
:description "Test system for transducers"
:perform (test-op (op c) (symbol-call :parachute :test :transducers/tests)))
(defsystem "transducers/jzon"
:version "1.2.0"
:author "Colin Woodbury <[email protected]>"
:license "LGPL-3.0-only"
:depends-on (:transducers :com.inuoe.jzon :trivia)
:components ((:module "jzon"
:components
((:file "jzon"))))
:description "JSON extension for Transducers.")
(defsystem "transducers/fset"
:version "1.2.0"
:author "Colin Woodbury <[email protected]>"
:license "LGPL-3.0-only"
:depends-on (:transducers :fset)
:components ((:module "fset"
:components
((:file "fset"))))
:description "Fset extension for Transducers.")
| 1,650 | Common Lisp | .asd | 47 | 26.851064 | 78 | 0.5875 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 7a62e3140222258a21927ce2387404c0511770fd87748181b433a04c1922588a | 2,315 | [
-1
] |
2,317 | .build.yml | fosskers_cl-transducers/.build.yml | image: archlinux
secrets:
- 5c5bf3b5-a730-49d9-b46a-cb6baa48092d
packages:
- sbcl
- quicklisp
- emacs-nox
- jq
sources:
- https://git.sr.ht/~fosskers/cl-transducers
tasks:
# If our project isn't in the special `common-lisp` directory, quicklisp won't
# be able to find it for loading.
- move: |
mkdir common-lisp
mv cl-transducers ~/common-lisp
- quicklisp: |
sbcl --non-interactive --load /usr/share/quicklisp/quicklisp.lisp --eval "(quicklisp-quickstart:install)"
- test: |
cd common-lisp/cl-transducers
sbcl --non-interactive --load ~/quicklisp/setup.lisp --load run-tests.lisp
- readme: |
cd common-lisp/cl-transducers
emacs README.org --batch --eval "(setq org-html-head-include-default-style nil)" -f org-html-export-to-html --kill
sed -i '/<title>/d; /<\/title>/d' README.html
- upload: |
cd common-lisp/cl-transducers
set +x # Avoid echoing the token
jq -sR '{
"query": "mutation UpdateRepo($id: Int!, $readme: String!) {
updateRepository(id: $id, input: { readme: $readme }) { id }
}", "variables": {
"id": 363617,
"readme": .
} }' < README.html \
| curl --oauth2-bearer $(cat ~/.readme-token) \
-H "Content-Type: application/json" \
-d@- https://git.sr.ht/query
echo "README Uploaded."
| 1,321 | Common Lisp | .l | 39 | 29.692308 | 118 | 0.653666 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 4ba783ed5853f64f131455b066b5bd75fb4ab7db008e7b0cb1f68339203ada5e | 2,317 | [
-1
] |
2,319 | qlfile.lock | fosskers_cl-transducers/qlfile.lock | ("quicklisp" .
(:class qlot/source/dist:source-dist
:initargs (:distribution "https://beta.quicklisp.org/dist/quicklisp.txt" :%version :latest)
:version "2023-10-21"))
("ultralisp" .
(:class qlot/source/dist:source-dist
:initargs (:distribution "https://dist.ultralisp.org" :%version :latest)
:version "20240719191501"))
| 331 | Common Lisp | .l | 8 | 39.125 | 93 | 0.73065 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 0707519e9f61530e0cdaed82881623a3840e99bf9dfb294bd2e3751a23ade4d0 | 2,319 | [
-1
] |
2,322 | index.html | fosskers_cl-transducers/docs/index.html | <!DOCTYPE html> <html lang="EN"> <head> <meta charset="utf-8"> <title>Transducers</title> <style>html body{margin:0 auto 0 auto;padding:20px;max-width:1024px;font-family:sans-serif;font-size:14pt;overflow-y:scroll;}html body a{text-decoration:none;}html body a[href]{color:#0055AA;}html body a[href]:hover{color:#0088EE;}html body pre{background:#FAFAFA;border:1px solid #DDDDDD;padding:0.75em;overflow-x:auto;}html body pre >code a[href]{color:#223388;}article.project h1{font-size:1.7em;}article.project h1,article.project h2,article.project h3,article.project h4,article.project h5,article.project h6{margin:0.2em 0 0.1em 0;text-indent:1em;}article.project >header{text-align:center;}article.project >header img.logo{display:block;margin:auto;max-height:170px;}article.project >header h1{display:inline-block;text-indent:0;font-size:2.5em;}article.project >header .version{vertical-align:bottom;}article.project >header .languages{margin-top:-0.5em;text-transform:capitalize;}article.project >header .description{margin:0;}article.project >header .pages{margin-top:0.5em;font-size:1.2em;text-transform:capitalize;}article.project >header .pages a{display:inline-block;padding:0 0.2em;}article.project >section{margin:1em 0 1em 0;}article.project #index >ul{list-style:none;margin:0;padding:0;}article.project .row label{display:inline-block;min-width:8em;}article.project #system .row{display:flex;}article.project #system #dependencies{display:inline;margin:0;padding:0;}article.project #system #dependencies li{display:inline;padding:0 0.2em;}article.project #system #author label{vertical-align:top;}article.project #system #author ul{display:inline-block;margin:0;padding:0;list-style:none;}article.definition{margin:1em 0 0 0;}article.definition >header h1,article.definition >header h2,article.definition >header h3,article.definition >header h4,article.definition >header h5,article.definition >header h6{text-indent:0;display:inline-block;}article.definition >header ul{display:inline-block;list-style:none;margin:0;padding:0;}article.definition >header ul li{display:inline-block;padding:0 0.2em 0 0;}article.definition >header .visibility{display:none;}article.definition >header .visibility,article.definition >header .type{text-transform:lowercase;}article.definition >header .source-link{visibility:hidden;float:right;}article.definition >header .source-link:after{visibility:visible;content:"[SRC]";}article.definition .docstring{margin:0 0 0 1em;}article.definition .docstring pre{font-size:0.8em;white-space:pre-wrap;}.definition.package >header ul.nicknames{display:inline-block;list-style:none;margin:0;padding:0 0 0 1em;}.definition.package >header ul.nicknames li{display:inline;}.definition.package >header ul.nicknames:before{content:"(";}.definition.package >header ul.nicknames:after{content:")";}.definition.package ul.definitions{margin:0;list-style:none;padding:0 0 0 0.5em;}.definition.callable >header .name:before,.definition.type >header .name:before{content:"(";font-weight:normal;}.definition.callable >header .arguments:after,.definition.type >header .arguments:after{content:")";}.definition.callable >header .arguments .arguments:before,.definition.type >header .arguments .arguments:before{content:"(";}.definition.callable >header .arguments .argument,.definition.type >header .arguments .argument{padding:0;}.definition.callable >header .arguments .argument.lambda-list-keyword,.definition.type >header .arguments .argument.lambda-list-keyword{color:#991155;}.definition li>mark{background:none;border-left:0.3em solid #0088EE;padding-left:0.3em;display:block;}</style> </head> <body> <article class="project"> <header> <h1>transducers</h1> <span class="version">1.0.1</span> <p class="description">Ergonomic, efficient data processing.</p> <nav class="pages"> <a href="index.html">transducers</a> <a href="transducers/tests/index.html">transducers/tests</a> <a href="transducers-jzon/index.html">transducers jzon</a> </nav> </header> <section id="documentation"> </section> <section id="system"> <h2>System Information</h2> <div class="row"> <label for="version">Version:</label> <a id="version">1.0.1</a> </div> <div class="row"> <label for="dependencies">Dependencies:</label> <ul id="dependencies"><li><a class="external" href="http://ndantam.github.io/sycamore">sycamore</a></li></ul> </div> <div class="row" id="author"> <label for="author">Author:</label> <a href="mailto:[email protected]">Colin Woodbury</a> </div> <div class="row"> <label for="license">License:</label> <a id="license" href="file:///home/colin/code/common-lisp/cl-transducers/LICENSE">LGPL-3.0-only</a> </div> </section> <section id="index"> <h2>Definition Index</h2> <ul> <li> <article class="definition package" id="PACKAGE TRANSDUCERS"> <header> <h3> <a href="#PACKAGE%20TRANSDUCERS">TRANSDUCERS</a> </h3> <ul class="nicknames"></ul> </header> <div class="docstring"><pre>Ergonomic, efficient data processing.</pre></div> <ul class="definitions"> <li> <article class="definition condition" id="CONDITION TRANSDUCERS:EMPTY-TRANSDUCTION"> <header> <span class="visibility">EXTERNAL</span> <span class="type">CONDITION</span> <h4 class="name"> <a href="#CONDITION%20TRANSDUCERS%3AEMPTY-TRANSDUCTION">EMPTY-TRANSDUCTION</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/conditions.lisp#10:0">Source</a> </header> <div class="docstring"><pre>A transduction was empty when it was expected not to be.</pre></div> </article> </li> <li> <article class="definition condition" id="CONDITION TRANSDUCERS:IMBALANCED-PLIST"> <header> <span class="visibility">EXTERNAL</span> <span class="type">CONDITION</span> <h4 class="name"> <a href="#CONDITION%20TRANSDUCERS%3AIMBALANCED-PLIST">IMBALANCED-PLIST</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/conditions.lisp#3:0">Source</a> </header> <div class="docstring"><pre>A given `plist' source had an uneven number of keys.</pre></div> </article> </li> <li> <article class="definition structure" id="STRUCTURE TRANSDUCERS:PLIST"> <header> <span class="visibility">EXTERNAL</span> <span class="type">STRUCTURE</span> <h4 class="name"> <a href="#STRUCTURE%20TRANSDUCERS%3APLIST">PLIST</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/sources.lisp#10:0">Source</a> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:ALLP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AALLP">ALLP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#106:0">Source</a> </header> <div class="docstring"><pre>Reducer: Yield non-NIL if all elements of the transduction satisfy PRED.
Short-circuits with NIL if any element fails the test.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:ANYP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AANYP">ANYP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#83:0">Source</a> </header> <div class="docstring"><pre>Reducer: Yield non-NIL if any element in the transduction satisfies PRED.
Short-circuits the transduction as soon as the condition is met.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:AVERAGE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AAVERAGE">AVERAGE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#57:1">Source</a> </header> <div class="docstring"><pre>Reducer: Calculate the average value of all numeric elements in a transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:BRANCH"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ABRANCH">BRANCH</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> <li class="argument">TA</li> <li class="argument">TB</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#537:0">Source</a> </header> <div class="docstring"><pre>Transducer: If a PRED yields non-NIL on a value, proceed with transducer chain
TA. Otherwise, follow chain TB. This produces a kind of diamond pattern of data
flow within the transduction:
/4a-5a-6a\
1-2-3 7-8-9
\4b-5b---/
Assuming that TA here is some composition of three transducer steps, and TB is a
composition of two. Naturally, if you have other steps beyond the fork (Step 7
above), you should make sure that they can handle the return values of both
sides!
(transduce (comp (map #'1+)
(branch #'evenp
(map (comp #'write-to-string #'1+))
(map (const "Odd!")))
(map #'length))
#'cons (range 1 6))
=> (1 4 1 4 1)
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:COMP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ACOMP">COMP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">FUNCTION</li> <li class="argument lambda-list-keyword">&REST</li> <li class="argument">FUNCTIONS</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/utils.lisp#9:0">Source</a> </header> <div class="docstring"><pre>Function composition.
(funcall (comp #'1+ #'length) "foo") == (1+ (length "foo"))</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:CONCATENATE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ACONCATENATE">CONCATENATE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#170:1">Source</a> </header> <div class="docstring"><pre>Transducer: Concatenate all the sublists in the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:CONS"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ACONS">CONS</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#4:0">Source</a> </header> <div class="docstring"><pre>Reducer: Collect all results as a list.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:CONST"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ACONST">CONST</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">ITEM</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/utils.lisp#21:1">Source</a> </header> <div class="docstring"><pre>Return a function that ignores its argument and returns ITEM instead.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:COUNT"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ACOUNT">COUNT</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#50:0">Source</a> </header> <div class="docstring"><pre>Reducer: Count the number of elements that made it through the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:DEDUP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ADEDUP">DEDUP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#363:1">Source</a> </header> <div class="docstring"><pre>Transducer: Remove adjacent duplicates from the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:DROP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ADROP">DROP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">N</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#97:0">Source</a> </header> <div class="docstring"><pre>Transducer: Drop the first N elements of the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:DROP-WHILE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ADROP-WHILE">DROP-WHILE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#113:0">Source</a> </header> <div class="docstring"><pre>Transducer: Drop elements from the front of the transduction that satisfy PRED.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:ENUMERATE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AENUMERATE">ENUMERATE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#287:1">Source</a> </header> <div class="docstring"><pre>Transducer: Index every value passed through the transduction into a cons pair.
Starts at 0.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FILTER"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFILTER">FILTER</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#65:0">Source</a> </header> <div class="docstring"><pre>Transducer: Only keep elements from the transduction that satisfy PRED.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FILTER-MAP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFILTER-MAP">FILTER-MAP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">F</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#78:0">Source</a> </header> <div class="docstring"><pre>Transducer: Apply a function F to the elements of the transduction, but only
keep results that are non-nil.
(transduce (filter-map #'cl:first) #'cons '(() (2 3) () (5 6) () (8 9)))
=> (2 5 8)
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FIND"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFIND">FIND</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#224:0">Source</a> </header> <div class="docstring"><pre>Reducer: Find the first element in the transduction that satisfies a given PRED.
Yields `nil' if no such element were found.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FIRST"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFIRST">FIRST</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#118:1">Source</a> </header> <div class="docstring"><pre>Reducer: Yield the first value of the transduction. As soon as this first value
is yielded, the entire transduction stops.
# Conditions
- `empty-transduction': when no values made it through the transduction.
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FLATTEN"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFLATTEN">FLATTEN</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#184:1">Source</a> </header> <div class="docstring"><pre>Transducer: Entirely flatten all lists in the transduction, regardless of
nesting.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FOLD"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFOLD">FOLD</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">F</li> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">SEED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#171:0">Source</a> </header> <div class="docstring"><pre>Reducer: The fundamental reducer. `fold' creates an ad-hoc reducer based on
a given 2-argument function. An optional SEED value can also be given as the
initial accumulator value, which also becomes the return value in case there
were no input left in the transduction.
Functions like `+' and `*' are automatically valid reducers, because they yield
sane values even when given 0 or 1 arguments. Other functions like `max' cannot
be used as-is as reducers since they can't be called without arguments. For
functions like this, `fold' is appropriate.
# Conditions
- `empty-transduction': if no SEED is given and the transduction is empty.
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FOR-EACH"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFOR-EACH">FOR-EACH</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&REST</li> <li class="argument">VARGS</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#235:1">Source</a> </header> <div class="docstring"><pre>Reducer: Run through every item in a transduction for their side effects.
Throws away all results and yields t.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:FROM-CSV"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AFROM-CSV">FROM-CSV</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#451:1">Source</a> </header> <div class="docstring"><pre>Transducer: Interpret the data stream as CSV data.
The first item found is assumed to be the header list, and it will be used to
construct useable hashtables for all subsequent items.
Note: This function makes no attempt to convert types from the
original parsed strings. If you want numbers, you will need to
further parse them yourself.
This function is expected to be passed "bare" to `transduce', so there is no
need for the caller to manually pass a REDUCER.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:GROUP-BY"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AGROUP-BY">GROUP-BY</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">F</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#241:0">Source</a> </header> <div class="docstring"><pre>Transducer: Group the input stream into sublists via some function F. The cutoff
criterion is whether the return value of F changes between two consecutive elements of the
transduction.
(transduce (group-by #'evenp) #'cons '(2 4 6 7 9 1 2 4 6 3))
=> ((2 4 6) (7 9 1) (2 4 6) (3))
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:HASH-TABLE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AHASH-TABLE">HASH-TABLE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#38:0">Source</a> </header> <div class="docstring"><pre>Reducer: Collect a stream of key-value cons pairs into a hash table.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:INJECT"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AINJECT">INJECT</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">F</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#597:1">Source</a> </header> <div class="docstring"><pre>Transducer: For each value in the transduction that actually affects the final
result (tested with `EQ'), inject an extra transduction step into the chain
immediately after this point. Accumulates, such that each new injection appears
before the previous one.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:INTERSPERSE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AINTERSPERSE">INTERSPERSE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">ELEM</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#270:1">Source</a> </header> <div class="docstring"><pre>Transducer: Insert an ELEM between each value of the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:INTO-CSV"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AINTO-CSV">INTO-CSV</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">HEADERS</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#490:0">Source</a> </header> <div class="docstring"><pre>Transducer: Given a sequence of HEADERS, rerender each item in the data stream
into a CSV string. It's assumed that each item in the transduction is a hash
table whose keys are strings that match the values found in HEADERS.
# Conditions
- `empty-argument': when an empty HEADERS sequence is given.
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:INTS"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AINTS">INTS</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">START</li> <li class="argument lambda-list-keyword">&KEY</li> <li class="argument">STEP</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/sources.lisp#38:0">Source</a> </header> <div class="docstring"><pre>Source: Yield all integers, beginning with START and advancing by an optional
STEP value which can be positive or negative. If you only want a specific range
within the transduction, then use `take-while' within your transducer chain.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:LAST"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ALAST">LAST</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#142:1">Source</a> </header> <div class="docstring"><pre>Reducer: Yield the last value of the transduction.
# Conditions
- `empty-transduction': when no values made it through the transduction.
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:LOG"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ALOG">LOG</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">LOGGER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#300:1">Source</a> </header> <div class="docstring"><pre>Transducer: Call some LOGGER function for each step of the transduction. The
LOGGER must accept the running results and the current element as input. The
original results of the transduction are passed through as-is.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:MAKE-REDUCED"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AMAKE-REDUCED">MAKE-REDUCED</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&KEY</li> <li class="argument">VAL</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#41:0">Source</a> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:MAP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AMAP">MAP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">F</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#54:0">Source</a> </header> <div class="docstring"><pre>Transducer: Apply a function F to all elements of the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:MAX"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AMAX">MAX</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">DEFAULT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#206:1">Source</a> </header> <div class="docstring"><pre>Deprecated: Use `fold' and pass it `cl:max' instead.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:MIN"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AMIN">MIN</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">DEFAULT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#218:0">Source</a> </header> <div class="docstring"><pre>Deprecated: Use `fold' and pass it `cl:min' instead.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:ONCE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AONCE">ONCE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">ITEM</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#432:1">Source</a> </header> <div class="docstring"><pre>Transducer: Inject some ITEM into the front of the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:PASS"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3APASS">PASS</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#45:0">Source</a> </header> <div class="docstring"><pre>Transducer: Just pass along each value of the transduction. Same in intent with
applying `map' to `identity', but this should be slightly more efficient. It is
at least shorter to type.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:PLIST"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3APLIST">PLIST</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PLIST</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/sources.lisp#13:0">Source</a> </header> <div class="docstring"><pre>Source: Yield key-value pairs from a Property List, usually known as a 'plist'.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:RANDOM"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ARANDOM">RANDOM</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">LIMIT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/sources.lisp#53:0">Source</a> </header> <div class="docstring"><pre>Source: Yield an endless stream of random numbers.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:REDUCED-P"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AREDUCED-P">REDUCED-P</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">OBJECT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#41:0">Source</a> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:REDUCED-VAL"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AREDUCED-VAL">REDUCED-VAL</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">INSTANCE</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#41:0">Source</a> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:(SETF REDUCED-VAL)"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3A%28SETF%20REDUCED-VAL%29">(SETF REDUCED-VAL)</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">VALUE</li> <li class="argument">INSTANCE</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#41:0">Source</a> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:REPEAT"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AREPEAT">REPEAT</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">ITEM</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/sources.lisp#30:0">Source</a> </header> <div class="docstring"><pre>Source: Endlessly yield a given ITEM.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:SCAN"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ASCAN">SCAN</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">F</li> <li class="argument">SEED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#413:0">Source</a> </header> <div class="docstring"><pre>Transducer: Build up successsive values from the results of previous
applications of a given function F.
(transduce (scan #'+ 0) #'cons '(1 2 3 4))
=> (0 1 3 6 10)</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:SEGMENT"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ASEGMENT">SEGMENT</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">N</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#200:0">Source</a> </header> <div class="docstring"><pre>Transducer: Partition the input into lists of N items. If the input stops, flush
any accumulated state, which may be shorter than N.
# Conditions
- `non-positive-integer': when a non-positive integer N is given.
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:SHUFFLE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ASHUFFLE">SHUFFLE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">VEC</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/sources.lisp#61:0">Source</a> </header> <div class="docstring"><pre>Source: Endlessly yield random elements from a given vector. Recall also that
strings are vectors too, so:
(transduce (take 5) #'string (shuffle "Númenor"))
=> "mNNrú"
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:SNOC"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ASNOC">SNOC</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#11:0">Source</a> </header> <div class="docstring"><pre>Reducer: Collect all results as a list, but results are reversed.
In theory, slightly more performant than `cons' since it performs no final
reversal.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:SPLIT"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ASPLIT">SPLIT</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">TA</li> <li class="argument">RA</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#572:1">Source</a> </header> <div class="docstring"><pre>Transducer: Split off a new transducer chain, feeding it each input as well. It
reduces on its own given RA reducer. The final result is a cons-cell where the
first value is the result of the original transduction, and the second is that
of the branch.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:STEP"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ASTEP">STEP</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">N</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#380:0">Source</a> </header> <div class="docstring"><pre>Transducer: Only yield every Nth element of the transduction. The first element
of the transduction is always included.
# Conditions
- `non-positive-integer': when a non-positive integer N is given.
# Examples
(transduce (step 2) #'cons '(1 2 3 4 5 6 7 8 9))
=> (1 3 5 7 9)
</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:STRING"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ASTRING">STRING</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#19:0">Source</a> </header> <div class="docstring"><pre>Reducer: Collect a stream of characters into to a single string.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:TAKE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ATAKE">TAKE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">N</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#128:0">Source</a> </header> <div class="docstring"><pre>Transducer: Keep only the first N elements of the transduction.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:TAKE-WHILE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3ATAKE-WHILE">TAKE-WHILE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#148:0">Source</a> </header> <div class="docstring"><pre>Transducer: Keep only elements which satisfy a given PRED, and stop the
transduction as soon as any element fails the test.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:UNCONS"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AUNCONS">UNCONS</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#158:1">Source</a> </header> <div class="docstring"><pre>Transducer: Split up a transduction of cons cells.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:UNIQUE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AUNIQUE">UNIQUE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">REDUCER</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#346:1">Source</a> </header> <div class="docstring"><pre>Transducer: Only allow values to pass through the transduction once each.
Stateful; this uses a hash table internally so could get quite heavy if you're
not careful.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:VECTOR"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AVECTOR">VECTOR</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument lambda-list-keyword">&OPTIONAL</li> <li class="argument">ACC</li> <li class="argument">INPUT</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#25:1">Source</a> </header> <div class="docstring"><pre>Reducer: Collect a stream of values into a vector.</pre></div> </article> </li> <li> <article class="definition function callable" id="FUNCTION TRANSDUCERS:WINDOW"> <header> <span class="visibility">EXTERNAL</span> <span class="type">FUNCTION</span> <h4 class="name"> <a href="#FUNCTION%20TRANSDUCERS%3AWINDOW">WINDOW</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">N</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/transducers.lisp#318:0">Source</a> </header> <div class="docstring"><pre>Transducer: Yield N-length windows of overlapping values. This is different from
`segment' which yields non-overlapping windows. If there were fewer items in the
input than N, then this yields nothing.
# Conditions
- `non-positive-integer': when a non-positive integer N is given.
</pre></div> </article> </li> <li> <article class="definition generic-function callable" id="GENERIC-FUNCTION TRANSDUCERS:CYCLE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">GENERIC-FUNCTION</span> <h4 class="name"> <a href="#GENERIC-FUNCTION%20TRANSDUCERS%3ACYCLE">CYCLE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">SEQ</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/sources.lisp#72:3">Source</a> </header> <div class="docstring"><pre>Source: Yield the values of a given SEQ endlessly.</pre></div> </article> </li> <li> <article class="definition generic-function callable" id="GENERIC-FUNCTION TRANSDUCERS:TRANSDUCE"> <header> <span class="visibility">EXTERNAL</span> <span class="type">GENERIC-FUNCTION</span> <h4 class="name"> <a href="#GENERIC-FUNCTION%20TRANSDUCERS%3ATRANSDUCE">TRANSDUCE</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">XFORM</li> <li class="argument">F</li> <li class="argument">SOURCE</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/entry.lisp#3:0">Source</a> </header> <div class="docstring"><pre>The entry-point for processing some data source via transductions.
This requires three things:
- A transducer function, or a composed chain of them
- A reducing function
- A source
Note: `comp' can be used to chain transducers together.
When ran, `transduce' will pull values from the source, transform them via the
transducers, and reduce into some single value (likely some collection but not
necessarily). `transduce' will only pull as many values from the source as are
actually needed, and does so one at a time. This ensures that large
sources (like files) don't consume too much memory.
# Examples
Assuming that you've required this library with a local nickname of `t', here's
how we can filter an infinite source and reduce into a single sum:
(t:transduce (t:comp (t:filter #'oddp)
(t:take 1000)
(t:map (lambda (n) (* n n))))
#'+ (t:ints 1))
;; => 1333333000 (31 bits, #x4F790C08)
Note that due to how transducer and reducer functions are composed internally,
the order provided to `comp' gets applied from top to bottom. In the above
example, this means that `filter' is applied first, and `map' last.
There are a variety of functions to instead reduce into a collection:
(t:transduce (t:map #'1+) #'t:vector '(1 2 3))
;; => #(2 3 4)
Many standard collections can be easily "sourced", including those that aren't
normally so conveniently traversed like Hash Tables, Property Lists, and lines
of a file.
;; Read key-value pairs from a plist and recollect into a Hash Table.
(t:transduce #'t:pass #'t:hash-table (t:plist `(:a 1 :b 2 :c 3)))
# Custom Sources
Since `transduce' is generic, you can use `defmethod' to define your own custom
sources. See `sources.lisp' and `entry.lisp' for examples of how to do this.
</pre></div> </article> </li> <li> <article class="definition macro callable" id="MACRO-FUNCTION TRANSDUCERS:ALL"> <header> <span class="visibility">EXTERNAL</span> <span class="type">MACRO</span> <h4 class="name"> <a href="#MACRO-FUNCTION%20TRANSDUCERS%3AALL">ALL</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#95:1">Source</a> </header> <div class="docstring"><pre>Deprecated: Use `allp'.</pre></div> </article> </li> <li> <article class="definition macro callable" id="MACRO-FUNCTION TRANSDUCERS:ANY"> <header> <span class="visibility">EXTERNAL</span> <span class="type">MACRO</span> <h4 class="name"> <a href="#MACRO-FUNCTION%20TRANSDUCERS%3AANY">ANY</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"> <li class="argument">PRED</li> </ul> <a class="source-link" href="file:///home/colin/code/common-lisp/cl-transducers/transducers/reducers.lisp#72:1">Source</a> </header> <div class="docstring"><pre>Deprecated: Use `anyp'.</pre></div> </article> </li> <li> <article class="definition source-transform" id="SOURCE-TRANSFORM TRANSDUCERS:MAKE-REDUCED"> <header> <span class="visibility">EXTERNAL</span> <span class="type">SOURCE-TRANSFORM</span> <h4 class="name"> <a href="#SOURCE-TRANSFORM%20TRANSDUCERS%3AMAKE-REDUCED">MAKE-REDUCED</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition source-transform" id="SOURCE-TRANSFORM TRANSDUCERS:(SETF MAKE-REDUCED)"> <header> <span class="visibility">EXTERNAL</span> <span class="type">SOURCE-TRANSFORM</span> <h4 class="name"> <a href="#SOURCE-TRANSFORM%20TRANSDUCERS%3A%28SETF%20MAKE-REDUCED%29">(SETF MAKE-REDUCED)</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition source-transform" id="SOURCE-TRANSFORM TRANSDUCERS:REDUCED-P"> <header> <span class="visibility">EXTERNAL</span> <span class="type">SOURCE-TRANSFORM</span> <h4 class="name"> <a href="#SOURCE-TRANSFORM%20TRANSDUCERS%3AREDUCED-P">REDUCED-P</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition source-transform" id="SOURCE-TRANSFORM TRANSDUCERS:(SETF REDUCED-P)"> <header> <span class="visibility">EXTERNAL</span> <span class="type">SOURCE-TRANSFORM</span> <h4 class="name"> <a href="#SOURCE-TRANSFORM%20TRANSDUCERS%3A%28SETF%20REDUCED-P%29">(SETF REDUCED-P)</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition source-transform" id="SOURCE-TRANSFORM TRANSDUCERS:REDUCED-VAL"> <header> <span class="visibility">EXTERNAL</span> <span class="type">SOURCE-TRANSFORM</span> <h4 class="name"> <a href="#SOURCE-TRANSFORM%20TRANSDUCERS%3AREDUCED-VAL">REDUCED-VAL</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> <li> <article class="definition source-transform" id="SOURCE-TRANSFORM TRANSDUCERS:(SETF REDUCED-VAL)"> <header> <span class="visibility">EXTERNAL</span> <span class="type">SOURCE-TRANSFORM</span> <h4 class="name"> <a href="#SOURCE-TRANSFORM%20TRANSDUCERS%3A%28SETF%20REDUCED-VAL%29">(SETF REDUCED-VAL)</a> </h4> <ul class="qualifiers"></ul> <ul class="arguments"></ul> </header> <div class="docstring"><i>No documentation provided.</i></div> </article> </li> </ul> </article> </li> </ul> </section> </article> <script>window.addEventListener("DOMContentLoaded", function(){
var unmarkElement = function(el){
if(el.tagName === "mark" || el.tagName === "MARK"){
[].forEach.call(el.childNodes, function(child){
el.parentNode.insertBefore(child, el);
});
el.parentNode.removeChild(el);
}else if(el.parentNode.tagName === "mark"){
return unmarkElement(el.parentNode);
}
return null;
}
var unmarkAll = function(root){
root = root || document;
[].forEach.call(root.querySelectorAll("mark"), unmarkElement);
}
var markElement = function(el){
if(el.parentNode.tagName === "mark" || el.parentNode.tagName === "MARK"){
return el.parentNode;
} else {
unmarkAll();
var marked = document.createElement("mark");
el.parentNode.insertBefore(marked, el);
marked.appendChild(el);
return marked;
}
}
var markFragmented = function(){
if(window.location.hash){
var el = document.getElementById(decodeURIComponent(window.location.hash.substr(1)));
if(el) markElement(el);
}
}
var registerXrefLink = function(link){
var el = document.getElementById(decodeURIComponent(link.getAttribute("href").substr(1)));
if(el){
link.addEventListener("click", function(){
markElement(el);
});
}
}
var registerXrefLinks = function(root){
root = root || document;
[].forEach.call(root.querySelectorAll("a.xref"), registerXrefLink);
}
markFragmented();
registerXrefLinks();
}); </script> </body> </html> | 53,673 | Common Lisp | .l | 183 | 289.021858 | 7,244 | 0.718523 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 5758064292f5c4fb3a8d6757ca4e4f916c030530c45b86dc28cf31c36f6d04ec | 2,322 | [
-1
] |
2,323 | index.html | fosskers_cl-transducers/docs/transducers/tests/index.html | <!DOCTYPE html> <html lang="EN"> <head> <meta charset="utf-8"> <title>Transducers/Tests</title> <style>html body{margin:0 auto 0 auto;padding:20px;max-width:1024px;font-family:sans-serif;font-size:14pt;overflow-y:scroll;}html body a{text-decoration:none;}html body a[href]{color:#0055AA;}html body a[href]:hover{color:#0088EE;}html body pre{background:#FAFAFA;border:1px solid #DDDDDD;padding:0.75em;overflow-x:auto;}html body pre >code a[href]{color:#223388;}article.project h1{font-size:1.7em;}article.project h1,article.project h2,article.project h3,article.project h4,article.project h5,article.project h6{margin:0.2em 0 0.1em 0;text-indent:1em;}article.project >header{text-align:center;}article.project >header img.logo{display:block;margin:auto;max-height:170px;}article.project >header h1{display:inline-block;text-indent:0;font-size:2.5em;}article.project >header .version{vertical-align:bottom;}article.project >header .languages{margin-top:-0.5em;text-transform:capitalize;}article.project >header .description{margin:0;}article.project >header .pages{margin-top:0.5em;font-size:1.2em;text-transform:capitalize;}article.project >header .pages a{display:inline-block;padding:0 0.2em;}article.project >section{margin:1em 0 1em 0;}article.project #index >ul{list-style:none;margin:0;padding:0;}article.project .row label{display:inline-block;min-width:8em;}article.project #system .row{display:flex;}article.project #system #dependencies{display:inline;margin:0;padding:0;}article.project #system #dependencies li{display:inline;padding:0 0.2em;}article.project #system #author label{vertical-align:top;}article.project #system #author ul{display:inline-block;margin:0;padding:0;list-style:none;}article.definition{margin:1em 0 0 0;}article.definition >header h1,article.definition >header h2,article.definition >header h3,article.definition >header h4,article.definition >header h5,article.definition >header h6{text-indent:0;display:inline-block;}article.definition >header ul{display:inline-block;list-style:none;margin:0;padding:0;}article.definition >header ul li{display:inline-block;padding:0 0.2em 0 0;}article.definition >header .visibility{display:none;}article.definition >header .visibility,article.definition >header .type{text-transform:lowercase;}article.definition >header .source-link{visibility:hidden;float:right;}article.definition >header .source-link:after{visibility:visible;content:"[SRC]";}article.definition .docstring{margin:0 0 0 1em;}article.definition .docstring pre{font-size:0.8em;white-space:pre-wrap;}.definition.package >header ul.nicknames{display:inline-block;list-style:none;margin:0;padding:0 0 0 1em;}.definition.package >header ul.nicknames li{display:inline;}.definition.package >header ul.nicknames:before{content:"(";}.definition.package >header ul.nicknames:after{content:")";}.definition.package ul.definitions{margin:0;list-style:none;padding:0 0 0 0.5em;}.definition.callable >header .name:before,.definition.type >header .name:before{content:"(";font-weight:normal;}.definition.callable >header .arguments:after,.definition.type >header .arguments:after{content:")";}.definition.callable >header .arguments .arguments:before,.definition.type >header .arguments .arguments:before{content:"(";}.definition.callable >header .arguments .argument,.definition.type >header .arguments .argument{padding:0;}.definition.callable >header .arguments .argument.lambda-list-keyword,.definition.type >header .arguments .argument.lambda-list-keyword{color:#991155;}.definition li>mark{background:none;border-left:0.3em solid #0088EE;padding-left:0.3em;display:block;}</style> </head> <body> <article class="project"> <header> <h1>transducers/tests</h1> <span class="version"></span> <p class="description">Test system for transducers</p> <nav class="pages"> <a href="../../index.html">transducers</a> <a href="index.html">transducers/tests</a> <a href="../../transducers-jzon/index.html">transducers jzon</a> </nav> </header> <section id="documentation"> </section> <section id="system"> <h2>System Information</h2> <div class="row"> <label for="dependencies">Dependencies:</label> <ul id="dependencies"><li><a class="external">transducers</a></li><li><a class="external">transducers-jzon</a></li><li><a class="external" href="https://Shinmera.github.io/parachute/">parachute</a></li></ul> </div> <div class="row" id="author"> <label for="author">Author:</label> <a href="mailto:[email protected]">Colin Woodbury</a> </div> <div class="row"> <label for="license">License:</label> <a id="license" href="file:///home/colin/code/common-lisp/cl-transducers/LICENSE">LGPL-3.0-only</a> </div> </section> </article> <script>window.addEventListener("DOMContentLoaded", function(){
var unmarkElement = function(el){
if(el.tagName === "mark" || el.tagName === "MARK"){
[].forEach.call(el.childNodes, function(child){
el.parentNode.insertBefore(child, el);
});
el.parentNode.removeChild(el);
}else if(el.parentNode.tagName === "mark"){
return unmarkElement(el.parentNode);
}
return null;
}
var unmarkAll = function(root){
root = root || document;
[].forEach.call(root.querySelectorAll("mark"), unmarkElement);
}
var markElement = function(el){
if(el.parentNode.tagName === "mark" || el.parentNode.tagName === "MARK"){
return el.parentNode;
} else {
unmarkAll();
var marked = document.createElement("mark");
el.parentNode.insertBefore(marked, el);
marked.appendChild(el);
return marked;
}
}
var markFragmented = function(){
if(window.location.hash){
var el = document.getElementById(decodeURIComponent(window.location.hash.substr(1)));
if(el) markElement(el);
}
}
var registerXrefLink = function(link){
var el = document.getElementById(decodeURIComponent(link.getAttribute("href").substr(1)));
if(el){
link.addEventListener("click", function(){
markElement(el);
});
}
}
var registerXrefLinks = function(root){
root = root || document;
[].forEach.call(root.querySelectorAll("a.xref"), registerXrefLink);
}
markFragmented();
registerXrefLinks();
}); </script> </body> </html> | 6,425 | Common Lisp | .l | 48 | 124.645833 | 4,741 | 0.720006 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | ea7a70b36a1b2859d99c777ab9ec0896dd644286d0efe40b57abf0b79a030dc8 | 2,323 | [
-1
] |
2,324 | index.html | fosskers_cl-transducers/docs/transducers-jzon/index.html | <!DOCTYPE html> <html lang="EN"> <head> <meta charset="utf-8"> <title>Transducers Jzon</title> <style>html body{margin:0 auto 0 auto;padding:20px;max-width:1024px;font-family:sans-serif;font-size:14pt;overflow-y:scroll;}html body a{text-decoration:none;}html body a[href]{color:#0055AA;}html body a[href]:hover{color:#0088EE;}html body pre{background:#FAFAFA;border:1px solid #DDDDDD;padding:0.75em;overflow-x:auto;}html body pre >code a[href]{color:#223388;}article.project h1{font-size:1.7em;}article.project h1,article.project h2,article.project h3,article.project h4,article.project h5,article.project h6{margin:0.2em 0 0.1em 0;text-indent:1em;}article.project >header{text-align:center;}article.project >header img.logo{display:block;margin:auto;max-height:170px;}article.project >header h1{display:inline-block;text-indent:0;font-size:2.5em;}article.project >header .version{vertical-align:bottom;}article.project >header .languages{margin-top:-0.5em;text-transform:capitalize;}article.project >header .description{margin:0;}article.project >header .pages{margin-top:0.5em;font-size:1.2em;text-transform:capitalize;}article.project >header .pages a{display:inline-block;padding:0 0.2em;}article.project >section{margin:1em 0 1em 0;}article.project #index >ul{list-style:none;margin:0;padding:0;}article.project .row label{display:inline-block;min-width:8em;}article.project #system .row{display:flex;}article.project #system #dependencies{display:inline;margin:0;padding:0;}article.project #system #dependencies li{display:inline;padding:0 0.2em;}article.project #system #author label{vertical-align:top;}article.project #system #author ul{display:inline-block;margin:0;padding:0;list-style:none;}article.definition{margin:1em 0 0 0;}article.definition >header h1,article.definition >header h2,article.definition >header h3,article.definition >header h4,article.definition >header h5,article.definition >header h6{text-indent:0;display:inline-block;}article.definition >header ul{display:inline-block;list-style:none;margin:0;padding:0;}article.definition >header ul li{display:inline-block;padding:0 0.2em 0 0;}article.definition >header .visibility{display:none;}article.definition >header .visibility,article.definition >header .type{text-transform:lowercase;}article.definition >header .source-link{visibility:hidden;float:right;}article.definition >header .source-link:after{visibility:visible;content:"[SRC]";}article.definition .docstring{margin:0 0 0 1em;}article.definition .docstring pre{font-size:0.8em;white-space:pre-wrap;}.definition.package >header ul.nicknames{display:inline-block;list-style:none;margin:0;padding:0 0 0 1em;}.definition.package >header ul.nicknames li{display:inline;}.definition.package >header ul.nicknames:before{content:"(";}.definition.package >header ul.nicknames:after{content:")";}.definition.package ul.definitions{margin:0;list-style:none;padding:0 0 0 0.5em;}.definition.callable >header .name:before,.definition.type >header .name:before{content:"(";font-weight:normal;}.definition.callable >header .arguments:after,.definition.type >header .arguments:after{content:")";}.definition.callable >header .arguments .arguments:before,.definition.type >header .arguments .arguments:before{content:"(";}.definition.callable >header .arguments .argument,.definition.type >header .arguments .argument{padding:0;}.definition.callable >header .arguments .argument.lambda-list-keyword,.definition.type >header .arguments .argument.lambda-list-keyword{color:#991155;}.definition li>mark{background:none;border-left:0.3em solid #0088EE;padding-left:0.3em;display:block;}</style> </head> <body> <article class="project"> <header> <h1>transducers jzon</h1> <span class="version">0.1.0</span> <p class="description">JSON extension for Transducers.</p> <nav class="pages"> <a href="../index.html">transducers</a> <a href="../transducers/tests/index.html">transducers/tests</a> <a href="index.html">transducers jzon</a> </nav> </header> <section id="documentation"> </section> <section id="system"> <h2>System Information</h2> <div class="row"> <label for="version">Version:</label> <a id="version">0.1.0</a> </div> <div class="row"> <label for="dependencies">Dependencies:</label> <ul id="dependencies"><li><a class="external">transducers</a></li><li><a class="external">com.inuoe.jzon</a></li><li><a class="external">trivia</a></li></ul> </div> <div class="row" id="author"> <label for="author">Author:</label> <a href="mailto:[email protected]">Colin Woodbury</a> </div> <div class="row"> <label for="license">License:</label> <a id="license" href="file:///home/colin/code/common-lisp/cl-transducers/LICENSE">LGPL-3.0-only</a> </div> </section> </article> <script>window.addEventListener("DOMContentLoaded", function(){
var unmarkElement = function(el){
if(el.tagName === "mark" || el.tagName === "MARK"){
[].forEach.call(el.childNodes, function(child){
el.parentNode.insertBefore(child, el);
});
el.parentNode.removeChild(el);
}else if(el.parentNode.tagName === "mark"){
return unmarkElement(el.parentNode);
}
return null;
}
var unmarkAll = function(root){
root = root || document;
[].forEach.call(root.querySelectorAll("mark"), unmarkElement);
}
var markElement = function(el){
if(el.parentNode.tagName === "mark" || el.parentNode.tagName === "MARK"){
return el.parentNode;
} else {
unmarkAll();
var marked = document.createElement("mark");
el.parentNode.insertBefore(marked, el);
marked.appendChild(el);
return marked;
}
}
var markFragmented = function(){
if(window.location.hash){
var el = document.getElementById(decodeURIComponent(window.location.hash.substr(1)));
if(el) markElement(el);
}
}
var registerXrefLink = function(link){
var el = document.getElementById(decodeURIComponent(link.getAttribute("href").substr(1)));
if(el){
link.addEventListener("click", function(){
markElement(el);
});
}
}
var registerXrefLinks = function(root){
root = root || document;
[].forEach.call(root.querySelectorAll("a.xref"), registerXrefLink);
}
markFragmented();
registerXrefLinks();
}); </script> </body> </html> | 6,467 | Common Lisp | .l | 48 | 125.520833 | 4,783 | 0.718409 | fosskers/cl-transducers | 103 | 4 | 5 | LGPL-3.0 | 9/19/2024, 11:25:29 AM (Europe/Amsterdam) | 147f8a16a07f5a01d736f1e5220565b1c1d2ac64d4620cc0c987cda5c1e8cd63 | 2,324 | [
-1
] |
2,345 | reverse-stream.lisp | j3pic_lisp-binary/reverse-stream.lisp | (defpackage :reverse-stream
(:use :common-lisp :trivial-gray-streams :lisp-binary/integer :lisp-binary-utils)
(:export :wrap-in-reverse-stream :with-wrapped-in-reverse-stream :reverse-stream)
(:documentation "A stream that reads from another stream and reverses the bit order
of each byte so that the low-order bit becomes the high-order bit and vice versa.
This functionality is called for by the TIFF file format, because \"It is easy and
inexpensive for writers to reverse bit order by using a 256-byte lookup table.\" It
is devillishly tricky to include this functionality directly in the DEFBINARY macro,
however, when the macro was written without gratuitous bit-reversal in mind.
The REVERSE-STREAM does not keep track of any file positioning information. That means
it can coexist with its client stream, and you can mix reads and/or writes between
the two.
REVERSE-STREAM is not limited to 8-bit bytes. It can handle any byte size that the
underlying Lisp implementation supports. On PC hardware, some Lisps can read byte
sizes that are multiples of 8 bits, such as (UNSIGNED-BYTE 24)."))
(in-package :reverse-stream)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun compute-reversed-byte (n bits)
(let ((result 0))
(loop repeat bits
for bits-left downfrom bits
do (push-bits (pop-bits 1 bits-left n) (- bits bits-left) result))
result)))
(defun make-lookup-table (bits)
(make-array (list (expt 2 bits))
:element-type `(unsigned-byte ,bits)
:initial-contents
(loop for n from 0 below (expt 2 bits)
collect (compute-reversed-byte n bits))))
(defvar *8-bit-lookup-table* (make-lookup-table 8))
(defclass reverse-stream (fundamental-binary-stream)
((element-bits :type fixnum :initform 8 :initarg :element-bits)
(lookup-table :initform nil :initarg :lookup-table)
(real-stream :type stream :initarg :real-stream)))
(defgeneric wrap-in-reverse-stream (object)
(:documentation "Creates a REVERSE-STREAM that can read one bit at a time from the OBJECT. The REVERSE-STREAM
can be discarded if BYTE-ALIGNED-P returns T."))
(defmethod wrap-in-reverse-stream ((object stream))
(let ((element-type (stream-element-type object)))
(assert (and (listp element-type)
(= (length element-type) 2)
(eq (car element-type) 'unsigned-byte)))
(let ((bits (cadr element-type)))
(make-instance 'reverse-stream :real-stream object
:element-bits bits
:lookup-table (if (= bits 8)
*8-bit-lookup-table*
(make-lookup-table bits))))))
(defmacro with-wrapped-in-reverse-stream ((var non-bitstream &key close-when-done) &body body)
`(let ((,var (wrap-in-reverse-stream ,non-bitstream)))
(unwind-protect
(progn
,@body)
(finish-output ,var)
,@(if close-when-done
`((if ,close-when-done
(close ,var)))))))
(defmethod stream-finish-output ((stream reverse-stream))
(finish-output (slot-value stream 'real-stream)))
(defmethod stream-force-output ((stream reverse-stream))
(force-output (slot-value stream 'real-stream)))
(defmethod close ((stream reverse-stream) &key abort)
(apply #'close (list* (slot-value stream 'real-stream)
(if abort
(list :abort abort)))))
(defun reverse-byte (byte lookup-table)
(aref lookup-table byte))
(declaim (inline reverse-byte))
(defmethod stream-read-byte ((stream reverse-stream))
(reverse-byte
(read-byte (slot-value stream 'real-stream))
(slot-value stream 'lookup-table)))
(defmethod stream-write-byte ((stream reverse-stream) integer)
(write-byte (reverse-byte integer
(slot-value stream 'lookup-table))
stream))
(defun %stream-write-sequence (stream sequence start end)
(let ((reversed (mapseq (lambda (element)
(reverse-byte element (slot-value stream 'lookup-table)))
sequence)))
(write-sequence reversed stream :start start :end end)))
(defmethod stream-write-sequence ((stream reverse-stream) sequence start end &key &allow-other-keys)
(%stream-write-sequence stream sequence (or start 0) (or end (1- (length sequence)))))
(defun %stream-read-sequence (stream sequence start end)
(prog1 (read-sequence sequence (slot-value stream 'real-stream) :start start :end end)
(if (listp sequence)
(loop for hd on sequence
while hd
do (rplaca hd (reverse-byte (car hd)
(slot-value stream 'lookup-table))))
(loop for ix from 0 below (length sequence)
do (setf (aref sequence ix)
(reverse-byte (aref sequence ix)
(slot-value stream 'lookup-table)))))))
(defmethod stream-read-sequence ((stream reverse-stream) sequence start end &key &allow-other-keys)
(%stream-read-sequence stream sequence start end))
(defmethod stream-file-position ((stream reverse-stream))
(file-position (slot-value stream 'real-stream)))
(defmethod (setf stream-file-position) (position-spec (stream reverse-stream))
(file-position (slot-value stream 'real-stream) position-spec))
| 4,988 | Common Lisp | .lisp | 100 | 45.74 | 111 | 0.72949 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | c948c89748e3688e5e0fe1883927fc8bf7d8c451cb78ae59cb67e3eb8b6d1fe4 | 2,345 | [
-1
] |
2,346 | simple-bit-stream.lisp | j3pic_lisp-binary/simple-bit-stream.lisp | (defpackage :simple-bit-stream
(:use :common-lisp :trivial-gray-streams :lisp-binary/integer :lisp-binary-utils)
(:export :wrap-in-bit-stream :with-wrapped-in-bit-stream :bit-stream :read-bits
:write-bits :read-bytes-with-partial :byte-aligned-p))
(in-package :simple-bit-stream)
(defclass bit-stream (fundamental-binary-stream fundamental-input-stream fundamental-output-stream)
((element-bits :type fixnum :initform 8 :initarg :element-bits)
(real-stream :type stream :initarg :real-stream)
(last-byte :type unsigned-byte :initform 0)
(last-op :type symbol :initform nil)
(bits-left :type integer :initform 0)
(byte-order :type keyword :initarg :byte-order :initform :little-endian)))
(defmethod stream-element-type ((stream bit-stream))
'(unsigned-byte 8))
(defun trace-read-byte (stream &optional (eof-error-p t) eof-value)
(read-byte stream eof-error-p eof-value))
(defun trace-write-byte (byte stream)
(write-byte byte stream))
(defun byte-aligned-p (bit-stream)
(= (slot-value bit-stream 'bits-left) 0))
(defgeneric wrap-in-bit-stream (object &key byte-order)
(:documentation "Creates a BIT-STREAM that can read one bit at a time from the OBJECT. The BIT-STREAM
can be discarded if BYTE-ALIGNED-P returns T."))
(defmethod wrap-in-bit-stream ((object stream) &key (byte-order :little-endian))
(make-instance 'bit-stream :real-stream object :byte-order byte-order))
(defmacro with-wrapped-in-bit-stream ((var non-bitstream &key (byte-order :little-endian)
close-when-done) &body body)
`(let ((,var (wrap-in-bit-stream ,non-bitstream :byte-order ,byte-order)))
(unwind-protect
(progn
,@body)
(finish-output ,var)
,@(if close-when-done
`((if ,close-when-done
(close ,var)))))))
(declaim (inline init-read init-write reset-op))
(defun reset-op (stream op)
(setf (slot-value stream 'last-op) op)
(setf (slot-value stream 'last-byte) 0)
(setf (slot-value stream 'bits-left) 0))
(defun init-read (stream)
(unless (eq (slot-value stream 'last-op) :read)
(reset-op stream :read)))
(defun init-write (stream)
(unless (eq (slot-value stream 'last-op) :write)
(reset-op stream :write)))
(defun read-partial-byte/big-endian (bits stream)
(cond
((= (slot-value stream 'bits-left) 0)
(setf (slot-value stream 'last-byte)
(restart-case (trace-read-byte (slot-value stream 'real-stream))
(continue ()
:report "Pretend the read returned a 0 byte."
0)))
(setf (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
(read-partial-byte/big-endian bits stream))
((>= (slot-value stream 'bits-left) bits)
(prog1
(pop-bits bits (slot-value stream 'bits-left)
(slot-value stream 'last-byte))
(decf (slot-value stream 'bits-left) bits)))
((< (slot-value stream 'bits-left) bits)
(let* ((bits-left (slot-value stream 'bits-left))
(remaining-bits (pop-bits (slot-value stream 'bits-left)
bits-left
(slot-value stream 'last-byte))))
(setf (slot-value stream 'bits-left) 0)
(logior
(ash remaining-bits (- bits bits-left))
(read-partial-byte/big-endian (- bits bits-left) stream))))))
(defun read-partial-byte/little-endian (bits stream)
(cond
((= (slot-value stream 'bits-left) 0)
(setf (slot-value stream 'last-byte)
(restart-case (trace-read-byte (slot-value stream 'real-stream))
(continue ()
:report "Pretend the read returned a 0 byte."
0)))
(setf (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
(read-partial-byte/little-endian bits stream))
((>= (slot-value stream 'bits-left) bits)
(prog1
(pop-bits/le bits (slot-value stream 'last-byte))
(decf (slot-value stream 'bits-left) bits)))
((< (slot-value stream 'bits-left) bits)
(let* ((bits-left (slot-value stream 'bits-left))
(remaining-bits (pop-bits/le bits-left (slot-value stream 'last-byte))))
(setf (slot-value stream 'bits-left) 0)
(logior
remaining-bits
(ash (read-partial-byte/little-endian (- bits bits-left) stream)
bits-left))))
(t (error "BUG: This should never happen!"))))
(defmethod stream-finish-output ((stream bit-stream))
(unless (or (not (eq (slot-value stream 'last-op) :write))
(= (slot-value stream 'bits-left) 0))
(trace-write-byte (ecase (slot-value stream 'byte-order)
(:little-endian (slot-value stream 'last-byte))
(:big-endian (ash (slot-value stream 'last-byte)
(- 8 (slot-value stream 'bits-left)))))
(slot-value stream 'real-stream))
(finish-output (slot-value stream 'real-stream))))
(defmethod stream-force-output ((stream bit-stream))
(stream-finish-output stream))
(defmethod close ((stream bit-stream) &key abort)
(declare (ignore abort))
(stream-finish-output stream)
(close (slot-value stream 'real-stream)))
(defmethod stream-read-byte ((stream bit-stream))
(init-read stream)
(cond ((= (slot-value stream 'bits-left) 0)
(trace-read-byte (slot-value stream 'real-stream)))
((= (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
(prog1
(slot-value stream 'last-byte)
(setf (slot-value stream 'last-byte) 0
(slot-value stream 'bits-left) 0)))
((< (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
(ecase (slot-value stream 'byte-order)
(:little-endian
(let ((bits-left (slot-value stream 'bits-left))
(last-byte (slot-value stream 'last-byte))
(next-bits nil))
(setf (slot-value stream 'bits-left) 0)
(setf (slot-value stream 'last-byte) 0)
(setf next-bits (read-partial-byte/little-endian (- (slot-value stream 'element-bits)
bits-left)
stream))
(logior last-byte
(ash next-bits bits-left))))
(:big-endian
(logior (ash (slot-value stream 'last-byte)
(- (slot-value stream 'element-bits)
(slot-value stream 'bits-left)))
(let ((bits-to-read (- (slot-value stream 'element-bits)
(slot-value stream 'bits-left))))
(setf (slot-value stream 'last-byte) 0
(slot-value stream 'bits-left) 0)
(read-partial-byte/big-endian bits-to-read stream))))))
((> (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
(ecase (slot-value stream 'byte-order)
(:little-endian
(prog1 (logand (1- (expt 2 (slot-value stream 'element-bits)))
(slot-value stream 'last-byte))
(decf (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
(setf (slot-value stream 'last-byte)
(ash (slot-value stream 'last-byte)
(- (slot-value stream 'element-bits))))))
(:big-endian
(error "Not implemented!"))))))
(defmethod stream-write-byte ((stream bit-stream) integer)
(init-write stream)
(cond ((= (slot-value stream 'bits-left) 0)
(trace-write-byte integer (slot-value stream 'real-stream)))
(t (let ((total-bits-left (+ (slot-value stream 'element-bits)
(slot-value stream 'bits-left))))
(multiple-value-bind (byte-to-write new-last-byte)
(ecase (slot-value stream 'byte-order)
(:little-endian
(push-bits integer (slot-value stream 'bits-left)
(slot-value stream 'last-byte))
(values (pop-bits/le (slot-value stream 'element-bits)
(slot-value stream 'last-byte))
(slot-value stream 'last-byte)))
(:big-endian
(push-bits/le integer (slot-value stream 'element-bits)
(slot-value stream 'last-byte))
(values (pop-bits (slot-value stream 'element-bits)
total-bits-left
(slot-value stream 'last-byte))
(slot-value stream 'last-byte))))
(setf (slot-value stream 'last-byte) new-last-byte)
(trace-write-byte byte-to-write (slot-value stream 'real-stream)))))))
(defun %stream-write-sequence (stream sequence start end)
(unless (>= end start)
(return-from %stream-write-sequence sequence))
(cond ((and (equal (slot-value stream 'bits-left) 0)
(streamp (slot-value stream 'real-stream)))
(write-sequence sequence (slot-value stream 'real-stream) :start start :end end))
(t (loop for ix from start below end
do (trace-write-byte (elt sequence ix) stream))
sequence)))
(defmethod stream-write-sequence ((stream bit-stream) sequence start end &key &allow-other-keys)
(%stream-write-sequence stream sequence (or start 0) (or end (1- (length sequence)))))
(defun %stream-read-sequence (stream sequence start end)
(declare (optimize (speed 0) (debug 3)))
(unless (> end start)
(return-from %stream-read-sequence 0))
(init-read stream)
(cond ((and (equal (slot-value stream 'bits-left) 0)
(streamp (slot-value stream 'real-stream)))
(read-sequence sequence (slot-value stream 'real-stream) :start start :end end))
(t
(loop for ix from start below end
do (setf (elt sequence ix)
(handler-case
(trace-read-byte stream)
(end-of-file ()
(return bytes-read))))
count t into bytes-read
finally (return bytes-read)))))
(defmethod stream-read-sequence ((stream bit-stream) sequence start end &key &allow-other-keys)
(%stream-read-sequence stream sequence start end))
(defmacro read-bytes-with-partial/macro (stream* bits byte-order &key adjustable)
(alexandria:with-gensyms (whole-bytes remaining-bits element-bits buffer
stream bytes-read)
`(let* ((,stream ,stream*)
(,element-bits (slot-value ,stream 'element-bits)))
(multiple-value-bind (,whole-bytes ,remaining-bits)
(floor ,bits ,element-bits)
(let ((,buffer (make-array ,whole-bytes
:element-type (list 'unsigned-byte ,element-bits)
:adjustable ,adjustable
:fill-pointer ,adjustable)))
(when (> ,whole-bytes 0)
(let ((,bytes-read (read-sequence ,buffer ,stream)))
(when (< ,bytes-read ,whole-bytes)
(cerror "Ignore the error." (make-condition 'end-of-file :stream ,stream)))))
(values ,buffer ,(ecase byte-order
(:little-endian
`(read-partial-byte/little-endian ,remaining-bits ,stream))
(:big-endian
`(read-partial-byte/big-endian ,remaining-bits, stream)))
,remaining-bits))))))
(defun read-bytes-with-partial (stream bits)
"Reads BITS bits from the STREAM, where BITS is expected to be more than a byte's worth
of bits. Returns three values:
1. A buffer containing as many whole bytes as possible. This buffer
is always read first, regardless of whether the bitstream is byte-aligned.
2. The partial byte.
3. The number of bits that were read for the partial byte.
The byte order is determined from the STREAM object, which must be a SIMPLE-BIT-STREAM:BIT-STREAM."
(ecase (slot-value stream 'byte-order)
(:big-endian
(init-read stream)
(read-bytes-with-partial/macro stream bits :big-endian :adjustable t))
(:little-endian
(init-read stream)
(read-bytes-with-partial/macro stream bits :little-endian :adjustable t))))
(defun read-bits/big-endian (bits stream)
(cond ((< bits (slot-value stream 'element-bits))
(read-partial-byte/big-endian bits stream))
((= bits (slot-value stream 'element-bits))
(trace-read-byte stream))
(t
(let ((result 0)
(element-bits (slot-value stream 'element-bits)))
(multiple-value-bind (buffer partial-byte remaining-bits)
(read-bytes-with-partial/macro stream bits :big-endian)
(loop for byte across buffer
for bit-shift from bits downto remaining-bits by element-bits
do (incf result (ash byte bit-shift)))
(logior result partial-byte))))))
(defun read-bits/little-endian (bits stream)
(cond ((< bits (slot-value stream 'element-bits))
(read-partial-byte/little-endian bits stream))
((= bits (slot-value stream 'element-bits))
(trace-read-byte stream))
(t
(let ((result 0)
(element-bits (slot-value stream 'element-bits)))
(multiple-value-bind (buffer partial-byte remaining-bits)
(read-bytes-with-partial/macro stream bits :little-endian)
(loop for byte across buffer
for bit-shift from 0 by element-bits
do (incf result (ash byte bit-shift)))
(logior result
(ash partial-byte
(- bits remaining-bits))))))))
(defun read-bits (bits stream)
"Reads BITS bits from STREAM. If the STREAM is big-endian, the most
significant BITS bits will be read, otherwise, the least significant BITS bits
will be. The result is an integer of BITS bits."
(ecase (slot-value stream 'byte-order)
(:little-endian
(init-read stream)
(read-bits/little-endian bits stream))
(:big-endian
(init-read stream)
(read-bits/big-endian bits stream))))
(defun write-bits (n n-bits stream)
(when (= n-bits 0)
(return-from write-bits (values)))
(ecase (slot-value stream 'byte-order)
(:little-endian
(init-write stream)
(push-bits n (slot-value stream 'bits-left)
(slot-value stream 'last-byte))
(incf (slot-value stream 'bits-left) n-bits)
(loop while (>= (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
do
(trace-write-byte (pop-bits/le (slot-value stream 'element-bits)
(slot-value stream 'last-byte))
(slot-value stream 'real-stream))
(decf (slot-value stream 'bits-left)
(slot-value stream 'element-bits))))
(:big-endian
(init-write stream)
(push-bits/le n n-bits
(slot-value stream 'last-byte))
(incf (slot-value stream 'bits-left) n-bits)
(loop while (>= (slot-value stream 'bits-left)
(slot-value stream 'element-bits))
do
(trace-write-byte (pop-bits (slot-value stream 'element-bits)
(slot-value stream 'bits-left)
(slot-value stream 'last-byte))
(slot-value stream 'real-stream))
(decf (slot-value stream 'bits-left)
(slot-value stream 'element-bits))))))
(defmethod stream-file-position ((stream bit-stream))
(cond ((slot-value stream 'real-stream)
(file-position (slot-value stream 'real-stream)))
(t (error "Not implemented for POSIX/Win32 descriptors."))))
(defmethod (setf stream-file-position) (position-spec (stream bit-stream))
(setf (slot-value stream 'bits-left) 0
(slot-value stream 'last-byte) 0)
(file-position (slot-value stream 'real-stream) position-spec))
(defmethod call-with-file-position ((stream bit-stream) position thunk)
(let ((bits-left (slot-value stream 'bits-left))
(last-byte (slot-value stream 'last-byte))
(last-op (slot-value stream 'last-op)))
(unwind-protect (call-next-method)
(setf (slot-value stream 'bits-left) bits-left
(slot-value stream 'last-byte) last-byte
(slot-value stream 'last-op) last-op))))
| 14,721 | Common Lisp | .lisp | 333 | 38.993994 | 103 | 0.67759 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 8e6d569cd1cea80a846c9b6d7de221a356aaf8e839a029487517a5115e19cfc3 | 2,346 | [
-1
] |
2,347 | integer.lisp | j3pic_lisp-binary/integer.lisp | (defpackage :lisp-binary/integer
(:use :common-lisp :lisp-binary-utils)
(:export :get-lsb-byte :encode-lsb :decode-lsb :encode-msb :decode-msb
:signed->unsigned :unsigned->signed :unsigned->signed/bits
:signed->unsigned/bits
:read-integer :write-integer :read-bytes :write-bytes :pop-bits
:split-bit-field :join-field-bits :pop-bits/le
:push-bits :push-bits/le :bit-stream :return-subseq))
(in-package :lisp-binary/integer)
;; (declaim (optimize (debug 0) (speed 3)))
(defun get-lsb-byte (number byte)
(declare (type integer number)
(type (signed-byte 32) byte))
(logand #xff (ash number (* byte -8))))
(defun encode-lsb (number bytes)
(declare (type integer number))
(let ((result (make-array (list bytes) :element-type '(unsigned-byte 8))))
(loop for x from 0 below bytes
do (setf (aref result x) (get-lsb-byte number x)))
result))
(declaim (inline encode-lsb))
(defun decode-lsb (bytes)
;; (declare (type (simple-array (unsigned-byte 8) (*)) bytes))
(let ((result 0))
(declare (type integer result))
(loop for b across bytes
for ix from 0 do
(setf result (logior result (ash b (* ix 8)))))
result))
(declaim (inline decode-lsb))
(defun decode-msb (bytes)
(decode-lsb (reverse bytes)))
(declaim (inline decode-msb))
(defun encode-msb (number bytes)
(declare (type integer number))
(reverse (encode-lsb number bytes)))
(declaim (inline encode-msb))
(defun signed->unsigned/bits (n bits)
(let ((negative-offset (expt 2 bits)))
(if (< n 0)
(the integer (+ n negative-offset))
n)))
(defun signed->unsigned (n bytes &optional (type :twos-complement))
(let ((n (ecase type
(:twos-complement n)
(:ones-complement (ones-complement->twos-complement n)))))
(signed->unsigned/bits n (* 8 bytes))))
(defun twos-complement->ones-complement (n bits)
"Given a number that has been decoded as two's complement,
correct it to what its value should be if the original bits
were a one's complement representation."
(cond ((>= n 0)
n)
((= n (1- (expt 2 bits)))
0)
(t
(1+ n))))
(defun ones-complement->twos-complement (n)
"Given a number that has been decoded as one's complement,
correct it to what its value should be if the original bits
were a two's complement representation. This function doesn't
need the number of bits because all ones in one's complement
represents 'negative zero', a value that can't be represented
in Common Lisp integers."
(if (>= n 0)
n
(1- n)))
(defun unsigned->signed/bits (n bits)
(let* ((negative-offset (expt 2 bits))
(max (- (/ negative-offset 2) 1)))
(if (> n max)
(- n negative-offset)
n)))
(defun unsigned->signed (n bytes &key (type :twos-complement))
(let ((twos-complement (unsigned->signed/bits n (* 8 bytes))))
(ecase type
(:twos-complement twos-complement)
(:ones-complement (twos-complement->ones-complement twos-complement (* 8 bytes))))))
(defgeneric write-bytes (buffer stream &optional bytes)
(:documentation "Write BYTES bytes of the BUFFER into the STREAM. If
BYTES is not provided, then the whole BUFFER is written.
For some types of stream, it is legal to use a fractional number for BYTES. In that case,
the whole bytes are written first, and then the leftover bits. The leftover bits must be given
their own byte at the end of the BUFFER. WRITE-BYTES assumes that all bytes are 8 bits long,
so to write 4 bits, you would give 1/2 as the value of BYTES.
NOTE: If you're using this with a bit-stream created with WRAP-IN-BIT-STREAM, the
:BYTE-ORDER given to that function should match the one given to this function."))
(defmethod write-bytes (buffer stream &optional bytes)
(setf bytes (or bytes (length buffer)))
(check-type bytes integer)
(write-sequence buffer stream :end bytes)
(length buffer))
(defgeneric read-bytes (n stream &key element-type)
(:documentation "Read N bytes of type ELEMENT-TYPE from STREAM and return them in a newly-allocated array.
Returns two values: The array containing the bytes, and the number of bytes read.
For some types of stream, it is legal to use a fractional number for N. In that case,
the whole bytes are read first, and then the leftover bits. The leftover bits are given
their own byte at the end of the returned array. The second return value (# of bytes read)
will also be fractional in this case. The fractional part can be used to calculate
how many bits the partial byte represents.
If you're using 8-bit bytes and want to read 11 bits (a whole byte plus three bits), give
11/8 as the value of N.
NOTE: If you're using this with a bit-stream created with WRAP-IN-BIT-STREAM, the :BYTE-ORDER given
to that function should match the one given to this function."))
(defmethod read-bytes (n stream &key (element-type '(unsigned-byte 8)))
(let* ((result (make-array n :element-type element-type))
(bytes-read (read-sequence result stream)))
(when (< bytes-read n)
(restart-case
(cerror "Ignore the error and proceed as if the remaining bytes were zeroes"
(make-condition 'end-of-file :stream stream))
(return-subseq ()
:report "Return a short array containing only the bytes read"
(setf result (subseq result 0 bytes-read)))))
(values result bytes-read)))
(defun write-integer (number size stream &key (byte-order :little-endian)
(signed-representation :twos-complement)
signed)
(when signed
(setf number (signed->unsigned number size signed-representation)))
(cond ((integerp size)
(write-bytes (ecase byte-order
((:big-endian) (encode-msb number size))
((:little-endian) (encode-lsb number size))
(otherwise (error "Invalid byte order: ~a" byte-order)))
stream))
(t (let* ((whole-bytes (floor size))
(too-big (funcall ;; TOO-BIG encodes the integer to be written with one more
;; byte for the fractional part.
(ecase byte-order
(:big-endian #'encode-msb)
(:little-endian #'encode-lsb))
number (1+ whole-bytes))))
(write-bytes too-big stream size)))))
(defmacro tlabels (labels &body body)
`(labels ,(loop for (name args . bod) in labels
for gs = (gensym)
collect `(,name ,args
(let ((,gs (progn ,@bod)))
(format t "~s returned ~s~%"
(list ',name ,@args)
,gs)
,gs)))
,@body))
(defmacro tif (expr if-t if-nil)
(let ((expr* (gensym))
(res (gensym)))
`(let ((,expr* ,expr))
(if ,expr*
(let ((,res ,if-t))
(format t "IF condition: ~s~%Test result: TRUE~%Value: ~S~%"
,expr* ,res)
,res)
(let ((,res ,if-nil))
(format t "IF condition: ~s~%Test result: FALSE~%Value: ~S~%"
,expr* ,res)
,res)))))
(defun ash* (&rest integers)
(apply #'ash integers))
(defun logior* (&rest args)
(apply #'logior args))
(defun read-integer (length stream &key (byte-order :little-endian)
signed
(signed-representation :twos-complement))
"Reads an integer of LENGTH bytes from the STREAM in the specified BYTE-ORDER.
If SIGNED is non-NIL, the number is interpreted as being in two's complement format.
If the STREAM is a BIT-STREAM, then the LENGTH doesn't have to be an integer."
(multiple-value-bind (bytes bytes-read) (read-bytes length stream)
(let ((bytes (if (integerp bytes-read)
bytes
(subseq bytes 0 (1- (length bytes)))))
(partial-byte (unless (integerp bytes-read)
(aref bytes (1- (length bytes)))))
(extra-bits (multiple-value-bind (whole frac) (floor bytes-read)
(declare (ignore whole))
(* frac 8))))
(labels ((add-extra-bits (int)
(if partial-byte
(ecase byte-order
(:big-endian
(logior
;; Note: SBCL 1.4.13.debian claims that both
;; calls to ASH are unreachable, and prints
;; the message "deleting unreachable code"
;; for them. Yet, I have confirmed through
;; extensive tracing that the code is
;; indeed executed, and removing it changes
;; the return value of READ-INTEGER in
;; the relevant case (where BIT-STREAMs are
;; involved)
(ash int extra-bits)
partial-byte))
(:little-endian
(logior
(ash partial-byte (* (floor length) 8))
int)))
int))
(decode-msb* (bytes)
(add-extra-bits
(decode-msb bytes)))
(decode-lsb* (bytes)
(add-extra-bits
(decode-lsb bytes))))
(declare (inline add-extra-bits decode-msb* decode-lsb*))
(values
(let ((result (case byte-order
((:big-endian) (decode-msb* bytes))
((:little-endian) (decode-lsb* bytes))
(otherwise (error "Invalid byte order: ~a" byte-order)))))
(if signed
(unsigned->signed result length :type signed-representation)
result))
bytes-read)))))
(defun split-bit-field (integer field-bits &optional field-signedness)
"Given the INTEGER, split it up as a bit field. The sizes and number of elements are given
by the FIELD-BITS parameter. If FIELD-SIGNEDNESS is specified, then it must be a list
that contains NIL for each element that will be interpreted as an unsigned integer,
and non-NIL for signed integers.
Example:
CL-USER> (split-bit-field #xffaaff '(8 8 8))
255
170
255
CL-USER>
Better performance could be acheived if INTEGER could be a FIXNUM, but it can't.
"
(declare (type integer integer)
(type list field-bits))
(setf field-signedness (reverse field-signedness))
(apply #'values
(reverse (loop for bits of-type (unsigned-byte 29) in (reverse field-bits)
for mask = (- (ash 1 bits)
1)
for signed = (pop field-signedness)
collect (let ((unsigned-result (logand mask integer)))
(if signed
(unsigned->signed/bits unsigned-result bits)
unsigned-result))
do (setf integer (ash integer (- bits)))))))
(defun join-field-bits (field-bits field-signedness field-values)
(let ((result 0))
(loop for (bits next-bits)
on field-bits
for value in field-values
for signed = (pop field-signedness)
do
(setf result
(logior result
(if signed
(signed->unsigned value (/ bits 8))
value)))
(when next-bits
(setf result (ash result next-bits))))
result))
(defmacro push-bits (n integer-size integer-place)
"Pushes N onto the front of INTEGER-PLACE,
the 'front' being defined as the MOST significant bits. The
INTEGER-SIZE specifies how many bits are already in the
INTEGER-PLACE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(integer-size-temp (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,integer-size-temp ,integer-size)
(,(car newval) (+ ,old-value (ash ,n ,integer-size-temp)))
,@(cdr newval))
,setter))))
(defmacro push-bits/le (n n-bits integer-place)
"Pushes N-BITS bits from N onto the front of INTEGER-PLACE,
the 'front' being defined as the LEAST significant bits. The
INTEGER-SIZE specifies how many bits are already in the
INTEGER-PLACE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(n-ones (gensym))
(n-bits-temp (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,(car newval) (+ (ash ,old-value ,n-bits-temp) (logand ,n ,n-ones)))
,@(cdr newval))
,setter))))
(defmacro pop-bits (n-bits integer-size integer-place)
"Pops the N most significant bits off the front of the INTEGER-PLACE and returns it.
INTEGER-SIZE is the number of unpopped bits in the integer."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym "OLD-VALUE-"))
(n-ones (gensym "N-ONES-"))
(integer-size-temp (gensym "INTEGER-SIZE-"))
(n-bits-temp (gensym "N-BITS-"))
(selected-bits (gensym "SELECTED-BITS-")))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,integer-size-temp ,integer-size)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,selected-bits (logand ,old-value (ash ,n-ones (- ,integer-size-temp ,n-bits-temp))))
(,(car newval) (- ,old-value ,selected-bits))
,@(cdr newval))
,setter
(ash ,selected-bits
(- (- ,integer-size-temp ,n-bits-temp)))))))
(defmacro pop-bits/le (n-bits integer-place)
"Pops the N LEAST significant bits off the front of the INTEGER-PLACE and returns it.
INTEGER-SIZE is the number of bits in the integer."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion integer-place)
(let ((old-value (gensym))
(n-ones (gensym))
(n-bits-temp (gensym))
(selected-bits (gensym)))
`(let* (,@(mapcar #'list dummies vals)
(,old-value ,getter)
(,n-bits-temp ,n-bits)
(,n-ones (1- (ash 1 ,n-bits-temp)))
(,selected-bits (logand ,old-value ,n-ones))
(,(car newval) (ash ,old-value (- ,n-bits-temp)))
,@(cdr newval))
,setter
,selected-bits))))
| 13,161 | Common Lisp | .lisp | 325 | 36.009231 | 108 | 0.678381 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | a5d04b4dac8ebd954c887780ebed3acf0a72f6df4afb61e6afbf058129fef296 | 2,347 | [
-1
] |
2,348 | types.lisp | j3pic_lisp-binary/types.lisp | (in-package :lisp-binary)
(define-lisp-binary-type type-info (type)
(if (gethash type *enum-definitions*)
(values 'symbol
`(read-enum ',type ,stream-symbol)
`(write-enum ',type ,name ,stream-symbol))
(values type
`(read-binary ',type ,stream-symbol)
`(write-binary ,name ,stream-symbol))))
(define-lisp-binary-type type-info (type &key reader writer (lisp-type t))
:where (eq type 'custom)
(documentation
(custom
"(CUSTOM &key reader writer (lisp-type t))
Specifies a slot of type LISP-TYPE that will be read by the provided
READER function and written with the provided WRITER function
The READER function must accept the lambda-list (STREAM), and its
argument will be the stream currently being read.
The WRITER function must accept the lambda-list (OBJECT STREAM), and
it is generally expected to write the OBJECT to the STREAM.
If these functions are specified as LAMBDA forms, then they will
be closures. The READER can expect every field that has been read
so far to be bound to their names, while the WRITER can expect
to be able to see all the slots in the struct being written.
Both functions are optional."))
(values lisp-type
(if reader
`(funcall ,reader ,stream-symbol)
'(values nil 0))
(if writer
`(funcall ,writer ,name ,stream-symbol)
'(progn 0))))
(define-lisp-binary-type type-info (type &key raw-type member-types)
:where (eq type 'bit-field)
(documentation
(bit-field
"(BIT-FIELD &key raw-type member-types)
NOTE: Direct use of this type by programs is deprecated. Instead,
just declare clusters of fields with (UNSIGNED-BYTE n) or (SIGNED-BYTE n)
without worrying if n is a whole number of bytes. The DEFBINARY macro
will combine them into BIT-FIELD fields as long as there is a combination of
fields that add up to a whole number of bytes.
Specifies that multiple values are to be OR'd into a single integer for serialization
purposes. The name of a slot of this type must be specified as a list of names,
one for each value in the bit field. :RAW-TYPE specifies the type of the single integer
into which everything is being stored, and must meet the following requirements:
1. Be of the form (UNSIGNED-BYTE n)
2. Where N is divisible by 8.
The :MEMBER-TYPES is an unevaluated list of types that must consist entirely of
(UNSIGNED-BYTE b) or (SIGNED-BYTE b) types. The Bs must add up to N above.
READ-BINARY will automatically separate the values in the bit field into their
slots, and WRITE-BINARY will automatically OR them back together.
The default value you specify for this field should be given as a list
of default values for each of the subfields."))
(let ((reader* nil)
(writer* nil))
(letf (((slot-value type-info 'type) raw-type))
(multiple-value-bind (real-raw-type reader writer)
(expand-defbinary-type-field type-info)
(declare (ignore writer))
(destructuring-case real-raw-type
((kwtype (type bits)) :where (and (eq type 'unsigned-byte)
(integerp bits)
(eq kwtype :type))
(let ((temp-var (gensym "TEMP-VAR-"))
(bytes-read (gensym "BYTES-READ-"))
(signedness nil)
(field-sizes nil))
(loop for (member-type bits) in member-types
do (push (eq member-type 'signed-byte)
signedness)
(push bits field-sizes))
(setf signedness (reverse signedness))
(setf field-sizes (reverse field-sizes))
(unless (= (apply #'+ field-sizes)
bits)
(error "Member types ~S don't add up to ~S bits~%"
member-types bits))
(setf reader*
;; FIXME: READER might not produce a BYTES-READ value if
;; it is supplied by the user via the :READER argument.
;; But it's unlikely that anyone will combine :READER
;; with BIT-FIELD.
`(multiple-value-bind (,temp-var ,bytes-read)
,reader
(incf ,byte-count-name ,bytes-read)
(split-bit-field ,temp-var (list ,@field-sizes)
',signedness)))
(setf writer*
`(write-integer (join-field-bits (list ,@field-sizes)
(list ,@signedness)
(list ,@name))
,(/ (apply #'+ field-sizes) 8)
,stream-symbol
:byte-order ,byte-order))
(cond ((eq byte-order '*byte-order*)
(setf reader* `(ecase *byte-order*
(:big-endian
(multiple-value-bind (,temp-var ,bytes-read)
,reader
(incf ,byte-count-name ,bytes-read)
(split-bit-field ,temp-var (list ,@field-sizes)
',signedness)))
(:little-endian
(multiple-value-bind (,temp-var ,bytes-read)
,reader
(incf ,byte-count-name ,bytes-read)
(split-bit-field ,temp-var (list ,@(reverse field-sizes))
',(reverse signedness))))))
(setf writer* `(ecase *byte-order*
(:little-endian
(write-integer
(join-field-bits (list ,@(reverse field-sizes))
(list ,@(reverse signedness))
(list ,@(reverse name)))
,(/ (apply #'+ field-sizes) 8)
,stream-symbol
:byte-order ,byte-order))
(:big-endian ,writer*))))
((eq byte-order :little-endian)
(setf reader*
`(multiple-value-bind (,temp-var ,bytes-read)
,reader
(incf ,byte-count-name ,bytes-read)
(split-bit-field ,temp-var (list ,@(reverse field-sizes))
',(reverse signedness))))
(setf writer*
`(write-integer
(join-field-bits (list ,@(reverse field-sizes))
(list ,@(reverse signedness))
(list ,@(reverse name)))
,(/ (apply #'+ field-sizes) 8)
,stream-symbol
:byte-order ,byte-order))))
(values member-types
reader* writer*)))
(otherwise
(error "Invalid BIT-FIELD :RAW-TYPE value: ~S" raw-type)))))))
(define-lisp-binary-type type-info (type)
:where (eq type 'base-pointer)
(documentation
(base-pointer "Instead of reading or writing this field, CL:FILE-POSITION will be called
on the current stream, and the address returned will be stored under a tag
with the same name as this slot. The tag can then be used to calculate
file positions and offsets. See the POINTER type for an example."))
(values t
`(let ((file-position (file-position ,stream-symbol)))
(add-base-pointer-tag ',name file-position)
(values file-position 0))
`(progn
(setf ,name (file-position ,stream-symbol))
(add-base-pointer-tag ',name ,name)
0)))
(define-lisp-binary-type type-info (type)
:where (eq type 'file-position)
(documentation
(file-position "FILE-POSITION
Like BASE-POINTER, but no global tag is stored. The slot will contain the
address in the file of the next thing to be read. No actual reading or
writing is triggered by a slot of this type.
"))
(values 'integer
`(values (file-position ,stream-symbol)
0)
`(progn (setf ,name (file-position ,stream-symbol))
0)))
(define-lisp-binary-type type-info (type &key base-pointer-name)
:where (eq type 'region-tag)
(documentation
(region-tag "(REGION-TAG &key base-pointer-name)
Instead of writing the value of this slot, all POINTERs that have the same
REGION-TAG name as this slot will be written out here, and the corresponding
offsets will be updated. The file being written must be opened with
:DIRECTION :IO. The POINTERs themselves will be written as offsets from
whatever object has the BASE-POINTER named BASE-POINTER-NAME."))
(push name *ignore-on-write*)
(values t
`(values nil 0)
`(dump-tag ',name ,(if base-pointer-name
`(get-base-pointer-tag ',base-pointer-name)
0)
,stream-symbol)))
(define-lisp-binary-type type-info (type &key pointer-type data-type base-pointer-name region-tag validator)
:where (eq type 'pointer)
(documentation
(pointer "(POINTER &key pointer-type data-type base-pointer-name region-tag)
Specifies that the value is really a pointer to another value somewhere else
in the file. When reading, if a BASE-POINTER-NAME is supplied and a base-pointer
tag has been created, then the pointer will be treated as an offset from that
base-pointer. If no BASE-POINTER-NAME is provided, then the pointer is treated
as being an absolute file-position.
The :POINTER-TYPE key specifies the type of the pointer itself, and must be some kind
of integer.
The :DATA-TYPE specifies the data that is being pointed to.
The :REGION-TAG is used when writing. When WRITE-BINARY writes this field, what
it really does is just write a zero pointer (since the object being pointed to
proably occurs later in the file, so we don't know what the address is going to
be yet). Then WRITE-BINARY stores the address OF THE POINTER, along with a
serialized representation of the data to be written.
When any WRITE-BINARY method gets to a REGION-TAG field, it writes out all the data
that has been stored under that tag's name, and goes back to update the pointers.
POINTERs cannot be automatically written if they point to an earlier part of the file
than they themselves occur (no backwards-pointing pointers).
Because it must go back and change what it has previously written, the stream must
be opened with :DIRECTION :IO.
All I/O involving POINTERs, REGION-TAGs, or BASE-POINTERs should be performed
within a WITH-LOCAL-POINTER-RESOLVING-CONTEXT block.
Example:
(defbinary bar ()
(pointer-1 nil :type (pointer :pointer-type (unsigned-byte 16)
:data-type (terminated-string 1)
:base-pointer-name foo-base
:region-tag foo-region))
(pointer-2 0 :type (pointer :pointer-type (unsigned-byte 16)
:data-type quadruple-float
:base-pointer-name foo-base
:region-tag foo-region)))
(defbinary foo ()
(foo-base 0 :type base-pointer)
(bar nil :type bar)
;; POINTER-1 and POINTER-2 will point to this:
(foo-region nil :type (region-tag :base-pointer-name foo-base)))
(with-local-pointer-resolving-context
(let ((input (with-open-binary-file (in \"foo.bin\")
(read-binary 'foo in))))
(with-open-binary-file (out \"bar.bin\"
:direction :io)
(write-binary input stream))))
"))
(block nil
(letf (((slot-value type-info 'type) pointer-type))
(multiple-value-bind (pointer-defstruct-type pointer-reader pointer-writer)
(expand-defbinary-type-field type-info)
(declare (ignore pointer-defstruct-type)
(optimize (speed 0) (debug 3)))
(letf (((slot-value type-info 'type) data-type))
(multiple-value-bind (defstruct-type data-reader data-writer)
(expand-defbinary-type-field type-info)
(values (getf defstruct-type :type)
(alexandria:with-gensyms (pointer-value base-pointer-address pointer-bytes-read
pbr2 pv2)
`(let* ((,pointer-bytes-read nil)
(,base-pointer-address ,(if base-pointer-name
`(get-base-pointer-tag ',base-pointer-name)
0))
(,pointer-value (+ ,base-pointer-address
(multiple-value-bind (,pv2 ,pbr2)
,pointer-reader
(setf ,pointer-bytes-read ,pbr2)
,pv2))))
(restart-case
(progn
,@(if validator
`((funcall ,validator ,pointer-value)))
(with-file-position (,pointer-value ,stream-symbol)
(values ,data-reader ,pointer-bytes-read)))
(use-value (value)
:report ,(format nil "Provide a value of type ~S" data-type)
:interactive (lambda ()
(format t "Enter a value of type ~S: " ',data-type)
(force-output)
(list (eval (read))))
(values value 0)))))
(alexandria:with-gensyms (write-data write-pointer pointer-position)
`(let ((,name ,name))
(flet ((,write-data (,stream-symbol) ,data-writer)
(,write-pointer (,name ,stream-symbol) ,pointer-writer))
(queue-write-pointer ',region-tag
(let ((,pointer-position (file-position ,stream-symbol)))
(lambda (,name ,stream-symbol)
(with-file-position (,pointer-position ,stream-symbol)
(,write-pointer ,name ,stream-symbol))))
#',write-data)
(,write-pointer 0 ,stream-symbol)))))))))))
(define-lisp-binary-type type-info (type &key (actual-type '(unsigned-byte 16)) (value 0))
:where (eq type 'magic)
(documentation
(magic "(MAGIC &key actual-type value)
Specifies that a magic value will be read and written. The value will be
read as type ACTUAL-TYPE.
If the value read is not CL:EQUAL to the VALUE given, then a condition of type
BAD-MAGIC-VALUE will be raised.
A BAD-MAGIC-VALUE object contains the slots BAD-VALUE and REQUIRED-VALUE.
The error can be ignored by invoking the CL:CONTINUE restart."))
(if (and (listp actual-type)
(eq (car actual-type) 'quote))
(restart-case
(error ":ACTUAL-TYPE ~S should not be quoted" actual-type)
(unquote-it ()
:report "Well, unquote it, then!"
(setf actual-type (cadr actual-type)))))
(letf (((slot-value type-info 'type)
actual-type))
(multiple-value-bind (defstruct-type reader writer)
(expand-defbinary-type-field type-info)
(values
(getf defstruct-type :type)
(let ((v (gensym "READER-"))
(bytes-read (gensym "BYTES-READ-"))
(required-value (gensym "REQUIRED-VALUE-")))
`(let ((,required-value ,value))
(multiple-value-bind (,v ,bytes-read) ,reader
(unless (equal ,v ,required-value)
(restart-case
(error 'bad-magic-value :bad-value ,v
:required-value ,required-value
:format-control
"Invalid magic number: ~a (expected: ~a)~%"
:format-arguments (list ,v ,required-value))
(continue ()
:report "Ignore the error and continue loading"
nil)))
(values ,v ,bytes-read))))
`(progn
(setf ,name ,value)
,writer)))))
(define-lisp-binary-type type-info (type length &key (external-format :latin1) (padding-character #\Nul))
:where (member type '(fixed-length-string fixed-string))
(documentation
((fixed-length-string fixed-string)
"(FIXED-LENGTH-STRING length &key (external-format :latin1) (padding-character #\Nul))
Specifies a string of fixed length. When writing, any excess space
in the string will be padded with the PADDING-CHARACTER. The LENGTH is the
number of bytes desired after encoding.
If the input string is longer than the provided LENGTH, a condition of type
LISP-BINARY:INPUT-STRING-TOO-LONG will be raised. Invoke the restart CL:TRUNCATE
to trim enough excess characters from the string to make it equal to the LENGTH."))
(values 'string
(let ((bytes (gensym "BYTES-"))
(bytes* (gensym "BYTES*-"))
(buffer (gensym "BUFFER-")))
`(let ((,bytes nil))
(values
(string-right-trim
(list ,padding-character)
(octets-to-string
(multiple-value-bind (,buffer ,bytes*)
(read-bytes ,length ,stream-symbol)
(setf ,bytes ,bytes*)
,buffer)
:external-format ,external-format))
,bytes)))
`(write-bytes
(make-fixed-length-string ,name ,length ,external-format ,padding-character)
,stream-symbol)))
(define-lisp-binary-type type-info (type count-size &key (external-format :latin1))
:where (member type '(counted-string counted-buffer))
(documentation
((counted-string counted-buffer)
"(COUNTED-STRING count-size-in-bytes &key (EXTERNAL-FORMAT :latin1))
(COUNTED-BUFFER count-size-in-bytes)
These are like COUNTED-ARRAYS, but their elements are one byte long. Furthermore, a
COUNTED-STRING will be encoded or decoded into a Lisp string according to its EXTERNAL-FORMAT.
The encoding/decoding is done using the FLEXI-STREAMS library, and valid EXTERNAL-FORMATs are those
that are accepted by FLEXI-STREAMS:OCTETS-TO-STRING.
Example:
(defbinary foobar ()
(str \"\" :type (counted-string 2 :external-format :utf8)))"))
(values (ecase type
((counted-string) 'string)
((counted-buffer) '(simple-array (unsigned-byte 8))))
(let ((read-form `(read-counted-string ,count-size ,stream-symbol
:byte-order ,byte-order)))
(ecase type
((counted-string) (alexandria:with-gensyms (value bytes)
`(multiple-value-bind (,value ,bytes) ,read-form
(values
(octets-to-string ,value :external-format ,external-format)
,bytes))))
((counted-buffer) read-form)))
`(write-counted-string ,count-size ,stream-symbol
,(ecase type
((counted-string)
`(string-to-octets ,name :external-format ,external-format))
((counted-buffer)
name))
:byte-order ,byte-order)))
(define-lisp-binary-type type-info (counted-array count-size element-type &key bind-index-to)
:where (eq counted-array 'counted-array)
(documentation
(counted-array
"(COUNTED-ARRAY count-size-in-bytes element-type &key bind-index-to)
This is a SIMPLE-ARRAY preceded by an integer specifying how many
elements are in it.
Example:
(read-binary-type '(counted-array 2 (unsigned-byte 8)) stream)
The COUNT-SIZE-IN-BYTES does not have to be an integer. It can also be a
fraction, which will trigger non-byte-aligned I/O. (example, if the size is 1/2, then the count
is 4 bits wide, and the first element begins halfway into the same byte as the count) The
ELEMENT-TYPE can also be non-byte-aligned. Such a type can only be read from or written
to a BIT-STREAM.
See also: WITH-WRAPPED-IN-BIT-STREAM"))
(let ((count-size* (gensym "COUNT-SIZE-"))
(reader-value (gensym "READER-VALUE-"))
(reader-byte-count (gensym "READER-BYTE-COUNT-")))
(letf (((slot-value type-info 'type)
`(simple-array ,element-type ((read-integer ,count-size* ,stream-symbol :byte-order ,byte-order))
,@(if bind-index-to
`(:bind-index-to ,bind-index-to)))))
(multiple-value-bind (defstruct-type reader writer)
(expand-defbinary-type-field type-info)
(setf writer `(let ((,count-size* ,count-size))
(+
(write-integer (length ,name) ,count-size* ,stream-symbol :byte-order ,byte-order)
,writer)))
(setf reader `(let ((,count-size* ,count-size))
(multiple-value-bind (,reader-value ,reader-byte-count) ,reader
(values ,reader-value (+ ,count-size* ,reader-byte-count)))))
(values (getf defstruct-type :type) reader writer)))))
(define-lisp-binary-type type-info (simple-array type lengths &key bind-index-to)
:where (member simple-array '(simple-array))
(documentation
(simple-array "(SIMPLE-ARRAY element-type (size))
Example:
(defbinary foobar ()
(size 0 :type (unsigned-byte 16))
(arr #() :type (simple-array (unsigned-byte 8) (size))))
For the element type, any real or virtual type supported by DEFBINARY is allowed.
The SIZE is a Lisp expression that will be evaluated in an environment where all
previous members of the struct are bound to their names.
DEFBINARY will read and write all other CL objects using their READ-BINARY and
WRITE-BINARY methods, if defined."))
(let ((array-count-size nil)
(reader* nil)
(writer* nil))
(unless (listp lengths)
(restart-case
(error "Invalid simple-array type (~a ~a ~a): ~a should be a list."
simple-array type lengths lengths)
(dwim ()
:report "Assume a one-dimensional array."
(setf lengths (list lengths)))))
(unless (= (length lengths) 1)
(error "Invalid simple-array type (SIMPLE-ARRAY ~a ~a): DEFBINARY only supports 1-dimensional arrays."
type lengths))
(let ((length (car lengths))
(name-one (gensym "NAME-ONE-"))
(buffer (gensym "BUFFER-"))
(next-value (gensym "NEXT-VALUE-"))
(bytes (gensym "BYTES-"))
(local-byte-count (gensym "LOCAL-BYTE-COUNT-"))
(ix (gensym "IX-")))
(flet ((maybe-add-align (form readp)
(let ((move-op (if readp
'#'read-bytes
'(lambda (bytes stream)
(loop repeat bytes
do (write-byte 0 stream))))))
(if element-align
`(progn (incf ,local-byte-count (align-to-boundary (+ ,byte-count-name ,local-byte-count)
,element-align ,move-op ,stream-symbol))
,form)
form)))
(maybe-bind-index (form)
(if bind-index-to
`(let ((,bind-index-to ,ix))
(declare (ignorable ,bind-index-to))
,form)
form)))
;; Turn alignment off for subtypes. That way if we're reading an
;; array of array, our alignment doesn't spread to the next level down.
;; For example, if ELEMENT-ALIGN is 64 right now and we're reading an
;; array of strings, that means that each string is meant to be 64-byte
;; aligned. If the alignment is passed further down, each CHARACTER will
;; be 64-byte aligned.
(letf (((slot-value type-info 'align) nil)
((slot-value type-info 'element-align) nil)
((slot-value type-info 'type) type)
((slot-value type-info 'byte-count-name) local-byte-count)
((slot-value type-info 'name) name-one))
(multiple-value-bind (defstruct-type read-one write-one)
(expand-defbinary-type-field type-info)
(setf reader*
`(let ((,buffer (make-array ,length :element-type ',(cadr defstruct-type)))
(,local-byte-count 0))
;; FIXME: This code needs to be adapted to support
;; terminated arrays. The only difference
;; in the terminated case is that the loop
;; termination condition would be based on
;; a predicate instead of the length of the
;; buffer. The problem is there's no good
;; way to tell this code to expand the
;; terminated case instead of the fixed-length
;; case.
;;
;; It would also be useful if this code could have a
;; third case in which it somehow produced a lazy
;; sequence instead of an array. Specifically, this
;; would be applicable to cases where data should
;; be handled in a streaming manner. Then, client
;; code would only need to force each next element
;; when needed, and it would be read at that time.
;;
;; Ideally, the decision about whether to read in
;; a streaming fashion or all at once could be made
;; at runtime. That would require a totally different
;; expansion here.
;;
;; NOTE: Do not use CLAZY to implement lazy lists.
;; This library is incredibly SLOW! Perhaps
;; this is an inherent property of the whole
;; delay/force paradigm.
;;
;; In fact, ANY SRFI-41-like stream facility
;; in which promises are implemented as
;; closures will have the same performance
;; problems in SBCL, which is supposed to be
;; the fastest Lisp.
;;
;; Better to implement the stream as a closure
;; that simply closes over the file stream,
;; and reads one element each time it's called.
;;
;; NOTE2: Racket's implementation of SRFI-41 streams
;; is very fast. I wonder what the difference is?
;;
;; NOTE3: My CL implementation of SRFI-41 ported to
;; Racket is very fast, even though I copy
;; the use of closures to implement promises!
;; WTF?! The difference is entirely in GC time.
;;
;; NOTE4: Creating a simple one-closure counter is
;; far more efficient than creating a lazy
;; infinite sequence that creates a new closure with
;; each new number generated.
;;
(loop for ,ix from 0 below ,(if array-count-size
`(multiple-value-bind (array-size bytes-read)
(read-integer ,array-count-size ,stream-symbol
:byte-order ,byte-order)
(incf ,local-byte-count bytes-read)
array-size)
`(length ,buffer)) do
(multiple-value-bind (,next-value ,bytes)
(restart-case
,(maybe-bind-index (maybe-add-align read-one t))
(use-value (val)
:report ,(format nil "Enter a new value for the next element of ~a" name)
:interactive (lambda ()
(format t "Enter a new value of type ~a (evaluated): " ',(cadr defstruct-type))
(list (eval (read))))
(values val 1)))
(setf (aref ,buffer ,ix) ,next-value)
(incf ,local-byte-count ,bytes)))
(values ,buffer ,local-byte-count)))
(setf writer*
`(let ((,local-byte-count 0))
(loop for ,ix from 0 below (length ,name)
do (incf ,local-byte-count ,(maybe-bind-index
(maybe-add-align
`(symbol-macrolet ((,name-one (aref ,name ,ix))) ,write-one) nil))))
,local-byte-count))
(values `(simple-array ,(cadr defstruct-type))
reader* writer*)))))))
(define-lisp-binary-type type-info (type-name type-generating-form)
:where (eq type-name 'eval)
(documentation
(eval "(EVAL unquoted-type-expression)
The EVAL type specifier causes the type to be computed at runtime. The
UNQUOTED-TYPE-EXPRESSION will be evaluated just before attempting to read
the field of this type in an environment where all the previously-defined
fields are bound to their names.
Example:
(defbinary foobar ()
(type-tag 0 :type (unsigned-byte 32))
(data nil :type (eval
(case type-tag
(1 '(unsigned-byte 16))
(2 '(counted-string 1 :external-format :utf-8))))))
In the above example, READ-BINARY will first read the TYPE-TAG as an
(UNSIGNED-BYTE 32), then it will evaluate the CASE expression in order to
get the type of the DATA. Then, because of a special optimization that has
been applied to this type when a CASE form is presented to it, the bodies
of the cases are evaluated at macro-expansion time, and their values
used to generate the code to read and write the corresponding types. A
similar case form is compiled into the READ-BINARY and WRITE-BINARY
methods, with the types being replaced by reader or writer code. If this
mechanism fails, a fallback mechanism, described below, is used.
The following forms support this optimization:
case ecase typecase etypecase cond
If any other form is provided, then the EVAL expander resorts to its
default behavior, which is to pass whatever type is produced by the form
to an internal function in order to generate the code that will be used
to perform the reading or writing, and then to EVAL the resulting form.
The same thing happens if any of the bodies of the cases signals a
condition at macro expansion time, which could be an indication that
the case bodies require information that is only available at runtime.
The CASE expression is not actually evaluated with a runtime call
to EVAL. Instead, it is embedded directly in the source code of the
generated READ-BINARY and WRITE-BINARY methods.
If the UNQUOTED-TYPE-EXPRESSION evaluates to another EVAL type specifier,
then that specifier will be expanded once again. The EVAL expander
tries to be as smart as possible to avoid actually calling EVAL at
runtime, but sometimes it's unavoidable.
"))
(let ((case-template nil)
(readers nil)
(writers nil))
;; The following implements an optimization for a common case:
;; If the EVAL expression is a CASE, ECASE, TYPECASE, or ETYPECASE,
;; it may be possible to replace the types that these forms return
;; with the reader/writer code that each type would expand to. For
;; example, if you specify this type:
;;
;; (eval (case foo
;; (1 'counted-string)
;; (2 '(unsigned-byte 16))))
;;
;; ...without the optimization, it would expand to:
;;
;; Reader: (read-binary-type (case foo ...))
;; Writer: (write-binary-type (case foo ...))
;;
;; ...and then at runtime, READ-BINARY-TYPE/WRITE-BINARY-TYPE will
;; create a reader or writer form from the type and EVAL it.
;;
;; But with the optimization, the CASE form expands to:
;;
;; Reader: (case foo
;; (1 (read-binary 'counted-string #:stream-symbol))
;; (2 (read-integer 2 #:stream-symbol :byte-order :little-endian
;; :signed nil :signed-representation :twos-complement)))
;; Writer: (case foo
;; (1 (write-binary bar #:stream-symbol))
;; (2 (write-integer bar 2 #:stream-symbol :byte-order ...)))
;;
;; ...which skips the runtime EVAL and is therefore more efficient.
(setf case-template
(block make-case-template
(if (member (car type-generating-form) '(case ecase typecase etypecase cond))
`(,(first type-generating-form)
,(second type-generating-form)
,@(loop for (case . body) in (cddr type-generating-form)
collect (handler-case
(letf (((slot-value type-info 'type)
(eval `(progn ,@body))))
(multiple-value-bind (type reader writer)
(expand-defbinary-type-field type-info)
(declare (ignore type))
(let ((placeholder (gensym)))
(push (cons placeholder reader) readers)
(push (cons placeholder writer) writers)
(list case placeholder))))
(t ()
;; Most likely error: The form in question has something in
;; it that would only work with an EVAL at read or write time,
;; not at compile time. So we just return the unoptimized FORM,
;; then.
(return-from make-case-template nil))))))))
(labels ((fill-template (expansions)
(list* (first case-template)
(second case-template)
(loop for (case placeholder) in (cddr case-template)
collect (list case (cdr (assoc placeholder expansions)))))))
(if case-template
(values t (fill-template readers) (fill-template writers))
(values
t
`(read-binary-type ,type-generating-form ,stream-symbol :byte-order ,byte-order
:align ,align :element-align ,element-align)
`(write-binary-type ,name ,type-generating-form ,stream-symbol
:byte-order ,byte-order :align ,align
:element-align ,element-align))))))
(define-lisp-binary-type type-info (byte-type bits &key (signed-representation :twos-complement))
:where (member byte-type '(unsigned-byte signed-byte))
(documentation
((unsigned-byte signed-byte)
"(UNSIGNED-BYTE n) and (SIGNED-BYTE n &key (signed-representation :twos-complement),
where N is the number of bits. Since these types are used so frequently in DEFBINARY
structs, there is a shorthand for them: You can simply use the number of bits as the
type. Positive for unsigned, and negative for signed (two's complement only).
Example:
(defbinary foobar ()
(x 0 :type 16) ;; 16-bit unsigned
(y 1 :type -16)) ;; 16-bit signed
If you need to read one's complement, it must be written out:
(defbinary foobar ()
(x 0 :type (signed-byte 16 :signed-representation :ones-complement)))"))
(values `(,byte-type ,bits)
`(read-integer ,(/ bits 8) ,stream-symbol
:byte-order ,byte-order
:signed ,(eq byte-type 'signed-byte)
:signed-representation ,signed-representation)
`(write-integer ,name ,(/ bits 8) ,stream-symbol
:byte-order ,byte-order
:signed-representation ,signed-representation
:signed ,(eq byte-type 'signed-byte))))
(define-lisp-binary-type type-info (float-type &key (byte-order byte-order))
:where (member float-type '(float single-float half-float double-float quadruple-float quad-float
octuple-float octo-float))
(documentation
((float single-float)
"IEEE Single Precision")
(double-float "IEEE Double Precision")
(half-float "Read and written as IEEE half-precision, stored in memory as single-precision")
((quadruple-float quad-float)
"Read and written as IEEE quadruple precision, stored in memory as CL:RATIONAL
to avoid loss of prcision.")
((octuple-float octo-float)
"Read and written as IEEE octuple precision, stored in memory as CL:RATIONAL
to avoid loss of precision."))
(let ((float-format (case float-type
(half-float :half)
((float single-float) :single)
(double-float :double)
((quadruple-float quad-float) :quadruple)
((octuple-float octo-float) :octuple)))
(float-type (case float-type
((float single-float double-float)
float-type)
(half 'single-float)
#+clisp ((quadruple-float quad-float
octuple-float octo-float) 'long-float)
(otherwise 'number))))
(values float-type
`(read-float ,float-format :stream ,stream-symbol :byte-order ,byte-order
:result-type ',float-type)
`(write-float ,float-format ,name :stream ,stream-symbol
:byte-order ,byte-order))))
(define-lisp-binary-type type-info (null-type)
:where (eq null-type 'null)
(documentation
(null "Reading and writing will be a no-op. The value of a field of type NULL will always read
as NIL and be ignored when writing."))
(values 'null
`(progn (values nil 0))
`(progn 0)))
(define-lisp-binary-type type-info (type termination-length &key (external-format :latin1) (terminator 0))
:where (member type '(terminated-string terminated-buffer))
(documentation
((terminated-string terminated-buffer)
"(TERMINATED-STRING termination-length &key (terminator 0) (extenal-format :latin1))
(TERMINATED-BUFFER termination-length &key (terminator 0))
Specifies a C-style terminated string. The TERMINATOR is an integer that will be en/decoded
according to the field's BYTE-ORDER. As such, it is capable of being more than one byte long,
so it can be used to specify multi-character terminators such as CRLF."))
(let ((real-terminator `(ecase ,byte-order
((:little-endian) (encode-lsb (or ,terminator 0) ,termination-length))
((:big-endian) (encode-msb (or ,terminator 0) ,termination-length)))))
(let ((reader `(read-terminated-string ,stream-symbol :terminator ,real-terminator))
(name (ecase type
((terminated-string) `(string-to-octets ,name :external-format ,external-format))
((terminated-buffer) name))))
(if (eq type 'terminated-string)
(setf reader `(read-octets-to-string ,reader :external-format ,external-format)))
(values
(ecase type
((terminated-string) 'string)
((terminated-buffer) '(simple-array (unsigned-byte 8))))
reader
`(write-terminated-string ,name ,stream-symbol :terminator ,real-terminator)))))
(define-lisp-binary-type type-info (type)
:where (integerp type)
;; Let a positive numeric type n be shorthand for (unsigned-byte n),
;; and a negative one be shorthand for (signed-byte -n).
(setf (slot-value type-info 'type)
(cond ((> type 0)
`(unsigned-byte ,type))
((< type 0)
`(signed-byte ,(- type)))
(t (restart-case
(error "0 is not a valid type.")
(unsigned-byte-8 ()
:report "Use (UNSIGNED-BYTE 8)"
'(unsigned-byte 8))
(signed-byte-8 ()
:report "Use (SIGNED-BYTE 8)"
'(signed-byte 8))
(specify (new-type)
:report "Specify a type to use."
:interactive (lambda ()
(format t "Specify a type to use (unevaluated): ")
(force-output)
(list (read)))
new-type)))))
(multiple-value-bind (defstruct-type reader writer)
(expand-defbinary-type-field type-info)
(values (getf defstruct-type :type) reader writer)))
| 35,602 | Common Lisp | .lisp | 778 | 39.755784 | 122 | 0.670614 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 29aa6725cbb8fba8bc57d637ef82206a2b4c5131c7831bd99a74706fc4266826 | 2,348 | [
-1
] |
2,349 | float.lisp | j3pic_lisp-binary/float.lisp | (defpackage :lisp-binary/float
(:use :common-lisp :lisp-binary/integer)
(:export :decode-float-bits :encode-float-bits :read-float :write-float :nanp :infinityp
:+inf :-inf :quiet-nan :signalling-nan))
(in-package :lisp-binary/float)
(declaim (optimize (debug 0) (speed 3)))
;; Support actual NaNs and infinities on
;; Lisp implementations that support them.
;; Use keywords to represent them on
;; implementations that don't. Doubles
;; are preferred because some functions
;; need to detect NaN and infinity via
;; the C functions, which only accept
;; doubles (and CFFI doesn't do automatic
;; type promotion like the C compiler does).
;; It would be neat to test for these features
;; instead of relying on implementation names,
;; but unfortunately, some implementations actually
;; crash or hang when trying to evaluate NaNs or
;; infinities, so the tests would crash Lisp
;; instead of failing gracefully.
(eval-when (:compile-toplevel :load-toplevel :execute)
#+(and (or sbcl ccl)
cffi)
(progn
(pushnew :float-infinity *features*)
(pushnew :float-quiet-nan *features*)))
;; Don't make these constants. Floating point arithmetic errors
;; were seen at COMPILE TIME in SBCL.
(defvar +inf
#+(and float-infinity
(not ccl))
(let ((x 9218868437227405312))
(cffi:with-foreign-object (ptr :uint64)
(setf (cffi:mem-ref ptr :uint64) x)
(cffi:mem-ref ptr :double)))
#+ccl 1d++0
#-float-infinity :+inf)
(defvar -inf
#+(and float-infinity
(not ccl))
(let ((x 18442240474082181120))
(cffi:with-foreign-object (ptr :uint64)
(setf (cffi:mem-ref ptr :uint64) x)
(cffi:mem-ref ptr :double)))
#+ccl -1d++0
#-float-infinity :-inf)
;; This is treated as a signalling NaN in CLISP,
;; and thus cannot be evaluated without raising
;; a condition:
(defvar quiet-nan
#+(and float-quiet-nan
(not ccl))
(let ((x 9221120237041090560))
(cffi:with-foreign-object (ptr :uint64)
(setf (cffi:mem-ref ptr :uint64) x)
(cffi:mem-ref ptr :double)))
#+ccl 1d+-0
#-float-quiet-nan
:quiet-nan)
;; SBCL can't represent a Signalling NaN. Attempting
;; to evaluate this causes it to hang. CCL throws
;; an exception when trying to generate it, and
;; so does CLISP.
(defvar signalling-nan
#+float-signalling-nan
(let ((x 9219994337134247936))
(cffi:with-foreign-object (ptr :uint64)
(setf (cffi:mem-ref ptr :uint64) x)
(cffi:mem-ref ptr :double)))
#-float-signalling-nan :signalling-nan)
(defun float-value (sign significand exponent &optional (base 2))
"Given the decoded parameters of a floating-point number,
calculate its numerical value."
(* (expt -1 sign)
significand
(expt base exponent)))
(defun calculate-exponent (sign fraction)
(coerce (floor
(/ (log (* fraction (expt -1 sign)))
(log 2)))
'integer))
(defmacro popbit (place)
`(prog1 (logand ,place 1)
(setf ,place (ash ,place -1))))
(defun nanp (decoded-value)
(or #-float-signalling-nan
(eq decoded-value :signalling-nan)
#-float-quiet-nan
(eq decoded-value :quiet-nan)
#+(or float-signalling-nan float-quiet-nan)
(/= (cffi:foreign-funcall #+win32 "_isnan" #-win32 "isnan" :double (coerce decoded-value 'double-float) :int) 0)))
(defun infinityp (decoded-value)
"Returns two values:
T if the DECODED-VALUE represents a floating-point infinity
T if the DECODED-VALUE represents positive infinity, or NIL if it's negative infinity.
Some Lisp implementations support real floating-point infinities, but the ANSI standard does
not require it, and some Lisp implementations don't bother to support them. On those implementations,
infinities are represented by the keywords :+INF and :-INF. To detect positive/negative infinity portably,
use this function."
#-float-infinity
(case decoded-value
(:+inf (values t t))
(:-inf (values t nil))
(otherwise nil))
#+float-infinity
(and (not (nanp decoded-value))
(values #-win32(/= (cffi:foreign-funcall "isinf" :double (coerce decoded-value 'double-float) :int)
0)
#+win32 (= (cffi:foreign-funcall "_finite" :double (coerce decoded-value 'double-float) :int))
(> decoded-value 0))))
(defun float-coerce (value result-type)
"Coerce the VALUE to the RESULT-TYPE, taking into account the fact that values
generated by this library are not always actually numbers. So on Lisp systems that
don't support infinity, (FLOAT-COERCE :+INF 'DOUBLE-FLOAT) will actually leave it
alone.
Also takes into account the fact that even on Lisps that do support infinities and NaNs,
you can't coerce them to non-floating-point numbers, so it passes infinities and NaNs
through untouched if the RESULT-TYPE isn't floating-point.
There should never be an error as a result of trying to decode a floating-point bit pattern
to a number."
#+(and float-infinity float-quiet-nan float-signalling-nan)
(when (member result-type '(float single-float double-float))
(return-from float-coerce
(coerce value result-type)))
(cond ((infinityp value)
#-float-infinity
value
#+float-infinity
(if (member result-type '(float single-float double-float))
(coerce value result-type)
value))
((nanp value)
value)
(t (handler-case (coerce value result-type)
#+clisp
(system::simple-floating-point-underflow ()
value)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
;; Syntax:
;; (:name significand-bits-with-implicit-bit exponent-bits exponent-bias)
(defvar *format-table*
'((:half 11 5 15)
(:single 24 8 127)
(:double 53 11 1023)
(:quadruple 113 15 16383)
(:octuple 237 19 262143)))
(defun get-format (format)
(or (assoc format *format-table*)
(restart-case
(error "Unknown floating-point format ~a" format)
(use-value (new-format)
:report "Enter a different format to use"
:interactive (lambda ()
(format t "Supported formats:~%~%")
(loop for (format) in *format-table*
do (format t " ~s~%" format))
(terpri)
(format t "Format to use (unevaluated): ")
(force-output)
(list (read)))
(get-format new-format)))))
(defun format-size (format)
"Returns the size in bytes of a given floating-point format."
(destructuring-bind (format some-bits more-bits who-cares)
(get-format format)
(declare (ignore format who-cares))
(/ (+ some-bits more-bits) 8))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro decode-float-bits/arithmetic-macro (integer &key (format :single) (result-type ''single-float))
(alexandria:with-gensyms (runtime-format result-type* integer* significand-bits exponent-bits exponent-bias temp-result)
`(let ((,result-type* ,result-type)
(,integer* ,integer))
,(cond ((keywordp format)
(destructuring-bind (format significand-bits exponent-bits exponent-bias) (get-format format)
(declare (ignore format))
`(let ((,temp-result (decode-float-bits/arithmetic ,integer* ,significand-bits ,exponent-bits ,exponent-bias)))
(if (or (nanp ,temp-result)
(infinityp ,temp-result))
,temp-result
(float-coerce ,temp-result ,result-type*)))))
(t
`(destructuring-bind (,runtime-format ,significand-bits ,exponent-bits ,exponent-bias) (get-format ,format)
(declare (ignore ,runtime-format))
(let ((,temp-result (decode-float-bits/arithmetic ,integer* ,significand-bits ,exponent-bits ,exponent-bias)))
(if (or (nanp ,temp-result)
(infinityp ,temp-result))
,temp-result
(float-coerce ,temp-result ,result-type*)))))))))
(defmacro decode-float-bits (integer &key (format :single)
(result-type ''float))
"Decodes the bits from an IEEE floating point number. Supported formats are
listed in the variable LISP-BINARY/FLOAT::*FORMAT-TABLE*.
If the FORMAT is either :SINGLE or :DOUBLE, then the decoding is
done by storing the bits in memory and having the CPU reinterpret that buffer
as a float. Otherwise, arithmetic methods are used to arrive at the correct value.
To prevent precision loss if you are decoding a larger type such as :QUADRUPLE
or :OCTUPLE precision, use 'RATIONAL for the RESULT-TYPE to avoid a conversion to
a smaller 32- or 64-bit float.
"
;; This declaration is REQUIRED under CCL because its optimizer
;; does something crazy that results in the DECODE-FLOAT-BITS/ARITHMETIC
;; expansion always being chosen.
#+ccl (declare (optimize (speed 0) (debug 3)))
(alexandria:with-gensyms (integer* format* result-type*)
`(let ((,integer* ,integer)
(,format* ,format)
(,result-type* ,result-type))
,(cond #+cffi
((and (member format '(:single :double))
(member result-type '('float 'single-float 'double-float) :test #'equal))
`(handler-case
(float-coerce (decode-float-bits/cffi ,integer* :format ,format*)
,result-type*)
#+clisp
(system::simple-floating-point-underflow ()
(decode-float-bits/arithmetic-macro ,integer* :format ,format* :result-type ,result-type*))))
(t `(decode-float-bits/arithmetic-macro ,integer* :format ,format* :result-type ,result-type*)))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun get-exponent (integer significand-bits exponent-bits exponent-bias)
(- (logand (- (ash 1 exponent-bits) 1)
(ash integer (- (- significand-bits 1))))
exponent-bias))
(defun get-significand (integer significand-bits)
"Given an INTEGER that represents the bit-pattern of a floating point number,
extract the bits that represent the significand. SIGNIFICAND-BITS specifies the
number of bits in the significand. Does not add the implicit bit."
(logand (- (ash 1 significand-bits) 1)
integer))
(defun exponent-all-ones-p (integer significand-bits exponent-bits)
(= (get-exponent integer significand-bits exponent-bits 0)
(1- (ash 1 exponent-bits))))
(defun %infinityp (integer significand-bits exponent-bits)
(and (exponent-all-ones-p integer significand-bits exponent-bits)
(= (get-significand integer (1- significand-bits)) 0)))
(defun %qnanp (integer significand-bits exponent-bits)
(let ((significand (get-significand integer (1- significand-bits))))
(and (exponent-all-ones-p integer significand-bits exponent-bits)
(= significand (ash 1 (- significand-bits 2))))))
(defun %snanp (integer significand-bits exponent-bits)
(let ((significand (get-significand integer (1- significand-bits))))
(and (exponent-all-ones-p integer significand-bits exponent-bits)
(= significand (ash 1 (- significand-bits 3))))))
(defun decode-significand (significand significand-bits raw-exponent)
"Given an encoded SIGNIFICAND of length SIGNIFICAND-BITS, calculate the
number it represents. RAW-EXPONENT is only used to determine whether to use
the denormalized interpretation of the SIGNIFICAND. The value of SIGNIFICAND-BITS
includes the 'implicit bit' which is not actually encoded in the significand. So,
if the SIGNIFICAND is physically 23 bits, plus one implicit bit, then SIGNIFICAND-BITS
is 24."
(unless (= 0 raw-exponent)
;; If the exponent is all 0s, that means we're decoding a "denormalized"
;; number with no implicit leading 1 bit.
;;
(setf significand (logior (ash 1 (1- significand-bits)) significand)))
(loop for i from (1- significand-bits) downto 0
for bit = (popbit significand)
sum (* bit (expt 2 (- i)))))
(defun exponent-zero-p (integer significand-bits exponent-bits)
(zerop (get-exponent integer significand-bits exponent-bits 0)))
(defun decode-float-bits/arithmetic (integer significand-bits exponent-bits exponent-bias)
"Decodes IEEE floating-point from an integer bit-pattern."
(declare (type integer integer significand-bits exponent-bits))
(let ((sign (ash integer (- (+ (- significand-bits 1) exponent-bits))))
(exponent (get-exponent integer significand-bits exponent-bits
exponent-bias))
(significand (get-significand integer (1- significand-bits))))
(cond ((%infinityp integer significand-bits exponent-bits)
(if (= sign 0)
+inf
-inf))
((%qnanp integer significand-bits exponent-bits)
quiet-nan)
((%snanp integer significand-bits exponent-bits)
signalling-nan)
((exponent-zero-p integer significand-bits exponent-bits)
;; Denormal decoding
(float-value sign (decode-significand significand significand-bits 0) (- (1- exponent-bias))))
(t
(float-value sign (decode-significand significand significand-bits
(get-exponent integer significand-bits exponent-bits 0)) exponent)))))
(defun make-smallest-denormal (format result-type)
(decode-float-bits 1 :format format :result-type result-type))
(defun make-largest-denormal (format result-type)
(let ((significand-bits (second (get-format format))))
(decode-float-bits (1- (ash 1 (1- significand-bits))) :format format :result-type result-type))))
(defparameter *denormals*
(loop for (format) in *format-table*
collect (list format (make-smallest-denormal format 'rational)
(make-largest-denormal format 'rational))))
(defun denormalp (number format)
(destructuring-bind (smallest largest) (cdr (assoc format *denormals*))
;; FIXME: CCL can't compare infinity to rational numbers!
(< smallest (abs number) largest)))
(defun denormalp/arithmetic (number significand-bits exponent-bits exponent-bias)
(denormalp number
(loop for (format signif-bits exp-bits exp-bias) in *format-table*
when (equal (list signif-bits exp-bits exp-bias)
(list significand-bits exponent-bits exponent-bias))
return format)))
(defun encode-significand (significand significand-bits)
;; The ASH is to remove an anomalous extra bit that ends up in
;; the output somehow.
(ash (loop for b from 0 to significand-bits
for power-of-two = (expt 2 (- b))
if (>= significand power-of-two)
do (decf significand power-of-two)
and sum (ash 1 (- significand-bits b)))
-1))
(defun %make-infinity (positivep significand-bits exponent-bits)
(logior (ash (if positivep 0 1)
(+ (1- significand-bits) exponent-bits))
(ash (1- (ash 1 exponent-bits))
(1- significand-bits))))
(defun %make-quiet-nan (significand-bits exponent-bits)
(logior (ash (1- (ash 1 exponent-bits))
(1- significand-bits))
(ash 1 (- significand-bits 2))))
(defun %make-signalling-nan (significand-bits exponent-bits)
(logior (ash (1- (ash 1 exponent-bits))
(1- significand-bits))
(ash 1 (- significand-bits 3))))
(defun calculate-significand (fraction exponent significand-bits)
"Given a FRACTION and number of SIGNIFICAND-BITS, calculates the
integer significand. The significand returned includes the implicit
bit, which must be removed in the final floating-point encoding."
(multiple-value-bind (int-part frac-part)
(floor (/ fraction (expt 2 exponent)))
(let ((bits-consumed (if (= int-part 0)
0
(1+ (loop for n from 0 unless
(< (ash 1 n) int-part)
return n)))))
(logior
(ash int-part (- significand-bits bits-consumed))
(loop for bit downfrom (- significand-bits bits-consumed)
repeat (- significand-bits bits-consumed)
sum (multiple-value-bind (int frac)
(floor (* frac-part 2))
(setf frac-part frac)
(incf bits-consumed)
(ash int (1- bit))))))))
(defun encode-float-bits/arithmetic (fraction significand-bits exponent-bits exponent-bias)
"Calculate the bits of a floating-point number using plain arithmetic, given the FRACTION
and the format information SIGNIFICAND-BITS, EXPONENT-BITS, and EXPONENT-BIAS. The returned
value is an integer."
(case fraction
#-float-infinity (:+inf (%make-infinity t significand-bits exponent-bits))
#-float-infinity (:-inf (%make-infinity nil significand-bits exponent-bits))
#-float-quiet-nan (:quiet-nan (%make-quiet-nan significand-bits exponent-bits))
#-float-signalling-nan (:signalling-nan (%make-signalling-nan significand-bits exponent-bits))
(otherwise
#+float-infinity
(when (infinityp fraction)
(return-from encode-float-bits/arithmetic
(%make-infinity (> fraction 0.0d0) significand-bits exponent-bits)))
;; The question of how to tell a quiet NaN from
;; a signalling NaN cannot be answered until I
;; see a Lisp implementation that can evaluate
;; signalling NaNs. In currently supported implementations,
;; signalling NaN will be represented by the keyword
;; :SIGNALLING-NAN, and quiet NaNs might be, too.
#+(or float-signalling-nan float-quiet-nan)
(when (nanp fraction)
(return-from encode-float-bits/arithmetic
(%make-quiet-nan significand-bits exponent-bits)))
(when (= fraction 0)
(return-from encode-float-bits/arithmetic 0))
(let* ((denormalp (denormalp/arithmetic fraction significand-bits exponent-bits exponent-bias))
(sign (if (> fraction 0)
0 1))
(exponent (if denormalp
0
(calculate-exponent sign fraction)))
(significand (if denormalp
(calculate-significand (/ fraction (expt 2 (- (1- exponent-bias)))) exponent (1- significand-bits))
(calculate-significand fraction exponent significand-bits))))
(logior (ash sign (+ (1- significand-bits) exponent-bits))
(logand
(1- (ash 1 (1- significand-bits)))
significand)
(ash
(if denormalp 0
(+ exponent exponent-bias))
(1- significand-bits)))))))
#+cffi
(defun encode-float-bits/cffi (fraction &key (format :single))
(declare (type float fraction))
(multiple-value-bind (c-float-type c-int-type lisp-type)
(ecase format
(:single (values :float :uint32 'single-float))
(:double (values :double :uint64 'double-float)))
(cffi:with-foreign-object (x c-float-type)
(setf (cffi:mem-ref x c-float-type) (coerce fraction lisp-type))
(cffi:mem-ref x c-int-type))))
#+cffi
(defun encode-float-bits/runtime-format (fraction format)
(if (member format '(:single :double))
(encode-float-bits/cffi (coerce fraction 'float) :format format)
(destructuring-bind (format significand-bits exponent-bits exponent-bias)
(get-format format)
(declare (ignore format))
(encode-float-bits/arithmetic fraction significand-bits exponent-bits exponent-bias))))
(defmacro encode-float-bits/arithmetic-macro (fraction format)
(cond ((keywordp format)
(destructuring-bind (format significand-bits exponent-bits exponent-bias) (get-format format)
(declare (ignore format))
`(encode-float-bits/arithmetic ,fraction ,significand-bits ,exponent-bits ,exponent-bias)))
(t
`(encode-float-bits/runtime-format ,fraction ,format))))
(defmacro encode-float-bits (fraction &key (format :single))
(cond ((member format '(:single :double))
(alexandria:with-gensyms (fraction-value)
#-(and float-infinity float-quiet-nan float-signalling-nan)
`(let ((,fraction-value ,fraction))
#+cffi
(if (symbolp ,fraction-value)
(encode-float-bits/arithmetic-macro ,fraction-value ,format)
(handler-case
(encode-float-bits/cffi (coerce ,fraction-value ,(case format
(:single ''single-float)
(:double ''double-float)))
:format ,format)
#+clisp
(system::simple-floating-point-underflow ()
(encode-float-bits/arithmetic-macro ,fraction-value ,format))))
#-cffi
(encode-float-bits/arithmetic-macro ,fraction-value ,format))
#+(and float-infinity float-quiet-nan float-signalling-nan)
`(encode-float-bits/cffi (coerce ,fraction-value 'float) :format ,format)))
(t `(encode-float-bits/arithmetic-macro ,fraction ,format))))
#+cffi
(defun decode-float-bits/cffi (integer &key (format :single))
"Decodes the bits from a read-in floating-point number using the hardware. Assumes
that only :SINGLE and :DOUBLE work."
(let (#-(and float-quiet-nan
float-signalling-nan
float-infinity)
(format-info (get-format format))
(c-float-type (ecase format
(:single :float)
(:double :double)))
(c-int-type (ecase format
(:single :uint32)
(:double :uint64))))
#-float-quiet-nan
(when (%qnanp integer (second format-info) (third format-info))
(return-from decode-float-bits/cffi quiet-nan))
#-float-signalling-nan
(when (%snanp integer (second format-info) (third format-info))
(return-from decode-float-bits/cffi signalling-nan))
#-float-infinity
(when (%infinityp integer (second format-info) (third format-info))
(return-from decode-float-bits/cffi
(decode-float-bits/arithmetic integer (second format-info) (third format-info) (fourth format-info))))
(cffi:with-foreign-object (x c-int-type)
(setf (cffi:mem-ref x c-int-type) integer)
(cffi:mem-ref x c-float-type))))
(defun make-infinity (positivep format)
"Creates a floating-point infinity. Returns the integer bit pattern."
(destructuring-bind (format-name significand-bits exponent-bits exponent-bias) (get-format format)
(declare (ignore exponent-bias format-name))
(%make-infinity positivep significand-bits exponent-bits)))
(defun make-quiet-nan (format)
(destructuring-bind (format-name significand-bits exponent-bits exponent-bias) (get-format format)
(declare (ignore format-name exponent-bias))
(%make-quiet-nan significand-bits exponent-bits)))
(defun make-signalling-nan (format)
(destructuring-bind (format-name significand-bits exponent-bits exponent-bias) (get-format format)
(declare (ignore format-name exponent-bias))
(%make-signalling-nan significand-bits exponent-bits)))
(defun %read-float (format stream result-type byte-order)
(let ((size (format-size format)))
(values
(decode-float-bits (read-integer size stream :byte-order byte-order)
:result-type result-type :format format)
size)))
(defmacro read-float (format &key (stream *standard-input*) (result-type ''float) (byte-order :little-endian))
(if (keywordp format) ;; Is the format known at compile time?
(let ((size (format-size format)))
`(values (decode-float-bits (read-integer ,size ,stream :byte-order ,byte-order)
:format ,format :result-type ,result-type)
,size))
`(%read-float ,format ,stream ,result-type ,byte-order)))
(defun %write-float (format fraction stream byte-order)
(let ((size (format-size format)))
(write-integer (encode-float-bits fraction :format format)
size stream :byte-order byte-order)))
(defmacro write-float (format fraction &key (stream *standard-input*) (byte-order :little-endian))
(if (keywordp format)
(let ((size (format-size format)))
`(write-integer (encode-float-bits ,fraction :format ,format)
,size ,stream :byte-order ,byte-order))
`(%write-float ,format ,fraction ,stream ,byte-order)))
| 23,008 | Common Lisp | .lisp | 494 | 41.874494 | 124 | 0.708356 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 827c5747af962a4c0c33143ed7bb8010fb4d7ea2b9b143278ee4881cf175dde2 | 2,349 | [
-1
] |
2,350 | binary-2.lisp | j3pic_lisp-binary/binary-2.lisp | (in-package :lisp-binary)
(defun expand-defbinary-type-field (type-info)
"Expands the :TYPE field of a DEFBINARY form. Returns three values:
1. A :TYPE specifier that can be spliced into a slot definition in a DEFSTRUCT form.
2. A READER-FORM that can be spliced into another function to read a datum of the specified
type. The READER-FORM will assume that it will be spliced into a scope where there's
a readable stream. The name of this stream must be stored in (SLOT-VALUE TYPE-INFO 'STREAM-SYMBOL).
3. A WRITER-FORM to write such a datum. It can be spliced into a scope similar to that of the READER-FORM.
"
(declare (type defbinary-type type-info)
(optimize (safety 3) (debug 3) (speed 0)))
(loop for expander in *type-expanders*
do (handler-bind ((no-destructuring-match
(lambda (exn)
(declare (ignore exn))
#-allegro
(continue)
#+allegro
(invoke-restart 'continue-with-next-expander)
)))
(restart-case
(return (multiple-value-bind (type reader writer)
(apply expander (cons type-info (let ((type (slot-value type-info 'type)))
(if (listp type)
type
(list type)))))
(values `(:type ,type)
(aif (slot-value type-info 'reader)
`(funcall ,it ,(slot-value type-info 'stream-symbol))
reader)
(aif (slot-value type-info 'writer)
`(funcall ,it
,(slot-value type-info 'name)
,(slot-value type-info 'stream-symbol))
writer))))
#-allegro
(continue () nil)
#+allegro
(continue-with-next-expander () nil)
))
finally (error "Unknown LISP-BINARY type: ~s" (slot-value type-info 'type))))
(defun defbinary-constructor-name (name defstruct-options)
(let ((con (getf defstruct-options :constructor)))
(or (if (consp con)
(car con)
con)
(let ((*print-case* :upcase))
(intern (format nil "MAKE-~a" name) (symbol-package name))))))
(defun expand-defbinary-field (name default-value &rest other-keys &key type (byte-order :little-endian)
byte-count-name
align element-align bit-stream-id
reader writer stream-symbol previous-defs-symbol
bind-index-to &allow-other-keys)
"Expands the field into three values: A slot-descriptor suitable for CL:DEFSTRUCT, a form that reads this slot
from a stream, and a form that writes it to a stream. The reader and writer must be evaluated in a context where
the NAME is bound to the slot's value."
(declare (optimize (safety 3) (debug 3) (speed 0)))
(assert byte-count-name)
(setf other-keys (remove-plist-keys other-keys :type :byte-order :encoding :terminator :reader :writer :stream-symbol :previous-defs-symbol
:byte-count-name :align :element-align :bind-index-to))
(multiple-value-bind (real-type read-form write-form)
(expand-defbinary-type-field
(make-instance 'defbinary-type
:name name
:type type
:byte-order byte-order
:reader reader
:writer writer
:stream-symbol (or bit-stream-id stream-symbol)
:previous-defs-symbol previous-defs-symbol
:byte-count-name byte-count-name
:align align
:element-align element-align
:bind-index-to bind-index-to))
(make-binary-field
:type type
:name name
:defstruct-field `(,name ,default-value
,@real-type ,@other-keys)
:bit-stream-id bit-stream-id
:read-form (if align
`(progn
(incf ,byte-count-name (align-to-boundary ,byte-count-name
,align #'read-bytes ,stream-symbol))
,read-form)
read-form)
:write-form (if align
`(progn
(incf ,byte-count-name
(align-to-boundary ,byte-count-name
,align (lambda (bytes stream)
(loop repeat bytes
do (write-byte 0 stream)))
,stream-symbol))
,write-form)
write-form))))
(defun bitfield-spec->defstruct-specs (name default-values options untyped-struct)
(check-type name list)
(let ((type (getf options :type)))
(check-type type list)
(unless (= (length name)
(length type))
(error "In bitfield: Number of values ~a ~S doesn't match number of types ~a ~S"
(length name) name (length type) type))
(loop for real-name in name
for default-value in default-values
for real-type in type
collect `(,real-name ,default-value
:type ,(if untyped-struct
t
real-type)
,@(remove-plist-keys options :type)))))
(defun find-bit-field-groups (list &key (key #'identity))
"Identifies those fields in the LIST of fields that must be
read/written either as a BIT-FIELD or through a BIT-STREAM wrapper.
A list of the original fields is returned, with those groups
that will be read/written in a non-byte-aligned mode grouped
in sublists.
See also: TYPE-SIZE"
(named-let local-loop
((current-group nil)
(result nil)
(running-total 0)
(list list))
(let* ((field (car list))
(bits (and list
(funcall key field))))
(cond ((null list)
(reverse
(if current-group
(cons (reverse current-group) result)
result)))
((not (divisiblep (+ running-total bits) 8))
(local-loop (cons field current-group)
result
(+ running-total bits)
(cdr list)))
((divisiblep (+ running-total bits) 8)
(local-loop nil
(cons (if current-group
(reverse (cons field current-group))
field)
result)
(+ running-total bits)
(cdr list)))
(t (error "Shouldn't ever be reached"))))))
(defun field-description-plist (field-description)
(cddr field-description))
(defun field-option (field-description option &optional default)
(getf (field-description-plist field-description) option default))
(defun field-description-type (field-description)
(getf (field-description-plist field-description)
:type))
(defun combine-field-descriptions (field-descriptions)
"Group the FIELD-DESCRIPTIONS according to how they should be grouped into bit-fields.
Returns two values:
1. A list of fields very similar to the FIELD-DESCRIPTIONS, except that some elements of the
list will be replaced by lists of fields that should be grouped together. Since a single
field description is itself a list, use LIST-OF-FIELDS-P to tell the difference between
one field and a list of fields.
2. Either :BIT-STREAM-REQUIRED if the whole struct can only be read with a bit-stream,
or no second value otherwise.
"
(find-bit-field-groups field-descriptions
:key (lambda (field)
(multiple-value-bind (bits can-use-bit-field contagious-bit-stream)
(type-size (field-description-type field))
(declare (ignore can-use-bit-field))
(cond
((eq contagious-bit-stream :bit-stream-only)
(return-from combine-field-descriptions
(values field-descriptions :bit-stream-required)))
(t bits))))))
(defun bit-field-type-p (type)
(destructuring-case type
((type-name size) :where (and (member type-name '(unsigned-byte signed-byte))
(integerp size))
t)
(otherwise nil)))
(defun list-of-fields-p (datum)
(destructuring-case datum
((variables default-value &rest options &key type &allow-other-keys)
:where (and (or (and (listp variables)
(listp type)
(eq (car type) 'bit-field))
(symbolp variables)))
(declare (ignore options default-value))
nil)
(otherwise t)))
(defun expand-byte-shorthand (n)
(if (numberp n)
(if (> n 0)
`(unsigned-byte ,n)
`(signed-byte ,(- n)))
n))
(defun make-bit-field (source-fields)
(let ((types (mapcar #'expand-byte-shorthand
(mapcar #'field-description-type source-fields)))
(default-values (mapcar #'second source-fields)))
(if (divisiblep (apply #'+ (mapcar 'type-size types)) 8)
`(,(mapcar #'car source-fields)
,default-values
:type (bit-field :member-types ,(loop for type in types
collect (if (bit-field-type-p type)
type
(invoke-restart 'cant-make-bit-field)))
:raw-type (unsigned-byte ,(loop for (nil bits) in types
sum bits))))
(invoke-restart 'cant-make-bit-field))))
(defun add-bit-stream-id (field-descriptions)
(loop for (name default-value . options) in field-descriptions
with stream-id = (gensym "BITSTREAM-")
collect (list* name default-value :bit-stream-id stream-id options)))
(defun externally-byte-aligned-p (field-descriptions)
(divisiblep (apply #'+
(mapcar (lambda (f)
(type-size (field-description-type f)))
field-descriptions))
8))
(defun convert-to-bit-fields (field-descriptions)
"Converts groups of non-byte-aligning field descriptions into bitfields where possible.
If they can't be read as bitfields, then a :BIT-STREAM-ID option is added to the field. "
(cond ((externally-byte-aligned-p field-descriptions)
(multiple-value-bind (combined-field-descriptions message)
(combine-field-descriptions field-descriptions)
(cond ((eq message :bit-stream-required)
(values field-descriptions :bit-stream-required))
;; I want to decide dynamically whether to COLLECT the
;; result of MAKE-BIT-FIELD or APPEND the MAYBE-FIELD
;; it tried to operate on, depending on whether a restart
;; is invoked. LOOP doesn't allow this easily, so instead,
;; I build a SCRIPT that consists of :APPEND and :COLLECT
;; commands, and then interpret that script to get the
;; final result.
(t (let ((script
(loop for maybe-field in combined-field-descriptions
append (if (list-of-fields-p maybe-field)
(restart-case
`(:collect ,(make-bit-field maybe-field))
(cant-make-bit-field ()
`(:append ,(add-bit-stream-id maybe-field))))
`(:collect ,maybe-field)))))
(loop for (command object) on script by #'cddr
if (eq command :collect)
collect object
else if (eq command :append)
append object
else do (error "Internal error: Unknown command ~S" command)))))))
(t (values field-descriptions :bit-stream-required))))
(defun recursive-field-list (current-list parents)
"Build a list of fields; grandparents are included
as their field lists are inclusive."
(append (loop for p in (if (listp parents)
parents
(list parents))
nconcing (get p :lisp-binary-fields))
current-list))
(defparameter *last-f* nil)
(defun %make-reader-let-def (f form-value most-recent-byte-count previous-defs previous-defs-push previous-defs-symbol
byte-count-name byte-order)
"Creates a single variable definition to go in the let-def form within READ-BINARY. F is a
BINARY-FIELD object that describes the field."
(let* ((f-name (slot-value f 'name))
(f-form
(if (listp f-name)
(slot-value f 'read-form)
`(multiple-value-bind (,form-value ,most-recent-byte-count)
,(slot-value f 'read-form)
(cond ((not (numberp ,most-recent-byte-count))
(restart-case
(error (format nil "Evaluation of ~a did not produce a byte count as its second value"
(with-output-to-string (out)
(print ',(slot-value f 'read-form) out))))
(use-value (val) :report "Enter an alternate value, dropping whatever was read."
:interactive (lambda ()
(format t "Enter a new value for ~a: " ',f-name)
(list (eval (read))))
(setf ,form-value val)
(setf ,most-recent-byte-count 0))
(enter-size (size) :report "Enter a byte count manually"
:interactive (lambda ()
(format t "Enter the byte count: ")
(force-output)
(list (eval (read))))
(setf ,most-recent-byte-count size))))
(t
(incf ,byte-count-name ,most-recent-byte-count)
,form-value)))))
(x-form (subst* `((,previous-defs-symbol ,(reverse previous-defs)))
f-form)))
(when (listp f-name)
(setf f-name (ecase byte-order
(:little-endian (reverse f-name))
(:big-endian f-name)))
(loop for real-name in f-name
do (funcall previous-defs-push (list real-name (list 'inject real-name))))
(funcall previous-defs-push (list f-name (list 'inject f-name))))
(list f-name x-form)))
(defmacro make-reader-let-def (f)
`(%make-reader-let-def ,f form-value most-recent-byte-count previous-defs (lambda (new-def)
(push new-def previous-defs))
previous-defs-symbol
byte-count-name byte-order))
(defun var-bit-stream (var bit-stream-groups)
(maphash (lambda (stream vars)
(let ((field-object (find-if (lambda (field-object)
(eq var (slot-value field-object 'name)))
vars)))
(if field-object
(return-from var-bit-stream (values stream field-object)))))
bit-stream-groups))
(defun reverse-bit-stream-groups (bit-stream-hash real-stream-symbol let-defs)
(loop for group in (group let-defs
:key (lambda (def)
(var-bit-stream (car def) bit-stream-hash)))
append (if (eq (var-bit-stream (caar group) bit-stream-hash)
real-stream-symbol)
group
(reverse group))))
(defun add-stream-definitions (bit-stream-groups stream-symbol byte-order let-defs)
"If the LET-DEFS contain fields that must be read from a bit-stream, this function
adds the necessary BIT-STREAM type variables to them. BIT-STREAM-GROUPS is a hash table
that maps each bit-stream variable name to the BINARY-FIELD objects of the variables that
must be read from that bit-stream. The STREAM-SYMBOL is the name of the default stream,
and BYTE-ORDER is the :BYTE-ORDER option passed to the DEFBINARY macro (only :BIG-ENDIAN
and :LITTLE-ENDIAN are supported. Handling for :DYNAMIC byte order must happen elsewhere)."
(assert (member byte-order '(:big-endian :little-endian)))
(loop for stream being the hash-keys in bit-stream-groups
for var = (slot-value (car (last (gethash stream bit-stream-groups)))
'name)
do (setf let-defs
(insert-before var
`(,stream (wrap-in-bit-stream ,stream-symbol :byte-order ,byte-order))
let-defs
:key #'car)))
let-defs)
(defun add-bit-stream-vars (bit-stream-groups stream-symbol byte-order make-let-def let-defs)
(loop for (var def) in (add-stream-definitions bit-stream-groups stream-symbol byte-order let-defs)
collect (multiple-value-bind (stream field-object)
(var-bit-stream var bit-stream-groups)
(if stream
(funcall make-let-def field-object stream)
`(,var ,def)))))
(defun group-write-forms (stream-names write-forms)
"Groups a list of WRITE-FORMS according to which stream they write to. The
streams are identified by matching them to their names, which must be given in
STREAM-NAMES."
(labels ((stream-used-here (form)
(recursive-find-if
(lambda (node)
(member node stream-names))
form)))
(loop for write-form-group in (group write-forms
:key #'stream-used-here)
for stream-name = (stream-used-here write-form-group)
collect (cons stream-name write-form-group))))
(defmacro defbinary (name (&rest defstruct-options
&key (byte-order :little-endian)
(preserve-*byte-order* t)
align
untyped-struct
include
documentation
export (byte-count-name (gensym "BYTE-COUNT-")) &allow-other-keys) &body field-descriptions)
"Defines a struct that represents binary data. Also generates two methods for this struct, named
READ-BINARY and WRITE-BINARY, which (de)serialize the struct to or from a stream. The serialization is
a direct binary representation of the fields of the struct. For instance, if there's a field with a :TYPE of
(UNSIGNED-BYTE 32), 4 bytes will be written in the specified :BYTE-ORDER. The fields are written (or read) in
the order in which they are specified in the body of the DEFBINARY form.
ARGUMENTS
NAME - Used as the name in the generated DEFSTRUCT form.
:BYTE-ORDER - The byte-order to use when reading or writing multi-byte
data. Accepted values are :BIG-ENDIAN, :LITTLE-ENDIAN,
and :DYNAMIC. If :DYNAMIC is specified, then the
READ- and WRITE-BINARY methods will consult the special
variable LISP-BINARY:*BYTE-ORDER* at runtime to decide
which byte order to use. That variable is expected to
be either :LITTLE-ENDIAN or :BIG-ENDIAN.
:PRESERVE-*BYTE-ORDER* - Don't revert changes that get made to
LISP-BINARY:*BYTE-ORDER* during the call
to either READ- or WRITE-BINARY.
:ALIGN - Align to the specified byte boundary before reading or writing
the struct.
:EXPORT - Export all symbols associated with the generated struct,
including the name of the struct, the name of the constructor,
and all the slot names.
:BYTE-COUNT-NAME - In all value and type forms, bind to this name
the number of bytes in the struct written so far.
&ALLOW-OTHER-KEYS - All other keyword arguments will be passed through
to the generated CL:DEFSTRUCT form as part of the
NAME-AND-OPTIONS argument.
FIELD-DESCRIPTIONS - A list of slot specifications, having the following structure:
(FIELD-NAME DEFAULT-VALUE &KEY TYPE BYTE-ORDER ALIGN ELEMENT-ALIGN
READER WRITER BIND-INDEX-TO)
The parameters have the following meanings:
FIELD-NAME - The name of the slot.
DEFAULT-VALUE - The default value.
TYPE - The type of the field. Some Common Lisp types such as
(UNSIGNED-BYTE 32) are supported. Any type defined
with DEFBINARY is also supported. For more info, see
'TYPES' below.
BYTE-ORDER - The byte order to use when reading or writing this
field. Defaults to the BYTE-ORDER given for the whole
struct.
ALIGN - If specified, reads and writes will be aligned on this
boundary. When reading, bytes will be thrown away until
alignment is achieved. When writing, NUL bytes will be
written.
UNTYPED-STRUCT - Don't declare the :TYPEs of the fields in the generated
DEFSTRUCT form.
ELEMENT-ALIGN - If the TYPE is an array, each element of the array will
be aligned to this boundary.
READER - If speficied, this function will be used to read the field.
It must accept one argument (a stream), and return two
values - The object read, and the the number of bytes read.
The number of bytes read is used for alignment purposes.
WRITER - If specified, this function will be used to write the field.
It must accept two arguments (the object to write, and the
stream), and return the number of bytes written, which is
used for alignment purposes.
BIND-INDEX-TO - If the EVAL type specifier is used as an array's element type
(see below), BIND-INDEX-TO will be bound to the current index
into the array, in case that matters for determining the type
of the next element.
Example:
(defbinary simple-binary (:export t
:byte-order :little-endian)
(magic 38284 :type (magic :actual-type (unsigned-byte 16)
:value 38284))
(size 0 :type (unsigned-byte 32))
(oddball-value 0 :type (unsigned-byte 32)
:byte-order :big-endian)
((b g r) 0 :type (bit-field :raw-type (unsigned-byte 8)
:member-types
((unsigned-byte 2)
(unsigned-byte 3)
(unsigned-byte 3))))
(name \"\" :type (counted-string 1 :external-format :utf8))
(alias #() :type (counted-buffer 4)
:byte-order :big-endian)
(floating-point 0.0d0 :type double-float)
(big-float 0 :type octuple-float)
(odd-float 0 :type (double-float :byte-order :big-endian))
(c-string \"\" :type (terminated-buffer 1 :terminator 0))
(nothing nil :type null) ;; Reads and writes nothing.
(other-struct nil :type other-binary
:reader #'read-other-binary
:writer #'write-other-binary)
(struct-array #() :type (counted-array 1 simple-binary))
(blah-type 0 :type (unsigned-byte 32))
(blah nil :type (eval (case oddball-value
((1) '(unsigned-byte 32))
((2) '(counted-string 2)))))
(an-array #() :type (simple-array (unsigned-byte 32) ((length c-string))))
(body #() :type (simple-array (unsigned-byte 8) (size))))
The above generates a DEFSTRUCT definition for SIMPLE-BINARY, along with
a definition for a READ-BINARY method and a WRITE-BINARY method.
`
The READ-BINARY method is EQL-specialized, and will construct the needed
object for you. It can be invoked like this:
(read-binary 'simple-binary stream)
The WRITE-BINARY method is called like this:
(write-binary object stream)
TYPES
DEFBINARY supports two kinds of types: Ordinary Common Lisp types, and Virtual Types.
The list of type names known to the library are listed below. Each one has its own
docstring, which can be accessed in several ways:
1. Emacs/SLIME's built-in docstring integraton: C-d d
2. (CL:DOCUMENTATION symbol 'LISP-BINARY:LISP-BINARY-TYPE)
3. (DESCRIBE symbol)
UNSIGNED-BYTE
SIGNED-BYTE
SIMPLE-ARRAY
COUNTED-ARRAY
COUNTED-STRING
COUNTED-BUFFER
TERMINATED-STRING
TERMINATED-BUFFER
FIXED-LENGTH-STRING
MAGIC
BASE-POINTER
FILE-POSITION
(REGION-TAG &key base-pointer-name)
(POINTER &key pointer-type data-type base-pointer-name region-tag)
(BIT-FIELD &key raw-type member-types)
(CUSTOM &key reader writer (lisp-type t))
NULL
EVAL - For runtime type selection
NON-BYTE-ALIGNED I/O: AN ALTERNATIVE TO BIT FIELDS
DEFBINARY supports non-byte-aligned reads. For example, if you want to read a 4-bit
unsigned integer and a 12-bit signed integer:
(defbinary non-conforming (:byte-order :big-endian)
(x 0 :type 4)
(y 0 :type 12)) ;; Total: 16 bits.
The above will compile to a single 16-bit read, and the two values will be automatically
extracted into their respective fields. The reverse operation is generated for writing.
In fact, the above is converted into a BIT-FIELD declaration, so it is exactly equivalent
to the following:
(defbinary non-conforming-bit-field-version (:byte-order :big-endian)
((x y) 0 :type (bit-field :raw-type (unsigned-byte 16)
:member-types ((unsigned-byte 4)
(unsigned-byte 12)))))
The macro will group sets signed or unsigned bytes to achieve a read that consists of
whole bytes. This grouping mechanism only works for SIGNED-BYTE and UNSIGNED-BYTE integers.
For other types, DEFBINARY will generate a temporary BIT-STREAM for the non-byte-aligned parts:
(defbinary non-byte-aligned-string (:byte-order :big-endian)
(x 0 :type 4)
(string \"\" :type (counted-string 1))
(y 0 :type 4))
;; End of non-byte-aligned part
(z \"\" :type (counted-string 1)))
As long as the sum of the bits adds up to a whole number of bytes, no
special handling is required on the part of the programmer. Internally,
the above generates a temporary bit-stream and reads from it, and it discards
the bit-stream before reading Z, because Z doesn't require non-byte-aligned I/O.
This is slower than doing whole-byte reads.
Finally, you can specify bytes that throw off the byte-alignment of the
stream:
(defbinary stays-non-byte-aligned ()
(x 0 :type 3))
If the macro cannot group the fields in the struct into byte-aligned reads,
then the struct can only be read from a BIT-STREAM and not a normal
stream (see WRAP-IN-BIT-STREAM and WITH-WRAPPED-IN-BIT-STREAM). In this
case, the macro will generate READ-BINARY and WRITE-BINARY methods that
are specialized to a second argument of type BIT-STREAM.
BIT-STREAMs can wrap any type of stream, including other BIT-STREAMs. This
means that you can nest one struct that does BIT-STREAM I/O inside another:
(defbinary stays-non-byte-aligned ()
(x 0 :type 3)
(y nil :type non-byte-aligned-string)) ;; See above
NON-BYTE-ALIGNED FIELDS and LITTLE ENDIANNESS
Bit fields are inherently confusing when they are applied to little-endian data (unlike
big-endian data, where they make perfect sense). This is because programmers who write
specifications for little-endian formats sometimes still describe the bit fields by
starting with the most significant bit.
Also, code that handles bit fields from little endian data may also handle that data
starting with the most significant bit (including some byte-order-independent code in
this library).
The BIT-FIELD type in DEFBINARY adds to this confusion, since the fields must always
be given starting with the most significant bit, regardless of the format's byte order.
However, when specifying non-byte-aligned fields without using BIT-FIELDs, they must be
specified starting with the LEAST significant bit in a LITTLE-ENDIAN format, but they
must be specified starting with the MOST significant bit in a BIG-ENDIAN format. For
example, consider the following toy format:
(defbinary toy-format (:byte-order :little-endian)
(a 0 :type 4)
(b 0 :type 16)
(c 0 :type 4))
Write it to disk with the following code:
(with-open-binary-file (out #P\"/tmp/test-1.bin\" :direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-binary (make-toy-format :a #x1 :b #x2345 :c #x6) out))
The resulting file would produce the following confusing hex dump:
51 34 62
What is that 5 from the middle doing at the very beginning?!?! Since 0x5 is
the second-least-significant nibble in the structure, it appears in the
most significant nibble of the least significant byte.
Reading the above as a little-endian, 24-bit unsigned integer gives the
integer #x623451, which is what you should have been expecting, since
C is the most significant field, and its value is 6.
You can also specify the above format using the BIT-FIELD type. But then you
have to account for the fact that in a BIT-FIELD type description, you always
describe the most significant bits first, no matter what. So the variables
and their corresponding types have to be reversed:
(defbinary toy-format/bit-field (:byte-order :little-endian)
((c b a) nil :type (bit-field :raw-type (unsigned-byte 24)
:member-types ((unsigned-byte 4)
(unsigned-byte 16)
(unsigned-byte 4)))))
ALIGNMENT
DEFBINARY can generate aligned structures. Alignment is calculated as an offset from the beginning of the structure
being defined. If a SIMPLE-ARRAY is defined with :ALIGN-ELEMENT {boundary}, then each element will be aligned to that
boundary. On writes, the alignment is achieved by writing NUL (0) bytes. On reads, the alignment is performed by
reading bytes from the stream one at a time. Alignment is always performed before reading and writing, never after.
MANUAL ALIGNMENT
If the &KEY argument :BYTE-COUNT-NAME is specified, then the name given will be bound as a variable whose value is the number of bytes read or
written so far. This binding is visible in forms that are evaluated at runtime, such as array-length specifiers and EVAL type
specifiers.
FLOATING-POINT NUMBERS
DEFBINARY can read IEEE floats ranging from half-precision up to octuple precision. Double-precision and below are
represented in memory by hardware floats, while larger-precision floats are decoded into RATIONALs.
Furthermore, single and double-precision floats are decoded from their byte representation by using CFFI, which
lets the hardware do the work on those systems that have FPUs (such as x86/AMD machines).
All other types of floating-point number are encoded and decoded using arithmetic.
"
(setf defstruct-options
(remove-plist-keys defstruct-options :export :include :byte-order :byte-count-name :align :untyped-struct :preserve-*byte-order* :documentation))
(let-values* ((stream-symbol (gensym "STREAM-SYMBOL-"))
(*ignore-on-write* nil)
(bit-stream-groups (make-hash-table))
(previous-defs-symbol (gensym "PREVIOUS-DEFS-SYMBOL-"))
(most-recent-byte-count (gensym "MOST-RECENT-BYTE-COUNT-"))
(form-value (gensym "FORM-VALUE-"))
((field-descriptions bit-stream-required) (convert-to-bit-fields
(recursive-field-list field-descriptions
include)))
(fields (loop for f in field-descriptions
collect (apply #'expand-defbinary-field
(append f `(:stream-symbol ,stream-symbol :byte-count-name ,byte-count-name
:previous-defs-symbol ,previous-defs-symbol)
(if (field-option f :byte-order)
nil
`(:byte-order ,(if (eq byte-order :dynamic)
'*byte-order*
byte-order)))))))
(name-and-options (if defstruct-options
(cons name
(loop for (key value) on (remove-plist-keys defstruct-options :byte-order) by #'cddr
collect (list key value)))
name))
(documentation (if documentation
(list documentation)
nil))
(previous-defs nil))
(declare (optimize (safety 3)))
(pushover (cons name field-descriptions) *known-defbinary-types*
:key #'car)
(setf (get name :lisp-binary-fields)
field-descriptions)
(loop for f in fields do
(awhen (slot-value f 'bit-stream-id)
(push f (gethash it bit-stream-groups nil))))
((lambda (form)
(if preserve-*byte-order*
form
(remove-binding '*byte-order* form)))
`(progn
(defstruct ,name-and-options ,@documentation
,@(loop for (name default-value . options) in
(mapcar #'binary-field-defstruct-field fields)
for type = (getf options :type)
if (listp name)
append (bitfield-spec->defstruct-specs
name default-value options untyped-struct)
else collect (list* name default-value
:type (if untyped-struct t
type)
(remove-plist-keys options :type :bit-stream-id))))
(defmethod read-binary ((type (eql ',name)) ,(if bit-stream-required
`(,stream-symbol bit-stream)
stream-symbol))
,@(if align
`((let* ((current-pos (file-position ,stream-symbol))
(mod (mod current-pos ,align)))
(unless (= mod 0)
(file-position ,stream-symbol
(+ current-pos (- ,align mod)))))))
,(flet ((make-reader-body (byte-order)
`(let-values* ,(list* `(,byte-count-name 0)
'(*byte-order* *byte-order*)
(add-stream-definitions bit-stream-groups
stream-symbol
byte-order
(loop for f in fields
if (eq (slot-value f 'type) 'null)
collect
`(,(slot-value f 'name) nil)
else collect (make-reader-let-def f)
finally (setf previous-defs nil))))
(values
(,(defbinary-constructor-name name defstruct-options)
,@(loop for name in (mapcar #'binary-field-name fields)
if (symbolp name)
collect (intern (symbol-name name) :keyword)
and collect name
else append (loop for real-name in name
collect (intern (symbol-name real-name) :keyword)
collect real-name)))
,byte-count-name))))
(if (eq byte-order :dynamic)
`(ecase *byte-order*
(:big-endian ,(make-reader-body :big-endian))
(:little-endian ,(make-reader-body :little-endian)))
(make-reader-body byte-order))))
(defmethod write-binary ((,name ,name) ,(if bit-stream-required
`(,stream-symbol bit-stream)
stream-symbol))
,@(if align
`((let* ((current-pos (file-position ,stream-symbol))
(mod (mod current-pos ,align)))
(unless (= mod 0)
(loop repeat (- ,align mod) do (write-byte 0 ,stream-symbol))))))
,(let ((ignore-decls (append *ignore-on-write*
(loop for field in fields
when
(destructuring-case (binary-field-type field)
((eval &rest args)
:where (eq eval 'eval)
(declare (ignore args))
t)
(otherwise nil))
collect (binary-field-name field))))
(slots (loop for f in (mapcar #'binary-field-name
fields)
if (listp f)
append f
else collect f)))
`(let* ,(list `(,byte-count-name 0)
'(*byte-order* *byte-order*))
(with-slots ,slots ,name
,@(if ignore-decls
`((declare (ignorable ,@ignore-decls))))
,@(loop for (stream-name . body)
in (group-write-forms (cons stream-symbol
(remove nil (mapcar #'binary-field-bit-stream-id fields)))
(loop for processed-write-form in
(loop for write-form in (mapcar #'binary-field-write-form fields)
when (recursive-find 'eval write-form)
collect (let ((fixed-let-defs (loop for var in slots collect
(CONS VAR (CONS (list 'inject VAR) 'NIL)))))
(subst* `((,previous-defs-symbol ,fixed-let-defs))
write-form))
else collect write-form)
collect `(incf ,byte-count-name ,processed-write-form)))
collect `(,@(if (or (null stream-name)
(eq stream-name stream-symbol))
'(progn)
`(with-wrapped-in-bit-stream (,stream-name ,stream-symbol
:byte-order ,(if (eq byte-order :dynamic)
'*byte-order*
byte-order))))
,@body))
,byte-count-name))))
,@(when export
`((export ',name)
(export ',(defbinary-constructor-name name defstruct-options))
,@(loop for f in (mapcar #'binary-field-name fields)
if (listp f)
append (loop for real-name in f
collect `(export ',real-name))
else collect `(export ',f))))
',name))))
| 35,390 | Common Lisp | .lisp | 733 | 39.758527 | 146 | 0.651213 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 1ea7bd6ca481f9d388b01eea8eade4bbd591719b35da3bfbd1b6b3813188b779 | 2,350 | [
-1
] |
2,351 | exif.lisp | j3pic_lisp-binary/exif.lisp | (defpackage :exif
(:use :common-lisp :lisp-binary :lisp-binary-utils))
(in-package :exif)
(declaim (optimize (debug 3) (speed 0)))
(define-enum tiff-type 2 (:byte-order :dynamic)
(:unsigned-byte 1)
:ascii
:unsigned-short
:unsigned-long
:unsigned-rational ;; Two unsigned-longs
:signed-byte
:undefined
:signed-short
:signed-long
:signed-rational
:single-float
:double-float)
(define-enum tiff-byte-order 2 (:byte-order :little-endian)
(:little-endian #x4949)
(:big-endian #x4d4d))
(defvar *pending-buffers* nil)
(defvar *tiff-start* nil)
(defun slot-path (object &rest slots)
(loop for slot in slots do
(setf object (slot-value object slot)))
object)
(defun no-writer (obj stream)
(declare (ignore obj stream))
0)
(defun read-rational (type stream)
(let-values* ((signed (ecase type
(:unsigned-rational nil)
(:signed-rational t)))
((numerator numerator-bytes) (read-integer 4 stream :byte-order *byte-order*
:signed signed))
((denominator denominator-bytes) (read-integer 4 stream :byte-order *byte-order*
:signed signed)))
(values (/ numerator denominator)
(+ numerator-bytes denominator-bytes))))
(defun write-rational (value type stream)
(let* ((signed (ecase type
(:unsigned-rational nil)
(:signed-rational t))))
(+
(write-integer (numerator value) 4 stream :byte-order *byte-order*
:signed signed)
(write-integer (denominator value) 4 stream :byte-order *byte-order*
:signed signed))))
(defun ensure-non-null-pointer (pointer-value)
(assert (/= 0 pointer-value)))
(defun tiff-type->defbinary-type (type)
(ecase type
((:unsigned-long :undefined) '(unsigned-byte 32))
(:signed-long '(signed-byte 32))
(:double-float 'double-float)
(:single-float 'single-float)
(:ascii '(terminated-string 1))
((:signed-rational :unsigned-rational)
`(custom :reader (lambda (stream)
(read-rational ,type stream))
:writer (lambda (obj stream)
(write-rational obj ,type stream))))
(:signed-byte '(signed-byte 8))
(:unsigned-byte '(unsigned-byte 8))
(:signed-short '(signed-byte 16))
(:unsigned-short '(unsigned-byte 16))))
(defbinary directory-entry (:byte-order :dynamic)
(file-position 0 :type file-position)
(tag 0 :type (unsigned-byte 16))
(type 0 :type tiff-type)
(count 0 :type (unsigned-byte 32)
;; This custom writer ensures that the COUNT remains
;; synced with the length of the VALUE below.
:writer (lambda (obj stream)
(declare (ignore obj))
(setf count (if (eq type :ascii)
(1+ (length value))
(if (or (listp value)
(vectorp value))
(length value)
1)))
(write-integer count 4 stream :byte-order *byte-order*)))
;; The VALUE depends on both the TYPE and the COUNT. The total number of
;; bytes needed to store the VALUE is given by (size of the type) * (count).
;; If this size is > 4 bytes, then the type of the VALUE must resolve to:
;;
;; (pointer :pointer-type (unsigned-byte 32)
;; :data-type the-actual-type-of-the-value
;; :base-pointer 'tiff-base-pointer
;; :region-tag 'tiff-region)
;;
;; The BASE-POINTER is declared at the beginning of the TIFF type definition,
;; and tells the LISP-BINARY library that the pointer is an offset that
;; begins at the BASE-POINTER.
;;
;; The REGION-TAG is used in writing the pointer. The region tag named
;; TIFF-REGION is also declared in the TIFF type definition, and determines
;; where the data being pointed to will end up going. The value is merely
;; STORED when the pointer is written, and it gets written to disk when the
;; REGION-TAG is reached.
(value 0 :type (eval
(cond
;; This tells LISP-BINARY that strings with a count <= 4
;; (which includes the terminating NUL) will fit inside
;; the VALUE, so we don't need a pointer.
((and (eq type :ascii)
(<= count 4))
(tiff-type->defbinary-type :ascii))
;; This tells LISP-BINARY that byte arrays with
;; count <= 4 and short arrays with count <= 2
;; will fit within the VALUE.
((or (and (member type '(:signed-byte :unsigned-byte))
(<= count 4)
(> count 1))
(and (member type '(:signed-short :unsigned-short))
(= count 2)))
`(simple-array ,(tiff-type->defbinary-type type)
(,count)))
;; This makes any other array type into a pointer.
((> count 1)
`(pointer :pointer-type (unsigned-byte 32)
:data-type ,(if (eq type :ascii)
(tiff-type->defbinary-type :ascii)
`(simple-array ,(tiff-type->defbinary-type type) (,count)))
:base-pointer-name 'tiff-base-pointer
:validator #'ensure-non-null-pointer
:region-tag 'tiff-region))
;; Certain tags mark their value as being an
;; unsigned long, but they should really be treated
;; as pointers to Image File Directories.
((member tag '(34665 ;; EXIF
34853 ;; GPS
40965)) ;; Interoperability
`(pointer :pointer-type (unsigned-byte 32)
:data-type tiff-image-file-directory
:base-pointer-name 'tiff-base-pointer
:validator #'ensure-non-null-pointer
:region-tag 'tiff-region))
(t
(case type
((:undefined)
'(unsigned-byte 32))
;; Some types are just plain too big to fit in the VALUE.
;; Generate pointers to them.
((:double-float :signed-rational :unsigned-rational :ascii)
`(pointer :pointer-type (unsigned-byte 32)
:data-type ,(tiff-type->defbinary-type type)
:base-pointer-name 'tiff-base-pointer
:validator #'ensure-non-null-pointer
:region-tag 'tiff-region))
;; Some types will fit just fine.
(otherwise (tiff-type->defbinary-type type)))))))
;; If the VALUE doesn't use 32 bits, then it must be padded. The PADDING
;; is an unsigned integer that fills in the space not used by the VALUE.
(padding 0 :type (eval (if (> count 1)
'null
(ecase type
(:ascii
(if (>= count 4)
'null
`(unsigned-byte ,(* 8 (- 4 count)))))
((:unsigned-long :unsigned-rational :signed-rational :double-float :signed-long
:single-float :undefined)
'null)
((:signed-byte :unsigned-byte)
'(unsigned-byte 24))
((:signed-short :unsigned-short)
'(unsigned-byte 16)))))))
(defbinary tiff-image-file-directory
(:align 2 :byte-order :dynamic)
(directory-entries #() :type (counted-array 2 directory-entry))
(next-directory-offset 0 :type (unsigned-byte 32)))
(defun write-integer/debug (&rest arguments)
(format t "Calling ~S~%" (cons 'write-integer arguments))
(apply #'write-integer arguments))
(defbinary tiff (:byte-order :dynamic :preserve-*byte-order* nil)
(tiff-base-pointer 0 :type base-pointer)
(byte-order 0 :type tiff-byte-order :reader (lambda (stream)
(values
(setf *byte-order* (read-binary-type 'tiff-byte-order stream))
2)))
(magic 42 :type (magic :actual-type (unsigned-byte 16)
:value 42))
(offset-ptr 0 :type file-position)
(first-image-file-directory-offset 0 :type (unsigned-byte 32))
(image-directories nil :type (custom
:reader (lambda (stream)
(let* ((next-directory nil)
(byte-count 0)
(directories
(with-file-position (0 stream)
(loop for offset = first-image-file-directory-offset
then (slot-value next-directory 'next-directory-offset)
until (= offset 0)
collect (progn
(file-position stream (+ offset tiff-base-pointer))
(setf next-directory
(multiple-value-bind (dir bytes)
(read-binary 'tiff-image-file-directory stream)
(incf byte-count bytes)
dir)))))))
(values directories byte-count)))
:writer (lambda (obj stream)
(declare (ignore obj))
(force-output stream)
(let ((real-offset (file-length stream)))
(with-file-position (offset-ptr stream)
(write-integer (- real-offset tiff-base-pointer) 4 stream :byte-order *byte-order*)
(setf first-image-file-directory-offset (- real-offset tiff-base-pointer))
(file-position stream real-offset)
(loop for (dir . more-dirs) on image-directories sum
(let ((bytes (write-binary dir stream))
(new-eof (file-position stream)))
(force-output stream)
(file-position stream (- new-eof 4))
(write-integer (if more-dirs
(- new-eof tiff-base-pointer)
0) 4 stream :byte-order *byte-order*)
bytes)))))))
(tiff-region 0 :type (region-tag :base-pointer-name 'tiff-base-pointer)))
(defbinary jpeg-generic-tag (:byte-order :big-endian)
(offset 0 :type file-position)
(magic #xff :type (magic :actual-type (unsigned-byte 8)
:value #xff))
(code 0 :type (unsigned-byte 8))
(length-offset 0 :type file-position)
(length 0 :type (eval
(case code
((#xd8 #xd0 #xd1 #xd2 #xd3 #xd4 #xd5 #xd6 #xd7
#xd9 #xdd)
'null)
(otherwise
'(unsigned-byte 16)))))
(restart-interval nil :type (eval
(if (= code #xdd)
'(unsigned-byte 32)
'null))))
(defvar *exif-header* #x457869660000)
(defbinary jpeg-app1-body (:byte-order :big-endian)
(exif-header 0 :type (unsigned-byte 48))
(body nil :type (eval (if (= exif-header *exif-header*)
'tiff
'null))))
(defun jpeg-tag-no-length-p (tag)
(or (member (slot-value tag 'code)
'(#xd8 #xd0 #xd1 #xd2 #xd3 #xd4 #xd5 #xd6 #xd7
#xd9 #xdd))
(not (slot-value tag 'length))))
(defbinary jpeg-generic-segment (:byte-order :big-endian)
(file-position 0 :type file-position)
(tag nil :type jpeg-generic-tag)
(contents nil :type (eval
(cond ((= (slot-value tag 'code) 225)
'jpeg-app1-body)
((null (slot-value tag 'length))
'null)
(t `(simple-array (unsigned-byte 8) (,(- (slot-value tag 'length) 2)))))))
(buffer nil :type (eval
(if (or (and (jpeg-app1-body-p contents)
(tiff-p (slot-value contents 'body)))
(jpeg-tag-no-length-p tag))
'null
`(simple-array (unsigned-byte 8) (,(- (slot-value tag 'length) 8))))))
(file-positioner nil :type (custom :reader
(lambda (stream)
(values
(and (not (jpeg-tag-no-length-p tag))
(file-position stream
(+ (slot-value tag 'length-offset)
(slot-value tag 'length))))
0))
:writer
(lambda (obj stream)
(declare (ignore obj))
(if (jpeg-tag-no-length-p tag)
(let ((end-position (file-position stream)))
(with-file-position ((slot-value tag 'length-offset) stream)
(write-integer (- end-position (slot-value tag 'length-offset))
2 stream :byte-order :big-endian)))
0)))))
(defun read-rest-of-stream (stream)
(read-bytes (- (file-length stream)
(file-position stream))
stream))
(defun remove-exif-data (input-file output-file)
(with-open-binary-file (in input-file)
(let ((jpeg-segments (loop for segment = (read-binary 'jpeg-generic-segment in)
until (= (slot-value
(slot-value segment 'tag) 'code) 225)
collect segment))
(rest-of-image (read-rest-of-stream in)))
(with-open-binary-file (out output-file
:direction :io
:if-exists :supersede
:if-does-not-exist :create)
(loop for segment in jpeg-segments
do (write-binary segment out))
(write-bytes rest-of-image out)))))
(defun read/write-test (pathname object type &key (base-pointer 0) tags)
(with-local-pointer-resolving-context
(with-open-binary-file (out pathname
:direction :io
:if-exists :supersede
:if-does-not-exist :create)
(write-binary-type object
type out)
(loop for tag in tags
do (lisp-binary::dump-tag tag base-pointer out)))
(with-open-binary-file (in pathname
:direction :input)
(read-binary-type type in))))
| 12,216 | Common Lisp | .lisp | 311 | 32.861736 | 94 | 0.634876 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 4b6c2a738950381b3b5d5f8968c4fbeb641eb20ea0cf88728caf660a0f4e41f6 | 2,351 | [
-1
] |
2,352 | utils.lisp | j3pic_lisp-binary/utils.lisp | (cl:defpackage lisp-binary-utils
(:use :common-lisp :moptilities)
(:shadowing-import-from :closer-mop)
(:export :subst* :struct-like-defclass :bind-class-slots :remove-plist-keys :recursive-find
:recursive-map :assoc-cdr :aif :awhen :it :destructuring-case :destructuring-lambda
:no-destructuring-match :recursive-find/collect :plist-replace
:recursive-find-if :recursive-mapcar :letf :relative-file-position :group :let-values* :let-values :divisiblep
:named-let :pushover :insert-before :has-sublist-p :find-sublist :recursive-find-sublist :remove-binding :mapseq
:call-with-file-position :with-file-position :simple-define-condition))
(in-package :lisp-binary-utils)
(defun divisiblep (num denom)
(= (mod num denom) 0))
(defmacro simple-define-condition (name parent-classes slots &optional docstring)
(setf (documentation name 'type) docstring)
`(define-condition ,name ,parent-classes
,(loop for slot-name in slots
collect (if (listp slot-name)
slot-name
`(,slot-name :initarg ,(intern (symbol-name slot-name) :keyword))))))
(define-condition no-destructuring-match (warning) ())
(defmacro named-let (name defs &body body)
(let ((vars (mapcar #'first defs))
(values (mapcar #'second defs)))
`(labels ((,name ,vars ,@body))
(,name ,@values))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun take-while (pred list)
(loop for item = (car list)
while (funcall pred item)
collect (pop list) into taken
finally (return (values taken list))))
(defun recursive-find/collect (pred tree)
(loop for (first . rest) on tree
if (funcall pred first) collect first into result
else if (listp first) append (recursive-find/collect pred first) into result
unless (listp rest)
return (if (funcall pred rest)
(append result (list rest))
result)
finally (return result))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro destructuring-case (expression &rest cases)
"Matches the EXPRESSION against one of the CASES. Each CASE is of
the form (lambda-list &key where &body body) and can have a guard clause.
The first pattern that successfully DESTRUCTURING-BINDs against the EXPRESSION
without an error *and* satisfies the optional :WHERE expression is the one
that will be selected. OTHERWISE is supported and works just as in the CL:CASE
form.
Example:
(destructuring-case '(1 2 3)
((a b c) :where (symbolp a)
(declare (ignore b c))
(list :symbol a))
((a b &optional c) :where (number b)
(declare (ignore a c)))
(list :number b))
((a &rest b)
(declare (ignore b))
(list :whatever a))
(otherwise
:nothing-matched))
The DECLARE form is processed before the :WHERE clause even though it appears
after it.
"
(let ((var (gensym))
(block-name (gensym))
(result-form nil))
(loop for (lambda-list . body) in (reverse cases)
for case-implementation = (if (eq lambda-list 'otherwise)
`(return-from ,block-name (progn ,@body))
(let ((catch-tag (gensym))
(local-result (gensym))
(match-success-flag (gensym))
(where-clause (when (eq (car body) :where)
(pop body)
(pop body))))
(multiple-value-bind (declarations real-body)
(take-while (lambda (form)
(and (listp form)
(eq (car form) 'declare)))
body)
(loop for var in (remove-duplicates
(recursive-find/collect
(lambda (elem)
(and (symbolp elem)
(equalp (symbol-name elem) "_")))
lambda-list) :test #'eq)
do (push `(declare (ignore ,var)) declarations))
`(let ((,local-result
(let ((,match-success-flag nil))
(catch ',catch-tag
(handler-bind ((t (lambda (exn)
(declare (ignore exn))
(unless ,match-success-flag
(throw ',catch-tag ',catch-tag)))))
(destructuring-bind ,lambda-list ,var
,@declarations
,@(if where-clause
`((unless ,where-clause
(throw ',catch-tag ',catch-tag))))
(setf ,match-success-flag t)
(return-from ,block-name
(progn
,@real-body))))))))
(if (eq ,local-result ',catch-tag)
,result-form
,local-result)))))
do (setf result-form case-implementation))
`(let ((,var ,expression))
(block ,block-name
,result-form))))
(defmacro destructuring-lambda (lambda-list &body body)
(let ((args (gensym)))
`(lambda (&rest ,args)
(destructuring-case ,args
(,lambda-list ,@body)
(otherwise (warn 'no-destructuring-match)))))))
(defun group (list &key (test #'eql) (key #'identity))
(let ((groups nil)
(current-group nil))
(loop for (first . rest) on list
do (push first current-group)
(unless (and rest
(funcall test (funcall key first)
(funcall key (car rest))))
(push (reverse current-group) groups)
(setf current-group nil)))
(reverse groups)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun optimize-let-values (let let-values bindings body)
(flet ((multiple-value-binding-p (binding)
(listp (car binding))))
(let ((binding-groups
(group (reverse bindings)
:key #'multiple-value-binding-p))
(result `(progn ,@body)))
(loop for bindings in binding-groups
do (setf result
`(,(if (multiple-value-binding-p (car bindings))
let-values
let) ,(reverse bindings) ,@(if (eq (car result) 'progn)
(cdr result)
(list result)))))
result))))
(defmacro let-values* (bindings &body body)
"Optimized implementation of LET-VALUES*. You can bind a multiple-value expression to
a list of variables, or you can bind a single value. Generates as few nested MULTIPLE-VALUE-BIND
and LET* forms as possible."
(optimize-let-values 'let* 'let-values/stupid* bindings body))
(defmacro let-values/stupid* (bindings &body body)
"A naive implementation of LET-VALUES*. Each binding must bind a multiple-value expression
to a list of variables, and will expand to a nested MULTIPLE-VALUE-BIND expression."
(let ((result `(progn ,@body)))
(loop for (variables expression) in (reverse bindings)
do (setf result `(multiple-value-bind ,variables ,expression
,@(if (eq (car result) 'progn)
(cdr result)
(list result)))))
result))
(defmacro let-values (bindings &body body)
(flet ((multiple-value-binding-p (binding)
(listp (car binding))))
(if (null bindings)
`(let nil ,@body)
(let ((multiple-bindings (remove-if-not #'multiple-value-binding-p bindings))
(single-bindings (remove-if #'multiple-value-binding-p bindings)))
(let ((name->gensym (make-hash-table :test 'eq)))
(loop for var in (apply #'append (mapcar #'car multiple-bindings))
for g = (gensym)
do (setf (gethash var name->gensym) g))
(let ((final-form `(let ,(append
(loop for binding in multiple-bindings
append (loop for var in (car binding)
collect `(,var ,(gethash var name->gensym))))
single-bindings)
,@body)))
(loop for (variables expression) in multiple-bindings
do (setf final-form `(multiple-value-bind ,(loop for v in variables
collect (gethash v name->gensym))
,expression
,final-form)))
final-form))))))
(defun recursive-map (function tree)
(mapcar (lambda (node)
(if (listp node)
(recursive-map function node)
(funcall function node)))
tree))
(defun subst* (bindings form &key (test #'eql))
(recursive-map
(lambda (node)
(block mapper
(loop for (var val) in bindings
when (funcall test node var) do (return-from mapper val))
node)) form))
(defun expand-struct-like-defclass-slot (class-name name default-value &key type)
(let ((*print-case* :upcase))
`(,name :accessor ,(intern (format nil "~a-~a" class-name name))
:initform ,default-value
:initarg ,(intern (symbol-name name) :keyword)
,@(if type `(:type ,type)))))
(defun add-default-value-if-needed (def)
(if (keywordp (car def))
(cons nil def)
def))
(defun assoc-cdr (item assoc-list &key (test #'eql))
(loop for (car . cdr) in assoc-list
if (funcall test item cdr) return (cons car cdr)))
(defmacro struct-like-defclass (name superclasses &rest slot-defs)
"An extremely simplified version of DEFCLASS. Written because I needed to be able
to list the slots of a certain struct."
`(progn (defparameter ,name
(defclass ,name ,superclasses
,(loop for def in slot-defs collect
(if (listp def)
(apply #'expand-struct-like-defclass-slot (cons name (add-default-value-if-needed def)))
(expand-struct-like-defclass-slot name def nil)))))))
(defmacro bind-class-slots (class instance &body body)
"Evaluates BODY with the slots from the CLASS bound to the values taken from
INSTANCE. The CLASS must be a class object at compile-time, so the macro can
extract the needed variable names for binding."
(let ((instance-value (gensym))
(slot-names (slot-names (eval class))))
`(let ((,instance-value ,instance))
(declare (ignorable ,instance-value))
(let ,(loop for name in slot-names collect
`(,name (slot-value ,instance ',name)))
(declare (ignorable ,@slot-names))
,@body))))
(defun remove-plist-keys (plist &rest keys)
(loop for (key value) of-type (keyword t) on plist by #'cddr
unless (member key keys)
collect key
and collect value))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro aif (test then &optional else)
`(let ((it ,test))
(if it ,then ,else)))
(defmacro awhen (test &rest body)
`(aif ,test (progn ,@body)))
(defmacro acond (&rest cases)
(let ((result nil))
(loop for (condition . body) in (reverse cases)
do (setf result
`(aif ,condition
(progn ,@body)
,result)))
result)))
(defun recursive-find (item tree &key (test #'eql))
(acond ((null tree)
nil)
((atom tree)
(funcall test item tree))
((consp tree)
(acond ((funcall test item (car tree))
(car tree))
((recursive-find item (car tree) :test test)
it)
(t (recursive-find item (cdr tree) :test test))))))
(defun list-begins-with-p (list prefix &key (test #'eql))
(named-let local-loop
((list list)
(prefix* prefix))
(cond ((endp prefix*)
t)
((endp list)
nil)
((not (funcall test (car list) (car prefix*)))
nil)
(t
(local-loop (cdr list) (cdr prefix*))))))
(defun find-sublist (sublist list)
"Finds any part of LIST is equal to SUBLIST and returns it, otherwise
returns NIL"
(loop for remaining on list
when (list-begins-with-p remaining sublist)
return remaining))
(defun recursive-find-if (pred tree)
(if (funcall pred tree)
tree
(recursive-find nil tree
:test (lambda (bullshit node)
(declare (ignore bullshit))
(funcall pred node)))))
(defun mapseq (function sequence)
(map (type-of sequence) function sequence))
(defun recursive-find-sublist (sublist tree)
(recursive-find-if
(lambda (node)
(aif (and (listp node)
(find-sublist sublist node))
(return-from recursive-find-sublist it)))
tree))
(defun plist-replace (plist indicator new-value)
(loop for (key value) on plist by #'cddr
collect key
if (eq key indicator)
collect new-value
else collect value))
;(defmacro pop-lazy (place)
; "Like CL:POP, but for CLAZY lazy lists."
; `(prog1 (lazy:head ,place)
; (setf ,place (lazy:tail place))))
;(defmacro push-lazy (obj place)
; "Like CL:PUSH, but for CLAZY lazy lists."
; `(setf ,place
; (lazily (cons ,obj ,place))))
(defmacro pushover (obj* place &key (key '#'identity) (test '#'eql))
"Pushes the OBJ* into the PLACE. If an \"identical\" object is already there, it is overwritten.
Whether something in the PLACE is considered \"identical\" can be controlled with the :TEST
and :KEY keywords."
(alexandria:with-gensyms (tail obj)
`(let ((,obj ,obj*))
(loop for ,tail on ,place
when (funcall ,test
(funcall ,key (car ,tail))
(funcall ,key ,obj))
do (setf (car ,tail)
,obj)
(return ,obj)
finally (push ,obj ,place)))))
(defun recursive-mapcar (function tree &optional traverse-results result)
"Maps the FUNCTION onto every node in the TREE. Works correctly with
improper lists.
If TRAVERSE-RESULTS is non-NIL, then RECURSIVE-MAPCAR will traverse
the result of the FUNCTION even if it is not EQ to the original value.
"
(let ((new-tree (funcall function tree)))
(when traverse-results
(setf tree new-tree))
(cond ((not (eq new-tree tree))
(append (reverse result) new-tree))
((null tree)
(reverse result))
((atom tree)
(if result
(append (reverse result) tree)
tree))
((consp tree)
(recursive-mapcar function (cdr tree)
traverse-results
(cons (recursive-mapcar function (car tree)
traverse-results) result))))))
(defun remove-binding (var form)
"Removes any binding for VAR from all LET, LET*, LET-VALUES, or LET-VALUES* forms found
in the FORM."
(recursive-mapcar
(lambda (node)
(destructuring-case node
((let bindings &rest body)
:where (member let '(let let* let-values let-values*))
`(,let ,(remove var bindings :key #'car)
,@body))
(otherwise node)))
form t))
(defmacro with-letf-bindings ((temp-var place-var value-var temp-binding place-binding) &body body)
`(destructuring-bind (,temp-var ,place-var) ,temp-binding
(declare (ignore ,place-var))
(destructuring-bind (,place-var ,value-var) ,place-binding
,@body)))
(defun insert-before (before-item new-item list &key (test #'eql) (key #'identity))
(let ((result nil))
(loop for item = (pop list)
while item
do (if (funcall test (funcall key item) before-item)
(return-from insert-before
(append (reverse result)
(list* new-item item list)))
(push item result)))
(nreverse result)))
(defmacro letf (place-bindings &body body)
"Temporarily rebind places like you would special variables. Before control enters the BODY,
the PLACE-BINDINGS are altered using SETF, and after exiting the BODY, their values are restored
to their original values with SETF.
Similar to CL-LETF in Emacs."
(let* ((temp-gensyms (loop repeat (length place-bindings)
collect (gensym)))
(temp-bindings
(loop for temp-binding in temp-gensyms
for place in (mapcar #'car place-bindings)
collect `(,temp-binding ,place)))
(reversed-temp-bindings (reverse temp-bindings))
(reversed-place-bindings (reverse place-bindings))
(result-body nil))
(setf result-body `(progn ,@body))
(loop for (temp-var nil) in reversed-temp-bindings
for (place value) in reversed-place-bindings
do (setf result-body
`(progn
(setf ,place ,value)
(unwind-protect
,result-body
(setf ,place ,temp-var)))))
`(let ,temp-bindings
,@(cdr result-body))))
(defun relative-file-position (stream offset)
(let* ((starting-position (file-position stream))
(ending-position (max (+ starting-position offset)
0)))
(file-position stream ending-position)))
(defgeneric call-with-file-position (stream position thunk)
(:method (stream position thunk)
(let ((original-file-position (file-position stream)))
(unwind-protect
(progn
(file-position stream position)
(funcall thunk))
(file-position stream original-file-position)))))
(defmacro with-file-position ((position stream) &body body)
`(call-with-file-position ,stream ,position (lambda () . ,body)))
| 16,028 | Common Lisp | .lisp | 410 | 33.363415 | 116 | 0.658384 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | c1e06bacb35cc304d83c1dd8d19a14ec10124daa06ffc0af7335cacb442f1812 | 2,352 | [
-1
] |
2,353 | doom-wad.lisp | j3pic_lisp-binary/doom-wad.lisp | (defpackage :lisp-binary-doom-wad
(:use :common-lisp :lisp-binary))
(in-package :lisp-binary-doom-wad)
(defparameter *doom-wad* #P"/usr/share/games/doom/doom.wad")
(define-enum wad-type 1 ()
(i 73)
(p 80))
(defbinary index-entry (:export t)
(offset 0 :type (signed-byte 32))
(size 0 :type (unsigned-byte 32))
(name "" :type (fixed-length-string 8)))
(defbinary doom-wad-header (:export t)
(wad-type 0 :type wad-type)
(magic 0 :type (magic :actual-type (unsigned-byte 24)
:value #x444157))
(num-index-entries 0 :type (signed-byte 32))
(index-offset 0 :type (signed-byte 32))
(index-entries nil :type null))
(defbinary thing (:export t)
(x 0 :type (signed-byte 16))
(y 0 :type (signed-byte 16))
(angle 0 :type (unsigned-byte 16))
(type 0 :type (unsigned-byte 16))
((easy medium hard deaf multiplayer-only
not-in-deathmatch
not-in-coop reserved) 0 :type (bit-field :raw-type (unsigned-byte 16)
:member-types ((unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 9)))))
(defbinary linedef (:export t)
(start-vertex-ix 0 :type (unsigned-byte 32))
(end-vertex-ix 0 :type (unsigned-byte 32))
((impassable blocks-monsters two-sided
upper-texture-unpegged lower-texture-unpegged
secret blocks-sound never-map
;; FIXME: The fields below should really
;; be one field, five bits wide,
;; that form an ENUM. But the library
;; doesn't support using ENUMs in bit fields.
;; As written, there are more fields than there are
;; sizes.
always-map ;; 0x1
multi-activatable ;; 0x2
activate-on-use ;; 0x4
activate-on-monster-crossing ;; 0x8
activate-on-shooting ;; 0xc
activate-on-player-bump ;; 0x10
activate-on-projectile-crossing ;; 0x14
activate-on-use-with-passthrough ;; 0x18
;;
activatable-by-players-and-monsters
reserved-1 blocks-everything reserved-2)
0
:type (bit-field :raw-type
(unsigned-byte 16)
:member-types ((unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1)
(unsigned-byte 1))))
(type 0 :type (unsigned-byte 16))
(sector-tag 0 :type (unsigned-byte 16))
(left-sidedef-ix 0 :type (unsigned-byte 16))
(right-sidedef-ix 0 :type (unsigned-byte 16)))
(defun read-indices (stream offset num)
(let ((result (make-array num :element-type 'index-entry))
(old-file-position (file-position stream)))
(unwind-protect
(progn
(file-position stream offset)
(loop for ix from 0 below num
do (setf (aref result ix) (read-binary 'index-entry stream))))
(file-position stream old-file-position))
result))
(defun ad-hoc-read-wad (filename)
(with-open-file (in filename :element-type '(unsigned-byte 8))
(let* ((result (read-binary 'doom-wad-header in)))
(setf (slot-value result 'index-entries)
(read-indices in (slot-value result 'index-offset)
(slot-value result 'num-index-entries)))
result)))
| 3,473 | Common Lisp | .lisp | 97 | 29.989691 | 71 | 0.644239 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | c6d95399465a5537ab94fa8df9026f691c4c3fb5df4bd707694b41c94392d956 | 2,353 | [
-1
] |
2,354 | buffer-streams.lisp | j3pic_lisp-binary/buffer-streams.lisp | (defpackage :lisp-binary/buffer-streams
(:use :common-lisp :trivial-gray-streams))
(in-package :lisp-binary/buffer-streams)
(defclass buffer-stream (fundamental-binary-stream)
((buffer :initarg :buffer)
(read-pointer :initform 0)))
(defun make-buffer-stream (element-type)
(make-instance 'buffer-stream :buffer (make-array 0 :element-type element-type :adjustable t :fill-pointer t)))
(defmethod stream-write-byte ((stream buffer-stream) byte)
(vector-push-extend byte (slot-value stream 'buffer)))
(defmethod stream-read-byte ((stream buffer-stream))
(handler-case
(aref
(slot-value stream 'buffer)
(prog1 (slot-value stream 'read-pointer)
(incf (slot-value stream 'read-pointer))))
(t ()
:eof)))
;; TRIVIAL-GRAY-STREAMS seems to be broken on SBCL.
(defmethod stream-write-sequence ((stream buffer-stream) sequence &optional start end)
(loop for ix from start to (or end (1- (length sequence)))
do (write-byte (aref sequence ix) stream)))
(defmacro with-output-to-buffer ((var &key (element-type ''(unsigned-byte 8))) &body body)
`(let ((,var (make-buffer-stream ,element-type)))
,@body
(slot-value ,var 'buffer)))
| 1,206 | Common Lisp | .lisp | 26 | 41.923077 | 113 | 0.711322 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | b2007491a4be3c5e1d58281c9eff42b4d88e9831d8ec9449941f5ff645140625 | 2,354 | [
-1
] |
2,355 | test.lisp | j3pic_lisp-binary/test.lisp | (defpackage :lisp-binary-test
(:use :common-lisp :lisp-binary))
(in-package :lisp-binary-test)
(defbinary index-test ()
(pointers #() :type (counted-array 2 (unsigned-byte 32)))
(data #() :type (simple-array (unsigned-byte 32) ((length pointers)))))
(defparameter test-data
(make-index-test :pointers (make-array 3 :element-type '(unsigned-byte 32) :initial-contents '(0 0 0))
:data (make-array 3 :element-type '(unsigned-byte 32)
:initial-contents '(12 13 14))))
(defmacro with-output-file ((var filename) &body body)
`(with-open-file (,var ,filename
:direction :io
:if-exists :supersede
:if-does-not-exist :create
:element-type '(unsigned-byte 8))
,@body))
(defmacro with-input-file ((var filename) &body body)
`(with-open-file (,var ,filename
:direction :input
:element-type '(unsigned-byte 8))
,@body))
(defun write-test-data (filename)
(with-output-file (out filename)
(write-binary test-data out)))
(defbinary just-a-pointer-array ()
(arr nil :type (counted-array 2 (unsigned-byte 32))))
(defun write-pointer-array (arr stream)
(let ((wrapped (make-just-a-pointer-array :arr arr)))
(write-binary wrapped stream)))
(defun write-test-data/pointers-as-list (filename)
"This function implements the 'write the pointers as zero then
collect a list of their addresses and go back and fix the zeroes' approach
to resolving pointers at write-time.
Three major flaws:
1. The array of pointers gets written twice.
2. The list of pointers must be a literal raw list of pointers.
3. The list of pointers will take up a lot of memory, especially for
a large binary file.
Unlike the approach described in the comments in binary.lisp, we
don't create an association between the values in POINTERS and those
in DATA. Instead, we assume that the elements of DATA will be in the
same order as those in the POINTERS."
(with-output-file (out filename)
(write-pointer-array (slot-value test-data 'pointers) out)
(let ((pointer-addresses
(loop for value across (slot-value test-data 'data)
collect (prog1 (file-position out)
(write-integer value 4 out)))))
(file-position out 0)
(loop for addr in pointer-addresses
for ix from 0
do (setf (aref (slot-value test-data 'pointers) ix) addr))
(write-pointer-array (slot-value test-data 'pointers) out))))
(defun read-test-data (filename)
(with-input-file (in filename)
(read-binary 'index-test in)))
(defbinary employee ()
(name "" :type (counted-string 1))
(age 0 :type (unsigned-byte 8))
(job-title "" :type (counted-string 1))
(salary 0 :type (unsigned-byte 64)))
(defmacro fill-array-with (array size value-form)
(let ((ix (gensym)))
`(loop for ,ix from 0
repeat ,size
do (setf (aref ,array ,ix) ,value-form))))
(defmacro make-array-filled-with (size element-type value-form)
(let ((result (gensym))
(size* (gensym)))
`(let* ((,size* ,size)
(,result (make-array (list ,size*) :element-type ,element-type)))
(fill-array-with ,result ,size* ,value-form)
,result)))
(defun read-counted-array (type count-size stream)
(let ((count (read-integer count-size stream)))
(make-array-filled-with count t (read-binary type stream))))
(defun write-counted-array (array count-size stream)
(write-integer (length array) count-size stream)
(loop for object across array
do (write-binary array stream)))
(defun read-integer-counted-array (int-size/bytes count-size stream)
(make-array-filled-with (read-integer count-size stream) t
(read-integer int-size/bytes stream)))
(defun write-integer-counted-array (array int-size count-size stream)
(write-integer (length array) count-size stream)
(loop for integer across array
do (write-integer integer int-size stream)))
(defbinary department ()
(name "" :type (counted-string 1))
;; The T type allows the HEAD to exist in memory as
;; an EMPLOYEE object, even though it has to be converted
;; to an integer before writing it to disk.
(head nil :type t
:reader (lambda (stream)
(read-integer 4 stream))
:writer (lambda (obj stream)
(write-integer obj 4 stream)))
(peons nil :type t
:reader (lambda (stream)
(read-integer-counted-array 4 4 stream))
:writer (lambda (obj stream)
(write-integer-counted-array obj 4 4 stream))))
;; A test struct that contains values that have
;; pointers back into the parent object.
(defbinary company ()
(ceo nil :type employee)
(cfo nil :type employee)
(coo nil :type employee)
(departments nil :type (counted-array 4 department))
(peons nil :type (counted-array 4 employee)))
(defmacro draw-random (place)
(let ((n (gensym))
(head (gensym))
(pick (gensym))
(car (gensym))
(cdr (gensym)))
`(let ((,n (random (length ,place))))
(prog1 (nth ,n ,place)
(setf ,place
(loop for item in ,place
for nn from 0
unless (= nn ,n)
collect item))))))
(defparameter *first-names*
'("Jeremy" "Amine" "Gary" "Amy" "Donna" "Debi" "Sarah"
"Mike" "Randy" "Matt" "Brian" "Mick" "Nick" "Rudy"
"Bruce" "Joel" "Isabella" "Austin" "Doctor"))
(defparameter *surnames*
'("Phelps" "Bitar" "Zeidenstein" "Brugel" "O'Connor" "Striblen"
"Stinson" "Fatter" "Penis" "Feller" "Powers" "Evil" "Gonzales"
"Weiner" "Scarborough"))
(defun pick (list)
(nth (random (length list)) list))
(defun invent-name ()
(format nil "~a ~a" (pick *first-names*) (pick *surnames*)))
(defun random-between (low high)
(+ (random (- high low)) low))
(defun invent-employee (&key (salary 1) (job-title (pick '("Knob Polisher" "Ass Wiper" "Sack Scratcher"))))
(make-employee :name (invent-name)
:age (random-between 18 64)
:job-title job-title
:salary salary))
(defun promote (employee new-job-title new-salary)
(setf (slot-value employee 'job-title) new-job-title)
(setf (slot-value employee 'salary) new-salary)
employee)
(defun make-employees (count)
(let ((employees
(loop repeat count collect
(invent-employee))))
(make-array (length employees) :element-type 'employee
:initial-contents employees)))
(defparameter *employee-array* (make-employees 1000))
(defparameter *employee-pool* (coerce *employee-array* 'list))
(defparameter *department-pool* '("Accounts Receivable" "Accounts Payable" "Receiving" "Shipping"
"Quality Assurance" "Security" "Insecurity" "Energy" "Deli"
"Weapons" "Operations"))
(defun invent-department (max-size)
(let ((department-name (draw-random *department-pool*)))
(make-department :name department-name
:head (promote (draw-random *employee-pool*)
(format nil "Director of ~a" department-name)
50000)
:peons (remove nil
(make-array-filled-with (random max-size) t
(draw-random *employee-pool*))))))
(defparameter *company*
(make-company :ceo (invent-employee :job-title "CEO"
:salary 1000000)
:cfo (invent-employee :job-title "CFO"
:salary 500000)
:coo (invent-employee :job-title "COO"
:salary 250000)
:departments (make-array-filled-with (length *department-pool*)
'department
(invent-department 67))
:peons *employee-array*))
(defbinary test-1 (:byte-order :dynamic)
((a b c) nil :type (bit-field
:raw-type (unsigned-byte 24)
:member-types ((unsigned-byte 8)
(unsigned-byte 8)
(unsigned-byte 8)))))
(defbinary test-2 (:byte-order :little-endian)
(a #xabc :type (unsigned-byte 12))
(b #xdef :type 12))
| 7,594 | Common Lisp | .lisp | 187 | 36.31016 | 107 | 0.686634 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | a7fd015446882a37626d052d12eb7ab533e15d762dbdc3f1cd7746ed16242141 | 2,355 | [
-1
] |
2,356 | fast-kw.lisp | j3pic_lisp-binary/fast-kw.lisp | (defpackage :fast-kw
(:use :common-lisp)
(:export :defkwfun))
(in-package :fast-kw)
(defun symbol-append (&rest symbols)
(intern (apply #'concatenate
(cons 'string (mapcar #'symbol-name symbols)))
(symbol-package (car symbols))))
(defun lambda-keyword-p (symbol)
(and (symbolp symbol)
(char= (aref (symbol-name symbol) 0) #\&)))
(defun split-lambda-list (lambda-list)
(let ((result '(&positional))
(current-group nil))
(loop for symbol in lambda-list
do (cond ((lambda-keyword-p symbol)
(push (reverse current-group) result)
(push symbol result)
(setf current-group nil))
(t (push symbol current-group))))
(push (reverse current-group) result)
(reverse result)))
(defun make-kw-macro-body (real-name flat-lambda-list)
`(,real-name ,@flat-lambda-list))
(defmacro defkwfun (name lambda-list &body body)
(let* ((parsed-lambda-list (split-lambda-list lambda-list))
(static-lambda-list (getf parsed-lambda-list '&positional))
(sections
(remove '&positional
(remove-if-not #'symbolp parsed-lambda-list)))
(real-function-name (symbol-append name '- 'flat-arglist)))
(setf static-lambda-list
(append static-lambda-list
(loop for section in sections
append
(loop for arg in (getf parsed-lambda-list section)
if (symbolp arg) collect arg
else if (and (listp arg)
(= (length arg) 3))
collect (first arg)
and collect (third arg)
else if (listp arg) collect (first arg)))))
`(progn
(defun ,real-function-name ,static-lambda-list
,@body)
(defmacro ,name ,lambda-list
(make-kw-macro-body ',real-function-name (list ,@static-lambda-list))))))
| 1,713 | Common Lisp | .lisp | 47 | 31.489362 | 75 | 0.675198 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | b62371cd756e796e240fb23b4cbe74ab54c710b5f73c65cf92ae373ded29582d | 2,356 | [
-1
] |
2,357 | single-field-tests.lisp | j3pic_lisp-binary/test/single-field-tests.lisp | (in-package :lisp-binary-test)
(unit-test 'read/write-integer-test
(let* ((integer 2948)
(le-buffer (flexi-streams:with-output-to-sequence (out)
(write-integer integer 4 out)))
(be-buffer (flexi-streams:with-output-to-sequence (out)
(write-integer integer 4 out :byte-order :big-endian)))
(signed-buffer (flexi-streams:with-output-to-sequence (out)
(write-integer (- integer) 2 out :byte-order :big-endian :signed t))))
(assert-equalp le-buffer #(#x84 #xb 0 0))
(assert-equalp be-buffer #(0 0 #xb #x84))
(assert-equalp signed-buffer #(#xf4 #x7c))
(assert-equalp integer (flexi-streams:with-input-from-sequence (in le-buffer)
(read-integer 4 in)))
(assert-equalp integer (flexi-streams:with-input-from-sequence (in be-buffer)
(read-integer 4 in :byte-order :big-endian)))
(assert-equalp (- integer) (flexi-streams:with-input-from-sequence (in signed-buffer)
(read-integer 2 in :byte-order :big-endian :signed t)))))
(defmethod read-bytes (n (stream sequence)
&rest options &key &allow-other-keys)
(flexi-streams:with-input-from-sequence (in stream)
(apply #'read-bytes (list* n in options))))
(unit-test 'pi-test
(let* ((calculated-pi
(+ 3 (loop
for a from 2 by 2
for b from 3 by 2
for c from 4 by 2
for add = t then (not add)
repeat 2000
sum (if add
(/ 4.0 (* a b c))
(- (/ 4.0 (* a b c)))))))
(floats (loop for type in '(half-float single-float double-float quadruple-float octuple-float)
collect (cons type (flexi-streams:with-output-to-sequence (out)
(write-binary-type calculated-pi type out))))))
(format t ">>>>>>>>>>>>> TESTING ENCODING AND DECODING OF ~a IN VARIOUS FLOATING-POINT PRECISIONS~%" (coerce calculated-pi 'double-float))
(format t ">>>>>>>>> HALF-FLOAT~%")
(assert= (read-binary-type 'half-float (cdr (assoc 'half-float floats)))
201/64)
(format t ">>>>>>>>> SINGLE-FLOAT~%")
(assert= (read-binary-type 'single-float (cdr (assoc 'single-float floats)))
3.1415927)
(loop for type in '(double-float quadruple-float octuple-float)
do
(format t ">>>>>>>> ~a~%" type)
(assert= (read-binary-type type (cdr (assoc type floats))) calculated-pi))))
(unit-test 'float-denormal-test
(let* ((smallest-denormal (lisp-binary/float::make-smallest-denormal :single 'number))
(largest-denormal (lisp-binary/float::make-largest-denormal :single 'number))
(test-value (+ smallest-denormal
(/ (- largest-denormal
smallest-denormal)
2)))
(test-buffer (flexi-streams:with-output-to-sequence
(out :element-type '(unsigned-byte 8))
(write-binary-type test-value 'single-float out :byte-order :big-endian))))
(assert-equalp test-buffer (buffer 0 #x40 0 0))
(assert= (flexi-streams:with-input-from-sequence
(in test-buffer)
(read-binary-type 'single-float in :byte-order :big-endian))
test-value)))
(unit-test 'string-tests
(let ((ascii-string "The quick brown fox jumps over the lazy dog."))
(let ((counted-string-buffer (flexi-streams:with-output-to-sequence (out)
(write-binary-type ascii-string '(counted-string 1) out)))
(terminated-string-buffer (flexi-streams:with-output-to-sequence (out)
(write-binary-type ascii-string '(terminated-string 1 :terminator 0) out))))
(assert= (aref counted-string-buffer 0) (length ascii-string))
(assert= (length counted-string-buffer) (1+ (length ascii-string)))
(assert-equalp (flexi-streams:with-input-from-sequence (in counted-string-buffer)
(read-binary-type '(counted-string 1) in))
ascii-string)
(assert= (aref terminated-string-buffer (1- (length terminated-string-buffer))) 0)
(assert= (length terminated-string-buffer) (1+ (length ascii-string)))
(assert-equalp (flexi-streams:with-input-from-sequence (in terminated-string-buffer)
(read-binary-type '(terminated-string 1 :terminator 0) in))
ascii-string))))
(unit-test 'ones-complement-test
(let ((buffer (flexi-streams:with-output-to-sequence (out)
(write-integer #xf0 1 out :byte-order :big-endian))))
(loop for (complement value)
in '((:ones-complement -15)
(:twos-complement -16))
do
(assert= (flexi-streams:with-input-from-sequence (in buffer)
(read-binary-type `(signed-byte 8 :signed-representation ,complement)
in :byte-order :big-endian))
value)
(assert-equalp (flexi-streams:with-output-to-sequence (out)
(write-binary-type value `(signed-byte 8 :signed-representation ,complement)
out :byte-order :big-endian))
buffer))))
(unit-test 'short-input-test
(loop for wrapper in (list 'simple-bit-stream:wrap-in-bit-stream 'identity)
do
(handler-case
(flexi-streams:with-input-from-sequence (in #(1 1))
(read-binary-type '(unsigned-byte 32) in)
(error "Failed to short input test with wrapper ~a." wrapper))
(end-of-file ()
:pass))))
(unit-test 'short-bit-input-test
(flexi-streams:with-input-from-sequence (in #(255))
(with-wrapped-in-bit-stream (in-bitstream in)
(read-bytes 1/2 in-bitstream)
(handler-case
(progn
(read-bytes 1 in-bitstream)
(error "Failed short-bit-input test."))
(end-of-file ()
:pass)))))
(unit-test 'read-sequence-bit-stream-test
(flexi-streams:with-input-from-sequence (in #(155))
(with-wrapped-in-bit-stream (in-bitstream in)
(read-bytes 1/2 in-bitstream)
(let ((seq (make-array 1)))
(assert-equalp
(read-sequence seq in-bitstream)
0)))))
(unit-test 'eval-no-case-test
(with-read-stream #(12 12 12 12)
(assert-equalp
(read-binary-type `(eval '(unsigned-byte 32)) *stream*)
#x0c0c0c0c))
(assert-equalp
(with-write-stream-to-buffer
(write-binary-type #x0c0c0c0c `(eval '(unsigned-byte 32)) *stream*))
#(12 12 12 12)))
(unit-test 'eval-with-case-test
(with-read-stream #(12 12 12 12)
(assert-equalp
(read-binary-type `(eval (case t (otherwise '(unsigned-byte 32)))) *stream*)
#x0c0c0c0c))
(assert-equalp
(with-write-stream-to-buffer
(write-binary-type #x0c0c0c0c `(eval (case t (otherwise '(unsigned-byte 32)))) *stream*))
#(12 12 12 12)))
(define-enum simple-enum 1 (:byte-order :big-endian)
zero one two)
(unit-test 'simple-enum-test
(with-read-stream #(0 1 2)
(assert-equalp (read-binary-type 'simple-enum *stream*) 'zero)
(assert-equalp (read-binary-type 'simple-enum *stream*) 'one)
(assert-equalp (read-binary-type 'simple-enum *stream*) 'two))
(assert-equalp
(with-write-stream-to-buffer
(loop for symbol in '(zero one two)
do (write-binary-type symbol 'simple-enum *stream*)))
#(0 1 2)))
(define-enum custom-reader-enum 1 (:reader (lambda (size stream &rest boo-hoo)
(declare (ignore boo-hoo size stream))
(values 123 1))
:writer (lambda (n size stream &rest boo-hoo)
(declare (ignore boo-hoo size n))
(write-integer 255 1 stream)))
(:the-value 123))
(unit-test 'custom-reader-enum-test
(with-read-stream #(0 1 2 3)
(multiple-value-bind (value bytes-read)
(read-binary-type 'custom-reader-enum *stream*)
(assert-equalp value :the-value)
(assert= bytes-read 1)))
(assert-equalp
(with-write-stream-to-buffer
(assert= (write-binary-type :whatever 'custom-reader-enum *stream*)
1))
#(255)))
(define-enum boolean-enum 1 ()
(nil 0)
(t 1))
(unit-test 'boolean-enum-test
(with-read-stream #(0 1)
(assert-equalp
(loop repeat 2 collect (read-binary-type 'boolean-enum *stream*))
'(nil t)))
(assert-equalp
(with-write-stream-to-buffer
(loop for val in '(t nil)
do (write-binary-type val 'boolean-enum *stream*)))
#(1 0)))
| 7,872 | Common Lisp | .lisp | 181 | 37.900552 | 142 | 0.662698 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 865598cbe249a90ae4e1558dd9021d97866db9c6b0a90d2cccf05a0dbc723c7c | 2,357 | [
-1
] |
2,358 | basic-test.lisp | j3pic_lisp-binary/test/basic-test.lisp | ;; -*- eval: (put 'unit-test 'common-lisp-indent-function 2) -*-
(defpackage :lisp-binary-test
(:use :common-lisp :lisp-binary :unit-test))
(in-package :lisp-binary-test)
(declaim (optimize (debug 3) (safety 3) (speed 0)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro assert= (x y)
(let ((x* (gensym "X"))
(y* (gensym "Y")))
`(let ((,x* ,x)
(,y* ,y))
(or (= ,x* ,y*)
(error "~S != ~S" ,x* ,y*))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro assert= (x y)
(let ((x* (gensym "X"))
(y* (gensym "Y")))
`(let ((,x* ,x)
(,y* ,y))
(or (= ,x* ,y*)
(error "~S != ~S" ,x* ,y*)))))
(defmacro assert-eq (x y)
(let ((x* (gensym "X"))
(y* (gensym "Y")))
`(let ((,x* ,x)
(,y* ,y))
(or (eq ,x* ,y*)
(error "~S is not EQ to ~S" ,x* ,y*)))))
(defmacro assert-equal (x y)
(let ((x* (gensym "X"))
(y* (gensym "Y")))
`(let ((,x* ,x)
(,y* ,y))
(or (equal ,x* ,y*)
(error "~S is not EQUAL to ~S" ,x* ,y*)))))
(defmacro assert-equalp (x y)
(let ((x* (gensym "X"))
(y* (gensym "Y")))
`(let ((,x* ,x)
(,y* ,y))
(or (equalp ,x* ,y*)
(error "~S is not EQUALP to ~S" ,x* ,y*))))))
(defbinary other-binary ()
(x 1 :type (unsigned-byte 1))
(y #x1d :type (unsigned-byte 7)))
(defbinary dynamic-other-binary (:byte-order :dynamic)
(x 1 :type (unsigned-byte 1))
(y #x1d :type (unsigned-byte 7)))
(defbinary be-other-binary (:byte-order :big-endian)
(x 1 :type (unsigned-byte 1))
(y #x1d :type (unsigned-byte 7)))
(defbinary with-terminated-buffer ()
(c-string (buffer 12 13 14) :type (terminated-buffer 1 :terminator 0)))
(defun write-other-binary (ob stream)
(write-binary ob stream))
(defun read-other-binary (stream)
(read-binary 'other-binary stream))
(defbinary simple-binary (:export t
:byte-order :little-endian)
(magic 38284 :type (magic :actual-type (unsigned-byte 16)
:value 38284))
(size 0 :type (unsigned-byte 32))
(oddball-value 1 :type (unsigned-byte 32)
:byte-order :big-endian)
(b 0 :type (unsigned-byte 2))
(g 0 :type (unsigned-byte 3))
(r 0 :type (unsigned-byte 3))
(name "" :type (counted-string 1 :external-format :utf8))
(alias (buffer) :type (counted-buffer 4)
:byte-order :big-endian)
(floating-point 0.0d0 :type double-float)
(big-float 0 :type octuple-float)
(odd-float 0.0d0 :type (double-float :byte-order :big-endian))
(c-string (buffer) :type (terminated-buffer 1 :terminator 0))
(nothing nil :type null) ;; Reads and writes nothing.
(other-struct (make-other-binary :x 0 :y #x20)
:type other-binary
:reader #'read-other-binary
:writer #'write-other-binary)
(struct-array (make-array 0 :element-type 'other-binary
:initial-element (make-other-binary :x 1 :y #x13))
:type (counted-array 1 other-binary))
(blah-type 0 :type (unsigned-byte 32))
(blah nil :type (eval (case oddball-value
((1) '(unsigned-byte 32))
((2) '(counted-string 2)))))
(an-array (make-array 0 :element-type '(unsigned-byte 32))
:type (simple-array (unsigned-byte 32) ((length c-string))))
(body (make-array 0 :element-type '(unsigned-byte 8))
:type (simple-array (unsigned-byte 8) (size))))
(defun call-test-round-trip (test-name write-thunk read-thunk &key (out-direction :output))
(format t ">>>>>>>>>>>>>>>>>>>>> ~a~%" test-name)
(format t "Writing data....~%")
(with-open-binary-file (*standard-output* "/tmp/foobar.bin"
:direction out-direction
:if-exists :supersede)
(funcall write-thunk))
(format t "Reading it back...~%")
(with-open-binary-file (*standard-input* "/tmp/foobar.bin")
(funcall read-thunk)))
(defmacro test-round-trip (test-name write-form read-form &key (out-direction :output))
`(call-test-round-trip ,test-name (lambda () ,write-form)
(lambda () ,read-form)
:out-direction ,out-direction))
(defun simple-test ()
(declare (optimize (safety 3) (debug 3) (speed 0)))
(let ((simple-binary (make-simple-binary :blah 34)))
(test-round-trip "OVERALL ROUND TRIP TEST"
(write-binary simple-binary *standard-output*)
(let ((input-binary (read-binary 'simple-binary *standard-input*)))
(assert-equal simple-binary input-binary)))))
(unit-test 'quadruple-precision-floating-point-test ()
(test-round-trip "QUADRUPLE PRECISION FLOATING POINT TEST"
(write-binary-type 3/2 'quadruple-float *standard-output*)
(assert (= (read-binary-type 'quadruple-float *standard-input*)
3/2))))
(unit-test 'octuple-precision-floating-point-test
(test-round-trip "OCTUPLE PRECISION FLOATING POINT TEST"
(write-binary-type 3/2 'octuple-float *standard-output*)
(assert (= (read-binary-type 'octuple-float *standard-input*)
3/2))))
;; FIXME: This test fails. I've determined that it's the encoding side that is
;; incorrect. When using hardware, 1.5d0 encodes as 4609434218613702656,
;; which decodes correctly using arithmetic. But the arithmetic encoder
;; is coming up with 4607182418800017408. Decoding is correct.
(unit-test 'double-precision-floating-point-test
(test-round-trip "DOUBLE PRECISION FLOATING POINT TEST"
(write-binary-type 1.5d0 'double-float *standard-output*)
(assert= (read-binary-type 'double-float *standard-input*)
1.5d0)))
(defun other-binary-dynamic-test (&optional (*byte-order* :little-endian))
(let ((other-binary (make-dynamic-other-binary :x 0 :y #x20)))
(test-round-trip (format nil "BIT STREAMS - DYNAMIC BYTE ORDER ~a TEST" *byte-order*)
(write-binary other-binary *standard-output*)
(assert-equalp (read-binary 'dynamic-other-binary *standard-input*)
other-binary))))
(defun other-binary-le-test ()
(let ((other-binary (make-other-binary :x 0 :y #x20)))
(test-round-trip (format nil "BIT STREAMS - STATIC BYTE ORDER LITTLE-ENDIAN TEST")
(write-binary other-binary *standard-output*)
(assert-equalp (read-binary 'other-binary *standard-input*)
other-binary))))
(defun other-binary-be-test ()
(let ((other-binary (make-be-other-binary :x 0 :y #x20)))
(test-round-trip (format nil "BIT STREAMS - STATIC BYTE ORDER BIG-ENDIAN TEST")
(write-binary other-binary *standard-output*)
(assert-equalp (read-binary 'be-other-binary *standard-input*)
other-binary))))
(defun other-binary-functions-test ()
(let ((other-binary (make-other-binary :x 0 :y #x20)))
(test-round-trip "OTHER-BINARY TEST"
(write-other-binary other-binary *standard-output*)
(assert-equalp (read-other-binary *standard-input*)
other-binary))))
(unit-test 'other-binary-test
(other-binary-dynamic-test)
(other-binary-dynamic-test :big-endian)
(other-binary-le-test)
(other-binary-be-test)
(other-binary-functions-test))
(unit-test 'terminated-buffer-test
(let ((terminated-buffer (make-with-terminated-buffer)))
(test-round-trip "TERMINATED-BUFFER TEST"
(write-binary terminated-buffer *standard-output*)
(assert-equalp terminated-buffer
(read-binary 'with-terminated-buffer *standard-input*)))))
(defbinary multi-byte-bit-fields (:byte-order :dynamic)
(x 256 :type (unsigned-byte 12))
(y 127 :type (unsigned-byte 12)))
(defbinary implicit-bit-stream (:byte-order :dynamic)
(x 13 :type (unsigned-byte 4))
(f 1.5d0 :type double-float)
(y 10 :type (unsigned-byte 4)))
(unit-test 'multi-byte-bit-field-test
(let ((struct (make-multi-byte-bit-fields)))
(assert= (slot-value struct 'x) 256)
(assert= (slot-value struct 'y) 127)
(loop for *byte-order* in '(:little-endian :big-endian)
do
(test-round-trip (format nil "MULTI BYTE BIT FIELD TEST (~a)" *byte-order*)
(write-binary struct *standard-output*)
(assert-equalp struct
(read-binary 'multi-byte-bit-fields
*standard-input*))))))
(defbinary pointer-test-inner ()
(pointer-1 0 :type (pointer :pointer-type (unsigned-byte 16)
:data-type (counted-string 1)
:base-pointer-name base
:region-tag the-region))
(pointer-2 0 :type (pointer :pointer-type (unsigned-byte 16)
:data-type (unsigned-byte 8)
:base-pointer-name base
:region-tag the-region)))
(defbinary pointer-test-outer ()
(magic #xff :type (magic :actual-type (unsigned-byte 8)
:value #xff))
(base 0 :type base-pointer)
(thing-with-pointers nil :type pointer-test-inner)
(the-region nil :type (region-tag :base-pointer-name base)))
(unit-test 'pointer/base-pointer/region-test
(let* ((inner (make-pointer-test-inner :pointer-1 "The string I chose for the test."
:pointer-2 #x7f))
(outer (make-pointer-test-outer :thing-with-pointers inner)))
(with-local-pointer-resolving-context
(test-round-trip "POINTER/BASE-POINTER/REGION TEST"
(write-binary outer *standard-output*)
(assert-equalp outer
(read-binary 'pointer-test-outer
*standard-input*))
:out-direction :io))))
(defbinary pointer-test-inner-no-base-pointer ()
(pointer-1 0 :type (pointer :pointer-type (unsigned-byte 16)
:data-type (counted-string 1)
:region-tag the-region))
(pointer-2 0 :type (pointer :pointer-type (unsigned-byte 16)
:data-type (unsigned-byte 8)
:region-tag the-region)))
(defbinary pointer-test-no-base-pointer ()
(thing-with-pointers nil :type pointer-test-inner)
(the-region nil :type (region-tag)))
(unit-test 'pointer/region-test
(let* ((inner (make-pointer-test-inner :pointer-1 "The string I chose for the test."
:pointer-2 #x7f))
(outer (make-pointer-test-outer :thing-with-pointers inner)))
(with-local-pointer-resolving-context
(test-round-trip "POINTER/REGION TEST (no base pointer)"
(write-binary outer *standard-output*)
(assert-equalp outer
(read-binary 'pointer-test-outer
*standard-input*))
:out-direction :io))))
(defbinary array-length-test ()
(length 0 :type (unsigned-byte 8))
(data nil :type (eval (case length
(0 'null)
(otherwise `(simple-array (unsigned-byte 8) (,length)))))))
(unit-test 'eval-case-runtime-only-test
;; If you use the EVAL type specifier with a CASE
;; form, EVAL optimizes the code so that the reader/
;; writer code is generated at compile time from the
;; type specifiers that the CASE form might evaluate
;; to. So instead of a CASE form that evaluates to
;; different types, you get a CASE form that performs
;; different read/write code.
;;
;; There's one case where this won't work: If any of
;; the original type specifiers incorporate data
;; that is only available at runtime, then they can't
;; be expanded at compile time. In that case, we
;; abort the optimization and just do an EVAL at
;; runtime. This test makes sure that this degradation
;; works. The DATA member here has an EVAL type with a
;; CASE form, that creates a type containing the
;; object's LENGTH value, which is only available
;; at runtime.
(let ((empty (make-array-length-test))
(full (make-array-length-test :length 1
:data (buffer 1))))
(test-round-trip "EVAL optimizer test"
(progn
(write-binary empty *standard-output*)
(write-binary full *standard-output*))
(progn
(assert-equalp empty (read-binary 'array-length-test *standard-input*))
(assert-equalp full (read-binary 'array-length-test *standard-input*))))))
;; I wrote a program that generated a bunch of warnings. This
;; should be enough to reproduce it.
(defbinary packet ()
(data (buffer) :type (counted-buffer 32)))
(unit-test 'implicit-bit-stream-test
(let ((struct (make-implicit-bit-stream)))
(loop for *byte-order* in '(:little-endian :big-endian)
do
(test-round-trip (format nil "IMPLICIT BIT STREAM TEST (~a)" *byte-order*)
(with-wrapped-in-bit-stream (*standard-output* *standard-output*)
(write-binary struct *standard-output*))
(assert-equalp struct
(with-wrapped-in-bit-stream
(*standard-input* *standard-input*)
(read-binary 'implicit-bit-stream
*standard-input*)))))))
(defbinary example (:untyped-struct t)
(a 0 :type (unsigned-byte 24))
(b 0 :type (magic :actual-type (unsigned-byte 4)
:value 5))
(c 0 :type (unsigned-byte 20)))
(unit-test 'untyped-struct-test
(flexi-streams:with-input-from-sequence (in '(0 0 0))
(handler-bind
(((or end-of-file bad-magic-value)
(lambda (cond)
(declare (ignore cond))
(invoke-restart 'continue))))
(let ((obj (read-binary 'example in)))
(assert= (slot-value obj 'a) 0)
(assert= (slot-value obj 'b) 0)
(assert= (slot-value obj 'c) 0)))))
(defbinary example-2 (:include example)
(d 0 :type (unsigned-byte 8)))
(unit-test 'include-test
(let ((obj (make-example-2 :a #xbedead
:b 4
:c #xbefed
:d #xff)))
(test-round-trip ":INCLUDE test"
(write-binary obj *standard-output*)
(assert-equalp obj (read-binary 'example-2 *standard-input*)))))
(defun run-test ()
(let ((test-results (do-tests)))
(format t ">>>>>>>>>>>>>>>>>>>>>>>> TEST RESULTS: ~S~%" test-results)
(when (loop for (nil result) in test-results
thereis (eq result :fail))
(format t "TEST FAILED")
(loop for (name result) in test-results
when (eq result :fail)
do (format t "~%~S~%" name)
(unit-test::run-test name)))))
| 13,548 | Common Lisp | .lisp | 317 | 37.842271 | 91 | 0.658863 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 2bc8b1907db0fe1f6716f3214e9355ed3f741d26d7688ee23572e65536dadab8 | 2,358 | [
-1
] |
2,359 | tiff.lisp | j3pic_lisp-binary/test/tiff.lisp | (defpackage :tiff-format
(:use :lisp-binary
:common-lisp
:lisp-binary-utils))
(in-package :tiff-format)
(define-enum tiff-type 2 (:byte-order :dynamic)
(:unsigned-byte 1)
:ascii
:unsigned-short
:unsigned-long
:unsigned-rational ;; Two unsigned-longs
:signed-byte
:undefined
:signed-short
:signed-long
:signed-rational
:single-float
:double-float)
(define-enum photometric-interpretation 2 (:byte-order :dynamic)
:low
:high
:rgb)
(define-enum fill-order 2 (:byte-order :dynamic)
(:reversed-bits 1)
(:normal-bits 2))
(defbinary new-subfile-type (:byte-order :dynamic)
(reserved 0 :type (unsigned-byte 29))
(transparency-mask-p 0 :type (unsigned-byte 1))
(one-of-many-pages-p 0 :type (unsigned-byte 1))
(reduced-resolution-p 0 :type (unsigned-byte 1)))
(eval-when (:compile-toplevel :load-toplevel :execute)
;; TODO: Finish this. The number of possible tags is huge, and
;; many of them require complicated handlers to be written
;; for them. I could be at this for months!
(defparameter *tag-info*
`((:new-subfile-type 254
:type new-subfile-type
:n 1
:documentation "A few flags.")
(:image-width 256
:type (or :unsigned-short :unsigned-long)
:n 1)
(:image-length 257
:type (or :unsigned-short :unsigned-long)
:n 1)
(:bits-per-sample 258
:type :unsigned-short
:default 1
:n :samples-per-pixel
:documentation "In an RGB file, there must be a separate
one of these for each of the components.")
(:compression 259
:type :unsigned-short
:n 1
:default 1
:documentation "1 = No compression.
2 = CCITT Group Modified Huffman RLE. :BITS-PER-SAMPLE must be 1.
32773 = PackBits compression.")
(:cell-width 264
:type :unsigned-short
:n 1
:documentation "The width of a dithering or halftoning matrix")
(:cell-length 265
:type :unsigned-short
:n 1
:documentation "The length of a dithering or halftoning matrix. Should only
exist if :THRESHOLDING = 2")
(:photometric-interpretation 262)
(:fill-order 266
:type fill-order
:default :reversed-bits
:n 1
:documentation "If equal to :REVERSED-BITS, then the high-order bit in each
byte of a pixel is actually the low-order bit, and vice versa. If equal to :NORMAL,
then the bytes can be interpreted as they are found on disk. Adobe recommends :REVERSED-BITS,
which is the default, and :NORMAL isn't required to be supported by
TIFF readers.")
(:image-description 270
:type :ascii
:documentation "Some text to describe the image.")
(:scanner-make 271
:type :ascii
:documentation "The manufacturer of the scanner that scanned this image.")
(:scanner-model 272
:type :ascii
:documentation "The model of the scanner that scanned the image.")
(:strip-offsets 273)
(:samples-per-pixel 277)
(:strip-byte-counts 279)
(:rows-per-strip 278)
(:min-sample-value 280
:type :unsigned-short
:default 0
:n :samples-per-pixel
:default 0)
(:max-sample-value 281
:type :unsigned-short
:n :samples-per-pixel
:default (1- (expt 2 :bits-per-sample))
:documentation "The maximum sample value that appears in the image.")
(:x-resolution 282)
(:y-resolution 283)
(:free-offsets 288
:type :unsigned-long
:documentation "Not recommended for general interchange")
(:free-byte-counts 289
:type :unsigned-long
:documentation "Not recommended for general interchange.")
(:gray-response-unit 290
:type :unsigned-short
:n 1
:default 2
:documentation "The absolute value of the negative exponent of 10 that will be
multiplied with the :GRAY-RESPONSE-CURVE to obtain the actual value.")
(:gray-response-curve 291
:type :unsigned-short
:n (expt 2 :bits-per-sample)
:documentation "For grayscale data, the optical density of each pixel.")
(:resolution-unit 296)
(:software 305)
(:datetime 306
:type :ascii
:n 20
:documentation "YYYY:MM:DD HH:MM:SS")
(:artist 315
:type :ascii
:documentation "Who created this? Sometimes contains copyright notice.")
(:host-computer 316
:type :ascii
:documentation "Gratuitous information to compromise the security of the person who created the TIFF file.
Adobe recommends that it contain \"the computer and/or operating system\" of the author.")
(:color-map 320
:type :unsigned-short
:n (* 3 (expt 2 :bits-per-sample))
:documentation "A color map for palletted images.
The first 2^BITS-PER-SAMPLE integers are the reds, the second
set are the greens, and finally the blues. Each integer represents
an intensity of the color whose section of the array it occupies.")
(:extra-samples 338
:type :unsigned-short
:n ":samples-per-pixel - (the number of samples expected given the :PHOTOMETRIC-INTERPRETATION)"
:documentation
"If the :SAMPLES-PER-PIXEL are greater than the number
of components needed for the :PHOTOMETRIC-INTERPRETATION, then this field
defines what each of the extra components is for. This array will contain one element
for each extra component-per-pixel, and each element will have one of the following values:
0 = Unspecified
1 = Associated Alpha with pre-multiplied color
2 = Unassociated alpha"
(:copyright 33432 :type :ascii)))))
(define-enum tag 2 (:byte-order :dynamic)
(:new-subfile-type 254)
(:image-width 256)
(:image-length 257)
(:bits-per-sample 258)
(:compression 259)
(:photometric-interpretation 262)
(:strip-offsets 273)
(:samples-per-pixel 277)
(:strip-byte-counts 279)
(:rows-per-strip 278)
(:x-resolution 282)
(:y-resolution 283)
(:resolution-unit 296)
(:software 305)
(:datetime 306)
(:artist 315)
(:color-map 320))
(define-enum tiff-byte-order 2 (:byte-order :little-endian)
(:little-endian #x4949)
(:big-endian #x4d4d))
(defbinary directory-entry (:byte-order :dynamic)
(tag 0 :type tag)
(type 0 :type tiff-type)
(count 0 :type (unsigned-byte 32))
(value/offset 0 :type (eval
(if (> count 1)
'(unsigned-byte 32)
(ecase type
((:unsigned-long :unsigned-rational :signed-rational :double-float :ascii :undefined)
'(unsigned-byte 32))
(:signed-long '(signed-byte 32))
(:single-float 'single-float)
(:unsigned-byte '(unsigned-byte 8))
(:signed-byte '(signed-byte 8))
(:signed-short '(signed-byte 16))
(:unsigned-short '(unsigned-byte 16))))))
(padding 0 :type (eval (if (> count 1)
'null
(ecase type
((:unsigned-long :unsigned-rational :signed-rational :double-float :ascii :signed-long
:single-float :undefined)
'null)
((:signed-byte :unsigned-byte)
'(unsigned-byte 24))
((:signed-short :unsigned-short)
'(unsigned-byte 16)))))))
(defbinary image-file-directory
(:align 2 :byte-order :dynamic)
(directory-entries #() :type (counted-array 2 directory-entry))
(next-directory-offset 0 :type (unsigned-byte 32)))
(defbinary tiff (:byte-order :dynamic :preserve-*byte-order* nil)
(byte-order 0 :type tiff-byte-order :reader (lambda (stream)
(values
(setf *byte-order* (read-enum 'tiff-byte-order stream))
2)))
(magic 42 :type (magic :actual-type (unsigned-byte 16)
:value 42))
(first-image-file-directory-offset 0 :type (unsigned-byte 32))
(offset-ptr 0 :type (unsigned-byte 32)
:reader (lambda (stream)
(declare (optimize (debug 3) (speed 0)))
(values
(- (file-position stream) 4)
0))
:writer (lambda (obj stream)
(declare (ignore obj))
(setf offset-ptr (- (file-position stream) 4))
0))
(image-directories nil :type list
:reader (lambda (stream)
(let* ((next-directory nil)
(byte-count 0)
(directories
(loop for offset = first-image-file-directory-offset
then (slot-value next-directory 'next-directory-offset)
until (= offset 0)
collect (progn
(file-position stream offset)
(setf next-directory
(multiple-value-bind (dir bytes)
(read-binary 'image-file-directory stream)
(incf byte-count bytes)
dir))))))
(values directories byte-count)))
:writer (lambda (obj stream)
(declare (ignore obj))
(force-output stream)
(let ((real-offset (file-length stream)))
(file-position stream offset-ptr)
(write-integer real-offset 4 stream :byte-order *byte-order*)
(setf first-image-file-directory-offset real-offset)
(file-position stream real-offset)
(loop for (dir . more-dirs) on image-directories sum
(let ((bytes (write-binary dir stream))
(new-eof (file-position stream)))
(force-output stream)
(file-position stream (- new-eof 4))
(write-integer (if more-dirs new-eof 0) 4 stream :byte-order *byte-order*)
bytes))))))
(defun read-tiff-file (filename)
(handler-bind ((bad-enum-value
(lambda (exn)
(unless (eq (slot-value exn 'enum-name) 'tiff-byte-order)
(cond ((slot-value exn 'integer-value)
(invoke-restart 'use-value (make-symbol
(format nil "UNKNOWN-~a" (slot-value exn 'integer-value))))))))))
(with-open-binary-file (in filename)
(read-binary 'tiff in))))
(defun passing-test ()
(with-open-binary-file (in #P"/usr/share/apps/quanta/templates/images/others/demo.tif")
(let ((tiff (read-binary 'tiff in)))
(with-open-binary-file (out #P"/tmp/test.tif"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-binary tiff out))
(with-open-binary-file (in* #P"/tmp/test.tif")
(read-binary 'tiff in*)))))
(defun create-sample-tif (filename)
(with-open-binary-file (out filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-integer #x4d4d002a00000014 8 out :byte-order :big-endian)
(loop for (integer size) in
'((0 12)
(#xc 2)
(#x00fe00040000000100000000 12)
(#x0100000400000001000007d0 12)
(#x010100040000000100000bb8 12)
(#x010300030000000180050000 12)
(#x010600030000000100010000 12)
(#x01110004000000bc000000b6 12)
(#x011600040000000100000010 12)
(#x01170003000000bc000003a6 12)
(#x011a00050000000100000696 12)
(#x011b0005000000010000069e 12)
(#x013100020000000e000006a6 12)
(#x0132000200000014000006b6 12)
(0 4))
do (write-integer integer size out :byte-order :big-endian))))
| 10,889 | Common Lisp | .lisp | 292 | 31.181507 | 113 | 0.661014 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | d00c912e935f27cf83e4f7f287666e8a110800f634c49553c8ad1585280e663c | 2,359 | [
-1
] |
2,360 | setup-test-environment.lisp | j3pic_lisp-binary/test/setup-test-environment.lisp | (load "quicklisp.lisp")
(quicklisp-quickstart:install)
(defun ql-util:press-enter-to-continue ()
t)
(ql:add-to-init-file)
#+sbcl (exit)
#+ccl (ccl:quit)
#+clisp (ext:exit)
| 176 | Common Lisp | .lisp | 8 | 20.5 | 41 | 0.722892 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 452ecf4d2db94134250d39fc70460cf7411569cac7581c0a6bd285a1c5d0c02b | 2,360 | [
-1
] |
2,361 | run-tests.lisp | j3pic_lisp-binary/test/run-tests.lisp | (format t "~%>>>>>>>>>>> Test program loading~%")
(load "init.lisp")
(load "fake-asdf.lisp")
(format t "~%>>>>>>>>>>>>> Loaded init file~%")
(ql:quickload :asdf)
(push '*default-pathname-defaults* asdf:*central-registry*)
(defmacro warnings-to-errors (&body body)
`(handler-bind (((and warning
#-ccl (not asdf/parse-defsystem::bad-system-name))
(lambda (exn) (error exn))))
,@body))
(defun local-projects-dir ()
(with-open-file (in "local-projects-dir.txt")
(let ((result (make-string (file-length in))))
(read-sequence result in)
result)))
(warnings-to-errors
(fake-asdf-load (merge-pathnames (local-projects-dir) "lisp-binary.asd"))
(fake-asdf-load "lisp-binary-test.asd"))
(format t "~%>>>>>>>> LISP-BINARY test system successfully loaded~%")
(lisp-binary-test::run-test)
#+sbcl (exit)
#+clisp (ext:exit)
#+ccl (ccl:quit)
| 865 | Common Lisp | .lisp | 24 | 33.375 | 74 | 0.661483 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | acac6b2b457548b6157c26179f353f7d9f6bfa2a95a46d343890cbb350d96318 | 2,361 | [
-1
] |
2,362 | install-quicklisp | j3pic_lisp-binary/test/install-quicklisp | #!/bin/bash
LISP="$1"
set -x -e -o pipefail
wget --no-check-certificate https://beta.quicklisp.org/quicklisp.lisp
echo " Running SBCL version: " `sbcl --version`
echo "<<<<<<<<<<<<<<<<<< STATS"
echo
free -h
echo
echo '>>>>>>>>>>>>>> INSTALLING QUICKLISP'
(yes '' || true) | $LISP setup-test-environment.lisp
( cd ..
dir=`pwd`
cd ..
cp -fdR $dir $HOME/quicklisp/local-projects
)
echo -n $HOME/quicklisp/local-projects/lisp-binary/ > local-projects-dir.txt
| 470 | Common Lisp | .lisp | 17 | 25.764706 | 76 | 0.673423 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 7021768f32e6e6aa6b3551a200ee64b4fdad7268b1ff4cebedc3dd94679ab4a5 | 2,362 | [
-1
] |
2,363 | unit-test.lisp | j3pic_lisp-binary/test/unit-test.lisp | (defpackage :unit-test
(:use :common-lisp)
(:export :unit-test :do-tests))
(in-package :unit-test)
(defmacro aif (cond true &optional false)
`(let ((it ,cond))
(if it ,true ,false)))
(defmacro set-assoc (key place new-value)
`(aif (assoc ,key ,place)
(setf (cdr it) ,new-value)
(push (cons ,key ,new-value) ,place)))
(defun sift (pred list)
(loop for item in list
if (funcall pred item)
collect item into gold
else collect item into dirt
finally (return (values gold dirt))))
(defparameter *unit-tests* nil)
(defmacro unit-test (name &body body)
`(progn (set-assoc ,name *unit-tests*
(lambda ()
(handler-bind ((condition
(lambda (exn)
(declare (ignorable exn))
(aif (find-restart 'fail-test)
(invoke-restart it)))))
(compile ,name (list 'lambda nil
'(declare (optimize (speed 3) (debug 0)))
(list* 'let nil ',body)))
;; The test has to be run twice: Once compiled and with full optimization,
;; to make it the most likely that compiler macros will be used, and the
;; second time interpreted, to make it unlikely that they'll be used.
;; This way we test both the compiler macro and the real functions
;; where compiler macros exist.
(eval (list* 'let nil ',body))
(funcall ,name)
t)))))
(defun do-tests ()
(sift (lambda (result)
(eq (second result) :fail))
(mapcar (lambda (test)
(format t "~%>>>>> ~a~%" (first test))
(list (first test)
(restart-case
(progn
(funcall (cdr test))
:pass)
(fail-test () :fail)))) *unit-tests*)))
(defun run-test (name)
(funcall (cdr (assoc name *unit-tests*))))
| 1,706 | Common Lisp | .lisp | 50 | 28.88 | 80 | 0.626829 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | fc026dea5644f6989ba2272060b665358bbef00af25193dd011937fd60fd4983 | 2,363 | [
-1
] |
2,364 | pointers.lisp | j3pic_lisp-binary/test/pointers.lisp | (in-package :lisp-binary-test)
(defbinary object-with-pointers ()
(pointer-1 nil :type (pointer :pointer-type (unsigned-byte 16)
:data-type (terminated-string 1)
:base-pointer-name foo-base
:region-tag foo-region))
(pointer-2 0 :type (pointer :pointer-type (unsigned-byte 16)
:data-type quadruple-float
:base-pointer-name foo-base
:region-tag foo-region)))
(defbinary object-with-base-pointer ()
(foo-base 0 :type base-pointer)
(bar nil :type object-with-pointers)
;; POINTER-1 and POINTER-2 will point to this:
(foo-region nil :type (region-tag :base-pointer-name foo-base)))
(with-local-pointer-resolving-context
(let ((input (with-open-binary-file (in "foo.bin")
(read-binary 'foo in))))
(with-open-binary-file (out "bar.bin"
:direction :io)
(write-binary input stream))))
(unit-test 'pointers-and-tags
(let* ((object-with-pointers
(make-object-with-pointers
:pointer-1 "This is a string!"
:pointer-2 22/7))
(object-with-base-pointer
(make-object-with-base-pointer
:bar object-with-pointers)))
(test-round-trip "POINTER AND TAG TEST"
(write-binary object-with-base-pointer *standard-output*)
(let ((round-trip-object (read-binary 'object-with-base-pointer *standard-input*)))
(assert
(<
(abs (- (slot-value
(slot-value round-trip-object 'bar)
'pointer-2)
(slot-value
(slot-value object-with-base-pointer 'bar)
'pointer-2)))
1/1000000))
(setf (slot-value
(slot-value round-trip-object 'bar)
'pointer-2) 22/7)
(assert-equalp object-with-base-pointer
round-trip-object))
:out-direction :io)))
| 1,895 | Common Lisp | .lisp | 47 | 30.829787 | 90 | 0.59631 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 6af39e074e9e6ec36e0bfad42b443d8468186dc9fbca7a7faa37c98255c017b7 | 2,364 | [
-1
] |
2,365 | fake-asdf.lisp | j3pic_lisp-binary/test/fake-asdf.lisp | (defun determine-load-order (components &optional load-order)
"Given the COMPONENTS (which is just the :components section of the ASDF
def above), determine the order in which to load things so that dependencies
are always satisfied."
(cond ((null components)
(reverse load-order))
(t
(destructuring-bind (&key file depends-on) (car components)
(if (every (lambda (dep)
(member dep load-order :test #'string=))
depends-on)
(determine-load-order (cdr components)
(cons file load-order))
(determine-load-order (append (cdr components)
(list (car components)))
load-order))))))
(defmacro acond (&rest cases)
(let ((result nil))
(loop for (condition . body) in (reverse cases)
do (setf result
`(aif ,condition
(progn ,@body)
,result)))
result))
(defmacro aif (test then &optional else)
`(let ((it ,test))
(if it ,then ,else)))
(defun read-all-forms (stream)
(let ((eof (gensym)))
(loop for next-form = (read stream nil eof)
until (eq next-form eof)
collect next-form)))
(defun recursive-find-if (pred tree)
(if (funcall pred tree)
tree
(recursive-find nil tree
:test (lambda (bullshit node)
(declare (ignore bullshit))
(funcall pred node)))))
(defun recursive-find (item tree &key (test #'eql))
(acond ((null tree)
nil)
((atom tree)
(funcall test item tree))
((consp tree)
(acond ((funcall test item (car tree))
(car tree))
((recursive-find item (car tree) :test test)
it)
(t (recursive-find item (cdr tree) :test test))))))
(defun load-system-def (pathname)
(with-open-file (in pathname)
(recursive-find-if
(lambda (form)
(and (consp form)
(eq (car form) 'asdf:defsystem)))
(read-all-forms in))))
(defun components (system-def)
(getf system-def :components))
(defun dirname (pathname)
(let ((directory (pathname-directory pathname))
(name (pathname-name pathname)))
(unless name
(setf directory (butlast directory)))
(let ((dirname (make-pathname :host (pathname-host pathname)
:device (pathname-device pathname)
:directory directory)))
(if (equalp dirname #P"")
nil
dirname))))
(defun fake-asdf-load (asd-pathname)
"Load a system from a .asd file without ASDF."
(let ((system-def (load-system-def asd-pathname)))
(ql:quickload (getf system-def :depends-on))
(let ((*default-pathname-defaults* (or (dirname asd-pathname)
*default-pathname-defaults*)))
(loop for file in (determine-load-order (components system-def))
do (load file)))))
| 2,613 | Common Lisp | .lisp | 78 | 28.910256 | 76 | 0.665214 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | e5ed14adafbbb731aab9b681abc6bea487e9df8d1927a2854cd3c4a37184665b | 2,365 | [
-1
] |
2,366 | type-field-expansion-tests.lisp | j3pic_lisp-binary/test/type-field-expansion-tests.lisp | (in-package :lisp-binary-test)
(defvar *stream* nil)
(defvar *previous-defs* nil)
(defvar *byte-count* nil)
(defvar *index* nil)
(defvar *bit-stream-id* nil)
(defvar *field* nil)
(defun call-form (binary-field-object stream which-form)
(check-type binary-field-object lisp-binary::binary-field)
(let ((*stream* stream))
(eval (slot-value binary-field-object (intern (symbol-name which-form) :lisp-binary)))))
(defmacro with-read-stream (contents &body body)
`(flexi-streams:with-input-from-sequence (*stream* ,contents)
,@body))
(defmacro with-write-stream-to-buffer (&body body)
`(flexi-streams:with-output-to-sequence (*stream*)
,@body))
(defun expand-defbinary-field (default-value &rest keys)
(apply #'lisp-binary::expand-defbinary-field (list* '*field* default-value
:stream-symbol '*stream*
:previous-defs-symbol '*previous-defs*
:byte-count-name '*byte-count*
:bind-index-to '*index*
keys)))
(unit-test 'base-pointer-test
(let ((binary-field-object (expand-defbinary-field 0 :type 'base-pointer)))
(assert-equal (slot-value binary-field-object 'lisp-binary::defstruct-field)
'(*field* 0 :type t))
(let ((lisp-binary::*base-pointer-tags* nil))
(with-read-stream (buffer 0 0 0)
(read-bytes 2 *stream*)
(multiple-value-bind (file-position bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert= bytes-read 0)
(assert= file-position 2)
(assert-equal (assoc '*field* lisp-binary::*base-pointer-tags*)
'(*field* . 2)))))
(with-write-stream-to-buffer
(write-bytes (buffer 0 0) *stream*)
(let ((*field* 0)
(lisp-binary::*base-pointer-tags* nil))
(call-form binary-field-object *stream* :write-form)
(assert= *field* 2)
(assert-equal (assoc '*field* lisp-binary::*base-pointer-tags*)
'(*field* . 2))))))
(unit-test 'file-position-test
(let ((binary-field-object (expand-defbinary-field 0 :type 'file-position)))
(assert-equal (slot-value binary-field-object 'lisp-binary::defstruct-field)
'(*field* 0 :type integer))
(with-read-stream (buffer 0 0 0)
(read-bytes 2 *stream*)
(multiple-value-bind (file-position bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert= bytes-read 0)
(assert= file-position 2)))
(with-write-stream-to-buffer
(write-bytes (buffer 0 0) *stream*)
(assert= (call-form binary-field-object *stream* :write-form) 0)
(assert= *field* 2))))
(unit-test 'custom-type-test
(let ((binary-field-object (expand-defbinary-field nil :type `(custom :reader ,(lambda (stream)
(values (read-byte stream) 1))
:writer ,(lambda (obj stream)
(write-byte obj stream)
1)
:lisp-type (unsigned-byte 4)))))
(assert-equal (slot-value binary-field-object 'lisp-binary::defstruct-field)
'(*field* nil :type (unsigned-byte 4)))
(with-read-stream (buffer 15)
(multiple-value-bind (byte bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert= byte 15)
(assert= bytes-read 1)))
(assert-equalp
(with-write-stream-to-buffer
(let ((*field* 15))
(assert= (call-form binary-field-object *stream* :write-form) 1)))
(buffer 15))))
(unit-test 'magic-number-test
(let ((binary-field-object (expand-defbinary-field nil
:type '(magic :actual-type (unsigned-byte 8)
:value #x56))))
(with-read-stream (buffer 15)
(handler-case
(progn
(call-form binary-field-object *stream* :read-form)
(error "No BAD-MAGIC-VALUE error!"))
(bad-magic-value ()
t)))
(with-read-stream (buffer #x56)
(multiple-value-bind (magic bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert= magic #x56)
(assert= bytes-read 1)))
(assert-equalp
(with-write-stream-to-buffer
(let ((*field* nil))
(call-form binary-field-object *stream* :write-form)))
(buffer #x56))))
(unit-test 'fixed-string-test
(let ((binary-field-object (expand-defbinary-field "12345678"
:type '(fixed-string 8 :padding-character (code-char 1)))))
(assert-equalp (slot-value binary-field-object 'lisp-binary::defstruct-field)
'(*field* "12345678" :type string))
(with-read-stream (buffer 49 50 51 52 53 54 55 56 12 12 12 12 12)
(multiple-value-bind (value bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert-equalp value "12345678")
(assert= bytes-read 8)))
(assert-equalp
(buffer 49 50 51 1 1 1 1 1)
(with-write-stream-to-buffer
(assert= 8
(let ((*field* "123"))
(call-form binary-field-object *stream* :write-form)))))))
(unit-test 'counted-string-test
(let ((binary-field-object (expand-defbinary-field "foobar"
:type '(counted-string 8))))
(assert-equalp (slot-value binary-field-object 'lisp-binary::defstruct-field)
'(*field* "foobar" :type string))
(with-read-stream (buffer 5 0 0 0 0 0 0 0 120 121 122 122 121)
(multiple-value-bind (value bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert-equalp value "xyzzy")
(assert-equalp bytes-read 13)))
(assert-equalp (buffer 5 0 0 0 0 0 0 0 120 121 122 122 121)
(with-write-stream-to-buffer
(let ((*field* "xyzzy"))
(call-form binary-field-object *stream* :write-form))))))
(unit-test 'counted-buffer-test
(let ((binary-field-object (expand-defbinary-field (buffer 1 2 3)
:type '(counted-buffer 1))))
(assert-equalp (slot-value binary-field-object 'lisp-binary::defstruct-field)
`(*field* ,(buffer 1 2 3) :type (simple-array (unsigned-byte 8))))
(with-read-stream (buffer 3 1 2 3)
(multiple-value-bind (buf bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert-equalp buf (buffer 1 2 3))
(assert= bytes-read 4)))
(assert-equalp (buffer 4 4 3 2 1)
(with-write-stream-to-buffer
(let ((*field* (buffer 4 3 2 1)))
(call-form binary-field-object *stream* :write-form))))))
(unit-test 'counted-array-test
(let* ((array-of-strings (coerce (vector "one" "two" "three") 'simple-array))
(binary-field-object (expand-defbinary-field array-of-strings
:type '(counted-array 1 (counted-string 1)
:bind-index-to *index*))))
(with-read-stream (buffer 3 3 111 110 101 3 116 119 111 5 116 104 114 101 101)
(multiple-value-bind (value bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert-equalp value array-of-strings)
(assert= bytes-read 15)))
(assert-equalp (buffer 3 3 111 110 101 3 116 119 111 5 116 104 114 101 101)
(with-write-stream-to-buffer
(let ((*field* array-of-strings))
(call-form binary-field-object *stream* :write-form)))))
(let* ((type `(counted-array 1
(custom :reader (lambda (stream)
(assert= *index* 0)
(values (read-byte stream) 1))
:writer (lambda (obj stream)
(write-byte obj stream)
1)
:lisp-type (unsigned-byte 8))
:bind-index-to *index*))
(binary-field-object (expand-defbinary-field (coerce #() 'simple-array)
:type type)))
(assert-equalp (slot-value binary-field-object 'lisp-binary::defstruct-field)
`(*field* ,(coerce #() 'simple-array) :type (simple-array (unsigned-byte 8))))
(with-read-stream (buffer 1 14)
(multiple-value-bind (byte bytes-read)
(call-form binary-field-object *stream* :read-form)
(assert-equalp byte (buffer 14))
(assert= bytes-read 2)))))
| 7,690 | Common Lisp | .lisp | 175 | 37.8 | 99 | 0.650857 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 7fc66b6f8caafde9b65ab7232e5e581bfc318b2c5050b61968f1671b219ea861 | 2,366 | [
-1
] |
2,367 | lisp-binary.asd | j3pic_lisp-binary/lisp-binary.asd | #-lisp-binary/never-use-own-asdf
(let ((asdf-version (when (find-package :asdf)
(let ((ver (symbol-value
(or (find-symbol (string :*asdf-version*) :asdf)
(find-symbol (string :*asdf-revision*) :asdf)))))
(etypecase ver
(string ver)
(cons (with-output-to-string (s)
(loop for (n . m) on ver
do (princ n s)
(when m (princ "." s)))))
(null "1.0"))))))
(unless (string>= asdf-version "3.1.5")
(pushnew :lisp-binary-upgrade-asdf *features*)))
(asdf:defsystem :lisp-binary
:author ("Jeremy Phelps")
:version "1"
:license "GPLv3"
:description "Declare binary formats as structs and then read and write them."
:depends-on (:closer-mop :moptilities :flexi-streams :quasiquote-2.0
:alexandria #-lisp-binary/no-cffi :cffi)
:components
((:file "binary-1" :depends-on ("utils" "float" "integer" "simple-bit-stream" "reverse-stream"))
(:file "binary-2" :depends-on ("utils" "float" "integer" "simple-bit-stream" "reverse-stream" "binary-1"))
(:file "types" :depends-on ("utils" "binary-1" "binary-2"))
#+(and lisp-binary-upgrade-asdf
(not lisp-binary/never-use-own-asdf)) (:file "asdf")
(:file "simple-bit-stream" :depends-on ("integer" "utils"))
(:file "reverse-stream" :depends-on ("integer"))
(:file "integer" :depends-on ("utils"))
(:file "float" :depends-on ("integer"))
(:file "utils")))
| 1,637 | Common Lisp | .asd | 32 | 39.03125 | 109 | 0.541771 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | ec717961abd6df111f978215fab79ac4a086fdf01016dc0a45262ca68b7a1dc2 | 2,367 | [
-1
] |
2,368 | lisp-binary-test.asd | j3pic_lisp-binary/test/lisp-binary-test.asd | (asdf:defsystem :lisp-binary-test
:author ("Jeremy Phelps")
:version "1"
:license "GPLv3"
:description "Test the LISP-BINARY system."
:depends-on (:lisp-binary)
:components
((:file "unit-test")
(:file "basic-test" :depends-on ("unit-test"))
(:file "single-field-tests" :depends-on ("basic-test"))
(:file "type-field-expansion-tests" :depends-on ("basic-test"))))
| 387 | Common Lisp | .asd | 11 | 32.090909 | 68 | 0.672872 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | b5450cc8e0a31e8e857c7feb02ddf5d90b75ffed565f56228efa0f602bc7eaff | 2,368 | [
-1
] |
2,384 | test-on-implementation | j3pic_lisp-binary/test/test-on-implementation | #!/bin/bash
set -x -e -o pipefail
LISP="$1"
INIT=$HOME/"$2"
$base_dir/install-quicklisp "$LISP"
cp $INIT init.lisp
echo '>>>>>>>>>>>>>> RUNNING TEST'
(yes '' || true) | $LISP run-tests.lisp
rm -rf ~/quicklisp
rm -f init.lisp
rm -rf quicklisp.lisp
| 252 | Common Lisp | .l | 11 | 21.454545 | 39 | 0.65678 | j3pic/lisp-binary | 91 | 15 | 8 | GPL-3.0 | 9/19/2024, 11:25:36 AM (Europe/Amsterdam) | 4cf98e0c718de66cf110ab4c3b78824e6600f9f729a91ee693a39a9e75fe9af9 | 2,384 | [
-1
] |
2,408 | web_with_persistent_backend.lisp | adamtornhill_LispForTheWeb/web_with_persistent_backend.lisp | ;;; Copyright (C) 2014 Adam Tornhill
;;;
;;; Distributed under the GNU General Public License v3.0,
;;; see http://www.gnu.org/licenses/gpl.html
;;; The following module contains parts of the source code for
;;; my book Lisp for the Web. You can get a copy of the book here:
;;; https://leanpub.com/lispweb
(defpackage :retro-games
(:use :cl :cl-who :hunchentoot :parenscript :cl-mongo))
(in-package :retro-games)
;; Domain model
;; ============
;; A simple domain model of our games together with
;; access methods.
(defclass game ()
((name :reader name
:initarg :name)
(votes :accessor votes
:initarg :votes ; when read from persistent storage
:initform 0)))
;; By default the printed representation of CLOS objects isn't
;; particularly informative to a human. We can override the default
;; behaviour by specializing the generic function
;; print-object for our game (print-unreadable-object is
;; just a standard macro that helps us with the stream set-up
;; and display of type information).
(defmethod print-object ((object game) stream)
(print-unreadable-object (object stream :type t)
(with-slots (name votes) object
(format stream "name: ~s with ~d votes" name votes))))
(defmethod vote-for (game)
(incf (votes game)))
;; Backend
;; =======
;; Pre-requisite: a mongod daemon process runs on localhost
;; using the default port.
;; Here we establish a connection to the database games that
;; we'll use for all storage:
(cl-mongo:db.use "games")
;; We store all game documents in the following collection:
(defparameter *game-collection* "game")
;; We encapsulate all knowledge of the concrete storage
;; medium in the following functions:
(defun game->doc (game)
($ ($ "name" (name game))
($ "votes" (votes game))))
(defun doc->game (game-doc)
(make-instance 'game :name (get-element "name" game-doc)
:votes (get-element "votes" game-doc)))
(defmethod vote-for :after (game)
"In this method we update the votes in the persistent storage.
An after method in CLOS gives us an Observer-like behaviour;
once the primary method has run, CLOS invokes our after method."
(let ((game-doc (game->doc game)))
(db.update *game-collection* ($ "name" (name game)) game-doc)))
(defun game-from-name (name)
"Queries the database for a game matching the
given name.
Note that db.find behaves like Mongo's findOne by default, so
when we found-games we know there can be only one."
(let ((found-games (docs (db.find *game-collection* ($ "name" name)))))
(when found-games
(doc->game (first found-games)))))
(defun game-stored? (name)
(game-from-name name))
(defun games ()
"Returns a sequence of all games, sorted on
their number of votes in descending order.
The implementation is straightforwards since
cl-mongo provides a db.sort macro. We just need
to remember that we get a lazy sequence back and
have to realize it (iterate to the end) using iter."
(mapcar #'doc->game
(docs (iter (db.sort *game-collection* :all
:field "votes"
:asc nil)))))
(defun unique-index-on (field)
(db.ensure-index *game-collection*
($ field 1)
:unique t))
;; We want to avoid duplicates. In the current version with
;; a limited domain model, the name alone is used for uniqueness.
;; As we evolve the domain we probably want to modify this constraint too.
(unique-index-on "name")
(defun add-game (name)
"Add a game with the given name to the database.
In this version we don't check for duplicates."
(let ((game (make-instance 'game :name name)))
(db.insert *game-collection* (game->doc game))))
;; Web Server - Hunchentoot
(defun start-server (port)
(start (make-instance 'easy-acceptor :port port)))
(defun publish-static-content ()
(push (create-static-file-dispatcher-and-handler
"/logo.jpg" "static/Commodore64.jpg") *dispatch-table*)
(push (create-static-file-dispatcher-and-handler
"/retro.css" "static/retro.css") *dispatch-table*))
;; DSL for our web pages
;; =====================
;; Here we grow a small domain-specific language for
;; creating dynamic web pages.
; Control the cl-who output format (default is XHTML, we
; want HTML5):
(setf (html-mode) :html5)
(defmacro standard-page ((&key title script) &body body)
"All pages on the Retro Games site will use the following macro;
less to type and a uniform look of the pages (defines the header
and the stylesheet).
The macro also accepts an optional script argument. When present, the
script form is expected to expand into valid JavaScript."
`(with-html-output-to-string
(*standard-output* nil :prologue t :indent t)
(:html :lang "en"
(:head
(:meta :charset "utf-8")
(:title ,title)
(:link :type "text/css"
:rel "stylesheet"
:href "/retro.css")
,(when script
`(:script :type "text/javascript"
(str ,script))))
(:body
(:div :id "header" ; Retro games header
(:img :src "/logo.jpg"
:alt "Commodore 64"
:class "logo")
(:span :class "strapline"
"Vote on your favourite Retro Game"))
,@body))))
;; HTML
;; ====
;; The functions responsible for generating the actual pages of our app go here.
;; We use the Hunchentoot macro define-easy-handler to automatically
;; push our uri to the dispatch table of the server and associate the
;; request with a function that will handle it.
(define-easy-handler (retro-games :uri "/retro-games") ()
(standard-page (:title "Top Retro Games")
(:h1 "Vote on your all time favourite retro games!")
(:p "Missing a game? Make it available for votes " (:a :href "new-game" "here"))
(:h2 "Current stand")
(:div :id "chart" ; Used for CSS styling of the links.
(:ol
(dolist (game (games))
(htm
(:li (:a :href (format nil "vote?name=~a" (url-encode ; avoid injection attacks
(name game))) "Vote!")
(fmt "~A with ~d votes" (escape-string (name game))
(votes game)))))))))
(define-easy-handler (new-game :uri "/new-game") ()
(standard-page (:title "Add a new game"
:script (ps ; client side validation
(defvar add-form nil)
(defun validate-game-name (evt)
"For a more robust event handling
mechanism you may want to consider
a library (e.g. jQuery) that encapsulates
all browser-specific quirks."
(when (= (@ add-form name value) "")
(chain evt (prevent-default))
(alert "Please enter a name.")))
(defun init ()
(setf add-form (chain document
(get-element-by-id "addform")))
(chain add-form
(add-event-listener "submit" validate-game-name false)))
(setf (chain window onload) init)))
(:h1 "Add a new game to the chart")
(:form :action "/game-added" :method "post" :id "addform"
(:p "What is the name of the game?" (:br)
(:input :type "text" :name "name" :class "txt"))
(:p (:input :type "submit" :value "Add" :class "btn")))))
(define-easy-handler (game-added :uri "/game-added") (name)
(unless (or (null name) (zerop (length name))) ; In case JavaScript is turned off.
(add-game name))
(redirect "/retro-games")) ; back to the front page
(define-easy-handler (vote :uri "/vote") (name)
(when (game-stored? name)
(vote-for (game-from-name name)))
(redirect "/retro-games")) ; back to the front page
;; Alright, everything has been defined - launch Hunchentoot and have it
;; listen to incoming requests:
(publish-static-content)
(start-server 8080)
| 8,478 | Common Lisp | .lisp | 184 | 37.141304 | 99 | 0.605642 | adamtornhill/LispForTheWeb | 85 | 28 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | c1d40e54390215cdf0892bb9e60ca6665a730a0e7f6a558ffcb25d596d67dd2e | 2,408 | [
-1
] |
2,409 | web_with_proto_backend.lisp | adamtornhill_LispForTheWeb/web_with_proto_backend.lisp | ;;; Copyright (C) 2014 Adam Tornhill
;;;
;;; Distributed under the GNU General Public License v3.0,
;;; see http://www.gnu.org/licenses/gpl.html
;;; The following module contains parts of the source code for
;;; my book Lisp for the Web. You can get a copy of the book here:
;;; https://leanpub.com/lispweb
(defpackage :retro-games
(:use :cl :cl-who :hunchentoot :parenscript))
(in-package :retro-games)
;; Domain model
;; ============
;; A simple domain model of our games together with
;; access methods.
(defclass game ()
((name :reader name
:initarg :name)
(votes :accessor votes
:initform 0)))
;; By default the printed representation of CLOS objects isn't
;; particularly informative to a human. We can override the default
;; behaviour by specializing the generic function
;; print-object for our game (print-unreadable-object is
;; just a standard macro that helps us with the stream set-up
;; and display of type information).
(defmethod print-object ((object game) stream)
(print-unreadable-object (object stream :type t)
(with-slots (name votes) object
(format stream "name: ~s with ~d votes" name votes))))
(defmethod vote-for (game)
(incf (votes game)))
;; Backend
;; =======
;; A prototypic backend that stores all games in
;; a list. Later, we'll move to a persistent storage and
;; only need to modify these accessor functions:
(defvar *games* '())
;; We encapsulate all knowledge of the concrete storage
;; medium in the following functions:
(defun game-from-name (name)
(find name *games* :test #'string-equal :key #'name))
(defun game-stored? (game-name)
(game-from-name game-name))
(defun games ()
(sort (copy-list *games*) #'> :key #'votes))
(defun add-game (name)
(unless (game-stored? name)
(push (make-instance 'game :name name) *games*)))
;; Web Server - Hunchentoot
(defun start-server (port)
(start (make-instance 'easy-acceptor :port port)))
(defun publish-static-content ()
(push (create-static-file-dispatcher-and-handler
"/logo.jpg" "static/Commodore64.jpg") *dispatch-table*)
(push (create-static-file-dispatcher-and-handler
"/retro.css" "static/retro.css") *dispatch-table*))
;; DSL for our web pages
;; =====================
;; Here we grow a small domain-specific language for
;; creating dynamic web pages.
; Control the cl-who output format (default is XHTML, we
; want HTML5):
(setf (html-mode) :html5)
;; This is the initial version of our standard page template.
;; We'll evolve it later in the tutorial, making it accept
;; scripts as well (used to inject JavaScript for validation
;; into the HTML header).
(defmacro standard-page-1 ((&key title) &body body)
"All pages on the Retro Games site will use the following macro;
less to type and a uniform look of the pages (defines the header
and the style sheet)."
`(with-html-output-to-string
(*standard-output* nil :prologue t :indent t)
(:html :lang "en"
(:head
(:meta :charset "utf-8")
(:title ,title)
(:link :type "text/css"
:rel "stylesheet"
:href "/retro.css"))
(:body
(:div :id "header" ; Retro games header
(:img :src "/logo.jpg"
:alt "Commodore 64"
:class "logo")
(:span :class "strapline"
"Vote on your favourite Retro Game"))
,@body))))
(defmacro standard-page ((&key title script) &body body)
"All pages on the Retro Games site will use the following macro;
less to type and a uniform look of the pages (defines the header
and the stylesheet).
The macro also accepts an optional script argument. When present, the
script form is expected to expand into valid JavaScript."
`(with-html-output-to-string
(*standard-output* nil :prologue t :indent t)
(:html :lang "en"
(:head
(:meta :charset "utf-8")
(:title ,title)
(:link :type "text/css"
:rel "stylesheet"
:href "/retro.css")
,(when script
`(:script :type "text/javascript"
(str ,script))))
(:body
(:div :id "header" ; Retro games header
(:img :src "/logo.jpg"
:alt "Commodore 64"
:class "logo")
(:span :class "strapline"
"Vote on your favourite Retro Game"))
,@body))))
;; HTML
;; ====
;; The functions responsible for generating the actual pages of our app go here.
;; We use the Hunchentoot macro define-easy-handler to automatically
;; push our uri to the dispatch table of the server and associate the
;; request with a function that will handle it.
(define-easy-handler (retro-games :uri "/retro-games") ()
(standard-page (:title "Top Retro Games")
(:h1 "Vote on your all time favourite retro games!")
(:p "Missing a game? Make it available for votes " (:a :href "new-game" "here"))
(:h2 "Current stand")
(:div :id "chart" ; Used for CSS styling of the links.
(:ol
(dolist (game (games))
(htm
(:li (:a :href (format nil "vote?name=~a" (url-encode ; avoid injection attacks
(name game))) "Vote!")
(fmt "~A with ~d votes" (escape-string (name game))
(votes game)))))))))
(define-easy-handler (new-game :uri "/new-game") ()
(standard-page (:title "Add a new game"
:script (ps ; client side validation
(defvar add-form nil)
(defun validate-game-name (evt)
"For a more robust event handling
mechanism you may want to consider
a library (e.g. jQuery) that encapsulates
all browser-specific quirks."
(when (= (@ add-form name value) "")
(chain evt (prevent-default))
(alert "Please enter a name.")))
(defun init ()
(setf add-form (chain document
(get-element-by-id "addform")))
(chain add-form
(add-event-listener "submit" validate-game-name false)))
(setf (chain window onload) init)))
(:h1 "Add a new game to the chart")
(:form :action "/game-added" :method "post" :id "addform"
(:p "What is the name of the game?" (:br)
(:input :type "text" :name "name" :class "txt"))
(:p (:input :type "submit" :value "Add" :class "btn")))))
(define-easy-handler (game-added :uri "/game-added") (name)
(unless (or (null name) (zerop (length name))) ; In case JavaScript is turned off.
(add-game name))
(redirect "/retro-games")) ; back to the front page
(define-easy-handler (vote :uri "/vote") (name)
(when (game-stored? name)
(vote-for (game-from-name name)))
(redirect "/retro-games")) ; back to the front page
;; Alright, everything has been defined - launch Hunchentoot and have it
;; listen to incoming requests:
(publish-static-content)
(start-server 8080)
| 7,564 | Common Lisp | .lisp | 168 | 35.357143 | 99 | 0.583978 | adamtornhill/LispForTheWeb | 85 | 28 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 495abd4e62a2d301caa8b39f3ffc26f66973b2b9a1029b4aba0319d4e4c2c273 | 2,409 | [
-1
] |
2,410 | map_reduce_in_mongo.lisp | adamtornhill_LispForTheWeb/map_reduce_in_mongo.lisp | ;;; Copyright (C) 2014 Adam Tornhill
;;;
;;; Distributed under the GNU General Public License v3.0,
;;; see http://www.gnu.org/licenses/gpl.html
;;; The following module contains parts of the source code for
;;; my book Lisp for the Web. You can get a copy of the book here:
;;; https://leanpub.com/lispweb
(defpackage :retro-games
(:use :cl :parenscript :cl-mongo))
(in-package :retro-games)
;; Domain model
;; ============
;; I've extended the model in comparison
;; with earlier versions. Now we're also able to categorize
;; a game. I've removed the CLOS functions here in order to
;; keep this module as minimalistic as possible:
(defclass game ()
((name :reader name
:initarg :name)
(votes :accessor votes
:initarg :votes
:initform 0)
(category :accessor category
:initarg :category)))
;; Backend
;; =======
;; Pre-requisite: a mongod daemon process runs on localhost
;; using the default port.
;; Here we establish a connection to the database games that
;; we'll use for all storage:
(cl-mongo:db.use "games")
;; We store all game documents in the following collection:
(defparameter *game-collection* "game")
;; A stripped-down version, just enough to store some games:
(defun game->doc (game)
(with-slots (name votes category) game
($ ($ "name" name)
($ "votes" votes)
($ "category" category))))
(defun add-game (name category)
"Add a game with the given name to the database.
In this version we don't check for duplicates."
(let ((game (make-instance 'game :name name :category category)))
(db.insert *game-collection* (game->doc game))))
;; MapReduce
;; =========
;; MongoDB supports a mapReduce database command.
;; All we have to do as a client is to supply the map- and
;; reduce-functions to mongo. Mongo will execute the algorithm
;; in its daemon process (mongod).
;;
;; To invoke mapReduce, we define client-side JavaScript functions:
;; First our map-function. This one emits once for each game
;; category. Since we want to sum all games withing a category,
;; our value is a constant one (1).
(defjs map_category()
(emit this.category 1))
;; The reducer is straightforward: just sum up all values for
;; the given category (c). Since map_category emitted 1's, the
;; length of vals should actually be our answer.
(defjs sum_games(c vals)
((@ *array sum) vals))
;; cl-mongo provides a convenience macro for remote execution of
;; mapReduce. If we have defined the JavaScript functions we just
;; need to provide them _without_ any quoting (that's done in the
;; $map-reduce macro):
(defun sum-by-category ()
(pp (mr.p ($map-reduce "game" map_category sum_games))))
;; An alternative is to provide the raw JavaScript functions here.
;; That functions are identical to the ones generated by Parenscript,
;; sans the outer paranthesis.
(defun sum-by-category-1 ()
(pp (mr.p ($map-reduce "game"
"function (x) { return emit(this.category, 1);};"
"function (c, vals) { return Array.sum(vals);};"))))
| 3,096 | Common Lisp | .lisp | 75 | 38.026667 | 77 | 0.694639 | adamtornhill/LispForTheWeb | 85 | 28 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 8b9a7190b81185a1671d68aecdc4cec76cee25a70b0410b18bdb2b74eb7836cb | 2,410 | [
-1
] |
2,429 | build.lisp | hoytech_antiweb/build.lisp | ;; Antiweb (C) Doug Hoyte
;;;;;;;;;;;;;;; ANTIWEB BUILD OPTIONS ;;;;;;;;;;;;;;;;;
;; TIP: These options can be set in a file called local.lisp
;; For example: (setq aw-bin-dir "/usr/local/bin")
;; Directory to put antiweb perl launch script
(defvar aw-bin-dir "/usr/bin")
;; Directory to put libantiwebBITS.so and antiweb.SYS.image
(defvar aw-lib-dir "/usr/lib")
;; See lisp compiler messages during build of bundled libs?
(defvar aw-debugging nil)
;; Compile in BerkeleyDB support? Requires BerkeleyDB 4.6+
(defvar aw-use-bdb nil)
;; Extra flags for gcc
(defvar aw-extra-cflags "")
;; Lisp executables
(defvar aw-cmu-executable "lisp")
(defvar aw-clisp-executable "clisp")
(defvar aw-ccl-executable "ccl64")
(defvar aw-sbcl-executable "sbcl")
;;;;;;;;;;;;;;; END OF ANTIWEB BUILD OPTIONS ;;;;;;;;;;;;;;;;;
(defvar aw-warning-cflags "-Wall -Wformat=2 -Wpointer-arith")
(format t "************* Antiweb Build Script *************~%")
(ignore-errors
(load "local.lisp")
(format t "BUILD: Loaded site-local configuration from local.lisp~%"))
(defmacro redirect-standard-output-to-dev-null (&rest body)
`(let ((out *standard-output*))
(ignore-errors
(handler-bind ((error (lambda (c)
(format out "~%There was an ERROR building a bundled dependency:~2%")
(format out "~a~2%" c)
(format out "Trying to proceed anyways...~2%"))))
,(if aw-debugging
`(progn ,@body)
`(with-open-file (*standard-output* "/dev/null" :direction :output :if-exists :append)
(let ((*error-output* *standard-output*))
,@body)))))))
#+clisp (setq *compile-verbose* nil)
(format t "BUILD: Compiling and loading CL-PPCRE (please be patient)~%")
(redirect-standard-output-to-dev-null (load "bundled/cl-ppcre/load.lisp"))
(setf cl-ppcre:*regex-char-code-limit* 256)
(setf cl-ppcre:*use-bmh-matchers* nil)
(format t "BUILD: Compiling and loading CFFI (please be patient)~%")
(redirect-standard-output-to-dev-null (load "bundled/cffi/load.lisp"))
(format t "BUILD: Compiling and loading Let Over Lambda, Antiweb production edition~%")
(redirect-standard-output-to-dev-null
(load "bundled/lol.lisp") ; Need to load before compiling because it uses its own read macros
(load (compile-file "bundled/lol.lisp")))
(format t "BUILD: Compiling and loading ISAAC random number generator~%")
(redirect-standard-output-to-dev-null
(load (compile-file "bundled/isaac.lisp")))
(format t "BUILD: Compiling and loading jsmin.lisp~%")
(redirect-standard-output-to-dev-null
(load (compile-file "bundled/jsmin.lisp")))
(format t "BUILD: Compiling and loading local-time~%")
(redirect-standard-output-to-dev-null
(load (compile-file "bundled/local-time.lisp")))
(format t "BUILD: Compiling and loading yason~%")
(redirect-standard-output-to-dev-null
(load "bundled/yason/load.lisp"))
(cffi:defcfun ("system" silent-system) :int (command :string))
(defun system (command)
(format t "SYSTEM: ~a~%" command)
(silent-system command))
(system "mkdir -p bin/")
(defvar aw-endian)
(defvar aw-bits)
(with-open-file (o "temp-type-size-finder.c" :direction :output :if-exists :supersede)
(format o #"
#include <stdio.h>
#include <sys/types.h>
#include <arpa/inet.h>
int main() {
printf("ilp %d %d %d\n", (int) sizeof(int), (int) sizeof(long), (int) sizeof(char *));
printf("time_t %d\n", (int) sizeof(time_t));
printf("off_t %d\n", (int) sizeof(off_t));
printf("size_t %d\n", (int) sizeof(size_t));
printf("endian %s\n", 1==htonl(1) ? "big" : "little");
return 0;
}
"#))
(system (format nil "gcc ~a -Wall -D_FILE_OFFSET_BITS=64 temp-type-size-finder.c -o temp-type-size-finder" aw-extra-cflags))
(system "./temp-type-size-finder > temp-type-size-finder.output")
(format t "BUILD: Discovering architecture... ")
(funcall (compile nil (lambda ()
(with-open-file (h "temp-type-size-finder.output" :direction :input)
(loop for l = (read-line h nil nil) while l do
(if-match (#~m/^ilp (\d+) (\d+) (\d+)/ l)
(setq aw-bits
(cond ((and (equal $1 "4") (equal $2 "4") (equal $3 "4")) 32) ; ILP32
((and (equal $1 "4") (equal $2 "8") (equal $3 "8")) 64) ; LP64
(t (error "unexpected architecture")))))
(if-match (#~m/^time_t (\d+)/ l)
(eval `(cffi:defctype :time_t ,(cond ((equal $1 "4") :int32)
((equal $1 "8") :int64)
(t (error "unexpected time_t value"))))))
(if-match (#~m/^off_t (\d+)/ l)
(eval `(cffi:defctype :off_t ,(cond ((equal $1 "4") (error "off_t must be 64 bits"))
((equal $1 "8") :int64)
(t (error "unexpected off_t value"))))))
(if-match (#~m/^size_t (\d+)/ l)
(eval `(cffi:defctype :size_t ,(cond ((equal $1 "4") :uint32)
((equal $1 "8") :uint64)
(t (error "unexpected size_t value"))))))
(if-match (#~m/^endian big$/ l)
(setq aw-endian 'big))
(if-match (#~m/^endian little$/ l)
(setq aw-endian 'little)))))))
(format t #"Detected ~a, ~a-endian~%"#
(ecase aw-bits
((32) "ILP32")
((64) "LP64"))
(ecase aw-endian
((little) "little")
((big) "big")))
(system "rm temp-type-size-finder*")
(setf *print-pretty* nil) ; faster on all platforms and required for clisp
(defconstant crlf (coerce '(#\return #\linefeed) 'string))
(defvar aw-isaac-ctx)
(defvar conn-table (make-hash-table))
(defvar inet-conn-table (make-hash-table))
(defvar worker-conn-table (make-hash-table))
(defvar locked-worker-table (make-hash-table))
(defvar host-to-conn-dispatch-table (make-hash-table :test #'equalp))
(defvar aw-hub-conf)
(defvar aw-hub-dir) ; used by hub AND workers
(defvar aw-worker-conf)
(defvar aw-worker-cache)
(defvar aw-worker-chroot)
(defvar all-antiweb-modules nil)
(defvar aw-fast-files-table (make-hash-table :test #'equal))
(defvar aw-start-time)
(defvar hub-stats-total-conns 0)
(defvar hub-stats-dispatched-conns 0)
(defvar worker-stats-total-conns 0)
(defvar worker-stats-total-requests 0)
(defun load-libantiweb ()
(cffi:load-foreign-library `(:default ,(format nil "libantiweb~a" aw-bits))))
(format t "BUILD: Compiling libantiweb~a.so~%" aw-bits)
(system (format nil "gcc ~a ~a -fPIC -s -O3 -D_FORTIFY_SOURCE=2 -D_FILE_OFFSET_BITS=64 -D~a_ENDIAN ~a-DUSE_~a src/libantiweb.c bundled/sha1.c -lz ~a-shared -o bin/libantiweb~a.so"
aw-extra-cflags
aw-warning-cflags
(if (eq aw-endian 'big) "BIG" "LITTLE")
(if aw-use-bdb "-DUSE_BDB " "")
#+(or linux :clc-os-debian) "EPOLL" #-(or linux :clc-os-debian) "KQUEUE"
(if aw-use-bdb "-ldb " "")
aw-bits))
(format t "BUILD: Linking in ./bin/libantiweb~a.so~%" aw-bits)
(let ((cffi:*foreign-library-directories* '("./bin/")))
(load-libantiweb))
;; HACK for CMUCL: After loading a library from a specific directory, CMUCL will store the
;; full path of the library in system::*global-table*. Instead, we change the value of
;; system::*global-table* manually before the image is saved so that it's loaded from
;; the system directory when the image is restarted.
#+cmu
(loop for i in system::*global-table* do
(if (cdr i)
(if-match (#~m|/(libantiweb\d\d[.]so)$| (cdr i))
(setf (cdr i) $1))))
;; HACK for CMUCL: On start-up, when CMUCL re-loads the antiweb foreign library it prints
;; the text Reloaded library "libantiweb32.so" which clutters the output of most antiweb
;; commands. This hack removes the function that prints this from ext:*after-save-initializations*
;; and puts in place a function that executes the original function but discards what was
;; written to standard output.
#+cmu
(when (ignore-errors (symbol-function 'system::reinitialize-global-table)) ; do nothing if this changes in CMUCL
(setf ext:*after-save-initializations*
(delete #'system::reinitialize-global-table ext:*after-save-initializations*))
(push
(funcall (compile nil (lambda ()
(let ((orig-global-table (symbol-function 'system::reinitialize-global-table)))
(lambda ()
(with-output-to-string (*standard-output*)
(funcall orig-global-table)))))))
ext:*after-save-initializations*))
(format t "BUILD: Converting libantiweb.h into libantiweb-h.lisp and loading it~%")
(funcall (compile nil (lambda ()
(with-open-file (h "src/libantiweb.h" :direction :input)
(with-open-file (o "src/libantiweb-h.lisp" :direction :output :if-exists :supersede)
(format o ";; DO NOT MODIFY THIS FILE~%;; It is autogenerated from libantiweb.h~%")
(loop for l = (read-line h nil nil) while l do
(setq l (#~s|//.*$|| l))
(setq l (#~s|\s*$|| l))
(labels ((proc-fun-args (s)
(let ((args (cl-ppcre:split "," s)))
(mapcar
(lambda (a)
(or (if-match (#~m/^\s*(\S+) ([^*]\S*)\s*$/ a)
(format nil " (~a :~a)" $2 $1))
(if-match (#~m/[*](\S*)\s*$/ a)
(format nil " (~a :pointer)" $1))))
args))))
(format o "~a~%"
(or
(if-match (#~m/^#define (\S+) (\S+)$/ l)
(format nil #"(defconstant ~a ~a)"# $1 $2))
(if-match (#~m/^struct (\S+) {$/ l)
(format nil #"(cffi:defcstruct ~a"# $1)) ; )
(if-match (#~m/^};$/ l) ; (
(format nil #")"#))
(if-match (#~m/^ (\S+) ([^*]\S*);$/ l)
(format nil #" (~a :~a)"# $2 $1))
(if-match (#~m/^ .*[*](\S*);$/ l)
(format nil #" (~a :pointer)"# $1))
(if-match (#~m/^extern (\S+) ([^*]\S*);$/ l)
(format nil #"(cffi:defcvar ("~a" ~a) :~a)"# $2 $2 $1))
(if-match (#~m/^extern .*[*](\S*);$/ l)
(format nil #"(cffi:defcvar ("~a" ~a) :pointer)"# $1 $1))
(if-match (#~m/^.* [*](\S+)\((.*)\);$/ l)
(format nil #"(cffi:defcfun ("~a" ~a) :pointer~% ~a)"#
$1 $1 (apply #'concatenate 'string (proc-fun-args $2))))
(if-match (#~m/^(\S+) ([^*]\S+)\((.*)\);$/ l)
(format nil #"(cffi:defcfun ("~a" ~a) :~a~% ~a)"#
$2 $2 $1 (apply #'concatenate 'string (proc-fun-args $3))))
"")))))))))
(load "src/libantiweb-h.lisp")
(format t "BUILD: Compiling and loading the Antiweb system:~%")
(dolist (f '("conf" "awp" "mime-types" "antiweb" "modules" "glue"))
(format t #"LISP: (load (compile-file "src/~a.lisp"))~%"# f)
(load (compile-file (format nil "src/~a.lisp" f))))
(format t "BUILD: Creating Antiweb launch script~%")
(with-open-file (o "bin/antiweb" :direction :output :if-exists :supersede)
(format o #"#!/usr/bin/env perl~%"#)
(format o #"use strict;~%"#)
(format o #"my $cl_sys = "~a";~%"# #+cmu "cmu" #+clisp "clisp" #+ccl "ccl" #+sbcl "sbcl")
(format o #"my $bin_dir = "~a";~%"# aw-bin-dir)
(format o #"my $lib_dir = "~a";~%"# aw-lib-dir)
(format o #"my $bits = ~a;~%"# aw-bits)
(format o #"my $AW_VERSION = "~a";~%"# AW_VERSION)
(format o #"my $cmu_exec = "~a";~%"# aw-cmu-executable)
(format o #"my $clisp_exec = "~a";~%"# aw-clisp-executable)
(format o #"my $ccl_exec = "~a";~%"# aw-ccl-executable)
(format o #"my $sbcl_exec = "~a";~%"# aw-sbcl-executable)
(princ #>END_OF_ANTIWEB_LAUNCH_SCRIPT
sub usage {
print <<END;
Antiweb v$AW_VERSION Launch Script - (C) Doug Hoyte
antiweb [optional flags] -command [parameters]
Installation Skeletons:
antiweb -skel-hub-dir <hub directory to create>
antiweb -skel-worker-basic
antiweb -skel-worker-full
antiweb -skel-worker-chrooted
Launching Antiweb:
antiweb -hub <hub directory>
antiweb -worker <worker conf file>
antiweb -check-worker <worker conf file>
Maintenance/Development:
antiweb -version [hub directory or worker conf file]
antiweb -reload <worker conf file>
antiweb -reopen-log-files <hub directory>
antiweb -add-listener <hub directory> <ip> <port>
antiweb -close-listener <hub directory> <ip> <port>
antiweb -kill <hub directory or worker conf file>
antiweb -stats <hub directory or worker conf file>
antiweb -room <hub directory or worker conf file>
antiweb -attach <hub directory or worker conf file>
antiweb -repl
antiweb -eval <expression>
antiweb -awp <awp file> <base directory>
Optional Flags:
-cmu -clisp -ccl -sbcl -nodaemon -noreadline
END
exit;
}
my $switch;
my $nodaemon;
my $noreadline;
while(1) {
$switch = shift or usage();
if ($switch eq "-cmu") {
$cl_sys = "cmu";
} elsif ($switch eq "-clisp") {
$cl_sys = "clisp";
} elsif ($switch eq "-ccl") {
$cl_sys = "ccl";
} elsif ($switch eq "-sbcl") {
$cl_sys = "sbcl";
} elsif ($switch eq "-nodaemon") {
$nodaemon = 1;
} elsif ($switch eq "-noreadline") {
$noreadline = 1;
} else {
last;
}
}
sub exec_lisp {
my $expr = shift;
if ($cl_sys eq "cmu") {
exec("$cmu_exec -quiet -core '$lib_dir/antiweb.cmu.image' -eval '$expr'");
die "Couldn't exec CMUCL program '$cmu_exec'";
} elsif ($cl_sys eq "clisp") {
my $q="";
$q = "cat | " if $noreadline;
exec("$q $clisp_exec -q -repl -M '$lib_dir/antiweb.clisp.image' -x '$expr'");
die "Couldn't exec CLISP program '$clisp_exec'";
} elsif ($cl_sys eq "ccl") {
exec("$ccl_exec -Q -I '$lib_dir/antiweb.ccl.image' -e '$expr'");
die "Couldn't exec ClozureCL program '$ccl_exec'";
} elsif ($cl_sys eq "sbcl") {
exec("$sbcl_exec --noinform --core '$lib_dir/antiweb.sbcl.image' --eval '$expr'");
die "Couldn't exec SBCL program '$sbcl_exec'";
}
die "Unknown cl_sys: $cl_sys";
}
sub attempt_connection_to_unix_socket {
use IO::Socket;
my $path = shift;
my $sock = IO::Socket::UNIX->new(Peer => $path, Type => SOCK_STREAM, Timeout => 2);
if (defined $sock) {
close($sock);
return 1;
}
return undef;
}
sub my_sleep {
my $v = shift;
select(undef,undef,undef,$v);
}
if ($switch eq "-hub") {
my $arg = shift or usage();
die "Not a hub directory: $arg" unless (-d $arg);
die "Path to hub directory must be absolute" unless $arg =~ m|^/|;
die "Couldn't find $arg/hub.conf" unless (-f "$arg/hub.conf");
die "Couldn't find $arg/aw_log/" unless (-d "$arg/aw_log");
die "Couldn't find $arg/empty/" unless (-d "$arg/empty");
if (attempt_connection_to_unix_socket("$arg/hub.socket")) {
print STDERR "Hub already running in hub directory '$arg'\n";
print STDERR "run 'antiweb -kill $arg' to stop it\n";
exit(-1);
}
my $rv = fork();
die "couldn't fork: $!" unless defined $rv;
if ($nodaemon) {
# When nodaemon mode is on, the hub process runs in the foreground
# but the logger process runs in the background. To do this, a child
# process is started before the hub process which waits a short amount
# of time and then launches the logger process
if ($rv == 0) {
my_sleep(0.5);
my $rv = fork();
die "couldn't fork: $!" unless defined $rv;
if ($rv) {
print "Started logger process ($rv)\n";
waitpid($rv, 0);
print "Logger process ($rv) terminated\n";
exit;
} else {
print "Launching logger process ($$)\n";
exec_lisp("(run-logger \"$arg\" t)");
}
}
print "Launching hub process ($$)\n";
exec_lisp("(run-hub \"$arg\" t)");
} else {
# In regular operation, a child process is forked which launches the hub
# in the background. If it exits successfully, the logger process is also
# launched in the background.
if ($rv == 0) {
exec_lisp("(run-hub \"$arg\")");
}
waitpid($rv, 0);
if ($?) {
print STDERR "antiweb: Unable to start hub process: $?\n";
} else {
exec_lisp("(run-logger \"$arg\")") unless $?;
}
}
print STDERR "*** Failed to start Antiweb ***\n";
exit(-1);
} elsif ($switch eq "-worker") {
my $arg = shift or usage();
die "Not a worker conf: $arg" unless (-f $arg);
die "Path to worker conf must be absolute" unless $arg =~ m|^/|;
if ($nodaemon) {
print "Launching worker process ($$)\n";
exec_lisp("(run-worker \"$arg\" :nodaemon t)");
}
exec_lisp("(run-worker \"$arg\")");
} elsif ($switch eq "-check-worker") {
my $arg = shift or usage();
die "Not a worker conf: $arg" unless (-f $arg);
die "Path to worker conf must be absolute" unless $arg =~ m|^/|;
if ($nodaemon) {
print "Checking worker process ($$)\n";
exec_lisp("(run-worker \"$arg\" :nodaemon t :checking t)");
}
exec_lisp("(run-worker \"$arg\" :checking t)");
} elsif ($switch eq "-reload") {
my $arg = shift or usage();
die "Not a worker conf: $arg" unless (-f $arg);
die "Path to worker conf must be absolute" unless $arg =~ m|^/|;
exec_lisp("(run-reload-worker-conf \"$arg\")");
} elsif ($switch eq "-reopen-log-files") {
my $arg = shift or usage();
die "Not a hub directory: $arg" unless (-d $arg);
die "Path to hubdir/worker conf must be absolute" unless $arg =~ m|^/|;
exec_lisp("(run-supervise-hub \"$arg\" \"(reopen-log-files)\" t)");
} elsif ($switch eq "-add-listener") {
my $dir = shift or usage();
my $ip = shift or usage();
my $port = shift or usage();
die "Not a hub directory: $dir" unless (-d $dir);
die "Path to hubdir must be absolute" unless $dir =~ m|^/|;
exec_lisp("(run-add-listener \"$dir\" \"$ip\" $port)");
} elsif ($switch eq "-close-listener") {
my $dir = shift or usage();
my $ip = shift or usage();
my $port = shift or usage();
die "Not a hub directory: $dir" unless (-d $dir);
die "Path to hubdir must be absolute" unless $dir =~ m|^/|;
exec_lisp("(run-supervise-hub \"$dir\" #\"(hub-close-inet-listener \"$ip\" $port)\"# t)");
} elsif ($switch eq "-attach") {
my $arg = shift or usage();
die "Path to hubdir/worker conf must be absolute" unless $arg =~ m|^/|;
if (-d $arg) {
exec_lisp("(run-supervise-hub \"$arg\")");
} elsif (-f $arg) {
exec_lisp("(run-supervise-worker \"$arg\")");
}
die "not a hub directory or worker conf file: $arg";
} elsif ($switch eq "-kill") {
my $arg = shift or usage();
die "Path to hubdir/worker conf must be absolute" unless $arg =~ m|^/|;
if (-d $arg) {
exec_lisp("(run-supervise-hub \"$arg\" \"(quit)\")");
} elsif (-f $arg) {
exec_lisp("(run-supervise-worker \"$arg\" \"(quit)\")");
}
die "not a hub directory or worker conf file: $arg";
} elsif ($switch eq "-stats") {
my $arg = shift or usage();
die "Path to hubdir/worker conf must be absolute" unless $arg =~ m|^/|;
if (-d $arg) {
exec_lisp("(run-supervise-hub \"$arg\" \"(stats)\" t)");
} elsif (-f $arg) {
exec_lisp("(run-supervise-worker \"$arg\" \"(stats)\" t)");
}
die "not a hub directory or worker conf file: $arg";
} elsif ($switch eq "-room") {
my $arg = shift or usage();
die "Path to hubdir/worker conf must be absolute" unless $arg =~ m|^/|;
if (-d $arg) {
exec_lisp("(run-supervise-hub \"$arg\" \"(aw-room)\" t)");
} elsif (-f $arg) {
exec_lisp("(run-supervise-worker \"$arg\" \"(aw-room)\" t)");
}
die "not a hub directory or worker conf file: $arg";
} elsif ($switch eq "-version") {
print "CURRENT INSTALLATION ON THIS SYSTEM:\n";
print " Antiweb version: $AW_VERSION\n";
print " Antiweb launch script: $bin_dir/antiweb\n";
print " Antiweb library: $lib_dir/libantiweb$bits.so\n";
print " Default lisp environment: $cl_sys\n";
print " Lisp binary: ";
print $cmu_exec if $cl_sys eq "cmu";
print $clisp_exec if $cl_sys eq "clisp";
print $ccl_exec if $cl_sys eq "ccl";
print $sbcl_exec if $cl_sys eq "sbcl";
print "\n";
print "\n";
my $arg = shift;
if (!$arg) {
print "Provide either a hub directory or a worker conf file as an argument to\n";
print "-version to see what version the specified hub or worker process is running.\n\n";
exit;
}
die "Path to hubdir/worker conf must be absolute" unless $arg =~ m|^/|;
if (-d $arg) {
print "HUB $arg is running Antiweb version...\n";
exec_lisp("(run-supervise-hub \"$arg\" \"AW_VERSION\" t)");
} elsif (-f $arg) {
print "WORKER $arg is running Antiweb version...\n";
exec_lisp("(run-supervise-worker \"$arg\" \"AW_VERSION\" t)");
}
die "not a hub directory or worker conf file: $arg";
} elsif ($switch eq "-repl") {
exec_lisp("(do-aw-init nil)");
} elsif ($switch eq "-eval") {
my $expr = shift or usage();
exec_lisp("(unwind-protect (progn $expr) (quit))");
} elsif ($switch eq "-awp") {
my $awpfile = shift or usage();
my $basedir = shift or usage();
die "first argument to -awp must be absolute path to an .awp file"
unless ($awpfile =~ m|^/| && $awpfile =~ m|/([^/]+[.]awp)$|i && (-f $awpfile));
$awpfile =~ m|/([^/]+[.]awp)|;
my $name = $1;
die "second argument to -awp must be absolute path to a base directory" unless ($basedir =~ m|^/| && (-d $basedir));
my $dirtomake = "$basedir/$name";
die ".awp files can't be compiled to the same directory they are stored" if (-f $dirtomake);
exec_lisp("(progn (do-aw-init nil) (unwind-protect (awp-compile \"$awpfile\" 0 \"$basedir/$name\") (quit)))");
} elsif ($switch eq "-skel-hub-dir") {
my $dir = shift or die "need a directory to create for the hub";
my $hub_user = 20000;
my $logger_user = 20001;
die "$dir already exists" if (-e $dir);
mkdir($dir) or die "unable to mkdir: $dir";
mkdir("$dir/aw_log") or die "unable to mkdir: $dir/aw_log";
system("chown $logger_user:$logger_user $dir/aw_log");
mkdir("$dir/empty") or die "unable to mkdir: $dir/empty";
skel_to_file("$dir/hub.conf", <<END);
(hub-uid $hub_user)
(logger-uid $logger_user)
(max-fds 10000)
(listen "0.0.0.0" 80)
END
print "Created Antiweb hub directory: $dir\n";
} elsif ($switch eq "-skel-worker-basic") {
print <<END;
(worker example)
(hub-dir "/var/aw")
(max-fds 32767)
(uid 20100)
(handler
:hosts ("localhost" "127.0.0.1"
"example.com" "www.example.com")
:root "/var/www/example.com"
:index ("index.html")
:etags
:cgi (pl)
)
END
} elsif ($switch eq "-skel-worker-full") {
print <<END;
(worker worker-full)
(hub-dir "/var/aw")
(max-fds 32767)
(uid "user")
(cache "/var/www/cache") ; must be owned by user
(keepalive 65 s)
(eval-every 6 h
(gc))
(handler
:hosts ("example.com" "www.example.com")
:root "/var/www/example.com"
:default-mime-type "text/plain"
:mime-type (htm "text/html; charset=iso-8859-1")
:index ("index.html" "index.pl")
:dir-listings :etags :download-resuming
:gzip (html txt css js)
:gzip-size-range (256 1000000)
:fast-1x1gif "/1x1.gif"
:fast-files ("/favicon.ico" "/robots.txt")
:cgi (pl)
:awp
)
(handler
:hosts ("static.example.com" "images.example.com"
"example.ca" "www.example.ca")
:simple-vhost-root "/var/www"
;; Maps to: /var/www/static.example.com/
;; * use symlinks to share directories
:index ("index.html")
:dir-listings :etags :download-resuming
)
END
} elsif ($switch eq "-skel-worker-chrooted") {
print <<END;
(worker sandboxed-worker)
(hub-dir "/var/aw") ; relative to the ORIGINAL root
(max-fds 32767)
(uid "noprivuser")
(chroot "/var/sandbox")
(cache "/cache") ; relative to the NEW root. /var/sandbox/cache
(handler
:hosts ("comehackme.example.com")
:root "/" ; relative to the NEW root. /var/sandbox
:awp ; no problem as long as you have a cache
)
END
} elsif ($switch =~ m/^--?h(elp|)$/i) {
usage();
} else {
die "Unknown switch: $switch";
}
sub skel_to_file {
my $filename = shift;
my $contents = shift;
open(FH, ">$filename");
print FH $contents;
close(FH);
}
END_OF_ANTIWEB_LAUNCH_SCRIPT o))
(system "chmod a+x bin/antiweb")
(format t "BUILD: Creating Antiweb install script~%")
(with-open-file (o "bin/install.sh" :direction :output :if-exists :supersede)
(format o #"#!/bin/sh
install -m 755 antiweb ~a/
install -m 644 libantiweb~a.so ~a/
install -m 644 antiweb.~a.image ~a/
"# aw-bin-dir
aw-bits aw-lib-dir
#+cmu "cmu" #+clisp "clisp" #+ccl "ccl" #+sbcl "sbcl" aw-lib-dir))
(system "chmod a+x bin/install.sh")
#+clisp
(progn
(setq custom:*prompt-finish* "* ")
(setq custom:*prompt-body* ""))
(setf *read-eval* nil) ; security. bind to t if needed
(format t "BUILD: Antiweb v~a build OK~%" AW_VERSION)
(let ((image-name (format nil "bin/antiweb.~a.image" #+cmu "cmu" #+clisp "clisp" #+ccl "ccl" #+sbcl "sbcl")))
(format t "************* Saving lisp image to ~a *************~%" image-name)
#+cmu (save-lisp image-name)
#+clisp (ext:saveinitmem image-name)
#+ccl (save-application image-name)
#+sbcl (sb-ext:save-lisp-and-die image-name)
)
| 24,927 | Common Lisp | .lisp | 608 | 36.25 | 179 | 0.611187 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 3cc290ac63dd0d992a003022a8c272e42f035d513223eed51762c4f77fa4405c | 2,429 | [
-1
] |
2,430 | mime-types.lisp | hoytech_antiweb/src/mime-types.lisp | ;; Antiweb (C) Doug Hoyte
(defun lookup-mime-type (m types)
(cadar (member m types :key #'car :test #'equalp)))
(defvar aw-default-mime-type
"text/plain; charset=utf-8")
(defvar aw-mime-types '(
("html" "text/html; charset=utf-8")
("htm" "text/html; charset=utf-8")
("txt" "text/plain; charset=utf-8")
("css" "text/css")
("js" "application/x-javascript")
("png" "image/png")
("gif" "image/gif")
("jpg" "image/jpeg")
("jpeg" "image/jpeg")
("ico" "image/vnd.microsoft.icon")
("wml" "text/vnd.wap.wml")
("tif" "image/tiff")
("tar" "application/x-tar")
("tgz" "application/x-gzip")
("gz" "application/x-gzip")
("bz2" "application/x-bzip2")
("rar" "application/x-rar-compressed")
("zip" "application/x-zip-compressed")
("pdf" "application/pdf")
("deb" "application/x-debian-package")
("xml" "text/xml")
("dtd" "text/xml")
("wav" "audio/wav")
("mid" "audio/midi")
("midi" "audio/midi")
("mp3" "audio/mpeg")
("mpg" "video/mpeg")
("mpeg" "video/mpeg")
("swf" "application/x-shockwave-flash")
("qt" "video/quicktime")
("mov" "video/quicktime")
("avi" "video/x-msvideo")
("a" "application/octet-stream")
("bin" "application/octet-stream")
("exe" "application/octet-stream")
("dump" "application/octet-stream")
("o" "application/octet-stream")
("so" "application/octet-stream")
("class" "application/java")
("eps" "application/postscript")
("ps" "application/postscript")
("dvi" "application/x-dvi")
("latex" "application/x-latex")
("rtf" "application/rtf")
("hqx" "application/mac-binhex40")
("sit" "application/x-stuffit")
("tex" "application/x-tex")
("texi" "application/x-texinfo")
("texinfo" "application/x-texinfo")
("doc" "application/msword")
("ppt" "application/powerpoint")
("mime" "message/rfc822")
("iso" "application/x-iso9660-image")
))
| 1,853 | Common Lisp | .lisp | 60 | 28 | 53 | 0.645251 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 55fe0a0ce9395e89cca98d76c84c4f7860b008dc65fc6f83ebf8b0fa3f520dcb | 2,430 | [
-1
] |
2,431 | modules.lisp | hoytech_antiweb/src/modules.lisp | ;; Antiweb (C) Doug Hoyte
;; Default HTTP modules
(antiweb-module mod-rewrite
:rewrite-phase
`(macrolet ((done-rewrite ()
'(return-from mod-rewrite-block nil)))
(block mod-rewrite-block
,@(xconf-get-all handler :rewrite))))
(antiweb-module mod-dir
:directory-handling-phase
`(let* ((real-path ,(http-root-translate handler 'http-path))
(stat (cffi:with-foreign-string (pstr real-path)
(aw_stat_returning_a_static_struct pstr)))
(directory-is-world-readable t))
(unless (cffi:null-pointer-p stat)
(unless (zerop (aw_stat_is_dir stat))
(if (zerop (aw_stat_is_world_readable stat))
(setq directory-is-world-readable nil))
(unless (#~m|/$| http-path)
(send-http-response-headers 301
("Location" "http://~a~a/" http-host http-path)
("Content-Length" "0"))
(return-this-closure keepalive-closure))
(tagbody
,@(mapcar
#`(let* ((index-file (format nil "~a~a" http-path ,a1))
(real-index-file ,(http-root-translate handler 'index-file))
(stat (cffi:with-foreign-string (pstr real-index-file)
(aw_stat_returning_a_static_struct pstr))))
(unless (cffi:null-pointer-p stat)
(setq http-path index-file)
(go escape)))
(xconf-get handler :index))
,(if (xconf-get handler :dir-listings)
'(progn
(unless directory-is-world-readable
(err-and-linger 403 "Directory is not world readable"))
(if (eq http-method 'post)
(err-and-linger 405 "Can't POST to a directory"))
(setq $u-keepalive nil)
(send-http-response-headers 200
("Content-Type" "text/html; charset=utf-8"))
(write-to-conn-from-string c
(format nil #"<html><head><title>Antiweb Directory Listing: ~a~a</title>
<style type="text/css"> <!--
body,h1 { margin:10px; font-family: Verdana, Arial, sans-serif; }
--> </style></head><h1>~a~a</h1><body>"#
http-host http-path http-host http-path))
(cffi:with-foreign-string (pstr real-path)
(aw_send_dir_listings c pstr))
(linger-this-http-conn c)
(write-to-conn-from-string c
(format nil #"<br><hr>End of Antiweb ~a Directory Listing</body></html>"# AW_VERSION))
(return-this-closure 'sent-dir-listing))
'(err-and-linger 404 "Directory index doesn't exist"))
escape)))))
(antiweb-module mod-awp
:awp-phase
(if (xconf-get handler :awp)
`(when-match (,(list-of-file-extensions-to-regex-with-path-info '(awp)) http-path)
(macrolet ((with-awp-error-handler (awp-exec-phase &rest body)
(let ((my-handler ',(case (xconf-get handler :awp-failure-reaction)
((:die)
`(error "AWP ~a error in ~a (~a)"
awp-exec-phase awp-file-path condition))
((nil :ignore-and-log-to-syslog)
`(progn
(aw-log () "AWP ~a error in ~a (~a)"
awp-exec-phase awp-file-path condition)
(err-and-linger 500 (format nil "AWP error. See syslog."))))
((:ignore-and-log-to-syslog+browser)
`(progn
(aw-log () "AWP ~a error in ~a (~a)"
awp-exec-phase awp-file-path condition)
(err-and-linger 500 (format nil "AWP ~a error in ~a <br><br> (~a)"
awp-exec-phase awp-file-path condition))))
(t
(error "Unknown :awp-failure-reaction parameter: ~a"
(xconf-get handler :awp-failure-reaction))))))
`(handler-bind ((error (lambda (condition)
(let ((awp-exec-phase ,awp-exec-phase))
,my-handler))))
,@body))))
(setq http-path $1)
(setq $u-path-info $2)
(let* ((real-path ,(http-root-translate handler 'http-path))
(stat (cffi:with-foreign-string (pstr real-path)
(aw_stat_returning_a_static_struct pstr))))
(if (cffi:null-pointer-p stat)
(err-and-linger 404 "File doesn't exist"))
(if (zerop (aw_stat_is_world_readable stat))
(err-and-linger 403 "AWP file isn't world readable"))
(when (zerop (length $u-path-info))
(send-http-response-headers 301
("Location" "http://~a~a/" http-host http-path)
("Content-Length" "0"))
(return-this-closure keepalive-closure))
(let ((awp-file-path ,(http-root-translate handler 'http-path))
(cache-path (format nil "~a/~a~a" (get-aw-worker-cache-or-error) ,(car (xconf-get handler :hosts)) http-path)))
(with-awp-error-handler "compile-time"
(awp-compile awp-file-path (aw_stat_get_mtime stat) cache-path))
(setq $u-awp-real-path (format nil "~a~a" cache-path (if (#~m|^/+$| $u-path-info)
"/index.html" $u-path-info)))
(with-awp-error-handler "run-time"
(when (eq http-method 'post)
(let ((post-len (parse-integer $h-content-length)))
(if (zerop post-len)
(err-and-linger 400 "Empty POST to AWP file"))
(if (> post-len AW_MAX_MSG_LENGTH)
(err-and-linger 413 "POST Content-Length too large for AWP file"))
(cffi:with-foreign-slots ((ready limit sep) c conn)
(return-from http-user-dispatch-macro
(read-fixed-length-message-from-conn-and-store-in-shared-input-buffer post-len
(block http-user-dispatch-macro
(with-awp-error-handler "run-time"
(let ((post-handlers (awp-page-post-handlers (gethash awp-file-path awp-loaded-pages))))
(dolist (ph post-handlers)
(let ((res (funcall ph $u-path-info
:cookie $h-cookie
:referer $h-referer
:args shared-input-buffer)))
(when (stringp res)
(send-raw res)
(keepalive))))))
(err-and-linger 405 "Unhandled POST to AWP file")))))))
(when (eq http-method 'get)
(let ((get-handlers (awp-page-get-handlers (gethash awp-file-path awp-loaded-pages))))
(dolist (gh get-handlers)
(let ((res (funcall gh $u-path-info
:ip $ip
:cookie $h-cookie
:referer $h-referer
:args http-args
:x-real-ip ,(if (xconf-get handler :accept-x-real-ip-from)
'$u-used-x-real-ip)
)))
(when (stringp res)
(send-raw res)
(keepalive)))))))))))))
(antiweb-module mod-cgi
:cgi-phase
(if (or (xconf-get handler :cgi) (xconf-get handler :naked-cgi))
`(let (this-is-a-cgi naked-cgi)
,(if (xconf-get handler :cgi)
`(when-match (,(list-of-file-extensions-to-regex-with-path-info (xconf-get handler :cgi)) http-path)
(setq http-path $1)
(setq $u-path-info $2)
(setq this-is-a-cgi t)))
,(if (xconf-get handler :naked-cgi)
`(when-match (,(list-of-file-extensions-to-regex-with-path-info (xconf-get handler :naked-cgi)) http-path)
(setq http-path $1)
(setq $u-path-info $2)
(setq this-is-a-cgi t
naked-cgi t)))
(when this-is-a-cgi
(let* ((real-path ,(http-root-translate handler 'http-path))
(stat (cffi:with-foreign-string (pstr real-path)
(aw_stat_returning_a_static_struct pstr))))
(if (cffi:null-pointer-p stat)
(err-and-linger 404 "File doesn't exist"))
(if (zerop (aw_stat_is_world_readable stat))
(err-and-linger 403 "CGI script isn't world readable"))
(if (zerop (aw_stat_is_world_executable stat))
(err-and-linger 403 "CGI script isn't world executable"))
(if (zerop (aw_stat_is_reg_file stat))
(err-and-linger 403 "CGI script is not a regular file"))
(let ((single-process-cgis-only ,(if (xconf-get handler :cgi-no-forking) 1 0))
(maxfiles ,(or (xconf-get handler :cgi-maxfiles) 50)))
(let ((cgi-conn
(cffi:with-foreign-string (pstr real-path)
(cffi:with-foreign-string (pistr $u-path-info)
(cffi:with-foreign-string (astr (or http-args ""))
(cffi:with-foreign-string (cstr (or $h-cookie ""))
(cffi:with-foreign-string (ctstr (or $h-content-type ""))
(if (eq http-method 'post)
(cffi:with-foreign-string (method "POST")
(aw_build_cgi_conn c pstr pistr astr method cstr ctstr $u-content-length-num
100000 50000 ; tune this
single-process-cgis-only maxfiles
(if naked-cgi 1 0)))
(cffi:with-foreign-string (method "GET")
(aw_build_cgi_conn c pstr pistr astr method cstr ctstr 0
0 0
single-process-cgis-only maxfiles
(if naked-cgi 1 0)))))))))))
(add-to-conn-table cgi-conn
'cgi-proxy-sink-should-never-become-ready)
(return-this-closure
(fsm cgi-source
(cffi:with-foreign-slots ((conntype) c conn)
(setf conntype AW_CONNTYPE_ZOMBIE))
(cffi:with-foreign-slots ((conntype) cgi-conn conn)
(setf conntype AW_CONNTYPE_ZOMBIE))
'proxy-sink-finished-sending-cgi-data)))))))))
(antiweb-module mod-jsmin
:jsmin-phase
(if (xconf-get handler :jsmin)
`(when (and (null $u-awp-real-path)
(#~m/[.]js$/ http-path))
(let* ((real-path ,(http-root-translate handler 'http-path))
(stat (cffi:with-foreign-string (pstr real-path)
(aw_stat_returning_a_static_struct pstr))))
(unless (cffi:null-pointer-p stat)
(ignore-errors ; invalid javascript file (ie unclosed comment), clients will be sent original
(let* ((orig-mtime (aw_stat_get_mtime stat))
(cache-path (format nil "~a/~a~a.min.js"
(get-aw-worker-cache-or-error)
,(car (xconf-get handler :hosts))
http-path))
(stat (cffi:with-foreign-string (pstr cache-path)
(aw_stat_returning_a_static_struct pstr))))
(when (or (cffi:null-pointer-p stat) (> orig-mtime (aw_stat_get_mtime stat)))
(cffi:with-foreign-string (cstr cache-path)
(aw_mkdir_dash_p cstr)
(jsmin:jsmin-file real-path cache-path)
(cffi:with-foreign-string (gstr (format nil "~a.gz" cache-path))
(aw_gzip_file cstr gstr))))
(setq $u-awp-real-path cache-path))))))))
(antiweb-module mod-cssmin
:cssmin-phase
(if (xconf-get handler :cssmin)
`(when (and (null $u-awp-real-path)
(#~m/[.]css$/ http-path))
(let* ((real-path ,(http-root-translate handler 'http-path))
(stat (cffi:with-foreign-string (pstr real-path)
(aw_stat_returning_a_static_struct pstr))))
(unless (cffi:null-pointer-p stat)
(ignore-errors ; invalid javascript file (ie unclosed comment), clients will be sent original
(let* ((orig-mtime (aw_stat_get_mtime stat))
(cache-path (format nil "~a/~a~a.min.css"
(get-aw-worker-cache-or-error)
,(car (xconf-get handler :hosts))
http-path))
(stat (cffi:with-foreign-string (pstr cache-path)
(aw_stat_returning_a_static_struct pstr))))
(when (or (cffi:null-pointer-p stat) (> orig-mtime (aw_stat_get_mtime stat)))
(cffi:with-foreign-string (cstr cache-path)
(aw_mkdir_dash_p cstr)
(cssmin-file real-path cache-path)
(cffi:with-foreign-string (gstr (format nil "~a.gz" cache-path))
(aw_gzip_file cstr gstr))))
(setq $u-awp-real-path cache-path))))))))
(defun expand-into-form-that-looks-up-mime-type-of-real-path-and-stores-in-$u-mime-type (handler)
`(progn
(when-match (#~m/[.](\w+)$/ real-path)
,(let ((mimes (mapcar (lambda (m) (list (if (stringp (car m)) (car m) (string-downcase (symbol-name (car m))))
(cadr m)))
(xconf-get-all handler :mime-type))))
(if mimes
`(setq $u-mime-type (lookup-mime-type $1 ',mimes))))
(unless $u-mime-type
(setq $u-mime-type (lookup-mime-type $1 aw-mime-types))))
(unless $u-mime-type
(setq $u-mime-type ,(if (xconf-get handler :default-mime-type)
(xconf-get handler :default-mime-type)
'aw-default-mime-type)))))
(antiweb-module mod-regular-file
:regular-file-phase
`(let* ((real-path (or $u-awp-real-path ,(http-root-translate handler 'http-path)))
(stat (cffi:with-foreign-string (pstr real-path)
(aw_stat_returning_a_static_struct pstr))))
(if (cffi:null-pointer-p stat)
(err-and-linger 404 "File doesn't exist"))
(if (zerop (aw_stat_is_reg_file stat))
(err-and-linger 403 "Requested resource is not a regular file"))
(if (eq http-method 'post)
(err-and-linger 405 "You can't POST to a regular file"))
(if (zerop (aw_stat_is_world_readable stat))
(err-and-linger 403 "File isn't world readable")
(progn
,(expand-into-form-that-looks-up-mime-type-of-real-path-and-stores-in-$u-mime-type handler)
(if $u-mime-type
(add-header-to-response "Content-Type: ~a" $u-mime-type))
,(if (xconf-get handler :etags)
(let ((hash (xconf-get handler :etag-hash)))
(if hash
`(setq $u-etag (format nil #""~a""#
(aw-sha1 (format nil #"~a-~a-~a-~a"#
,hash
(aw_stat_get_inode stat)
(aw_stat_get_file_size stat)
(aw_stat_get_mtime stat)))))
'(setq $u-etag (format nil #""~x-~x-~x""#
(aw_stat_get_inode stat)
(aw_stat_get_file_size stat)
(aw_stat_get_mtime stat))))))
,(if (xconf-get handler :etags)
'(when (equalp $u-etag $h-if-none-match)
(send-http-response-headers 304
("Etag" "~a" $u-etag))
(return-this-closure keepalive-closure)))
,(if (xconf-get handler :download-resuming)
'(if $h-range
(when-match (#~m/bytes=(\d+)-/ $h-range)
(let ((offset (parse-integer $1))
(file-size (aw_stat_get_file_size stat)))
(when (< 0 offset file-size)
(send-http-response-headers 206
("Content-Range" "~a-~a/~a" offset (1- file-size) file-size)
("Content-Length" "~a" (- file-size offset)))
(cffi:with-foreign-string (fstr real-path)
(aw_send_file_to_http_conn c fstr stat offset))
(return-this-closure keepalive-closure))))))
,(if (xconf-get handler :gzip)
`(if (or
(and $u-awp-real-path
(#~m/gzip/ $h-accept-encoding))
(and (,(list-of-file-extensions-to-regex (xconf-get handler :gzip)) http-path)
(#~m/gzip/ $h-accept-encoding)
(<= ,(or (car (xconf-get handler :gzip-size-range)) 256)
(aw_stat_get_file_size stat)
,(or (cadr (xconf-get handler :gzip-size-range)) 200000))))
(let* ((orig-mtime (aw_stat_get_mtime stat))
(cache-path (if $u-awp-real-path
(format nil "~a.gz" $u-awp-real-path)
(format nil "~a/~a~a.gz" (get-aw-worker-cache-or-error)
,(car (xconf-get handler :hosts))
http-path))))
(cffi:with-foreign-string (pstr cache-path)
(let ((stat (aw_stat_returning_a_static_struct pstr)))
(if (and $u-awp-real-path (cffi:null-pointer-p stat))
(fatal "Couldn't find gziped awp file ~a" $u-awp-real-path))
(if (or (cffi:null-pointer-p stat)
(> orig-mtime (aw_stat_get_mtime stat)))
(cffi:with-foreign-string (fstr real-path)
(aw_mkdir_dash_p pstr)
(aw_gzip_file fstr pstr)
(setq stat (aw_stat_returning_a_static_struct pstr))))
(send-http-response-headers 200
("Content-Length" "~a" (aw_stat_get_file_size stat))
("Content-Encoding" "gzip")
,@(if (xconf-get handler :etags)
'(("Etag" "~a" $u-etag))))
(aw_send_file_to_http_conn c pstr stat 0)
(return-this-closure keepalive-closure))))))
(send-http-response-headers 200
("Content-Length" "~a" (aw_stat_get_file_size stat))
,@(if (xconf-get handler :etags)
'(("Etag" "~a" $u-etag))))
(cffi:with-foreign-string (fstr real-path)
(aw_send_file_to_http_conn c fstr stat 0))
(return-this-closure keepalive-closure)))))
(defvar aw-fast-1x1gif-data
#.(coerce
(mapcar (lambda (e) (if (numberp e) (code-char e) e))
(read-from-string
; lisp
(#~s/,// ; /\ THE GOLDEN TRIANGLE
(#~s/0x/#x/ ; / \ \
(#~s/'/#\/ ;.----. perl \
(#~s/',// ; || \
(#~s|/[*].*?\n|| ; || THE HOLY TRINITY / \
; C / \
;; The following 43-byte 1x1 gif is from nginx:
;; /*
;; * Copyright (C) Igor Sysoev
;; */
#"(
'G', 'I', 'F', '8', '9', 'a', /* header */
/* logical screen descriptor */
0x01, 0x00, /* logical screen width */
0x01, 0x00, /* logical screen height */
0x80, /* global 1-bit color table */
0x01, /* background color #1 */
0x00, /* no aspect ratio */
/* global color table */
0x00, 0x00, 0x00, /* #0: black */
0xff, 0xff, 0xff, /* #1: white */
/* graphic control extension */
0x21, /* extension introducer */
0xf9, /* graphic control label */
0x04, /* block size */
0x01, /* transparent color is given, */
/* no disposal specified, */
/* user input is not expected */
0x00, 0x00, /* delay time */
0x01, /* transparent color #1 */
0x00, /* block terminator */
/* image descriptor */
0x2c, /* image separator */
0x00, 0x00, /* image left position */
0x00, 0x00, /* image top position */
0x01, 0x00, /* image width */
0x01, 0x00, /* image height */
0x00, /* no local color table, no interlaced */
/* table based image data */
0x02, /* LZW minimum code size, */
/* must be at least 2-bit */
0x02, /* block size */
0x4c, 0x01, /* compressed bytes 01_001_100, 0000000_1 */
/* 100: clear code */
/* 001: 1 */
/* 101: end of information code */
0x00, /* block terminator */
0x3B /* trailer */
)"#))))))) 'string))
(antiweb-module mod-fast-files
:fast-1x1gif-phase
(let ((v (xconf-get handler :fast-1x1gif)))
(if v
`(when (string= http-path ,v)
(send-http-response-headers 200
("Content-Type" "image/gif")
("Content-Length" "~a" (length aw-fast-1x1gif-data)))
(write-to-conn-from-string c aw-fast-1x1gif-data)
(return-this-closure keepalive-closure))))
:fast-files-phase
(let ((files (xconf-get handler :fast-files)))
(if files
`(labels
((send-fast-file (f)
(let* ((real-path ,(http-root-translate handler 'f))
(val (gethash real-path aw-fast-files-table)))
(if val
(if (stringp val)
(progn
(write-to-conn-from-string c val)
(return-this-closure keepalive-closure))
(err-and-keepalive 404 "File doesn't exist"))
(let ((file-data
(ignore-errors
(with-open-file (in real-path :direction :input :element-type '(unsigned-byte 8))
(let ((data-u8 (make-array (file-length in) :element-type '(unsigned-byte 8) :fill-pointer t))
(data-char (make-string (file-length in))))
(setf (fill-pointer data-u8) (read-sequence data-u8 in))
(loop for i from 0 below (file-length in) do
(setf (aref data-char i) (code-char (aref data-u8 i))))
data-char)))))
(when file-data
,(expand-into-form-that-looks-up-mime-type-of-real-path-and-stores-in-$u-mime-type handler)
(setf file-data (format nil
"HTTP/1.1 200 OK~aAntiweb/~a~aContent-Type: ~a~aContent-Length: ~a~a~a~a~a"
crlf AW_VERSION crlf $u-mime-type crlf
(length file-data) crlf
,(apply #'concatenate 'string
(mapcar (lambda (h) (format nil "~a~a" h crlf))
(xconf-get-all handler :fast-files-header)))
crlf file-data)))
(setf (gethash real-path aw-fast-files-table) (or file-data 404))
(send-fast-file f))))))
(cond
,@(mapcar #`((string= ,a1 http-path) (send-fast-file http-path)) files)))))
)
| 27,019 | Common Lisp | .lisp | 443 | 39.749436 | 128 | 0.43239 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | b95924d1eca0a99103fcbf4cf3a35c1c2bad18fc8e0c8a4e02b41e3524fa9ed0 | 2,431 | [
-1
] |
2,432 | conf.lisp | hoytech_antiweb/src/conf.lisp | ;; Antiweb (C) Doug Hoyte
;; In CL, there is no portable way to create or read a file with an
;; asterisk in its name. The following workaround works for CMU
;; (did I get all the chars?) but there is no way to do this in
;; CLISP so it will blow up if you have pathnames with * or ?.
;; VERY LUCKY that CLISP just passes : through OK (needed for vhosts like localhost:8080)
;; http://osdir.com/ml/lisp.clisp.general/2003-04/msg00101.html
(defun workaround-cl-pathnames (filename)
#+(or cmu sbcl) (setq filename (#~s/([\\:*?])/\\\1/ filename))
filename)
#|
In AW, a "conf" is a list of all the forms read from a file. The following two lines in a file
(worker blah)
(uid 1234)
would be loaded as this conf:
((WORKER BLAH)
(UID 1234))
* The key-value pairs are accessed with conf-get and conf-get-all
ie: (conf-get my-conf 'worker) => "blah"
|#
(defun load-conf-from-file (filename)
(load-conf-from-file-aux filename nil))
(defun load-conf-from-file-aux (filename already-inherited)
(let* ((conf (with-open-file (f (workaround-cl-pathnames filename) :direction :input)
(loop for i = (read f nil nil) while i collect i)))
(final-conf conf))
(loop for x in conf do
(unless (and (consp x) (symbolp (car x)))
(error "invalid xconf: ~a" x))
(when (eq (car x) 'inherit)
(if (member (cadr x) already-inherited :test #'equal)
(error "already inherited ~a" (cadr x)))
(setq final-conf (append final-conf
(load-conf-from-file-aux (cadr x) (cons (cadr x) already-inherited))))))
final-conf))
(defun conf-get-all (conf key)
(remove-if-not (lambda (e) (and (consp e) (eq key (car e)))) conf))
(defun conf-get (conf key)
(cadar (conf-get-all conf key)))
#|
Some elements in a conf are called "extended conf elements" or "xconfs". They are of the format:
(name-of-xconf [arguments]
:key1 (blah blah)
:key2 "sup?")
The number and meaning of [arguments] depends on the type of element (often there are none)
The :key key-value pairs are similar to destructuring keyword arguments except they may contain duplicates
and they are more robust (forgiving) in the event of accidental element additions/omissions.
* You must use conf-get-all to get xconfs because conf-get thows out info.
(xconf-get-all '(:a 1 :b 123 :a 2 :c 324) :a) => (1 2)
(xconf-get-all '(:a 1 :b 123 :a 2 :c 324) '(:a :b)) => ((:A 1) (:B 123) (:A 2))
(xconf-get '(:a 1 :b 123 :a 2 :c 324) :a) => 1
|#
(defun xconf-get (xconf key)
(let ((v (member key xconf)))
(if (and v (not (cdr v)))
t
(cadr v))))
(defun xconf-get-all (xconf key)
(unless (listp key) (setq key (list key)))
(if xconf
(let ((q (find (car xconf) key)))
(if q
(cons (if (> (length key) 1)
(list (car xconf) (cadr xconf))
(cadr xconf))
(xconf-get-all (cddr xconf) key))
(xconf-get-all (cdr xconf) key)))))
| 2,972 | Common Lisp | .lisp | 67 | 39.597015 | 106 | 0.645732 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | ebd56bb7116d895578d2934fc4c4fd05448e1db8feb32bcae7ec62eb2d10116f | 2,432 | [
-1
] |
2,433 | lol.lisp | hoytech_antiweb/bundled/lol.lisp | ;; Antiweb (C) Doug Hoyte
;; This is a "production" version of LOL with bug-fixes
;; and new features in the spirit of the book.
;; See http://letoverlambda.com
;; This is the source code for the book
;; _Let_Over_Lambda_ by Doug Hoyte.
;; This code is (C) 2002-2008, Doug Hoyte.
;;
;; You are free to use, modify, and re-distribute
;; this code however you want, except that any
;; modifications must be clearly indicated before
;; re-distribution. There is no warranty,
;; expressed nor implied.
;;
;; Attribution of this code to me, Doug Hoyte, is
;; appreciated but not necessary. If you find the
;; code useful, or would like documentation,
;; please consider buying the book!
;; April 8th, 2009:
;; * Added deflex and lmakunbound
;; * renamed pandoric-eval-tunnel to *pandoric-eval-tunnel*
;; to conform with Common Lisp name convention
(defun mkstr (&rest args)
(with-output-to-string (s)
(dolist (a args) (princ a s))))
(defun symb (&rest args)
(values (intern (apply #'mkstr args))))
(defun group (source n)
(if (zerop n) (error "zero length"))
(labels ((rec (source acc)
(let ((rest (nthcdr n source)))
(if (consp rest)
(rec rest (cons
(subseq source 0 n)
acc))
(nreverse
(cons source acc))))))
(if source (rec source nil) nil)))
(defun flatten (x)
(labels ((rec (x acc)
(cond ((null x) acc)
((atom x) (cons x acc))
(t (rec
(car x)
(rec (cdr x) acc))))))
(rec x nil)))
(defun fact (x)
(if (= x 0)
1
(* x (fact (- x 1)))))
(defun choose (n r)
(/ (fact n)
(fact (- n r))
(fact r)))
(defun g!-symbol-p (s)
(and (symbolp s)
(> (length (symbol-name s)) 2)
(string= (symbol-name s)
"G!"
:start1 0
:end1 2)))
(defmacro defmacro/g! (name args &rest body)
(let ((syms (remove-duplicates
(remove-if-not #'g!-symbol-p
(flatten body)))))
`(defmacro ,name ,args
(let ,(mapcar
(lambda (s)
`(,s (gensym ,(subseq
(symbol-name s)
2))))
syms)
,@body))))
(defun o!-symbol-p (s)
(and (symbolp s)
(> (length (symbol-name s)) 2)
(string= (symbol-name s)
"O!"
:start1 0
:end1 2)))
(defun o!-symbol-to-g!-symbol (s)
(symb "G!"
(subseq (symbol-name s) 2)))
(defmacro defmacro! (name args &rest body)
(let* ((os (remove-if-not #'o!-symbol-p args))
(gs (mapcar #'o!-symbol-to-g!-symbol os)))
`(defmacro/g! ,name ,args
`(let ,(mapcar #'list (list ,@gs) (list ,@os))
,(progn ,@body)))))
;; Nestable suggestion from Daniel Herring
(defun |#"-reader| (stream sub-char numarg)
(declare (ignore sub-char numarg))
(let (chars (state 'normal) (depth 1))
(loop do
(let ((curr (read-char stream)))
(cond ((eq state 'normal)
(cond ((char= curr #\#)
(push #\# chars)
(setq state 'read-sharp))
((char= curr #\")
(setq state 'read-quote))
(t
(push curr chars))))
((eq state 'read-sharp)
(cond ((char= curr #\")
(push #\" chars)
(incf depth)
(setq state 'normal))
(t
(push curr chars)
(setq state 'normal))))
((eq state 'read-quote)
(cond ((char= curr #\#)
(decf depth)
(if (zerop depth) (return))
(push #\" chars)
(push #\# chars)
(setq state 'normal))
(t
(push #\" chars)
(if (char= curr #\")
(setq state 'read-quote)
(progn
(push curr chars)
(setq state 'normal)))))))))
(coerce (nreverse chars) 'string)))
(set-dispatch-macro-character
#\# #\" #'|#"-reader|)
; This version is from Martin Dirichs
(defun |#>-reader| (stream sub-char numarg)
(declare (ignore sub-char numarg))
(let (chars)
(do ((curr (read-char stream)
(read-char stream)))
((char= #\newline curr))
(push curr chars))
(let ((pattern (nreverse chars))
output)
(labels ((match (pos chars)
(if (null chars)
pos
(if (char= (nth pos pattern) (car chars))
(match (1+ pos) (cdr chars))
(match 0 (cdr (append (subseq pattern 0 pos) chars)))))))
(do (curr
(pos 0))
((= pos (length pattern)))
(setf curr (read-char stream)
pos (match pos (list curr)))
(push curr output))
(coerce
(nreverse
(nthcdr (length pattern) output))
'string)))))
(set-dispatch-macro-character
#\# #\> #'|#>-reader|)
(defun segment-reader (stream ch n)
(if (> n 0)
(let ((chars))
(do ((curr (read-char stream)
(read-char stream)))
((char= ch curr))
(push curr chars))
(cons (coerce (nreverse chars) 'string)
(segment-reader stream ch (- n 1))))))
#+cl-ppcre
(defmacro! match-mode-ppcre-lambda-form (o!args o!mods)
``(lambda (,',g!str)
(cl-ppcre:scan
,(if (zerop (length ,g!mods))
(car ,g!args)
(format nil "(?~a)~a" ,g!mods (car ,g!args)))
,',g!str)))
#+cl-ppcre
(defmacro! subst-mode-ppcre-lambda-form (o!args)
``(lambda (,',g!str)
(cl-ppcre:regex-replace-all
,(car ,g!args)
,',g!str
,(cadr ,g!args))))
#+cl-ppcre
(defun |#~-reader| (stream sub-char numarg)
(declare (ignore sub-char numarg))
(let ((mode-char (read-char stream)))
(cond
((char= mode-char #\m)
(match-mode-ppcre-lambda-form
(segment-reader stream
(read-char stream)
1)
(coerce (loop for c = (read-char stream)
while (alpha-char-p c)
collect c
finally (unread-char c stream))
'string)))
((char= mode-char #\s)
(subst-mode-ppcre-lambda-form
(segment-reader stream
(read-char stream)
2)))
(t (error "Unknown #~~ mode character")))))
#+cl-ppcre
(set-dispatch-macro-character #\# #\~ #'|#~-reader|)
(defmacro! dlambda (&rest ds)
`(lambda (&rest ,g!args)
(case (car ,g!args)
,@(mapcar
(lambda (d)
`(,(if (eq t (car d))
t
(list (car d)))
(apply (lambda ,@(cdr d))
,(if (eq t (car d))
g!args
`(cdr ,g!args)))))
ds))))
;; Graham's alambda
(defmacro alambda (parms &body body)
`(labels ((self ,parms ,@body))
#'self))
;; Graham's aif
(defmacro aif (test then &optional else)
`(let ((it ,test))
(if it ,then ,else)))
(defun |#`-reader| (stream sub-char numarg)
(declare (ignore sub-char))
(unless numarg (setq numarg 1))
`(lambda ,(loop for i from 1 to numarg
collect (symb 'a i))
,(funcall
(get-macro-character #\`) stream nil)))
(set-dispatch-macro-character
#\# #\` #'|#`-reader|)
(defmacro alet% (letargs &rest body)
`(let ((this) ,@letargs)
(setq this ,@(last body))
,@(butlast body)
this))
(defmacro alet (letargs &rest body)
`(let ((this) ,@letargs)
(setq this ,@(last body))
,@(butlast body)
(lambda (&rest params)
(apply this params))))
(defun let-binding-transform (bs)
(if bs
(cons
(cond ((symbolp (car bs))
(list (car bs)))
((consp (car bs))
(car bs))
(t
(error "Bad let bindings")))
(let-binding-transform (cdr bs)))))
(defmacro pandoriclet (letargs &rest body)
(let ((letargs (cons
'(this)
(let-binding-transform
letargs))))
`(let (,@letargs)
(setq this ,@(last body))
,@(butlast body)
(dlambda
(:pandoric-get (sym)
,(pandoriclet-get letargs))
(:pandoric-set (sym val)
,(pandoriclet-set letargs))
(t (&rest args)
(apply this args))))))
(defun pandoriclet-get (letargs)
`(case sym
,@(mapcar #`((,(car a1)) ,(car a1))
letargs)
(t (error
"Unknown pandoric get: ~a"
sym))))
(defun pandoriclet-set (letargs)
`(case sym
,@(mapcar #`((,(car a1))
(setq ,(car a1) val))
letargs)
(t (error
"Unknown pandoric set: ~a"
sym))))
(declaim (inline get-pandoric))
(defun get-pandoric (box sym)
(funcall box :pandoric-get sym))
(defsetf get-pandoric (box sym) (val)
`(progn
(funcall ,box :pandoric-set ,sym ,val)
,val))
(defmacro with-pandoric (syms box &rest body)
(let ((g!box (gensym "box")))
`(let ((,g!box ,box))
(declare (ignorable ,g!box))
(symbol-macrolet
(,@(mapcar #`(,a1 (get-pandoric ,g!box ',a1))
syms))
,@body))))
(defun pandoric-hotpatch (box new)
(with-pandoric (this) box
(setq this new)))
(defmacro pandoric-recode (vars box new)
`(with-pandoric (this ,@vars) ,box
(setq this ,new)))
(defmacro plambda (largs pargs &rest body)
(let ((pargs (mapcar #'list pargs)))
`(let (this self)
(declare (ignorable this self))
(setq
this (lambda ,largs ,@body)
self (dlambda
(:pandoric-get (sym)
,(pandoriclet-get pargs))
(:pandoric-set (sym val)
,(pandoriclet-set pargs))
(t (&rest args)
(apply this args)))))))
(defvar *pandoric-eval-tunnel*)
(defmacro pandoric-eval (vars expr)
`(let ((*pandoric-eval-tunnel*
(plambda () ,vars t)))
(eval `(with-pandoric
,',vars *pandoric-eval-tunnel*
,,expr))))
;; Chapter 7
(set-dispatch-macro-character #\# #\f
(lambda (stream sub-char numarg)
(declare (ignore stream sub-char))
(setq numarg (or numarg 3))
(unless (<= numarg 3)
(error "Bad value for #f: ~a" numarg))
`(declare (optimize (speed ,numarg)
(safety ,(- 3 numarg))))))
(defmacro fast-progn (&rest body)
`(locally #f ,@body))
(defmacro safe-progn (&rest body)
`(locally #0f ,@body))
(defun fformat (&rest all)
(apply #'format all))
(define-compiler-macro fformat
(&whole form
stream fmt &rest args)
(if (constantp fmt)
(if stream
`(funcall (formatter ,fmt)
,stream ,@args)
(let ((g!stream (gensym "stream")))
`(with-output-to-string (,g!stream)
(funcall (formatter ,fmt)
,g!stream ,@args))))
form))
(declaim (inline make-tlist tlist-left
tlist-right tlist-empty-p))
(defun make-tlist () (cons nil nil))
(defun tlist-left (tl) (caar tl))
(defun tlist-right (tl) (cadr tl))
(defun tlist-empty-p (tl) (null (car tl)))
(declaim (inline tlist-add-left
tlist-add-right))
(defun tlist-add-left (tl it)
(let ((x (cons it (car tl))))
(if (tlist-empty-p tl)
(setf (cdr tl) x))
(setf (car tl) x)))
(defun tlist-add-right (tl it)
(let ((x (cons it nil)))
(if (tlist-empty-p tl)
(setf (car tl) x)
(setf (cddr tl) x))
(setf (cdr tl) x)))
(declaim (inline tlist-rem-left))
(defun tlist-rem-left (tl)
(if (tlist-empty-p tl)
(error "Remove from empty tlist")
(let ((x (car tl)))
(setf (car tl) (cdar tl))
(if (tlist-empty-p tl)
(setf (cdr tl) nil)) ;; For gc
(car x))))
(declaim (inline tlist-update))
(defun tlist-update (tl)
(setf (cdr tl) (last (car tl))))
(defun build-batcher-sn (n)
(let* (network
(tee (ceiling (log n 2)))
(p (ash 1 (- tee 1))))
(loop while (> p 0) do
(let ((q (ash 1 (- tee 1)))
(r 0)
(d p))
(loop while (> d 0) do
(loop for i from 0 to (- n d 1) do
(if (= (logand i p) r)
(push (list i (+ i d))
network)))
(setf d (- q p)
q (ash q -1)
r p)))
(setf p (ash p -1)))
(nreverse network)))
(defmacro! sortf (comparator &rest places)
(if places
`(tagbody
,@(mapcar
#`(let ((,g!a #1=,(nth (car a1) places))
(,g!b #2=,(nth (cadr a1) places)))
(if (,comparator ,g!b ,g!a)
(setf #1# ,g!b
#2# ,g!a)))
(build-batcher-sn (length places))))))
;;;;;; The following code is not from the book
#+cl-ppcre
(defun dollar-symbol-p (s)
(and (symbolp s)
(> (length (symbol-name s)) 1)
(string= (symbol-name s)
"$"
:start1 0
:end1 1)
(ignore-errors (parse-integer (subseq (symbol-name s) 1)))))
(defun prune-if-match-bodies-from-sub-lexical-scope (tree)
(if (consp tree)
(if (or (eq (car tree) 'if-match)
(eq (car tree) 'when-match))
(cddr tree)
(cons (prune-if-match-bodies-from-sub-lexical-scope (car tree))
(prune-if-match-bodies-from-sub-lexical-scope (cdr tree))))
tree))
;; WARNING: Not %100 correct. Removes forms like (... if-match ...) from the
;; sub-lexical scope even though this isn't an invocation of the macro.
#+cl-ppcre
(defmacro! if-match ((test str) conseq &optional altern)
(let ((dollars (remove-duplicates
(remove-if-not #'dollar-symbol-p
(flatten (prune-if-match-bodies-from-sub-lexical-scope conseq))))))
(let ((top (or (car (sort (mapcar #'dollar-symbol-p dollars) #'>)) 0)))
`(let ((,g!str ,str))
(multiple-value-bind (,g!s ,g!e ,g!ms ,g!me) (,test ,g!str)
(declare (ignorable ,g!e ,g!me))
(if ,g!s
(if (< (length ,g!ms) ,top)
(error "ifmatch: too few matches")
(let ,(mapcar #`(,(symb "$" a1) (subseq ,g!str (aref ,g!ms ,(1- a1))
(aref ,g!me ,(1- a1))))
(loop for i from 1 to top collect i))
,conseq))
,altern))))))
(defmacro when-match ((test str) conseq &rest more-conseq)
`(if-match (,test ,str)
(progn ,conseq ,@more-conseq)))
;; Like defvar, but for global lexicals
(defmacro deflex (var &optional val doc)
(let ((private-var (gensym (format nil "DEFLEX-~a-" var))))
`(progn
,(if val
`(defvar ,private-var ,val)
`(defvar ,private-var))
,(if doc
`(setf (documentation ',var 'variable) ,doc))
(define-symbol-macro ,var ,private-var))))
;; Always un-binds the global lexical binding, never any shadowing lexical bindings
(defun lmakunbound (var)
(makunbound (macroexpand-1 var))
var)
| 15,821 | Common Lisp | .lisp | 465 | 24.294624 | 101 | 0.503357 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | b702008889c633220880a028049d9451a1be192a7abfb585cd0f225016244f6a | 2,433 | [
-1
] |
2,434 | isaac.lisp | hoytech_antiweb/bundled/isaac.lisp | ;; isaac.lisp (C) May 2008 Doug Hoyte, HCSW
;; BSD license: you can do anything you want with it (but no warranty).
;;
;; Optimised Common Lisp implementation of Bob Jenkins' ISAAC-32 Algorithm:
;; Indirection, Shift, Accumulate, Add, and Count. More details and
;; the C reference implementations can be found here:
;;
;; ISAAC: a fast cryptographic random number generator
;; http://burtleburtle.net/bob/rand/isaacafa.html
;;
;; This lisp implementation is roughly as fast as Jenkins' optimised rand.c
;; when compiled with a good native-code lisp compiler. It also performs
;; well when byte-code compiled.
;;
;;
;; USAGE:
;;
;; First, create an isaac context. There are three functions that do this:
;;
;; isaac:init-kernel-seed => <isaac context>
;; *RECOMMENDED* Seeds with values from /dev/arandom on BSD
;; or /dev/urandom on Linux. Reads 1024 bytes from the device.
;;
;; isaac:init-common-lisp-random-seed => <isaac context>
;; Seeds with values from your Common Lisp implementation's
;; random function. Consumes 256 32-bit values from #'random.
;;
;; isaac:init-null-seed => <isaac context>
;; Seeds with all 0s. Always results in the same stream.
;; For comparing with Jenkins' reference implementations.
;;
;; These are functions you can pass an isaac context to. They will modify
;; the isaac context and return a random value:
;;
;; isaac:rand32 <isaac context> => <random 32-bit value>
;; Uses the ISAAC-32 algorithm to generate a new random value.
;;
;; isaac:rand-bits <isaac context> <N> => <random N-bit value>
;; Uses the ISAAC-32 algorithm to generate random values between
;; 0 and (1- (expt 2 N)). This function always consumes one or more
;; ISAAC-32 words. Note that the N parameter is different from
;; the CL random function parameter. Examples:
;; (isaac:rand-bits ctx 1) => [0,1] (consumes 1 ISAAC-32 word)
;; (isaac:rand-bits ctx 2) => [0,1,2,3] (ditto)
;; (isaac:rand-bits ctx 3) => [0,1,2,3,4,5,6,7] (ditto)
;; (isaac:rand-bits ctx 32) => [0,1,...,(1- (expt 2 32))] (ditto)
;; (isaac:rand-bits ctx 33) => [0,1,...,(1- (expt 2 33))] (consumes 2 words)
;; (isaac:rand-bits ctx 512) => [0,1,...,(1- (expt 2 512))] (consumes 16 words)
;;
;;
;; QUICK RECIPE:
;;
;; Generate a 128-bit session ID as a 0-padded hexadecimal string:
;; (compile-file "isaac.lisp")
;; (load "isaac")
;; (defvar my-isaac-ctx (isaac:init-kernel-seed))
;; (format nil "~32,'0x" (isaac:rand-bits my-isaac-ctx 128))
;; => "078585213B0EF01B1B9BECB291EF38F0"
;;
;;
;; FAQ:
;; Q) My Common Lisp implementation already uses the Mersenne Twister,
;; what are the advantages of ISAAC?
;;
;; A1) The Mersenne Twister is not a cryptographic PRNG. This means that it
;; is possible for someone to predict future values based on previously
;; observed values (just over 600 of them). As such, MT is particularly
;; undesirable for things like web session IDs. You can still use MT for
;; crypto, but you must use a cryptographic hash function on the MT output.
;; A2) isaac.lisp appears to be roughly as fast as the Mersenne Twister #'random
;; of CMUCL 19d on x86 before even considering the above-mentioned hash
;; function overhead requirement of MT.
;; A3) isaac.lisp is not implemented as an x86 VOP like CMUCL's Mersenne
;; Twister, but instead in 100% standard ANSI Common Lisp (except for the
;; kernel seed interface). This should mean comparable performance on all
;; architectures targeted by your lisp compiler. The non-x86 MT
;; implementation is apparently an order-of-magnitude slower.
;;
;; Q) How "random" can I expect these values to be?
;;
;; A) Very. From Bob Jenkins' website: "Cycles are guaranteed to be at least
;; (expt 2 40) values long, and they are (expt 2 8295) values long on
;; average. The results are uniformly distributed, unbiased, and unpredictable
;; unless you know the seed. [...] Why not use RC4? RC4 is three times slower,
;; more biased, has a shorter minimum and average cycle length, and is
;; proprietary. No way is known to break either RC4 or ISAAC; both are immune
;; to Gaussian elimination."
;;
;; Note that there is a $1000 prize you can win from Jenkins if you find
;; a flaw in ISAAC (but all flaws in isaac.lisp are of course mine).
(defpackage #:isaac
(:use :cl)
(:export #:init-null-seed
#:init-kernel-seed
#:init-common-lisp-random-seed
#:rand32
#:rand-bits))
(in-package #:isaac)
(defstruct isaac-ctx
(randcnt 0 :type (unsigned-byte 32))
(randrsl (make-array 256 :element-type '(unsigned-byte 32) :initial-element 0)
:type (simple-array (unsigned-byte 32) (256)))
(randmem (make-array 256 :element-type '(unsigned-byte 32) :initial-element 0)
:type (simple-array (unsigned-byte 32) (256)))
(a 0 :type (unsigned-byte 32))
(b 0 :type (unsigned-byte 32))
(c 0 :type (unsigned-byte 32)))
(defun generate-next-isaac-block (ctx)
(declare (optimize (speed 3) (safety 0)))
(incf (isaac-ctx-c ctx))
(incf (isaac-ctx-b ctx) (isaac-ctx-c ctx))
(loop for i from 0 below 256 do
(setf (isaac-ctx-a ctx)
(logxor (isaac-ctx-a ctx)
(logand #xFFFFFFFF
(the (unsigned-byte 32)
(ash (isaac-ctx-a ctx)
(ecase (logand i 3)
((0) 13)
((1) -6)
((2) 2)
((3) -16)))))))
(setf (isaac-ctx-a ctx)
(logand #xFFFFFFFF
(+ (isaac-ctx-a ctx)
(aref (isaac-ctx-randmem ctx) (logand (+ i 128) #xFF)))))
(let* ((x (aref (isaac-ctx-randmem ctx) i))
(y (logand #xFFFFFFFF
(+ (aref (isaac-ctx-randmem ctx) (logand (ash x -2) #xFF))
(isaac-ctx-a ctx)
(isaac-ctx-b ctx)))))
(setf (aref (isaac-ctx-randmem ctx) i) y)
(setf (isaac-ctx-b ctx)
(logand #xFFFFFFFF
(+ (aref (isaac-ctx-randmem ctx) (logand (ash y -10) #xFF)) x)))
(setf (aref (isaac-ctx-randrsl ctx) i) (isaac-ctx-b ctx)))))
(defun rand32 (ctx)
(let ((c (isaac-ctx-randcnt ctx)))
(declare (optimize (speed 3) (safety 0)))
(decf (isaac-ctx-randcnt ctx))
(if (zerop c)
(progn
(generate-next-isaac-block ctx)
(setf (isaac-ctx-randcnt ctx) 255)
(aref (isaac-ctx-randrsl ctx) 255))
(aref (isaac-ctx-randrsl ctx) (isaac-ctx-randcnt ctx)))))
(defun rand-bits (ctx n)
(let ((v 0))
(loop while (> n 0) do
(setq v (logior (ash v (min n 32))
(logand (1- (ash 1 (min n 32)))
(rand32 ctx))))
(decf n (min n 32)))
v))
(defmacro incf-wrap32 (a b)
`(setf ,a (logand #xFFFFFFFF (+ ,a ,b))))
(defmacro mix (a b c d e f g h)
`(progn
(setf ,a (logxor ,a (logand #xFFFFFFFF (ash ,b 11)))) (incf-wrap32 ,d ,a) (incf-wrap32 ,b ,c)
(setf ,b (logxor ,b (logand #xFFFFFFFF (ash ,c -2)))) (incf-wrap32 ,e ,b) (incf-wrap32 ,c ,d)
(setf ,c (logxor ,c (logand #xFFFFFFFF (ash ,d 8)))) (incf-wrap32 ,f ,c) (incf-wrap32 ,d ,e)
(setf ,d (logxor ,d (logand #xFFFFFFFF (ash ,e -16)))) (incf-wrap32 ,g ,d) (incf-wrap32 ,e ,f)
(setf ,e (logxor ,e (logand #xFFFFFFFF (ash ,f 10)))) (incf-wrap32 ,h ,e) (incf-wrap32 ,f ,g)
(setf ,f (logxor ,f (logand #xFFFFFFFF (ash ,g -4)))) (incf-wrap32 ,a ,f) (incf-wrap32 ,g ,h)
(setf ,g (logxor ,g (logand #xFFFFFFFF (ash ,h 8)))) (incf-wrap32 ,b ,g) (incf-wrap32 ,h ,a)
(setf ,h (logxor ,h (logand #xFFFFFFFF (ash ,a -9)))) (incf-wrap32 ,c ,h) (incf-wrap32 ,a ,b)))
(defun scramble (ctx)
(let (a b c d e f g h)
(setf a #x9e3779b9 b a c a d a e a f a g a h a) ; golden ratio
(loop for i from 0 below 4 do
(mix a b c d e f g h))
;; Pass #1
(loop for i from 0 below 256 by 8 do
(incf-wrap32 a (aref (isaac-ctx-randrsl ctx) (+ i 0)))
(incf-wrap32 b (aref (isaac-ctx-randrsl ctx) (+ i 1)))
(incf-wrap32 c (aref (isaac-ctx-randrsl ctx) (+ i 2)))
(incf-wrap32 d (aref (isaac-ctx-randrsl ctx) (+ i 3)))
(incf-wrap32 e (aref (isaac-ctx-randrsl ctx) (+ i 4)))
(incf-wrap32 f (aref (isaac-ctx-randrsl ctx) (+ i 5)))
(incf-wrap32 g (aref (isaac-ctx-randrsl ctx) (+ i 6)))
(incf-wrap32 h (aref (isaac-ctx-randrsl ctx) (+ i 7)))
(mix a b c d e f g h)
(setf (aref (isaac-ctx-randmem ctx) (+ i 0)) a)
(setf (aref (isaac-ctx-randmem ctx) (+ i 1)) b)
(setf (aref (isaac-ctx-randmem ctx) (+ i 2)) c)
(setf (aref (isaac-ctx-randmem ctx) (+ i 3)) d)
(setf (aref (isaac-ctx-randmem ctx) (+ i 4)) e)
(setf (aref (isaac-ctx-randmem ctx) (+ i 5)) f)
(setf (aref (isaac-ctx-randmem ctx) (+ i 6)) g)
(setf (aref (isaac-ctx-randmem ctx) (+ i 7)) h))
;; Pass #2
(loop for i from 0 below 256 by 8 do
(incf-wrap32 a (aref (isaac-ctx-randmem ctx) (+ i 0)))
(incf-wrap32 b (aref (isaac-ctx-randmem ctx) (+ i 1)))
(incf-wrap32 c (aref (isaac-ctx-randmem ctx) (+ i 2)))
(incf-wrap32 d (aref (isaac-ctx-randmem ctx) (+ i 3)))
(incf-wrap32 e (aref (isaac-ctx-randmem ctx) (+ i 4)))
(incf-wrap32 f (aref (isaac-ctx-randmem ctx) (+ i 5)))
(incf-wrap32 g (aref (isaac-ctx-randmem ctx) (+ i 6)))
(incf-wrap32 h (aref (isaac-ctx-randmem ctx) (+ i 7)))
(mix a b c d e f g h)
(setf (aref (isaac-ctx-randmem ctx) (+ i 0)) a)
(setf (aref (isaac-ctx-randmem ctx) (+ i 1)) b)
(setf (aref (isaac-ctx-randmem ctx) (+ i 2)) c)
(setf (aref (isaac-ctx-randmem ctx) (+ i 3)) d)
(setf (aref (isaac-ctx-randmem ctx) (+ i 4)) e)
(setf (aref (isaac-ctx-randmem ctx) (+ i 5)) f)
(setf (aref (isaac-ctx-randmem ctx) (+ i 6)) g)
(setf (aref (isaac-ctx-randmem ctx) (+ i 7)) h))
(generate-next-isaac-block ctx)
(setf (isaac-ctx-randcnt ctx) 256)
ctx))
(defun init-kernel-seed ()
(let ((ctx (make-isaac-ctx)))
(or
(ignore-errors
(with-open-file (r "/dev/arandom" :direction :input :element-type '(unsigned-byte 32))
#1=(loop for i from 0 below 256 do
(setf (aref (isaac-ctx-randrsl ctx) i) (read-byte r)))
t))
(ignore-errors
(with-open-file (r "/dev/urandom" :direction :input :element-type '(unsigned-byte 32))
#1#
t))
(error "couldn't open /dev/arandom or /dev/urandom"))
(scramble ctx)))
(defun init-common-lisp-random-seed ()
(let ((ctx (make-isaac-ctx)))
(loop for i from 0 below 256 do
(setf (aref (isaac-ctx-randrsl ctx) i)
(random (ash 1 32))))
(scramble ctx)))
(defun init-null-seed ()
(let ((ctx (make-isaac-ctx)))
(scramble ctx)))
;; Output is the same as Jenkins' randvect.txt
(defun jenkins-output (filename)
(let ((ctx (init-null-seed)))
(with-open-file (o filename :direction :output :if-exists :supersede)
(loop for i from 0 below 2 do
(generate-next-isaac-block ctx)
(loop for j from 0 below 256 do
(format o "~(~8,'0x~)" (aref (isaac-ctx-randrsl ctx) j))
(if (= 7 (logand j 7)) (terpri o)))))))
| 11,431 | Common Lisp | .lisp | 244 | 41.192623 | 100 | 0.6033 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 7c033ac7e9a957dc587522a16d7ec6266a2d8051bab1714aaf13c0ce42070f83 | 2,434 | [
-1
] |
2,435 | jsmin.lisp | hoytech_antiweb/bundled/jsmin.lisp | ;;; Re-packaged for Antiweb
;;; :overwrite changed to :supersede in jsmin-file
;;; Copyright (c) 2007, Ury Marshak
;;; This is a port of original C code by Douglas Crockford to
;;; Common Lisp. There was no attempt to make the code more
;;; "lispy", it is just a rather faithful translation. This code
;;; may be used under the same conditions as the C original, which
;;; has the following copyright notice:
;;;
;;; /* jsmin.c
;;; 2007-01-08
;;;
;;; Copyright (c) 2002 Douglas Crockford (www.crockford.com)
;;;
;;; 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 shall be used for Good, not Evil.
;;;
;;; 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.
;;; */
;;;
(defpackage #:jsmin
(:use :cl)
(:export #:jsmin
#:jsmin-file))
(in-package #:jsmin)
(defun is-alphanum (c)
"isAlphanum -- return true if the character is a letter, digit, underscore,
dollar sign, or non-ASCII character"
(and c
(or (and (char>= c #\a) (char<= c #\z))
(and (char>= c #\0) (char<= c #\9))
(and (char>= c #\A) (char<= c #\Z))
(char= c #\_)
(char= c #\$)
(char= c #\\)
(> (char-code c) 126))))
(defun %jsmin (in out)
(let (the-a the-b the-lookahead (pos 0))
(labels ((get-c ()
;; return the next character from stdin. Watch out for lookahead. If
;; the character is a control character, translate it to a space or
;; linefeed.
(let ((c the-lookahead))
(setf the-lookahead nil)
(unless c
(setf c (read-char in nil nil))
(incf pos))
(cond
((or (null c)
(char= c #\Newline)
(char>= c #\Space)) c)
((char= c (code-char 13)) #\Newline)
(t #\Space))))
(peek ()
;; get the next character without getting it
(setf the-lookahead (get-c)))
(next ()
;; get the next character, excluding comments. peek()
;; is used to see if a '/' is followed by a '/' or '*'.
(let ((c (get-c)))
(if (and c
(char= c #\/))
(case (peek)
(#\/
(loop for cc = (get-c)
while (and cc
(char> cc #\Newline))
finally (return cc)))
(#\*
(get-c)
(loop for cc = (get-c)
unless cc
do (error "JSMIN: Unterminated comment.")
when (and (char= cc #\*)
(char= (peek) #\/))
do (progn (get-c) (return #\Space))))
(otherwise
c))
c)))
(action (d)
;; action -- do something! What you do is determined by the argument:
;; 1 Output A. Copy B to A. Get the next B.
;; 2 Copy B to A. Get the next B. (Delete A).
;; 3 Get the next B. (Delete B).
;; action treats a string as a single character. Wow!
;; action recognizes a regular expression if it is
;; preceded by ( or , or =.
(when (= d 1)
(write-char the-a out))
(when (<= d 2)
(setf the-a the-b)
(when (and the-a
(or (char= the-a #\')
(char= the-a #\")))
(loop
(progn
(write-char the-a out)
(setf the-a (get-c))
(when (and the-a (char= the-a the-b))
(return))
(when (or (null the-a)
(char<= the-a #\Newline))
(error "JSMIN unterminated string literal: ~C at position ~A" the-b pos))
(when (char= the-a #\\)
(write-char the-a out)
(setf the-a (get-c)))))))
(when (<= d 3)
(setf the-b (next))
(when (and the-b
(char= the-b #\/)
(position the-a "(,=:[!&|?"))
(write-char the-a out)
(write-char the-b out)
(loop
(progn
(setf the-a (get-c))
(when (and the-a
(char= the-a #\/))
(return))
(when (and the-a
(char= the-a #\\))
(write-char the-a out)
(setf the-a (get-c)))
(when (or (null the-a)
(char<= the-a #\Newline))
(error "JSMIN: unterminated Regular Expression literal."))
(write-char the-a out)))
(setf the-b (next))))))
;; jsmin -- Copy the input to the output, deleting the characters
;; which are insignificant to JavaScript. Comments will be
;; removed. Tabs will be replaced with spaces. Carriage returns will
;; be replaced with linefeeds. Most spaces and linefeeds will be
;; removed.
(setf the-a #\Newline)
(action 3)
(loop while the-a
do (case the-a
(#\Space
(if (is-alphanum the-b)
(action 1)
(action 2)))
(#\Newline
(case the-b
((#\{ #\[ #\( #\+ #\-)
(action 1))
(#\Space
(action 3))
(otherwise
(if (is-alphanum the-b)
(action 1)
(action 2)))))
(otherwise
(case the-b
(#\Space
(if (is-alphanum the-a)
(action 1)
(action 3)))
(#\Newline
(case the-a
((#\} #\] #\) #\+ #\- #\" #\')
(action 1))
(otherwise
(if (is-alphanum the-a)
(action 1)
(action 3)))))
(otherwise
(action 1))))))
)))
(defun jsmin (js)
(with-output-to-string (out)
(with-input-from-string (in js)
(%jsmin in out))))
(defun jsmin-file (infile outfile)
(with-open-file (in infile :direction :input)
(with-open-file (out outfile :direction :output :if-exists :supersede :if-does-not-exist :create)
(%jsmin in out))))
| 8,146 | Common Lisp | .lisp | 191 | 27.376963 | 101 | 0.447272 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | ff62e509137de8414d826e2ea880eda6ffe39249b1cc396ae4f1792fe7ecf636 | 2,435 | [
-1
] |
2,436 | api.lisp | hoytech_antiweb/bundled/cl-ppcre/api.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/api.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; The external API for creating and using scanners.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(defgeneric create-scanner (regex &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(:documentation "Accepts a regular expression - either as a
parse-tree or as a string - and returns a scan closure which will scan
strings for this regular expression and a list mapping registers to
their names \(NIL stands for unnamed ones). The \"mode\" keyboard
arguments are equivalent to the imsx modifiers in Perl. If DESTRUCTIVE
is not NIL the function is allowed to destructively modify its first
argument \(but only if it's a parse tree)."))
#-:use-acl-regexp2-engine
(defmethod create-scanner ((regex-string string) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
;; parse the string into a parse-tree and then call CREATE-SCANNER
;; again
(let* ((*extended-mode-p* extended-mode)
(quoted-regex-string (if *allow-quoting*
(quote-sections (clean-comments regex-string extended-mode))
regex-string))
(*syntax-error-string* (copy-seq quoted-regex-string)))
;; wrap the result with :GROUP to avoid infinite loops for
;; constant strings
(create-scanner (cons :group (list (parse-string quoted-regex-string)))
:case-insensitive-mode case-insensitive-mode
:multi-line-mode multi-line-mode
:single-line-mode single-line-mode
:destructive t)))
#-:use-acl-regexp2-engine
(defmethod create-scanner ((scanner function) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
(when (or case-insensitive-mode multi-line-mode single-line-mode extended-mode)
(signal-ppcre-invocation-error
"You can't use the keyword arguments to modify an existing scanner."))
scanner)
#-:use-acl-regexp2-engine
(defmethod create-scanner ((parse-tree t) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(when extended-mode
(signal-ppcre-invocation-error
"Extended mode doesn't make sense in parse trees."))
;; convert parse-tree into internal representation REGEX and at the
;; same time compute the number of registers and the constant string
;; (or anchor) the regex starts with (if any)
(unless destructive
(setq parse-tree (copy-tree parse-tree)))
(let (flags)
(if single-line-mode
(push :single-line-mode-p flags))
(if multi-line-mode
(push :multi-line-mode-p flags))
(if case-insensitive-mode
(push :case-insensitive-p flags))
(when flags
(setq parse-tree (list :group (cons :flags flags) parse-tree))))
(let ((*syntax-error-string* nil))
(multiple-value-bind (regex reg-num starts-with reg-names)
(convert parse-tree)
;; simplify REGEX by flattening nested SEQ and ALTERNATION
;; constructs and gathering STR objects
(let ((regex (gather-strings (flatten regex))))
;; set the MIN-REST slots of the REPETITION objects
(compute-min-rest regex 0)
;; set the OFFSET slots of the STR objects
(compute-offsets regex 0)
(let* (end-string-offset
end-anchored-p
;; compute the constant string the regex ends with (if
;; any) and at the same time set the special variables
;; END-STRING-OFFSET and END-ANCHORED-P
(end-string (end-string regex))
;; if we found a non-zero-length end-string we create an
;; efficient search function for it
(end-string-test (and end-string
(plusp (len end-string))
(if (= 1 (len end-string))
(create-char-searcher
(schar (str end-string) 0)
(case-insensitive-p end-string))
(create-bmh-matcher
(str end-string)
(case-insensitive-p end-string)))))
;; initialize the counters for CREATE-MATCHER-AUX
(*rep-num* 0)
(*zero-length-num* 0)
;; create the actual matcher function (which does all the
;; work of matching the regular expression) corresponding
;; to REGEX and at the same time set the special
;; variables *REP-NUM* and *ZERO-LENGTH-NUM*
(match-fn (create-matcher-aux regex #'identity))
;; if the regex starts with a string we create an
;; efficient search function for it
(start-string-test (and (typep starts-with 'str)
(plusp (len starts-with))
(if (= 1 (len starts-with))
(create-char-searcher
(schar (str starts-with) 0)
(case-insensitive-p starts-with))
(create-bmh-matcher
(str starts-with)
(case-insensitive-p starts-with))))))
(declare (special end-string-offset end-anchored-p end-string))
;; now create the scanner and return it
(values (create-scanner-aux match-fn
(regex-min-length regex)
(or (start-anchored-p regex)
;; a dot in single-line-mode also
;; implicitly anchors the regex at
;; the start, i.e. if we can't match
;; from the first position we won't
;; match at all
(and (typep starts-with 'everything)
(single-line-p starts-with)))
starts-with
start-string-test
;; only mark regex as end-anchored if we
;; found a non-zero-length string before
;; the anchor
(and end-string-test end-anchored-p)
end-string-test
(if end-string-test
(len end-string)
nil)
end-string-offset
*rep-num*
*zero-length-num*
reg-num)
reg-names))))))
#+:use-acl-regexp2-engine
(declaim (inline create-scanner))
#+:use-acl-regexp2-engine
(defmethod create-scanner ((scanner regexp::regular-expression) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
(when (or case-insensitive-mode multi-line-mode single-line-mode extended-mode)
(signal-ppcre-invocation-error
"You can't use the keyword arguments to modify an existing scanner."))
scanner)
#+:use-acl-regexp2-engine
(defmethod create-scanner ((parse-tree t) &key case-insensitive-mode
multi-line-mode
single-line-mode
extended-mode
destructive)
(declare #.*standard-optimize-settings*)
(declare (ignore destructive))
(excl:compile-re parse-tree
:case-fold case-insensitive-mode
:ignore-whitespace extended-mode
:multiple-lines multi-line-mode
:single-line single-line-mode
:return :index))
(defgeneric scan (regex target-string &key start end real-start-pos)
(:documentation "Searches TARGET-STRING from START to END and tries
to match REGEX. On success returns four values - the start of the
match, the end of the match, and two arrays denoting the beginnings
and ends of register matches. On failure returns NIL. REGEX can be a
string which will be parsed according to Perl syntax, a parse tree, or
a pre-compiled scanner created by CREATE-SCANNER. TARGET-STRING will
be coerced to a simple string if it isn't one already. The
REAL-START-POS parameter should be ignored - it exists only for
internal purposes."))
#-:use-acl-regexp2-engine
(defmethod scan ((regex-string string) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
;; note that the scanners are optimized for simple strings so we
;; have to coerce TARGET-STRING into one if it isn't already
(funcall (create-scanner regex-string)
(maybe-coerce-to-simple-string target-string)
start end))
#-:use-acl-regexp2-engine
(defmethod scan ((scanner function) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
(funcall scanner
(maybe-coerce-to-simple-string target-string)
start end))
#-:use-acl-regexp2-engine
(defmethod scan ((parse-tree t) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
(funcall (create-scanner parse-tree)
(maybe-coerce-to-simple-string target-string)
start end))
#+:use-acl-regexp2-engine
(declaim (inline scan))
#+:use-acl-regexp2-engine
(defmethod scan ((parse-tree t) target-string
&key (start 0)
(end (length target-string))
((:real-start-pos *real-start-pos*) nil))
(declare #.*standard-optimize-settings*)
(when (< end start)
(return-from scan nil))
(let ((results (multiple-value-list (excl:match-re parse-tree target-string
:start start
:end end
:return :index))))
(declare (dynamic-extent results))
(cond ((null (first results)) nil)
(t (let* ((no-of-regs (- (length results) 2))
(reg-starts (make-array no-of-regs
:element-type '(or null fixnum)))
(reg-ends (make-array no-of-regs
:element-type '(or null fixnum)))
(match (second results)))
(loop for (start . end) in (cddr results)
for i from 0
do (setf (aref reg-starts i) start
(aref reg-ends i) end))
(values (car match) (cdr match) reg-starts reg-ends))))))
#-:cormanlisp
(define-compiler-macro scan (&whole form &environment env regex target-string &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex env)
`(scan (load-time-value (create-scanner ,regex))
,target-string ,@rest))
(t form)))
(defun scan-to-strings (regex target-string &key (start 0)
(end (length target-string))
sharedp)
(declare #.*standard-optimize-settings*)
"Like SCAN but returns substrings of TARGET-STRING instead of
positions, i.e. this function returns two values on success: the whole
match as a string plus an array of substrings (or NILs) corresponding
to the matched registers. If SHAREDP is true, the substrings may share
structure with TARGET-STRING."
(multiple-value-bind (match-start match-end reg-starts reg-ends)
(scan regex target-string :start start :end end)
(unless match-start
(return-from scan-to-strings nil))
(let ((substr-fn (if sharedp #'nsubseq #'subseq)))
(values (funcall substr-fn
target-string match-start match-end)
(map 'vector
(lambda (reg-start reg-end)
(if reg-start
(funcall substr-fn
target-string reg-start reg-end)
nil))
reg-starts
reg-ends)))))
#-:cormanlisp
(define-compiler-macro scan-to-strings
(&whole form &environment env regex target-string &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex env)
`(scan-to-strings (load-time-value (create-scanner ,regex))
,target-string ,@rest))
(t form)))
(defmacro register-groups-bind (var-list (regex target-string
&key start end sharedp)
&body body)
"Executes BODY with the variables in VAR-LIST bound to the
corresponding register groups after TARGET-STRING has been matched
against REGEX, i.e. each variable is either bound to a string or to
NIL. If there is no match, BODY is _not_ executed. For each element of
VAR-LIST which is NIL there's no binding to the corresponding register
group. The number of variables in VAR-LIST must not be greater than
the number of register groups. If SHAREDP is true, the substrings may
share structure with TARGET-STRING."
(with-rebinding (target-string)
(with-unique-names (match-start match-end reg-starts reg-ends
start-index substr-fn)
`(multiple-value-bind (,match-start ,match-end ,reg-starts ,reg-ends)
(scan ,regex ,target-string :start (or ,start 0)
:end (or ,end (length ,target-string)))
(declare (ignore ,match-end))
(when ,match-start
(let* ,(cons
`(,substr-fn (if ,sharedp
#'nsubseq
#'subseq))
(loop for (function var) in (normalize-var-list var-list)
for counter from 0
when var
collect `(,var (let ((,start-index
(aref ,reg-starts ,counter)))
(if ,start-index
(funcall ,function
(funcall ,substr-fn
,target-string
,start-index
(aref ,reg-ends ,counter)))
nil)))))
,@body))))))
(defmacro do-scans ((match-start match-end reg-starts reg-ends regex
target-string
&optional result-form
&key start end)
&body body
&environment env)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with MATCH-START, MATCH-END, REG-STARTS, and
REG-ENDS bound to the four return values of each match in turn. After
the last match, returns RESULT-FORM if provided or NIL otherwise. An
implicit block named NIL surrounds DO-SCANS; RETURN may be used to
terminate the loop immediately. If REGEX matches an empty string the
scan is continued one position behind this match. BODY may start with
declarations."
(with-rebinding (target-string)
(with-unique-names (%start %end %regex scanner loop-tag block-name)
(declare (ignorable %regex scanner))
;; the NIL BLOCK to enable exits via (RETURN ...)
`(block nil
(let* ((,%start (or ,start 0))
(,%end (or ,end (length ,target-string)))
,@(unless (constantp regex env)
;; leave constant regular expressions as they are -
;; SCAN's compiler macro will take care of them;
;; otherwise create a scanner unless the regex is
;; already a function (otherwise SCAN will do this
;; on each iteration)
`((,%regex ,regex)
(,scanner (typecase ,%regex
(function ,%regex)
(t (create-scanner ,%regex)))))))
;; coerce TARGET-STRING to a simple string unless it is one
;; already (otherwise SCAN will do this on each iteration)
(setq ,target-string
(maybe-coerce-to-simple-string ,target-string))
;; a named BLOCK so we can exit the TAGBODY
(block ,block-name
(tagbody
,loop-tag
;; invoke SCAN and bind the returned values to the
;; provided variables
(multiple-value-bind
(,match-start ,match-end ,reg-starts ,reg-ends)
(scan ,(cond ((constantp regex env) regex)
(t scanner))
,target-string :start ,%start :end ,%end
:real-start-pos (or ,start 0))
;; declare the variables to be IGNORABLE to prevent the
;; compiler from issuing warnings
(declare
(ignorable ,match-start ,match-end ,reg-starts ,reg-ends))
(unless ,match-start
;; stop iteration on first failure
(return-from ,block-name ,result-form))
;; execute BODY (wrapped in LOCALLY so it can start with
;; declarations)
(locally
,@body)
;; advance by one position if we had a zero-length match
(setq ,%start (if (= ,match-start ,match-end)
(1+ ,match-end)
,match-end)))
(go ,loop-tag))))))))
(defmacro do-matches ((match-start match-end regex
target-string
&optional result-form
&key start end)
&body body)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with MATCH-START and MATCH-END bound to the
start/end positions of each match in turn. After the last match,
returns RESULT-FORM if provided or NIL otherwise. An implicit block
named NIL surrounds DO-MATCHES; RETURN may be used to terminate the
loop immediately. If REGEX matches an empty string the scan is
continued one position behind this match. BODY may start with
declarations."
;; this is a simplified form of DO-SCANS - we just provide two dummy
;; vars and ignore them
(with-unique-names (reg-starts reg-ends)
`(do-scans (,match-start ,match-end
,reg-starts ,reg-ends
,regex ,target-string
,result-form
:start ,start :end ,end)
,@body)))
(defmacro do-matches-as-strings ((match-var regex
target-string
&optional result-form
&key start end sharedp)
&body body)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with MATCH-VAR bound to the substring of
TARGET-STRING corresponding to each match in turn. After the last
match, returns RESULT-FORM if provided or NIL otherwise. An implicit
block named NIL surrounds DO-MATCHES-AS-STRINGS; RETURN may be used to
terminate the loop immediately. If REGEX matches an empty string the
scan is continued one position behind this match. If SHAREDP is true,
the substrings may share structure with TARGET-STRING. BODY may start
with declarations."
(with-rebinding (target-string)
(with-unique-names (match-start match-end substr-fn)
`(let ((,substr-fn (if ,sharedp #'nsubseq #'subseq)))
;; simple use DO-MATCHES to extract the substrings
(do-matches (,match-start ,match-end ,regex ,target-string
,result-form :start ,start :end ,end)
(let ((,match-var
(funcall ,substr-fn
,target-string ,match-start ,match-end)))
,@body))))))
(defmacro do-register-groups (var-list (regex target-string
&optional result-form
&key start end sharedp)
&body body)
"Iterates over TARGET-STRING and tries to match REGEX as often as
possible evaluating BODY with the variables in VAR-LIST bound to the
corresponding register groups for each match in turn, i.e. each
variable is either bound to a string or to NIL. For each element of
VAR-LIST which is NIL there's no binding to the corresponding register
group. The number of variables in VAR-LIST must not be greater than
the number of register groups. After the last match, returns
RESULT-FORM if provided or NIL otherwise. An implicit block named NIL
surrounds DO-REGISTER-GROUPS; RETURN may be used to terminate the loop
immediately. If REGEX matches an empty string the scan is continued
one position behind this match. If SHAREDP is true, the substrings may
share structure with TARGET-STRING. BODY may start with declarations."
(with-rebinding (target-string)
(with-unique-names (substr-fn match-start match-end
reg-starts reg-ends start-index)
`(let ((,substr-fn (if ,sharedp
#'nsubseq
#'subseq)))
(do-scans (,match-start ,match-end ,reg-starts ,reg-ends
,regex ,target-string
,result-form :start ,start :end ,end)
(let ,(loop for (function var) in (normalize-var-list var-list)
for counter from 0
when var
collect `(,var (let ((,start-index
(aref ,reg-starts ,counter)))
(if ,start-index
(funcall ,function
(funcall ,substr-fn
,target-string
,start-index
(aref ,reg-ends ,counter)))
nil))))
,@body))))))
(defun all-matches (regex target-string
&key (start 0)
(end (length target-string)))
(declare #.*standard-optimize-settings*)
"Returns a list containing the start and end positions of all
matches of REGEX against TARGET-STRING, i.e. if there are N matches
the list contains (* 2 N) elements. If REGEX matches an empty string
the scan is continued one position behind this match."
(let (result-list)
(do-matches (match-start match-end
regex target-string
(nreverse result-list)
:start start :end end)
(push match-start result-list)
(push match-end result-list))))
#-:cormanlisp
(define-compiler-macro all-matches (&whole form &environment env regex &rest rest)
"Make sure that constant forms are compiled into scanners at
compile time."
(cond ((constantp regex env)
`(all-matches (load-time-value (create-scanner ,regex))
,@rest))
(t form)))
(defun all-matches-as-strings (regex target-string
&key (start 0)
(end (length target-string))
sharedp)
(declare #.*standard-optimize-settings*)
"Returns a list containing all substrings of TARGET-STRING which
match REGEX. If REGEX matches an empty string the scan is continued
one position behind this match. If SHAREDP is true, the substrings may
share structure with TARGET-STRING."
(let (result-list)
(do-matches-as-strings (match regex target-string (nreverse result-list)
:start start :end end :sharedp sharedp)
(push match result-list))))
#-:cormanlisp
(define-compiler-macro all-matches-as-strings (&whole form &environment env regex &rest rest)
"Make sure that constant forms are compiled into scanners at
compile time."
(cond ((constantp regex env)
`(all-matches-as-strings
(load-time-value (create-scanner ,regex))
,@rest))
(t form)))
(defun split (regex target-string
&key (start 0)
(end (length target-string))
limit
with-registers-p
omit-unmatched-p
sharedp)
(declare #.*standard-optimize-settings*)
"Matches REGEX against TARGET-STRING as often as possible and
returns a list of the substrings between the matches. If
WITH-REGISTERS-P is true, substrings corresponding to matched
registers are inserted into the list as well. If OMIT-UNMATCHED-P is
true, unmatched registers will simply be left out, otherwise they will
show up as NIL. LIMIT limits the number of elements returned -
registers aren't counted. If LIMIT is NIL (or 0 which is equivalent),
trailing empty strings are removed from the result list. If REGEX
matches an empty string the scan is continued one position behind this
match. If SHAREDP is true, the substrings may share structure with
TARGET-STRING."
;; initialize list of positions POS-LIST to extract substrings with
;; START so that the start of the next match will mark the end of
;; the first substring
(let ((pos-list (list start))
(counter 0))
;; how would Larry Wall do it?
(when (eql limit 0)
(setq limit nil))
(do-scans (match-start match-end
reg-starts reg-ends
regex target-string nil
:start start :end end)
(unless (and (= match-start match-end)
(= match-start (car pos-list)))
;; push start of match on list unless this would be an empty
;; string adjacent to the last element pushed onto the list
(when (and limit
(>= (incf counter) limit))
(return))
(push match-start pos-list)
(when with-registers-p
;; optionally insert matched registers
(loop for reg-start across reg-starts
for reg-end across reg-ends
if reg-start
;; but only if they've matched
do (push reg-start pos-list)
(push reg-end pos-list)
else unless omit-unmatched-p
;; or if we're allowed to insert NIL instead
do (push nil pos-list)
(push nil pos-list)))
;; now end of match
(push match-end pos-list)))
;; end of whole string
(push end pos-list)
;; now collect substrings
(nreverse
(loop with substr-fn = (if sharedp #'nsubseq #'subseq)
with string-seen = nil
for (this-end this-start) on pos-list by #'cddr
;; skip empty strings from end of list
if (or limit
(setq string-seen
(or string-seen
(and this-start
(> this-end this-start)))))
collect (if this-start
(funcall substr-fn
target-string this-start this-end)
nil)))))
#-:cormanlisp
(define-compiler-macro split (&whole form &environment env regex target-string &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex env)
`(split (load-time-value (create-scanner ,regex))
,target-string ,@rest))
(t form)))
(defun string-case-modifier (str from to start end)
(declare #.*standard-optimize-settings*)
(declare (type fixnum from to start end))
"Checks whether all words in STR between FROM and TO are upcased,
downcased or capitalized and returns a function which applies a
corresponding case modification to strings. Returns #'IDENTITY
otherwise, especially if words in the target area extend beyond FROM
or TO. STR is supposed to be bounded by START and END. It is assumed
that (<= START FROM TO END)."
(case
(if (or (<= to from)
(and (< start from)
(alphanumericp (char str (1- from)))
(alphanumericp (char str from)))
(and (< to end)
(alphanumericp (char str to))
(alphanumericp (char str (1- to)))))
;; if it's a zero-length string or if words extend beyond FROM
;; or TO we return NIL, i.e. #'IDENTITY
nil
;; otherwise we loop through STR from FROM to TO
(loop with last-char-both-case
with current-result
for index of-type fixnum from from below to
for chr = (char str index)
do (cond ((not #-:cormanlisp (both-case-p chr)
#+:cormanlisp (or (upper-case-p chr)
(lower-case-p chr)))
;; this character doesn't have a case so we
;; consider it as a word boundary (note that
;; this differs from how \b works in Perl)
(setq last-char-both-case nil))
((upper-case-p chr)
;; an uppercase character
(setq current-result
(if last-char-both-case
;; not the first character in a
(case current-result
((:undecided) :upcase)
((:downcase :capitalize) (return nil))
((:upcase) current-result))
(case current-result
((nil) :undecided)
((:downcase) (return nil))
((:capitalize :upcase) current-result)))
last-char-both-case t))
(t
;; a lowercase character
(setq current-result
(case current-result
((nil) :downcase)
((:undecided) :capitalize)
((:downcase) current-result)
((:capitalize) (if last-char-both-case
current-result
(return nil)))
((:upcase) (return nil)))
last-char-both-case t)))
finally (return current-result)))
((nil) #'identity)
((:undecided :upcase) #'string-upcase)
((:downcase) #'string-downcase)
((:capitalize) #'string-capitalize)))
;; first create a scanner to identify the special parts of the
;; replacement string (eat your own dog food...)
(defgeneric build-replacement-template (replacement-string)
(declare #.*standard-optimize-settings*)
(:documentation "Converts a replacement string for REGEX-REPLACE or
REGEX-REPLACE-ALL into a replacement template which is an
S-expression."))
#-:cormanlisp
(let* ((*use-bmh-matchers* nil)
(reg-scanner (create-scanner "\\\\(?:\\\\|\\{\\d+\\}|\\d+|&|`|')")))
(defmethod build-replacement-template ((replacement-string string))
(declare #.*standard-optimize-settings*)
(let ((from 0)
;; COLLECTOR will hold the (reversed) template
(collector '()))
;; scan through all special parts of the replacement string
(do-matches (match-start match-end reg-scanner replacement-string)
(when (< from match-start)
;; strings between matches are copied verbatim
(push (subseq replacement-string from match-start) collector))
;; PARSE-START is true if the pattern matched a number which
;; refers to a register
(let* ((parse-start (position-if #'digit-char-p
replacement-string
:start match-start
:end match-end))
(token (if parse-start
(1- (parse-integer replacement-string
:start parse-start
:junk-allowed t))
;; if we didn't match a number we convert the
;; character to a symbol
(case (char replacement-string (1+ match-start))
((#\&) :match)
((#\`) :before-match)
((#\') :after-match)
((#\\) :backslash)))))
(when (and (numberp token) (< token 0))
;; make sure we don't accept something like "\\0"
(signal-ppcre-invocation-error
"Illegal substring ~S in replacement string"
(subseq replacement-string match-start match-end)))
(push token collector))
;; remember where the match ended
(setq from match-end))
(when (< from (length replacement-string))
;; push the rest of the replacement string onto the list
(push (subseq replacement-string from) collector))
(nreverse collector))))
#-:cormanlisp
(defmethod build-replacement-template ((replacement-function function))
(declare #.*standard-optimize-settings*)
(list replacement-function))
#-:cormanlisp
(defmethod build-replacement-template ((replacement-function-symbol symbol))
(declare #.*standard-optimize-settings*)
(list replacement-function-symbol))
#-:cormanlisp
(defmethod build-replacement-template ((replacement-list list))
(declare #.*standard-optimize-settings*)
replacement-list)
;;; Corman Lisp's methods can't be closures... :(
#+:cormanlisp
(let* ((*use-bmh-matchers* nil)
(reg-scanner (create-scanner "\\\\(?:\\\\|\\{\\d+\\}|\\d+|&|`|')")))
(defun build-replacement-template (replacement)
(declare #.*standard-optimize-settings*)
(typecase replacement
(string
(let ((from 0)
;; COLLECTOR will hold the (reversed) template
(collector '()))
;; scan through all special parts of the replacement string
(do-matches (match-start match-end reg-scanner replacement)
(when (< from match-start)
;; strings between matches are copied verbatim
(push (subseq replacement from match-start) collector))
;; PARSE-START is true if the pattern matched a number which
;; refers to a register
(let* ((parse-start (position-if #'digit-char-p
replacement
:start match-start
:end match-end))
(token (if parse-start
(1- (parse-integer replacement
:start parse-start
:junk-allowed t))
;; if we didn't match a number we convert the
;; character to a symbol
(case (char replacement (1+ match-start))
((#\&) :match)
((#\`) :before-match)
((#\') :after-match)
((#\\) :backslash)))))
(when (and (numberp token) (< token 0))
;; make sure we don't accept something like "\\0"
(signal-ppcre-invocation-error
"Illegal substring ~S in replacement string"
(subseq replacement match-start match-end)))
(push token collector))
;; remember where the match ended
(setq from match-end))
(when (< from (length replacement))
;; push the rest of the replacement string onto the list
(push (nsubseq replacement from) collector))
(nreverse collector)))
(list
replacement)
(t
(list replacement)))))
(defun build-replacement (replacement-template
target-string
start end
match-start match-end
reg-starts reg-ends
simple-calls
element-type)
(declare #.*standard-optimize-settings*)
"Accepts a replacement template and the current values from the
matching process in REGEX-REPLACE or REGEX-REPLACE-ALL and returns the
corresponding string."
;; the upper exclusive bound of the register numbers in the regular
;; expression
(let ((reg-bound (if reg-starts
(array-dimension reg-starts 0)
0)))
(with-output-to-string (s nil :element-type element-type)
(loop for token in replacement-template
do (typecase token
(string
;; transfer string parts verbatim
(write-string token s))
(integer
;; replace numbers with the corresponding registers
(when (>= token reg-bound)
;; but only if the register was referenced in the
;; regular expression
(signal-ppcre-invocation-error
"Reference to non-existent register ~A in replacement string"
(1+ token)))
(when (svref reg-starts token)
;; and only if it matched, i.e. no match results
;; in an empty string
(write-string target-string s
:start (svref reg-starts token)
:end (svref reg-ends token))))
(function
(write-string
(cond (simple-calls
(apply token
(nsubseq target-string match-start match-end)
(map 'list
(lambda (reg-start reg-end)
(and reg-start
(nsubseq target-string reg-start reg-end)))
reg-starts reg-ends)))
(t
(funcall token
target-string
start end
match-start match-end
reg-starts reg-ends)))
s))
(symbol
(case token
((:backslash)
;; just a backslash
(write-char #\\ s))
((:match)
;; the whole match
(write-string target-string s
:start match-start
:end match-end))
((:before-match)
;; the part of the target string before the match
(write-string target-string s
:start start
:end match-start))
((:after-match)
;; the part of the target string after the match
(write-string target-string s
:start match-end
:end end))
(otherwise
(write-string
(cond (simple-calls
(apply token
(nsubseq target-string match-start match-end)
(map 'list
(lambda (reg-start reg-end)
(and reg-start
(nsubseq target-string reg-start reg-end)))
reg-starts reg-ends)))
(t
(funcall token
target-string
start end
match-start match-end
reg-starts reg-ends)))
s)))))))))
(defun replace-aux (target-string replacement pos-list reg-list start end
preserve-case simple-calls element-type)
(declare #.*standard-optimize-settings*)
"Auxiliary function used by REGEX-REPLACE and
REGEX-REPLACE-ALL. POS-LIST contains a list with the start and end
positions of all matches while REG-LIST contains a list of arrays
representing the corresponding register start and end positions."
;; build the template once before we start the loop
(let ((replacement-template (build-replacement-template replacement)))
(with-output-to-string (s nil :element-type element-type)
;; loop through all matches and take the start and end of the
;; whole string into account
(loop for (from to) on (append (list start) pos-list (list end))
;; alternate between replacement and no replacement
for replace = nil then (and (not replace) to)
for reg-starts = (if replace (pop reg-list) nil)
for reg-ends = (if replace (pop reg-list) nil)
for curr-replacement = (if replace
;; build the replacement string
(build-replacement replacement-template
target-string
start end
from to
reg-starts reg-ends
simple-calls
element-type)
nil)
while to
if replace
do (write-string (if preserve-case
;; modify the case of the replacement
;; string if necessary
(funcall (string-case-modifier target-string
from to
start end)
curr-replacement)
curr-replacement)
s)
else
;; no replacement
do (write-string target-string s :start from :end to)))))
(defun regex-replace (regex target-string replacement
&key (start 0)
(end (length target-string))
preserve-case
simple-calls
(element-type #+:lispworks 'lw:simple-char #-:lispworks 'character))
(declare #.*standard-optimize-settings*)
"Try to match TARGET-STRING between START and END against REGEX and
replace the first match with REPLACEMENT. Two values are returned;
the modified string, and T if REGEX matched or NIL otherwise.
REPLACEMENT can be a string which may contain the special substrings
\"\\&\" for the whole match, \"\\`\" for the part of TARGET-STRING
before the match, \"\\'\" for the part of TARGET-STRING after the
match, \"\\N\" or \"\\{N}\" for the Nth register where N is a positive
integer.
REPLACEMENT can also be a function designator in which case the
match will be replaced with the result of calling the function
designated by REPLACEMENT with the arguments TARGET-STRING, START,
END, MATCH-START, MATCH-END, REG-STARTS, and REG-ENDS. (REG-STARTS and
REG-ENDS are arrays holding the start and end positions of matched
registers or NIL - the meaning of the other arguments should be
obvious.)
Finally, REPLACEMENT can be a list where each element is a string,
one of the symbols :MATCH, :BEFORE-MATCH, or :AFTER-MATCH -
corresponding to \"\\&\", \"\\`\", and \"\\'\" above -, an integer N -
representing register (1+ N) -, or a function designator.
If PRESERVE-CASE is true, the replacement will try to preserve the
case (all upper case, all lower case, or capitalized) of the
match. The result will always be a fresh string, even if REGEX doesn't
match.
ELEMENT-TYPE is the element type of the resulting string."
(multiple-value-bind (match-start match-end reg-starts reg-ends)
(scan regex target-string :start start :end end)
(if match-start
(values (replace-aux target-string replacement
(list match-start match-end)
(list reg-starts reg-ends)
start end preserve-case
simple-calls element-type)
t)
(values (subseq target-string start end)
nil))))
#-:cormanlisp
(define-compiler-macro regex-replace
(&whole form &environment env regex target-string replacement &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex env)
`(regex-replace (load-time-value (create-scanner ,regex))
,target-string ,replacement ,@rest))
(t form)))
(defun regex-replace-all (regex target-string replacement
&key (start 0)
(end (length target-string))
preserve-case
simple-calls
(element-type #+:lispworks 'lw:simple-char #-:lispworks 'character))
(declare #.*standard-optimize-settings*)
"Try to match TARGET-STRING between START and END against REGEX and
replace all matches with REPLACEMENT. Two values are returned; the
modified string, and T if REGEX matched or NIL otherwise.
REPLACEMENT can be a string which may contain the special substrings
\"\\&\" for the whole match, \"\\`\" for the part of TARGET-STRING
before the match, \"\\'\" for the part of TARGET-STRING after the
match, \"\\N\" or \"\\{N}\" for the Nth register where N is a positive
integer.
REPLACEMENT can also be a function designator in which case the
match will be replaced with the result of calling the function
designated by REPLACEMENT with the arguments TARGET-STRING, START,
END, MATCH-START, MATCH-END, REG-STARTS, and REG-ENDS. (REG-STARTS and
REG-ENDS are arrays holding the start and end positions of matched
registers or NIL - the meaning of the other arguments should be
obvious.)
Finally, REPLACEMENT can be a list where each element is a string,
one of the symbols :MATCH, :BEFORE-MATCH, or :AFTER-MATCH -
corresponding to \"\\&\", \"\\`\", and \"\\'\" above -, an integer N -
representing register (1+ N) -, or a function designator.
If PRESERVE-CASE is true, the replacement will try to preserve the
case (all upper case, all lower case, or capitalized) of the
match. The result will always be a fresh string, even if REGEX doesn't
match.
ELEMENT-TYPE is the element type of the resulting string."
(let ((pos-list '())
(reg-list '()))
(do-scans (match-start match-end reg-starts reg-ends regex target-string
nil
:start start :end end)
(push match-start pos-list)
(push match-end pos-list)
(push reg-starts reg-list)
(push reg-ends reg-list))
(if pos-list
(values (replace-aux target-string replacement
(nreverse pos-list)
(nreverse reg-list)
start end preserve-case
simple-calls element-type)
t)
(values (subseq target-string start end)
nil))))
#-:cormanlisp
(define-compiler-macro regex-replace-all
(&whole form &environment env regex target-string replacement &rest rest)
"Make sure that constant forms are compiled into scanners at compile time."
(cond ((constantp regex env)
`(regex-replace-all (load-time-value (create-scanner ,regex))
,target-string ,replacement ,@rest))
(t form)))
#-:cormanlisp
(defmacro regex-apropos-aux ((regex packages case-insensitive &optional return-form)
&body body)
"Auxiliary macro used by REGEX-APROPOS and REGEX-APROPOS-LIST. Loops
through PACKAGES and executes BODY with SYMBOL bound to each symbol
which matches REGEX. Optionally evaluates and returns RETURN-FORM at
the end. If CASE-INSENSITIVE is true and REGEX isn't already a
scanner, a case-insensitive scanner is used."
(with-rebinding (regex)
(with-unique-names (scanner %packages next morep)
`(let* ((,scanner (create-scanner ,regex
:case-insensitive-mode
(and ,case-insensitive
(not (functionp ,regex)))))
(,%packages (or ,packages
(list-all-packages))))
(with-package-iterator (,next ,%packages :external :internal :inherited)
(loop
(multiple-value-bind (,morep symbol)
(,next)
(unless ,morep
(return ,return-form))
(when (scan ,scanner (symbol-name symbol))
,@body))))))))
;;; The following two functions were provided by Karsten Poeck
#+:cormanlisp
(defmacro do-with-all-symbols ((variable package-packagelist) &body body)
(with-unique-names (pack-var iter-sym)
`(if (listp ,package-packagelist)
(dolist (,pack-var ,package-packagelist)
(do-symbols (,iter-sym ,pack-var)
,@body))
(do-symbols (,iter-sym ,package-packagelist)
,@body))))
#+:cormanlisp
(defmacro regex-apropos-aux ((regex packages case-insensitive &optional return-form)
&body body)
"Auxiliary macro used by REGEX-APROPOS and REGEX-APROPOS-LIST. Loops
through PACKAGES and executes BODY with SYMBOL bound to each symbol
which matches REGEX. Optionally evaluates and returns RETURN-FORM at
the end. If CASE-INSENSITIVE is true and REGEX isn't already a
scanner, a case-insensitive scanner is used."
(with-rebinding (regex)
(with-unique-names (scanner %packages)
`(let* ((,scanner (create-scanner ,regex
:case-insensitive-mode
(and ,case-insensitive
(not (functionp ,regex)))))
(,%packages (or ,packages
(list-all-packages))))
(do-with-all-symbols (symbol ,%packages)
(when (scan ,scanner (symbol-name symbol))
,@body))
,return-form))))
(defun regex-apropos-list (regex &optional packages &key (case-insensitive t))
(declare #.*standard-optimize-settings*)
"Similar to the standard function APROPOS-LIST but returns a list of
all symbols which match the regular expression REGEX. If
CASE-INSENSITIVE is true and REGEX isn't already a scanner, a
case-insensitive scanner is used."
(let ((collector '()))
(regex-apropos-aux (regex packages case-insensitive collector)
(push symbol collector))))
(defun print-symbol-info (symbol)
"Auxiliary function used by REGEX-APROPOS. Tries to print some
meaningful information about a symbol."
(declare #.*standard-optimize-settings*)
(handler-case
(let ((output-list '()))
(cond ((special-operator-p symbol)
(push "[special operator]" output-list))
((macro-function symbol)
(push "[macro]" output-list))
((fboundp symbol)
(let* ((function (symbol-function symbol))
(compiledp (compiled-function-p function)))
(multiple-value-bind (lambda-expr closurep)
(function-lambda-expression function)
(push
(format nil
"[~:[~;compiled ~]~:[function~;closure~]]~:[~; ~A~]"
compiledp closurep lambda-expr (cadr lambda-expr))
output-list)))))
(let ((class (find-class symbol nil)))
(when class
(push (format nil "[class] ~S" class) output-list)))
(cond ((keywordp symbol)
(push "[keyword]" output-list))
((constantp symbol)
(push (format nil "[constant]~:[~; value: ~S~]"
(boundp symbol) (symbol-value symbol)) output-list))
((boundp symbol)
(push #+(or :lispworks :clisp) "[variable]"
#-(or :lispworks :clisp) (format nil "[variable] value: ~S"
(symbol-value symbol))
output-list)))
#-(or :cormanlisp :clisp)
(format t "~&~S ~<~;~^~A~@{~:@_~A~}~;~:>" symbol output-list)
#+(or :cormanlisp :clisp)
(loop for line in output-list
do (format t "~&~S ~A" symbol line)))
(condition ()
;; this seems to be necessary due to some errors I encountered
;; with LispWorks
(format t "~&~S [an error occured while trying to print more info]" symbol))))
(defun regex-apropos (regex &optional packages &key (case-insensitive t))
"Similar to the standard function APROPOS but returns a list of all
symbols which match the regular expression REGEX. If CASE-INSENSITIVE
is true and REGEX isn't already a scanner, a case-insensitive scanner
is used."
(declare #.*standard-optimize-settings*)
(regex-apropos-aux (regex packages case-insensitive)
(print-symbol-info symbol))
(values))
(let* ((*use-bmh-matchers* nil)
(non-word-char-scanner (create-scanner "[^a-zA-Z_0-9]")))
(defun quote-meta-chars (string &key (start 0) (end (length string)))
"Quote, i.e. prefix with #\\\\, all non-word characters in STRING."
(regex-replace-all non-word-char-scanner string "\\\\\\&"
:start start :end end)))
(let* ((*use-bmh-matchers* nil)
(*allow-quoting* nil)
(quote-char-scanner (create-scanner "\\\\Q"))
(section-scanner (create-scanner "\\\\Q((?:[^\\\\]|\\\\(?!Q))*?)(?:\\\\E|$)")))
(defun quote-sections (string)
"Replace sections inside of STRING which are enclosed by \\Q and
\\E with the quoted equivalent of these sections \(see
QUOTE-META-CHARS). Repeat this as long as there are such
sections. These sections may nest."
(flet ((quote-substring (target-string start end match-start
match-end reg-starts reg-ends)
(declare (ignore start end match-start match-end))
(quote-meta-chars target-string
:start (svref reg-starts 0)
:end (svref reg-ends 0))))
(loop for result = string then (regex-replace-all section-scanner
result
#'quote-substring)
while (scan quote-char-scanner result)
finally (return result)))))
(let* ((*use-bmh-matchers* nil)
(comment-scanner (create-scanner "(?s)\\(\\?#.*?\\)"))
(extended-comment-scanner (create-scanner "(?m:#.*?$)|(?s:\\(\\?#.*?\\))"))
(quote-token-scanner "\\\\[QE]")
(quote-token-replace-scanner "\\\\([QE])"))
(defun clean-comments (string &optional extended-mode)
"Clean \(?#...) comments within STRING for quoting, i.e. convert
\\Q to Q and \\E to E. If EXTENDED-MODE is true, also clean
end-of-line comments, i.e. those starting with #\\# and ending with
#\\Newline."
(flet ((remove-tokens (target-string start end match-start
match-end reg-starts reg-ends)
(declare (ignore start end reg-starts reg-ends))
(loop for result = (nsubseq target-string match-start match-end)
then (regex-replace-all quote-token-replace-scanner result "\\1")
;; we must probably repeat this because the comment
;; can contain substrings like \\Q
while (scan quote-token-scanner result)
finally (return result))))
(regex-replace-all (if extended-mode
extended-comment-scanner
comment-scanner)
string
#'remove-tokens))))
(defun parse-tree-synonym (symbol)
"Returns the parse tree the SYMBOL symbol is a synonym for. Returns
NIL is SYMBOL wasn't yet defined to be a synonym."
(get symbol 'parse-tree-synonym))
(defun (setf parse-tree-synonym) (new-parse-tree symbol)
"Defines SYMBOL to be a synonm for the parse tree NEW-PARSE-TREE."
(setf (get symbol 'parse-tree-synonym) new-parse-tree))
(defmacro define-parse-tree-synonym (name parse-tree)
"Defines the symbol NAME to be a synonym for the parse tree
PARSE-TREE. Both arguments are quoted."
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (parse-tree-synonym ',name) ',parse-tree)))
| 62,194 | Common Lisp | .lisp | 1,193 | 36.056999 | 105 | 0.542141 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 71e0f32641d77a34d73adb74863d7ea6baf30dda0bc5fef74c3a7e8d20ee91c0 | 2,436 | [
-1
] |
2,437 | lexer.lisp | hoytech_antiweb/bundled/cl-ppcre/lexer.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/lexer.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; The lexer's responsibility is to convert the regex string into a
;;; sequence of tokens which are in turn consumed by the parser.
;;;
;;; The lexer is aware of Perl's 'extended mode' and it also 'knows'
;;; (with a little help from the parser) how many register groups it
;;; has opened so far. (The latter is necessary for interpreting
;;; strings like "\\10" correctly.)
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(declaim (inline map-char-to-special-class))
(defun map-char-to-special-char-class (chr)
(declare #.*standard-optimize-settings*)
"Maps escaped characters like \"\\d\" to the tokens which represent
their associated character classes."
(case chr
((#\d)
:digit-class)
((#\D)
:non-digit-class)
((#\w)
:word-char-class)
((#\W)
:non-word-char-class)
((#\s)
:whitespace-char-class)
((#\S)
:non-whitespace-char-class)))
(locally
(declare #.*standard-optimize-settings*)
(defstruct (lexer (:constructor make-lexer-internal))
"LEXER structures are used to hold the regex string which is
currently lexed and to keep track of the lexer's state."
(str ""
:type string
:read-only t)
(len 0
:type fixnum
:read-only t)
(reg 0
:type fixnum)
(pos 0
:type fixnum)
(last-pos nil
:type list)))
(defun make-lexer (string)
(declare (inline make-lexer-internal)
#-genera (type string string))
(make-lexer-internal :str (maybe-coerce-to-simple-string string)
:len (length string)))
(declaim (inline end-of-string-p))
(defun end-of-string-p (lexer)
(declare #.*standard-optimize-settings*)
"Tests whether we're at the end of the regex string."
(<= (lexer-len lexer)
(lexer-pos lexer)))
(declaim (inline looking-at-p))
(defun looking-at-p (lexer chr)
(declare #.*standard-optimize-settings*)
"Tests whether the next character the lexer would see is CHR.
Does not respect extended mode."
(and (not (end-of-string-p lexer))
(char= (schar (lexer-str lexer) (lexer-pos lexer))
chr)))
(declaim (inline next-char-non-extended))
(defun next-char-non-extended (lexer)
(declare #.*standard-optimize-settings*)
"Returns the next character which is to be examined and updates the
POS slot. Does not respect extended mode."
(cond ((end-of-string-p lexer)
nil)
(t
(prog1
(schar (lexer-str lexer) (lexer-pos lexer))
(incf (lexer-pos lexer))))))
(defun next-char (lexer)
(declare #.*standard-optimize-settings*)
"Returns the next character which is to be examined and updates the
POS slot. Respects extended mode, i.e. whitespace, comments, and also
nested comments are skipped if applicable."
(let ((next-char (next-char-non-extended lexer))
last-loop-pos)
(loop
;; remember where we started
(setq last-loop-pos (lexer-pos lexer))
;; first we look for nested comments like (?#foo)
(when (and next-char
(char= next-char #\()
(looking-at-p lexer #\?))
(incf (lexer-pos lexer))
(cond ((looking-at-p lexer #\#)
;; must be a nested comment - so we have to search for
;; the closing parenthesis
(let ((error-pos (- (lexer-pos lexer) 2)))
(unless
;; loop 'til ')' or end of regex string and
;; return NIL if ')' wasn't encountered
(loop for skip-char = next-char
then (next-char-non-extended lexer)
while (and skip-char
(char/= skip-char #\)))
finally (return skip-char))
(signal-ppcre-syntax-error*
error-pos
"Comment group not closed")))
(setq next-char (next-char-non-extended lexer)))
(t
;; undo effect of previous INCF if we didn't see a #
(decf (lexer-pos lexer)))))
(when *extended-mode-p*
;; now - if we're in extended mode - we skip whitespace and
;; comments; repeat the following loop while we look at
;; whitespace or #\#
(loop while (and next-char
(or (char= next-char #\#)
(whitespacep next-char)))
do (setq next-char
(if (char= next-char #\#)
;; if we saw a comment marker skip until
;; we're behind #\Newline...
(loop for skip-char = next-char
then (next-char-non-extended lexer)
while (and skip-char
(char/= skip-char #\Newline))
finally (return (next-char-non-extended lexer)))
;; ...otherwise (whitespace) skip until we
;; see the next non-whitespace character
(loop for skip-char = next-char
then (next-char-non-extended lexer)
while (and skip-char
(whitespacep skip-char))
finally (return skip-char))))))
;; if the position has moved we have to repeat our tests
;; because of cases like /^a (?#xxx) (?#yyy) {3}c/x which
;; would be equivalent to /^a{3}c/ in Perl
(unless (> (lexer-pos lexer) last-loop-pos)
(return next-char)))))
(declaim (inline fail))
(defun fail (lexer)
(declare #.*standard-optimize-settings*)
"Moves (LEXER-POS LEXER) back to the last position stored in
\(LEXER-LAST-POS LEXER) and pops the LAST-POS stack."
(unless (lexer-last-pos lexer)
(signal-ppcre-syntax-error "LAST-POS stack of LEXER ~A is empty" lexer))
(setf (lexer-pos lexer) (pop (lexer-last-pos lexer)))
nil)
(defun get-number (lexer &key (radix 10) max-length no-whitespace-p)
(declare #.*standard-optimize-settings*)
"Read and consume the number the lexer is currently looking at and
return it. Returns NIL if no number could be identified.
RADIX is used as in PARSE-INTEGER. If MAX-LENGTH is not NIL we'll read
at most the next MAX-LENGTH characters. If NO-WHITESPACE-P is not NIL
we don't tolerate whitespace in front of the number."
(when (or (end-of-string-p lexer)
(and no-whitespace-p
(whitespacep (schar (lexer-str lexer) (lexer-pos lexer)))))
(return-from get-number nil))
(multiple-value-bind (integer new-pos)
(parse-integer (lexer-str lexer)
:start (lexer-pos lexer)
:end (if max-length
(let ((end-pos (+ (lexer-pos lexer)
(the fixnum max-length)))
(lexer-len (lexer-len lexer)))
(if (< end-pos lexer-len)
end-pos
lexer-len))
(lexer-len lexer))
:radix radix
:junk-allowed t)
(cond ((and integer (>= (the fixnum integer) 0))
(setf (lexer-pos lexer) new-pos)
integer)
(t nil))))
(declaim (inline try-number))
(defun try-number (lexer &key (radix 10) max-length no-whitespace-p)
(declare #.*standard-optimize-settings*)
"Like GET-NUMBER but won't consume anything if no number is seen."
;; remember current position
(push (lexer-pos lexer) (lexer-last-pos lexer))
(let ((number (get-number lexer
:radix radix
:max-length max-length
:no-whitespace-p no-whitespace-p)))
(or number (fail lexer))))
(declaim (inline make-char-from-code))
(defun make-char-from-code (number error-pos)
(declare #.*standard-optimize-settings*)
"Create character from char-code NUMBER. NUMBER can be NIL
which is interpreted as 0. ERROR-POS is the position where
the corresponding number started within the regex string."
;; only look at rightmost eight bits in compliance with Perl
(let ((code (logand #o377 (the fixnum (or number 0)))))
(or (and (< code char-code-limit)
(code-char code))
(signal-ppcre-syntax-error*
error-pos
"No character for hex-code ~X"
number))))
(defun unescape-char (lexer)
(declare #.*standard-optimize-settings*)
"Convert the characters(s) following a backslash into a token
which is returned. This function is to be called when the backslash
has already been consumed. Special character classes like \\W are
handled elsewhere."
(when (end-of-string-p lexer)
(signal-ppcre-syntax-error "String ends with backslash"))
(let ((chr (next-char-non-extended lexer)))
(case chr
((#\E)
;; if \Q quoting is on this is ignored, otherwise it's just an
;; #\E
(if *allow-quoting*
:void
#\E))
((#\c)
;; \cx means control-x in Perl
(let ((next-char (next-char-non-extended lexer)))
(unless next-char
(signal-ppcre-syntax-error*
(lexer-pos lexer)
"Character missing after '\\c' at position ~A"))
(code-char (logxor #x40 (char-code (char-upcase next-char))))))
((#\x)
;; \x should be followed by a hexadecimal char code,
;; two digits or less
(let* ((error-pos (lexer-pos lexer))
(number (get-number lexer :radix 16 :max-length 2 :no-whitespace-p t)))
;; note that it is OK if \x is followed by zero digits
(make-char-from-code number error-pos)))
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
;; \x should be followed by an octal char code,
;; three digits or less
(let* ((error-pos (decf (lexer-pos lexer)))
(number (get-number lexer :radix 8 :max-length 3)))
(make-char-from-code number error-pos)))
;; the following five character names are 'semi-standard'
;; according to the CLHS but I'm not aware of any implementation
;; that doesn't implement them
((#\t)
#\Tab)
((#\n)
#\Newline)
((#\r)
#\Return)
((#\f)
#\Page)
((#\b)
#\Backspace)
((#\a)
(code-char 7)) ; ASCII bell
((#\e)
(code-char 27)) ; ASCII escape
(otherwise
;; all other characters aren't affected by a backslash
chr))))
(defun collect-char-class (lexer)
(declare #.*standard-optimize-settings*)
"Reads and consumes characters from regex string until a right
bracket is seen. Assembles them into a list \(which is returned) of
characters, character ranges, like \(:RANGE #\\A #\\E) for a-e, and
tokens representing special character classes."
(let ((start-pos (lexer-pos lexer)) ; remember start for error message
hyphen-seen
last-char
list)
(flet ((handle-char (c)
"Do the right thing with character C depending on whether
we're inside a range or not."
(cond ((and hyphen-seen last-char)
(setf (car list) (list :range last-char c)
last-char nil))
(t
(push c list)
(setq last-char c)))
(setq hyphen-seen nil)))
(loop for first = t then nil
for c = (next-char-non-extended lexer)
;; leave loop if at end of string
while c
do (cond
((char= c #\\)
;; we've seen a backslash
(let ((next-char (next-char-non-extended lexer)))
(case next-char
((#\d #\D #\w #\W #\s #\S)
;; a special character class
(push (map-char-to-special-char-class next-char) list)
;; if the last character was a hyphen
;; just collect it literally
(when hyphen-seen
(push #\- list))
;; if the next character is a hyphen do the same
(when (looking-at-p lexer #\-)
(push #\- list)
(incf (lexer-pos lexer)))
(setq hyphen-seen nil))
((#\E)
;; if \Q quoting is on we ignore \E,
;; otherwise it's just a plain #\E
(unless *allow-quoting*
(handle-char #\E)))
(otherwise
;; otherwise unescape the following character(s)
(decf (lexer-pos lexer))
(handle-char (unescape-char lexer))))))
(first
;; the first character must not be a right bracket
;; and isn't treated specially if it's a hyphen
(handle-char c))
((char= c #\])
;; end of character class
;; make sure we collect a pending hyphen
(when hyphen-seen
(setq hyphen-seen nil)
(handle-char #\-))
;; reverse the list to preserve the order intended
;; by the author of the regex string
(return-from collect-char-class (nreverse list)))
((and (char= c #\-)
last-char
(not hyphen-seen))
;; if the last character was 'just a character'
;; we expect to be in the middle of a range
(setq hyphen-seen t))
((char= c #\-)
;; otherwise this is just an ordinary hyphen
(handle-char #\-))
(t
;; default case - just collect the character
(handle-char c))))
;; we can only exit the loop normally if we've reached the end
;; of the regex string without seeing a right bracket
(signal-ppcre-syntax-error*
start-pos
"Missing right bracket to close character class"))))
(defun maybe-parse-flags (lexer)
(declare #.*standard-optimize-settings*)
"Reads a sequence of modifiers \(including #\\- to reverse their
meaning) and returns a corresponding list of \"flag\" tokens. The
\"x\" modifier is treated specially in that it dynamically modifies
the behaviour of the lexer itself via the special variable
*EXTENDED-MODE-P*."
(prog1
(loop with set = t
for chr = (next-char-non-extended lexer)
unless chr
do (signal-ppcre-syntax-error "Unexpected end of string")
while (find chr "-imsx" :test #'char=)
;; the first #\- will invert the meaning of all modifiers
;; following it
if (char= chr #\-)
do (setq set nil)
else if (char= chr #\x)
do (setq *extended-mode-p* set)
else collect (if set
(case chr
((#\i)
:case-insensitive-p)
((#\m)
:multi-line-mode-p)
((#\s)
:single-line-mode-p))
(case chr
((#\i)
:case-sensitive-p)
((#\m)
:not-multi-line-mode-p)
((#\s)
:not-single-line-mode-p))))
(decf (lexer-pos lexer))))
(defun get-quantifier (lexer)
(declare #.*standard-optimize-settings*)
"Returns a list of two values (min max) if what the lexer is looking
at can be interpreted as a quantifier. Otherwise returns NIL and
resets the lexer to its old position."
;; remember starting position for FAIL and UNGET-TOKEN functions
(push (lexer-pos lexer) (lexer-last-pos lexer))
(let ((next-char (next-char lexer)))
(case next-char
((#\*)
;; * (Kleene star): match 0 or more times
'(0 nil))
((#\+)
;; +: match 1 or more times
'(1 nil))
((#\?)
;; ?: match 0 or 1 times
'(0 1))
((#\{)
;; one of
;; {n}: match exactly n times
;; {n,}: match at least n times
;; {n,m}: match at least n but not more than m times
;; note that anything not matching one of these patterns will
;; be interpreted literally - even whitespace isn't allowed
(let ((num1 (get-number lexer :no-whitespace-p t)))
(if num1
(let ((next-char (next-char-non-extended lexer)))
(case next-char
((#\,)
(let* ((num2 (get-number lexer :no-whitespace-p t))
(next-char (next-char-non-extended lexer)))
(case next-char
((#\})
;; this is the case {n,} (NUM2 is NIL) or {n,m}
(list num1 num2))
(otherwise
(fail lexer)))))
((#\})
;; this is the case {n}
(list num1 num1))
(otherwise
(fail lexer))))
;; no number following left curly brace, so we treat it
;; like a normal character
(fail lexer))))
;; cannot be a quantifier
(otherwise
(fail lexer)))))
(defun parse-register-name-aux (lexer)
"Reads and returns the name in a named register group. It is
assumed that the starting #\< character has already been read. The
closing #\> will also be consumed."
;; we have to look for an ending > character now
(let ((end-name (position #\>
(lexer-str lexer)
:start (lexer-pos lexer)
:test #'char=)))
(unless end-name
;; there has to be > somewhere, syntax error otherwise
(signal-ppcre-syntax-error*
(1- (lexer-pos lexer))
"Opening #\< in named group has no closing #\>"))
(let ((name (subseq (lexer-str lexer)
(lexer-pos lexer)
end-name)))
(unless (every #'(lambda (char)
(or (alphanumericp char)
(char= #\- char)))
name)
;; register name can contain only alphanumeric characters or #\-
(signal-ppcre-syntax-error*
(lexer-pos lexer)
"Invalid character in named register group"))
;; advance lexer beyond "<name>" part
(setf (lexer-pos lexer) (1+ end-name))
name)))
(defun get-token (lexer)
(declare #.*standard-optimize-settings*)
"Returns and consumes the next token from the regex string \(or NIL)."
;; remember starting position for UNGET-TOKEN function
(push (lexer-pos lexer)
(lexer-last-pos lexer))
(let ((next-char (next-char lexer)))
(cond (next-char
(case next-char
;; the easy cases first - the following six characters
;; always have a special meaning and get translated
;; into tokens immediately
((#\))
:close-paren)
((#\|)
:vertical-bar)
((#\?)
:question-mark)
((#\.)
:everything)
((#\^)
:start-anchor)
((#\$)
:end-anchor)
((#\+ #\*)
;; quantifiers will always be consumend by
;; GET-QUANTIFIER, they must not appear here
(signal-ppcre-syntax-error*
(1- (lexer-pos lexer))
"Quantifier '~A' not allowed"
next-char))
((#\{)
;; left brace isn't a special character in it's own
;; right but we must check if what follows might
;; look like a quantifier
(let ((this-pos (lexer-pos lexer))
(this-last-pos (lexer-last-pos lexer)))
(unget-token lexer)
(when (get-quantifier lexer)
(signal-ppcre-syntax-error*
(car this-last-pos)
"Quantifier '~A' not allowed"
(subseq (lexer-str lexer)
(car this-last-pos)
(lexer-pos lexer))))
(setf (lexer-pos lexer) this-pos
(lexer-last-pos lexer) this-last-pos)
next-char))
((#\[)
;; left bracket always starts a character class
(cons (cond ((looking-at-p lexer #\^)
(incf (lexer-pos lexer))
:inverted-char-class)
(t
:char-class))
(collect-char-class lexer)))
((#\\)
;; backslash might mean different things so we have
;; to peek one char ahead:
(let ((next-char (next-char-non-extended lexer)))
(case next-char
((#\A)
:modeless-start-anchor)
((#\Z)
:modeless-end-anchor)
((#\z)
:modeless-end-anchor-no-newline)
((#\b)
:word-boundary)
((#\B)
:non-word-boundary)
((#\k)
(cond ((and *allow-named-registers*
(looking-at-p lexer #\<))
;; back-referencing a named register
(incf (lexer-pos lexer))
(list :back-reference
(nreverse (parse-register-name-aux lexer))))
(t
;; false alarm, just unescape \k
#\k)))
((#\d #\D #\w #\W #\s #\S)
;; these will be treated like character classes
(map-char-to-special-char-class next-char))
((#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
;; uh, a digit...
(let* ((old-pos (decf (lexer-pos lexer)))
;; ...so let's get the whole number first
(backref-number (get-number lexer)))
(declare (type fixnum backref-number))
(cond ((and (> backref-number (lexer-reg lexer))
(<= 10 backref-number))
;; \10 and higher are treated as octal
;; character codes if we haven't
;; opened that much register groups
;; yet
(setf (lexer-pos lexer) old-pos)
;; re-read the number from the old
;; position and convert it to its
;; corresponding character
(make-char-from-code (get-number lexer :radix 8 :max-length 3)
old-pos))
(t
;; otherwise this must refer to a
;; backreference
(list :back-reference backref-number)))))
((#\0)
;; this always means an octal character code
;; (at most three digits)
(let ((old-pos (decf (lexer-pos lexer))))
(make-char-from-code (get-number lexer :radix 8 :max-length 3)
old-pos)))
(otherwise
;; in all other cases just unescape the
;; character
(decf (lexer-pos lexer))
(unescape-char lexer)))))
((#\()
;; an open parenthesis might mean different things
;; depending on what follows...
(cond ((looking-at-p lexer #\?)
;; this is the case '(?' (and probably more behind)
(incf (lexer-pos lexer))
;; we have to check for modifiers first
;; because a colon might follow
(let* ((flags (maybe-parse-flags lexer))
(next-char (next-char-non-extended lexer)))
;; modifiers are only allowed if a colon
;; or a closing parenthesis are following
(when (and flags
(not (find next-char ":)" :test #'char=)))
(signal-ppcre-syntax-error*
(car (lexer-last-pos lexer))
"Sequence '~A' not recognized"
(subseq (lexer-str lexer)
(car (lexer-last-pos lexer))
(lexer-pos lexer))))
(case next-char
((nil)
;; syntax error
(signal-ppcre-syntax-error
"End of string following '(?'"))
((#\))
;; an empty group except for the flags
;; (if there are any)
(or (and flags
(cons :flags flags))
:void))
((#\()
;; branch
:open-paren-paren)
((#\>)
;; standalone
:open-paren-greater)
((#\=)
;; positive look-ahead
:open-paren-equal)
((#\!)
;; negative look-ahead
:open-paren-exclamation)
((#\:)
;; non-capturing group - return flags as
;; second value
(values :open-paren-colon flags))
((#\<)
;; might be a look-behind assertion or a named group, so
;; check next character
(let ((next-char (next-char-non-extended lexer)))
(if (alpha-char-p next-char)
(progn
;; we have encountered a named group
;; are we supporting register naming?
(unless *allow-named-registers*
(signal-ppcre-syntax-error*
(1- (lexer-pos lexer))
"Character '~A' may not follow '(?<'"
next-char))
;; put the letter back
(decf (lexer-pos lexer))
;; named group
:open-paren-less-letter)
(case next-char
((#\=)
;; positive look-behind
:open-paren-less-equal)
((#\!)
;; negative look-behind
:open-paren-less-exclamation)
((#\))
;; Perl allows "(?<)" and treats
;; it like a null string
:void)
((nil)
;; syntax error
(signal-ppcre-syntax-error
"End of string following '(?<'"))
(t
;; also syntax error
(signal-ppcre-syntax-error*
(1- (lexer-pos lexer))
"Character '~A' may not follow '(?<'"
next-char ))))))
(otherwise
(signal-ppcre-syntax-error*
(1- (lexer-pos lexer))
"Character '~A' may not follow '(?'"
next-char)))))
(t
;; if next-char was not #\? (this is within
;; the first COND), we've just seen an opening
;; parenthesis and leave it like that
:open-paren)))
(otherwise
;; all other characters are their own tokens
next-char)))
;; we didn't get a character (this if the "else" branch from
;; the first IF), so we don't return a token but NIL
(t
(pop (lexer-last-pos lexer))
nil))))
(declaim (inline unget-token))
(defun unget-token (lexer)
(declare #.*standard-optimize-settings*)
"Moves the lexer back to the last position stored in the LAST-POS stack."
(if (lexer-last-pos lexer)
(setf (lexer-pos lexer)
(pop (lexer-last-pos lexer)))
(error "No token to unget \(this should not happen)")))
(declaim (inline start-of-subexpr-p))
(defun start-of-subexpr-p (lexer)
(declare #.*standard-optimize-settings*)
"Tests whether the next token can start a valid sub-expression, i.e.
a stand-alone regex."
(let* ((pos (lexer-pos lexer))
(next-char (next-char lexer)))
(not (or (null next-char)
(prog1
(member (the character next-char)
'(#\) #\|)
:test #'char=)
(setf (lexer-pos lexer) pos))))))
| 32,108 | Common Lisp | .lisp | 710 | 29.885915 | 99 | 0.489226 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | cb69452046c5976ff3056d1291f2da13c600836ce3cf16cecdb09b77b9745cc4 | 2,437 | [
-1
] |
2,438 | util.lisp | hoytech_antiweb/bundled/cl-ppcre/util.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/util.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; Utility functions and constants dealing with the hash-tables
;;; we use to encode character classes
;;; Hash-tables are treated like sets, i.e. a character C is a member of the
;;; hash-table H iff (GETHASH C H) is true.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
#+:lispworks
(eval-when (:compile-toplevel :load-toplevel :execute)
(import 'lw:with-unique-names))
#-:lispworks
(defmacro with-unique-names ((&rest bindings) &body body)
"Syntax: WITH-UNIQUE-NAMES ( { var | (var x) }* ) declaration* form*
Executes a series of forms with each VAR bound to a fresh,
uninterned symbol. The uninterned symbol is as if returned by a call
to GENSYM with the string denoted by X - or, if X is not supplied, the
string denoted by VAR - as argument.
The variable bindings created are lexical unless special declarations
are specified. The scopes of the name bindings and declarations do not
include the Xs.
The forms are evaluated in order, and the values of all but the last
are discarded \(that is, the body is an implicit PROGN)."
;; reference implementation posted to comp.lang.lisp as
;; <[email protected]> by Vebjorn Ljosa - see also
;; <http://www.cliki.net/Common%20Lisp%20Utilities>
`(let ,(mapcar #'(lambda (binding)
(check-type binding (or cons symbol))
(if (consp binding)
(destructuring-bind (var x) binding
(check-type var symbol)
`(,var (gensym ,(etypecase x
(symbol (symbol-name x))
(character (string x))
(string x)))))
`(,binding (gensym ,(symbol-name binding)))))
bindings)
,@body))
#+:lispworks
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (macro-function 'with-rebinding)
(macro-function 'lw:rebinding)))
#-:lispworks
(defmacro with-rebinding (bindings &body body)
"WITH-REBINDING ( { var | (var prefix) }* ) form*
Evaluates a series of forms in the lexical environment that is
formed by adding the binding of each VAR to a fresh, uninterned
symbol, and the binding of that fresh, uninterned symbol to VAR's
original value, i.e., its value in the current lexical environment.
The uninterned symbol is created as if by a call to GENSYM with the
string denoted by PREFIX - or, if PREFIX is not supplied, the string
denoted by VAR - as argument.
The forms are evaluated in order, and the values of all but the last
are discarded \(that is, the body is an implicit PROGN)."
;; reference implementation posted to comp.lang.lisp as
;; <[email protected]> by Vebjorn Ljosa - see also
;; <http://www.cliki.net/Common%20Lisp%20Utilities>
(loop for binding in bindings
for var = (if (consp binding) (car binding) binding)
for name = (gensym)
collect `(,name ,var) into renames
collect ``(,,var ,,name) into temps
finally (return `(let ,renames
(with-unique-names ,bindings
`(let (,,@temps)
,,@body))))))
(eval-when (:compile-toplevel :execute :load-toplevel)
(defvar *regex-char-code-limit* char-code-limit
"The upper exclusive bound on the char-codes of characters
which can occur in character classes. Change this value BEFORE
creating scanners if you don't need the \(full) Unicode support
of implementations like AllegroCL, CLISP, LispWorks, or SBCL.")
(declaim (type fixnum *regex-char-code-limit*))
(defun make-char-hash (test)
(declare #.*special-optimize-settings*)
"Returns a hash-table of all characters satisfying test."
(loop with hash = (make-hash-table)
for c of-type fixnum from 0 below char-code-limit
for chr = (code-char c)
if (and chr (funcall test chr))
do (setf (gethash chr hash) t)
finally (return hash)))
(declaim (inline word-char-p))
(defun word-char-p (chr)
(declare #.*standard-optimize-settings*)
"Tests whether a character is a \"word\" character.
In the ASCII charset this is equivalent to a-z, A-Z, 0-9, or _,
i.e. the same as Perl's [\\w]."
(or (alphanumericp chr)
(char= chr #\_)))
(unless (boundp '+whitespace-char-string+)
(defconstant +whitespace-char-string+
(coerce
'(#\Space #\Tab #\Linefeed #\Return #\Page)
'string)
"A string of all characters which are considered to be whitespace.
Same as Perl's [\\s]."))
(defun whitespacep (chr)
(declare #.*special-optimize-settings*)
"Tests whether a character is whitespace,
i.e. whether it would match [\\s] in Perl."
(find chr +whitespace-char-string+ :test #'char=)))
;; the following DEFCONSTANT statements are wrapped with
;; (UNLESS (BOUNDP ...) ...) to make SBCL happy
(unless (boundp '+digit-hash+)
(defconstant +digit-hash+
(make-char-hash (lambda (chr) (char<= #\0 chr #\9)))
"Hash-table containing the digits from 0 to 9."))
(unless (boundp '+word-char-hash+)
(defconstant +word-char-hash+
(make-char-hash #'word-char-p)
"Hash-table containing all \"word\" characters."))
(unless (boundp '+whitespace-char-hash+)
(defconstant +whitespace-char-hash+
(make-char-hash #'whitespacep)
"Hash-table containing all whitespace characters."))
(defun merge-hash (hash1 hash2)
(declare #.*standard-optimize-settings*)
"Returns the \"sum\" of two hashes. This is a destructive operation
on HASH1."
(cond ((> (hash-table-count hash2)
*regex-char-code-limit*)
;; don't walk through, e.g., the whole +WORD-CHAR-HASH+ if
;; the user has set *REGEX-CHAR-CODE-LIMIT* to a lower value
(loop for c of-type fixnum from 0 below *regex-char-code-limit*
for chr = (code-char c)
if (and chr (gethash chr hash2))
do (setf (gethash chr hash1) t)))
(t
(loop for chr being the hash-keys of hash2
do (setf (gethash chr hash1) t))))
hash1)
(defun merge-inverted-hash (hash1 hash2)
(declare #.*standard-optimize-settings*)
"Returns the \"sum\" of HASH1 and the \"inverse\" of HASH2. This is
a destructive operation on HASH1."
(loop for c of-type fixnum from 0 below *regex-char-code-limit*
for chr = (code-char c)
if (and chr (not (gethash chr hash2)))
do (setf (gethash chr hash1) t))
hash1)
(defun create-ranges-from-hash (hash &key downcasep)
(declare #.*standard-optimize-settings*)
"Tries to identify up to three intervals (with respect to CHAR<)
which together comprise HASH. Returns NIL if this is not possible.
If DOWNCASEP is true it will treat the hash-table as if it represents
both the lower-case and the upper-case variants of its members and
will only return the respective lower-case intervals."
;; discard empty hash-tables
(unless (and hash (plusp (hash-table-count hash)))
(return-from create-ranges-from-hash nil))
(loop with min1 and min2 and min3
and max1 and max2 and max3
;; loop through all characters in HASH, sorted by CHAR<
for chr in (sort (the list
(loop for chr being the hash-keys of hash
collect (if downcasep
(char-downcase chr)
chr)))
#'char<)
for code = (char-code chr)
;; MIN1, MAX1, etc. are _exclusive_
;; bounds of the intervals identified so far
do (cond
((not min1)
;; this will only happen once, for the first character
(setq min1 (1- code)
max1 (1+ code)))
((<= (the fixnum min1) code (the fixnum max1))
;; we're here as long as CHR fits into the first interval
(setq min1 (min (the fixnum min1) (1- code))
max1 (max (the fixnum max1) (1+ code))))
((not min2)
;; we need to open a second interval
;; this'll also happen only once
(setq min2 (1- code)
max2 (1+ code)))
((<= (the fixnum min2) code (the fixnum max2))
;; CHR fits into the second interval
(setq min2 (min (the fixnum min2) (1- code))
max2 (max (the fixnum max2) (1+ code))))
((not min3)
;; we need to open the third interval
;; happens only once
(setq min3 (1- code)
max3 (1+ code)))
((<= (the fixnum min3) code (the fixnum max3))
;; CHR fits into the third interval
(setq min3 (min (the fixnum min3) (1- code))
max3 (max (the fixnum max3) (1+ code))))
(t
;; we're out of luck, CHR doesn't fit
;; into one of the three intervals
(return nil)))
;; on success return all bounds
;; make them inclusive bounds before returning
finally (return (values (code-char (1+ min1))
(code-char (1- max1))
(and min2 (code-char (1+ min2)))
(and max2 (code-char (1- max2)))
(and min3 (code-char (1+ min3)))
(and max3 (code-char (1- max3)))))))
(defmacro maybe-coerce-to-simple-string (string)
(with-unique-names (=string=)
`(let ((,=string= ,string))
(cond ((simple-string-p ,=string=)
,=string=)
(t
(coerce ,=string= 'simple-string))))))
(declaim (inline nsubseq))
(defun nsubseq (sequence start &optional (end (length sequence)))
"Return a subsequence by pointing to location in original sequence."
(make-array (- end start)
:element-type (array-element-type sequence)
:displaced-to sequence
:displaced-index-offset start))
(defun normalize-var-list (var-list)
"Utility function for REGISTER-GROUPS-BIND and
DO-REGISTER-GROUPS. Creates the long form \(a list of \(FUNCTION VAR)
entries) out of the short form of VAR-LIST."
(loop for element in var-list
if (consp element)
nconc (loop for var in (rest element)
collect (list (first element) var))
else
collect (list '(function identity) element)))
(defun string-list-to-simple-string (string-list)
(declare #.*standard-optimize-settings*)
"Concatenates a list of strings to one simple-string."
;; this function provided by JP Massar; note that we can't use APPLY
;; with CONCATENATE here because of CALL-ARGUMENTS-LIMIT
(let ((total-size 0))
(declare (type fixnum total-size))
(dolist (string string-list)
#-genera (declare (type string string))
(incf total-size (length string)))
(let ((result-string (make-sequence 'simple-string total-size))
(curr-pos 0))
(declare (type fixnum curr-pos))
(dolist (string string-list)
#-genera (declare (type string string))
(replace result-string string :start1 curr-pos)
(incf curr-pos (length string)))
result-string)))
| 12,855 | Common Lisp | .lisp | 264 | 40.284091 | 98 | 0.631772 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | b84f3566cc8bdf8b113305e29a030f5b6b38c601f3145371942f57c3727a247e | 2,438 | [
-1
] |
2,439 | errors.lisp | hoytech_antiweb/bundled/cl-ppcre/errors.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/errors.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(defvar *syntax-error-string* nil
"The string which caused the syntax error.")
(define-condition ppcre-error (simple-error)
()
(:documentation "All errors signaled by CL-PPCRE are of
this type."))
(define-condition ppcre-syntax-error (ppcre-error)
((string :initarg :string
:reader ppcre-syntax-error-string)
(pos :initarg :pos
:reader ppcre-syntax-error-pos))
(:default-initargs
:pos nil
:string *syntax-error-string*)
(:report (lambda (condition stream)
(format stream "~?~@[ at position ~A~]~@[ in string ~S~]"
(simple-condition-format-control condition)
(simple-condition-format-arguments condition)
(ppcre-syntax-error-pos condition)
(ppcre-syntax-error-string condition))))
(:documentation "Signaled if CL-PPCRE's parser encounters an error
when trying to parse a regex string or to convert a parse tree into
its internal representation."))
(setf (documentation 'ppcre-syntax-error-string 'function)
"Returns the string the parser was parsing when the error was
encountered \(or NIL if the error happened while trying to convert a
parse tree).")
(setf (documentation 'ppcre-syntax-error-pos 'function)
"Returns the position within the string where the error occured
\(or NIL if the error happened while trying to convert a parse tree")
(define-condition ppcre-invocation-error (ppcre-error)
()
(:documentation "Signaled when CL-PPCRE functions are
invoked with wrong arguments."))
(defmacro signal-ppcre-syntax-error* (pos format-control &rest format-arguments)
`(error 'ppcre-syntax-error
:pos ,pos
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
(defmacro signal-ppcre-syntax-error (format-control &rest format-arguments)
`(signal-ppcre-syntax-error* nil ,format-control ,@format-arguments))
(defmacro signal-ppcre-invocation-error (format-control &rest format-arguments)
`(error 'ppcre-invocation-error
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
| 3,698 | Common Lisp | .lisp | 69 | 49.231884 | 100 | 0.728002 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 2f449244682955b0aa429c21ebd70dc236e6249b0f56f9460b043eafc9cac83c | 2,439 | [
-1
] |
2,440 | regex-class.lisp | hoytech_antiweb/bundled/cl-ppcre/regex-class.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/regex-class.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; This file defines the REGEX class and some utility methods for
;;; this class. REGEX objects are used to represent the (transformed)
;;; parse trees internally
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
;; Genera need the eval-when, here, or the types created by the class
;; definitions aren't seen by the typep calls later in the file.
(eval-when (:compile-toplevel :load-toplevel :execute)
(locally
(declare #.*standard-optimize-settings*)
(defclass regex ()
()
(:documentation "The REGEX base class. All other classes inherit
from this one."))
(defclass seq (regex)
((elements :initarg :elements
:accessor elements
:type cons
:documentation "A list of REGEX objects."))
(:documentation "SEQ objects represents sequences of
regexes. (Like \"ab\" is the sequence of \"a\" and \"b\".)"))
(defclass alternation (regex)
((choices :initarg :choices
:accessor choices
:type cons
:documentation "A list of REGEX objects"))
(:documentation "ALTERNATION objects represent alternations of
regexes. (Like \"a|b\" ist the alternation of \"a\" or \"b\".)"))
(defclass lookahead (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive."))
(:documentation "LOOKAHEAD objects represent look-ahead assertions."))
(defclass lookbehind (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX object we're checking.")
(positivep :initarg :positivep
:reader positivep
:documentation "Whether this assertion is positive.")
(len :initarg :len
:accessor len
:type fixnum
:documentation "The (fixed) length of the enclosed regex."))
(:documentation "LOOKBEHIND objects represent look-behind assertions."))
(defclass repetition (regex)
((regex :initarg :regex
:accessor regex
:documentation "The REGEX that's repeated.")
(greedyp :initarg :greedyp
:reader greedyp
:documentation "Whether the repetition is greedy.")
(minimum :initarg :minimum
:accessor minimum
:type fixnum
:documentation "The minimal number of repetitions.")
(maximum :initarg :maximum
:accessor maximum
:documentation "The maximal number of repetitions.
Can be NIL for unbounded.")
(min-len :initarg :min-len
:reader min-len
:documentation "The minimal length of the enclosed regex.")
(len :initarg :len
:reader len
:documentation "The length of the enclosed regex. NIL
if unknown.")
(min-rest :initform 0
:accessor min-rest
:type fixnum
:documentation "The minimal number of characters which must
appear after this repetition.")
(contains-register-p :initarg :contains-register-p
:reader contains-register-p
:documentation "If the regex contains a register."))
(:documentation "REPETITION objects represent repetitions of regexes."))
(defclass register (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex.")
(num :initarg :num
:reader num
:type fixnum
:documentation "The number of this register, starting from 0.
This is the index into *REGS-START* and *REGS-END*.")
(name :initarg :name
:reader name
:documentation "Name of this register or NIL."))
(:documentation "REGISTER objects represent register groups."))
(defclass standalone (regex)
((regex :initarg :regex
:accessor regex
:documentation "The inner regex."))
(:documentation "A standalone regular expression."))
(defclass back-reference (regex)
((num :initarg :num
:accessor num
:type fixnum
:documentation "The number of the register this
reference refers to.")
(name :initarg :name
:accessor name
:documentation "The name of the register this
reference refers to or NIL.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "Whether we check
case-insensitively."))
(:documentation "BACK-REFERENCE objects represent backreferences."))
(defclass char-class (regex)
((hash :initarg :hash
:reader hash
:type (or hash-table null)
:documentation "A hash table the keys of which are the
characters; the values are always T.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "If the char class
case-insensitive.")
(invertedp :initarg :invertedp
:reader invertedp
:documentation "Whether we mean the inverse of
the char class.")
(word-char-class-p :initarg :word-char-class-p
:reader word-char-class-p
:documentation "Whether this CHAR CLASS
represents the special class WORD-CHAR-CLASS."))
(:documentation "CHAR-CLASS objects represent character classes."))
(defclass str (regex)
((str :initarg :str
:accessor str
:type string
:documentation "The actual string.")
(len :initform 0
:accessor len
:type fixnum
:documentation "The length of the string.")
(case-insensitive-p :initarg :case-insensitive-p
:reader case-insensitive-p
:documentation "If we match case-insensitively.")
(offset :initform nil
:accessor offset
:documentation "Offset from the left of the whole
parse tree. The first regex has offset 0. NIL if unknown, i.e. behind
a variable-length regex.")
(skip :initform nil
:initarg :skip
:accessor skip
:documentation "If we can avoid testing for this
string because the SCAN function has done this already.")
(start-of-end-string-p :initform nil
:accessor start-of-end-string-p
:documentation "If this is the unique
STR which starts END-STRING (a slot of MATCHER)."))
(:documentation "STR objects represent string."))
(defclass anchor (regex)
((startp :initarg :startp
:reader startp
:documentation "Whether this is a \"start anchor\".")
(multi-line-p :initarg :multi-line-p
:reader multi-line-p
:documentation "Whether we're in multi-line mode,
i.e. whether each #\\Newline is surrounded by anchors.")
(no-newline-p :initarg :no-newline-p
:reader no-newline-p
:documentation "Whether we ignore #\\Newline at the end."))
(:documentation "ANCHOR objects represent anchors like \"^\" or \"$\"."))
(defclass everything (regex)
((single-line-p :initarg :single-line-p
:reader single-line-p
:documentation "Whether we're in single-line mode,
i.e. whether we also match #\\Newline."))
(:documentation "EVERYTHING objects represent regexes matching
\"everything\", i.e. dots."))
(defclass word-boundary (regex)
((negatedp :initarg :negatedp
:reader negatedp
:documentation "Whether we mean the opposite,
i.e. no word-boundary."))
(:documentation "WORD-BOUNDARY objects represent word-boundary assertions."))
(defclass branch (regex)
((test :initarg :test
:accessor test
:documentation "The test of this branch, one of
LOOKAHEAD, LOOKBEHIND, or a number.")
(then-regex :initarg :then-regex
:accessor then-regex
:documentation "The regex that's to be matched if the
test succeeds.")
(else-regex :initarg :else-regex
:initform (make-instance 'void)
:accessor else-regex
:documentation "The regex that's to be matched if the
test fails."))
(:documentation "BRANCH objects represent Perl's conditional regular
expressions."))
(defclass filter (regex)
((fn :initarg :fn
:accessor fn
:type (or function symbol)
:documentation "The user-defined function.")
(len :initarg :len
:reader len
:documentation "The fixed length of this filter or NIL."))
(:documentation "FILTER objects represent arbitrary functions
defined by the user."))
(defclass void (regex)
()
(:documentation "VOID objects represent empty regular expressions."))))
(defmethod initialize-instance :after ((char-class char-class) &rest init-args)
(declare #.*standard-optimize-settings*)
"Make large hash tables smaller, if possible."
(let ((hash (getf init-args :hash)))
(when (and hash
(> *regex-char-code-limit* 256)
(> (hash-table-count hash)
(/ *regex-char-code-limit* 2)))
(setf (slot-value char-class 'hash)
(merge-inverted-hash (make-hash-table)
hash)
(slot-value char-class 'invertedp)
(not (slot-value char-class 'invertedp))))))
(defmethod initialize-instance :after ((str str) &rest init-args)
(declare #.*standard-optimize-settings*)
(declare (ignore init-args))
"Automatically computes the length of a STR after initialization."
(let ((str-slot (slot-value str 'str)))
(unless (typep str-slot 'simple-string)
(setf (slot-value str 'str) (coerce str-slot 'simple-string))))
(setf (len str) (length (str str))))
;;; The following four methods allow a VOID object to behave like a
;;; zero-length STR object (only readers needed)
(defmethod len ((void void))
(declare #.*standard-optimize-settings*)
0)
(defmethod str ((void void))
(declare #.*standard-optimize-settings*)
"")
(defmethod skip ((void void))
(declare #.*standard-optimize-settings*)
nil)
(defmethod start-of-end-string-p ((void void))
(declare #.*standard-optimize-settings*)
nil)
(defgeneric case-mode (regex old-case-mode)
(declare #.*standard-optimize-settings*)
(:documentation "Utility function used by the optimizer (see GATHER-STRINGS).
Returns a keyword denoting the case-(in)sensitivity of a STR or its
second argument if the STR has length 0. Returns NIL for REGEX objects
which are not of type STR."))
(defmethod case-mode ((str str) old-case-mode)
(declare #.*standard-optimize-settings*)
(cond ((zerop (len str))
old-case-mode)
((case-insensitive-p str)
:case-insensitive)
(t
:case-sensitive)))
(defmethod case-mode ((regex regex) old-case-mode)
(declare #.*standard-optimize-settings*)
(declare (ignore old-case-mode))
nil)
(defgeneric copy-regex (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Implements a deep copy of a REGEX object."))
(defmethod copy-regex ((anchor anchor))
(declare #.*standard-optimize-settings*)
(make-instance 'anchor
:startp (startp anchor)
:multi-line-p (multi-line-p anchor)
:no-newline-p (no-newline-p anchor)))
(defmethod copy-regex ((everything everything))
(declare #.*standard-optimize-settings*)
(make-instance 'everything
:single-line-p (single-line-p everything)))
(defmethod copy-regex ((word-boundary word-boundary))
(declare #.*standard-optimize-settings*)
(make-instance 'word-boundary
:negatedp (negatedp word-boundary)))
(defmethod copy-regex ((void void))
(declare #.*standard-optimize-settings*)
(make-instance 'void))
(defmethod copy-regex ((lookahead lookahead))
(declare #.*standard-optimize-settings*)
(make-instance 'lookahead
:regex (copy-regex (regex lookahead))
:positivep (positivep lookahead)))
(defmethod copy-regex ((seq seq))
(declare #.*standard-optimize-settings*)
(make-instance 'seq
:elements (mapcar #'copy-regex (elements seq))))
(defmethod copy-regex ((alternation alternation))
(declare #.*standard-optimize-settings*)
(make-instance 'alternation
:choices (mapcar #'copy-regex (choices alternation))))
(defmethod copy-regex ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test)
branch
(make-instance 'branch
:test (if (typep test 'regex)
(copy-regex test)
test)
:then-regex (copy-regex (then-regex branch))
:else-regex (copy-regex (else-regex branch)))))
(defmethod copy-regex ((lookbehind lookbehind))
(declare #.*standard-optimize-settings*)
(make-instance 'lookbehind
:regex (copy-regex (regex lookbehind))
:positivep (positivep lookbehind)
:len (len lookbehind)))
(defmethod copy-regex ((repetition repetition))
(declare #.*standard-optimize-settings*)
(make-instance 'repetition
:regex (copy-regex (regex repetition))
:greedyp (greedyp repetition)
:minimum (minimum repetition)
:maximum (maximum repetition)
:min-len (min-len repetition)
:len (len repetition)
:contains-register-p (contains-register-p repetition)))
(defmethod copy-regex ((register register))
(declare #.*standard-optimize-settings*)
(make-instance 'register
:regex (copy-regex (regex register))
:num (num register)
:name (name register)))
(defmethod copy-regex ((standalone standalone))
(declare #.*standard-optimize-settings*)
(make-instance 'standalone
:regex (copy-regex (regex standalone))))
(defmethod copy-regex ((back-reference back-reference))
(declare #.*standard-optimize-settings*)
(make-instance 'back-reference
:num (num back-reference)
:case-insensitive-p (case-insensitive-p back-reference)))
(defmethod copy-regex ((char-class char-class))
(declare #.*standard-optimize-settings*)
(make-instance 'char-class
:hash (hash char-class)
:case-insensitive-p (case-insensitive-p char-class)
:invertedp (invertedp char-class)
:word-char-class-p (word-char-class-p char-class)))
(defmethod copy-regex ((str str))
(declare #.*standard-optimize-settings*)
(make-instance 'str
:str (str str)
:case-insensitive-p (case-insensitive-p str)))
(defmethod copy-regex ((filter filter))
(declare #.*standard-optimize-settings*)
(make-instance 'filter
:fn (fn filter)
:len (len filter)))
;;; Note that COPY-REGEX and REMOVE-REGISTERS could have easily been
;;; wrapped into one function. Maybe in the next release...
;;; Further note that this function is used by CONVERT to factor out
;;; complicated repetitions, i.e. cases like
;;; (a)* -> (?:a*(a))?
;;; This won't work for, say,
;;; ((a)|(b))* -> (?:(?:a|b)*((a)|(b)))?
;;; and therefore we stop REGISTER removal once we see an ALTERNATION.
(defgeneric remove-registers (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Returns a deep copy of a REGEX (see COPY-REGEX) and
optionally removes embedded REGISTER objects if possible and if the
special variable REMOVE-REGISTERS-P is true."))
(defmethod remove-registers ((register register))
(declare #.*standard-optimize-settings*)
(declare (special remove-registers-p reg-seen))
(cond (remove-registers-p
(remove-registers (regex register)))
(t
;; mark REG-SEEN as true so enclosing REPETITION objects
;; (see method below) know if they contain a register or not
(setq reg-seen t)
(copy-regex register))))
(defmethod remove-registers ((repetition repetition))
(declare #.*standard-optimize-settings*)
(let* (reg-seen
(inner-regex (remove-registers (regex repetition))))
;; REMOVE-REGISTERS will set REG-SEEN (see method above) if
;; (REGEX REPETITION) contains a REGISTER
(declare (special reg-seen))
(make-instance 'repetition
:regex inner-regex
:greedyp (greedyp repetition)
:minimum (minimum repetition)
:maximum (maximum repetition)
:min-len (min-len repetition)
:len (len repetition)
:contains-register-p reg-seen)))
(defmethod remove-registers ((standalone standalone))
(declare #.*standard-optimize-settings*)
(make-instance 'standalone
:regex (remove-registers (regex standalone))))
(defmethod remove-registers ((lookahead lookahead))
(declare #.*standard-optimize-settings*)
(make-instance 'lookahead
:regex (remove-registers (regex lookahead))
:positivep (positivep lookahead)))
(defmethod remove-registers ((lookbehind lookbehind))
(declare #.*standard-optimize-settings*)
(make-instance 'lookbehind
:regex (remove-registers (regex lookbehind))
:positivep (positivep lookbehind)
:len (len lookbehind)))
(defmethod remove-registers ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test)
branch
(make-instance 'branch
:test (if (typep test 'regex)
(remove-registers test)
test)
:then-regex (remove-registers (then-regex branch))
:else-regex (remove-registers (else-regex branch)))))
(defmethod remove-registers ((alternation alternation))
(declare #.*standard-optimize-settings*)
(declare (special remove-registers-p))
;; an ALTERNATION, so we can't remove REGISTER objects further down
(setq remove-registers-p nil)
(copy-regex alternation))
(defmethod remove-registers ((regex regex))
(declare #.*standard-optimize-settings*)
(copy-regex regex))
(defmethod remove-registers ((seq seq))
(declare #.*standard-optimize-settings*)
(make-instance 'seq
:elements (mapcar #'remove-registers (elements seq))))
(defgeneric everythingp (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Returns an EVERYTHING object if REGEX is equivalent
to this object, otherwise NIL. So, \"(.){1}\" would return true
(i.e. the object corresponding to \".\", for example."))
(defmethod everythingp ((seq seq))
(declare #.*standard-optimize-settings*)
;; we might have degenerate cases like (:SEQUENCE :VOID ...)
;; due to the parsing process
(let ((cleaned-elements (remove-if #'(lambda (element)
(typep element 'void))
(elements seq))))
(and (= 1 (length cleaned-elements))
(everythingp (first cleaned-elements)))))
(defmethod everythingp ((alternation alternation))
(declare #.*standard-optimize-settings*)
(with-slots (choices)
alternation
(and (= 1 (length choices))
;; this is unlikely to happen for human-generated regexes,
;; but machine-generated ones might look like this
(everythingp (first choices)))))
(defmethod everythingp ((repetition repetition))
(declare #.*standard-optimize-settings*)
(with-slots (maximum minimum regex)
repetition
(and maximum
(= 1 minimum maximum)
;; treat "<regex>{1,1}" like "<regex>"
(everythingp regex))))
(defmethod everythingp ((register register))
(declare #.*standard-optimize-settings*)
(everythingp (regex register)))
(defmethod everythingp ((standalone standalone))
(declare #.*standard-optimize-settings*)
(everythingp (regex standalone)))
(defmethod everythingp ((everything everything))
(declare #.*standard-optimize-settings*)
everything)
(defmethod everythingp ((regex regex))
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, BACK-REFERENCE, BRANCH, CHAR-CLASS,
;; LOOKAHEAD, LOOKBEHIND, STR, VOID, FILTER, and WORD-BOUNDARY
nil)
(defgeneric regex-length (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Return the length of REGEX if it is fixed, NIL otherwise."))
(defmethod regex-length ((seq seq))
(declare #.*standard-optimize-settings*)
;; simply add all inner lengths unless one of them is NIL
(loop for sub-regex in (elements seq)
for len = (regex-length sub-regex)
if (not len) do (return nil)
sum len))
(defmethod regex-length ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; only return a true value if all inner lengths are non-NIL and
;; mutually equal
(loop for sub-regex in (choices alternation)
for old-len = nil then len
for len = (regex-length sub-regex)
if (or (not len)
(and old-len (/= len old-len))) do (return nil)
finally (return len)))
(defmethod regex-length ((branch branch))
(declare #.*standard-optimize-settings*)
;; only return a true value if both alternations have a length and
;; if they're equal
(let ((then-length (regex-length (then-regex branch))))
(and then-length
(eql then-length (regex-length (else-regex branch)))
then-length)))
(defmethod regex-length ((repetition repetition))
(declare #.*standard-optimize-settings*)
;; we can only compute the length of a REPETITION object if the
;; number of repetitions is fixed; note that we don't call
;; REGEX-LENGTH for the inner regex, we assume that the LEN slot is
;; always set correctly
(with-slots (len minimum maximum)
repetition
(if (and len
(eql minimum maximum))
(* minimum len)
nil)))
(defmethod regex-length ((register register))
(declare #.*standard-optimize-settings*)
(regex-length (regex register)))
(defmethod regex-length ((standalone standalone))
(declare #.*standard-optimize-settings*)
(regex-length (regex standalone)))
(defmethod regex-length ((back-reference back-reference))
(declare #.*standard-optimize-settings*)
;; with enough effort we could possibly do better here, but
;; currently we just give up and return NIL
nil)
(defmethod regex-length ((char-class char-class))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-length ((everything everything))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-length ((str str))
(declare #.*standard-optimize-settings*)
(len str))
(defmethod regex-length ((filter filter))
(declare #.*standard-optimize-settings*)
(len filter))
(defmethod regex-length ((regex regex))
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and
;; WORD-BOUNDARY (which all have zero-length)
0)
(defgeneric regex-min-length (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the minimal length of REGEX."))
(defmethod regex-min-length ((seq seq))
(declare #.*standard-optimize-settings*)
;; simply add all inner minimal lengths
(loop for sub-regex in (elements seq)
for len = (regex-min-length sub-regex)
sum len))
(defmethod regex-min-length ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; minimal length of an alternation is the minimal length of the
;; "shortest" element
(loop for sub-regex in (choices alternation)
for len = (regex-min-length sub-regex)
minimize len))
(defmethod regex-min-length ((branch branch))
(declare #.*standard-optimize-settings*)
;; minimal length of both alternations
(min (regex-min-length (then-regex branch))
(regex-min-length (else-regex branch))))
(defmethod regex-min-length ((repetition repetition))
(declare #.*standard-optimize-settings*)
;; obviously the product of the inner minimal length and the minimal
;; number of repetitions
(* (minimum repetition) (min-len repetition)))
(defmethod regex-min-length ((register register))
(declare #.*standard-optimize-settings*)
(regex-min-length (regex register)))
(defmethod regex-min-length ((standalone standalone))
(declare #.*standard-optimize-settings*)
(regex-min-length (regex standalone)))
(defmethod regex-min-length ((char-class char-class))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-min-length ((everything everything))
(declare #.*standard-optimize-settings*)
1)
(defmethod regex-min-length ((str str))
(declare #.*standard-optimize-settings*)
(len str))
(defmethod regex-min-length ((filter filter))
(declare #.*standard-optimize-settings*)
(or (len filter)
0))
(defmethod regex-min-length ((regex regex))
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, BACK-REFERENCE, LOOKAHEAD,
;; LOOKBEHIND, VOID, and WORD-BOUNDARY
0)
(defgeneric compute-offsets (regex start-pos)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the offset the following regex would have
relative to START-POS or NIL if we can't compute it. Sets the OFFSET
slot of REGEX to START-POS if REGEX is a STR. May also affect OFFSET
slots of STR objects further down the tree."))
;; note that we're actually only interested in the offset of
;; "top-level" STR objects (see ADVANCE-FN in the SCAN function) so we
;; can stop at variable-length alternations and don't need to descend
;; into repetitions
(defmethod compute-offsets ((seq seq) start-pos)
(declare #.*standard-optimize-settings*)
(loop for element in (elements seq)
;; advance offset argument for next call while looping through
;; the elements
for pos = start-pos then curr-offset
for curr-offset = (compute-offsets element pos)
while curr-offset
finally (return curr-offset)))
(defmethod compute-offsets ((alternation alternation) start-pos)
(declare #.*standard-optimize-settings*)
(loop for choice in (choices alternation)
for old-offset = nil then curr-offset
for curr-offset = (compute-offsets choice start-pos)
;; we stop immediately if two alternations don't result in the
;; same offset
if (or (not curr-offset)
(and old-offset (/= curr-offset old-offset)))
do (return nil)
finally (return curr-offset)))
(defmethod compute-offsets ((branch branch) start-pos)
(declare #.*standard-optimize-settings*)
;; only return offset if both alternations have equal value
(let ((then-offset (compute-offsets (then-regex branch) start-pos)))
(and then-offset
(eql then-offset (compute-offsets (else-regex branch) start-pos))
then-offset)))
(defmethod compute-offsets ((repetition repetition) start-pos)
(declare #.*standard-optimize-settings*)
;; no need to descend into the inner regex
(with-slots (len minimum maximum)
repetition
(if (and len
(eq minimum maximum))
;; fixed number of repetitions, so we know how to proceed
(+ start-pos (* minimum len))
;; otherwise return NIL
nil)))
(defmethod compute-offsets ((register register) start-pos)
(declare #.*standard-optimize-settings*)
(compute-offsets (regex register) start-pos))
(defmethod compute-offsets ((standalone standalone) start-pos)
(declare #.*standard-optimize-settings*)
(compute-offsets (regex standalone) start-pos))
(defmethod compute-offsets ((char-class char-class) start-pos)
(declare #.*standard-optimize-settings*)
(1+ start-pos))
(defmethod compute-offsets ((everything everything) start-pos)
(declare #.*standard-optimize-settings*)
(1+ start-pos))
(defmethod compute-offsets ((str str) start-pos)
(declare #.*standard-optimize-settings*)
(setf (offset str) start-pos)
(+ start-pos (len str)))
(defmethod compute-offsets ((back-reference back-reference) start-pos)
(declare #.*standard-optimize-settings*)
;; with enough effort we could possibly do better here, but
;; currently we just give up and return NIL
(declare (ignore start-pos))
nil)
(defmethod compute-offsets ((filter filter) start-pos)
(declare #.*standard-optimize-settings*)
(let ((len (len filter)))
(if len
(+ start-pos len)
nil)))
(defmethod compute-offsets ((regex regex) start-pos)
(declare #.*standard-optimize-settings*)
;; the general case for ANCHOR, LOOKAHEAD, LOOKBEHIND, VOID, and
;; WORD-BOUNDARY (which all have zero-length)
start-pos)
| 31,237 | Common Lisp | .lisp | 697 | 36.74175 | 105 | 0.650717 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | a75bd2002dac9f71122ccad7e8f5753d59754090f36283ac4bffabb2b2457848 | 2,440 | [
-1
] |
2,441 | specials.lisp | hoytech_antiweb/bundled/cl-ppcre/specials.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/specials.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; globally declared special variables
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
;;; special variables used to effect declarations
(defvar *standard-optimize-settings*
'(optimize
speed
(safety 0)
(space 0)
(debug 1)
(compilation-speed 0)
#+:lispworks (hcl:fixnum-safety 0))
"The standard optimize settings used by most declaration expressions.")
(defvar *special-optimize-settings*
'(optimize speed space)
"Special optimize settings used only by a few declaration expressions.")
;;; special variables used by the lexer/parser combo
(defvar *extended-mode-p* nil
"Whether the parser will start in extended mode.")
(declaim (type boolean *extended-mode-p*))
;;; special variables used by the SCAN function and the matchers
(defvar *string* ""
"The string which is currently scanned by SCAN.
Will always be coerced to a SIMPLE-STRING.")
(declaim (type simple-string *string*))
(defvar *start-pos* 0
"Where to start scanning within *STRING*.")
(declaim (type fixnum *start-pos*))
(defvar *real-start-pos* nil
"The real start of *STRING*. This is for repeated scans and is only used internally.")
(declaim (type (or null fixnum) *real-start-pos*))
(defvar *end-pos* 0
"Where to stop scanning within *STRING*.")
(declaim (type fixnum *end-pos*))
(defvar *reg-starts* (make-array 0)
"An array which holds the start positions
of the current register candidates.")
(declaim (type simple-vector *reg-starts*))
(defvar *regs-maybe-start* (make-array 0)
"An array which holds the next start positions
of the current register candidates.")
(declaim (type simple-vector *regs-maybe-start*))
(defvar *reg-ends* (make-array 0)
"An array which holds the end positions
of the current register candidates.")
(declaim (type simple-vector *reg-ends*))
(defvar *end-string-pos* nil
"Start of the next possible end-string candidate.")
(defvar *rep-num* 0
"Counts the number of \"complicated\" repetitions while the matchers
are built.")
(declaim (type fixnum *rep-num*))
(defvar *zero-length-num* 0
"Counts the number of repetitions the inner regexes of which may
have zero-length while the matchers are built.")
(declaim (type fixnum *zero-length-num*))
(defvar *repeat-counters* (make-array 0
:initial-element 0
:element-type 'fixnum)
"An array to keep track of how often
repetitive patterns have been tested already.")
(declaim (type (array fixnum (*)) *repeat-counters*))
(defvar *last-pos-stores* (make-array 0)
"An array to keep track of the last positions
where we saw repetitive patterns.
Only used for patterns which might have zero length.")
(declaim (type simple-vector *last-pos-stores*))
(defvar *use-bmh-matchers* t
"Whether the scanners created by CREATE-SCANNER should use the \(fast
but large) Boyer-Moore-Horspool matchers.")
(defvar *allow-quoting* nil
"Whether the parser should support Perl's \\Q and \\E.")
(defvar *allow-named-registers* nil
"Whether the parser should support AllegroCL's named registers
\(?<name>\"<regex>\") and back-reference \\k<name> syntax.")
(pushnew :cl-ppcre *features*)
;; stuff for Nikodemus Siivola's HYPERDOC
;; see <http://common-lisp.net/project/hyperdoc/>
;; and <http://www.cliki.net/hyperdoc>
;; also used by LW-ADD-ONS
(defvar *hyperdoc-base-uri* "http://weitz.de/cl-ppcre/")
(let ((exported-symbols-alist
(loop for symbol being the external-symbols of :cl-ppcre
collect (cons symbol
(concatenate 'string
"#"
(string-downcase symbol))))))
(defun hyperdoc-lookup (symbol type)
(declare (ignore type))
(cdr (assoc symbol
exported-symbols-alist
:test #'eq))))
| 5,359 | Common Lisp | .lisp | 114 | 42.859649 | 102 | 0.716266 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 467c9b6e63b751c7671068efa3149637be7ffdf21dd3caf0e8145a8faa624145 | 2,441 | [
-1
] |
2,442 | scanner.lisp | hoytech_antiweb/bundled/cl-ppcre/scanner.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/scanner.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; Here the scanner for the actual regex as well as utility scanners
;;; for the constant start and end strings are created.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(defmacro bmh-matcher-aux (&key case-insensitive-p)
"Auxiliary macro used by CREATE-BMH-MATCHER."
(let ((char-compare (if case-insensitive-p 'char-equal 'char=)))
`(lambda (start-pos)
(declare (type fixnum start-pos))
(if (or (minusp start-pos)
(> (the fixnum (+ start-pos m)) *end-pos*))
nil
(loop named bmh-matcher
for k of-type fixnum = (+ start-pos m -1)
then (+ k (max 1 (aref skip (char-code (schar *string* k)))))
while (< k *end-pos*)
do (loop for j of-type fixnum downfrom (1- m)
for i of-type fixnum downfrom k
while (and (>= j 0)
(,char-compare (schar *string* i)
(schar pattern j)))
finally (if (minusp j)
(return-from bmh-matcher (1+ i)))))))))
(defun create-bmh-matcher (pattern case-insensitive-p)
(declare #.*standard-optimize-settings*)
"Returns a Boyer-Moore-Horspool matcher which searches the (special)
simple-string *STRING* for the first occurence of the substring
PATTERN. The search starts at the position START-POS within *STRING*
and stops before *END-POS* is reached. Depending on the second
argument the search is case-insensitive or not. If the special
variable *USE-BMH-MATCHERS* is NIL, use the standard SEARCH function
instead. (BMH matchers are faster but need much more space.)"
;; see <http://www-igm.univ-mlv.fr/~lecroq/string/node18.html> for
;; details
(unless *use-bmh-matchers*
(let ((test (if case-insensitive-p #'char-equal #'char=)))
(return-from create-bmh-matcher
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (not (minusp start-pos))
(search pattern
*string*
:start2 start-pos
:end2 *end-pos*
:test test))))))
(let* ((m (length pattern))
(skip (make-array *regex-char-code-limit*
:element-type 'fixnum
:initial-element m)))
(declare (type fixnum m))
(loop for k of-type fixnum below m
if case-insensitive-p
do (setf (aref skip (char-code (char-upcase (schar pattern k)))) (- m k 1)
(aref skip (char-code (char-downcase (schar pattern k)))) (- m k 1))
else
do (setf (aref skip (char-code (schar pattern k))) (- m k 1)))
(if case-insensitive-p
(bmh-matcher-aux :case-insensitive-p t)
(bmh-matcher-aux))))
(defmacro char-searcher-aux (&key case-insensitive-p)
"Auxiliary macro used by CREATE-CHAR-SEARCHER."
(let ((char-compare (if case-insensitive-p 'char-equal 'char=)))
`(lambda (start-pos)
(declare (type fixnum start-pos))
(and (not (minusp start-pos))
(loop for i of-type fixnum from start-pos below *end-pos*
thereis (and (,char-compare (schar *string* i) chr) i))))))
(defun create-char-searcher (chr case-insensitive-p)
(declare #.*standard-optimize-settings*)
"Returns a function which searches the (special) simple-string
*STRING* for the first occurence of the character CHR. The search
starts at the position START-POS within *STRING* and stops before
*END-POS* is reached. Depending on the second argument the search is
case-insensitive or not."
(if case-insensitive-p
(char-searcher-aux :case-insensitive-p t)
(char-searcher-aux)))
(declaim (inline newline-skipper))
(defun newline-skipper (start-pos)
(declare #.*standard-optimize-settings*)
(declare (type fixnum start-pos))
"Find the next occurence of a character in *STRING* which is behind
a #\Newline."
;; we can start with (1- START-POS) without testing for (PLUSP
;; START-POS) because we know we'll never call NEWLINE-SKIPPER on
;; the first iteration
(loop for i of-type fixnum from (1- start-pos) below *end-pos*
thereis (and (char= (schar *string* i)
#\Newline)
(1+ i))))
(defmacro insert-advance-fn (advance-fn)
"Creates the actual closure returned by CREATE-SCANNER-AUX by
replacing '(ADVANCE-FN-DEFINITION) with a suitable definition for
ADVANCE-FN. This is a utility macro used by CREATE-SCANNER-AUX."
(subst
advance-fn '(advance-fn-definition)
'(lambda (string start end)
(block scan
;; initialize a couple of special variables used by the
;; matchers (see file specials.lisp)
(let* ((*string* string)
(*start-pos* start)
(*end-pos* end)
;; we will search forward for END-STRING if this value
;; isn't at least as big as POS (see ADVANCE-FN), so it
;; is safe to start to the left of *START-POS*; note
;; that this value will _never_ be decremented - this
;; is crucial to the scanning process
(*end-string-pos* (1- *start-pos*))
;; the next five will shadow the variables defined by
;; DEFPARAMETER; at this point, we don't know if we'll
;; actually use them, though
(*repeat-counters* *repeat-counters*)
(*last-pos-stores* *last-pos-stores*)
(*reg-starts* *reg-starts*)
(*regs-maybe-start* *regs-maybe-start*)
(*reg-ends* *reg-ends*)
;; we might be able to optimize the scanning process by
;; (virtually) shifting *START-POS* to the right
(scan-start-pos *start-pos*)
(starts-with-str (if start-string-test
(str starts-with)
nil))
;; we don't need to try further than MAX-END-POS
(max-end-pos (- *end-pos* min-len)))
(declare (type fixnum scan-start-pos)
(type function match-fn))
;; definition of ADVANCE-FN will be inserted here by macrology
(labels ((advance-fn-definition))
(declare (inline advance-fn))
(when (plusp rep-num)
;; we have at least one REPETITION which needs to count
;; the number of repetitions
(setq *repeat-counters* (make-array rep-num
:initial-element 0
:element-type 'fixnum)))
(when (plusp zero-length-num)
;; we have at least one REPETITION which needs to watch
;; out for zero-length repetitions
(setq *last-pos-stores* (make-array zero-length-num
:initial-element nil)))
(when (plusp reg-num)
;; we have registers in our regular expression
(setq *reg-starts* (make-array reg-num :initial-element nil)
*regs-maybe-start* (make-array reg-num :initial-element nil)
*reg-ends* (make-array reg-num :initial-element nil)))
(when end-anchored-p
;; the regular expression has a constant end string which
;; is anchored at the very end of the target string
;; (perhaps modulo a #\Newline)
(let ((end-test-pos (- *end-pos* (the fixnum end-string-len))))
(declare (type fixnum end-test-pos)
(type function end-string-test))
(unless (setq *end-string-pos* (funcall end-string-test
end-test-pos))
(when (and (= 1 (the fixnum end-anchored-p))
(> *end-pos* scan-start-pos)
(char= #\Newline (schar *string* (1- *end-pos*))))
;; if we didn't find an end string candidate from
;; END-TEST-POS and if a #\Newline at the end is
;; allowed we try it again from one position to the
;; left
(setq *end-string-pos* (funcall end-string-test
(1- end-test-pos))))))
(unless (and *end-string-pos*
(<= *start-pos* *end-string-pos*))
;; no end string candidate found, so give up
(return-from scan nil))
(when end-string-offset
;; if the offset of the constant end string from the
;; left of the regular expression is known we can start
;; scanning further to the right; this is similar to
;; what we might do in ADVANCE-FN
(setq scan-start-pos (max scan-start-pos
(- (the fixnum *end-string-pos*)
(the fixnum end-string-offset))))))
(cond
(start-anchored-p
;; we're anchored at the start of the target string,
;; so no need to try again after first failure
(when (or (/= *start-pos* scan-start-pos)
(< max-end-pos *start-pos*))
;; if END-STRING-OFFSET has proven that we don't
;; need to bother to scan from *START-POS* or if the
;; minimal length of the regular expression is
;; longer than the target string we give up
(return-from scan nil))
(when starts-with-str
(locally
(declare (type fixnum starts-with-len))
(cond ((and (case-insensitive-p starts-with)
(not (*string*-equal starts-with-str
*start-pos*
(+ *start-pos*
starts-with-len)
0 starts-with-len)))
;; the regular expression has a
;; case-insensitive constant start string
;; and we didn't find it
(return-from scan nil))
((and (not (case-insensitive-p starts-with))
(not (*string*= starts-with-str
*start-pos*
(+ *start-pos* starts-with-len)
0 starts-with-len)))
;; the regular expression has a
;; case-sensitive constant start string
;; and we didn't find it
(return-from scan nil))
(t nil))))
(when (and end-string-test
(not end-anchored-p))
;; the regular expression has a constant end string
;; which isn't anchored so we didn't check for it
;; already
(block end-string-loop
;; we temporarily use *END-STRING-POS* as our
;; starting position to look for end string
;; candidates
(setq *end-string-pos* *start-pos*)
(loop
(unless (setq *end-string-pos*
(funcall (the function end-string-test)
*end-string-pos*))
;; no end string candidate found, so give up
(return-from scan nil))
(unless end-string-offset
;; end string doesn't have an offset so we
;; can start scanning now
(return-from end-string-loop))
(let ((maybe-start-pos (- (the fixnum *end-string-pos*)
(the fixnum end-string-offset))))
(cond ((= maybe-start-pos *start-pos*)
;; offset of end string into regular
;; expression matches start anchor -
;; fine...
(return-from end-string-loop))
((and (< maybe-start-pos *start-pos*)
(< (+ *end-string-pos* end-string-len) *end-pos*))
;; no match but maybe we find another
;; one to the right - try again
(incf *end-string-pos*))
(t
;; otherwise give up
(return-from scan nil)))))))
;; if we got here we scan exactly once
(let ((next-pos (funcall match-fn *start-pos*)))
(when next-pos
(values (if next-pos *start-pos* nil)
next-pos
*reg-starts*
*reg-ends*))))
(t
(loop for pos = (if starts-with-everything
;; don't jump to the next
;; #\Newline on the first
;; iteration
scan-start-pos
(advance-fn scan-start-pos))
then (advance-fn pos)
;; give up if the regular expression can't fit
;; into the rest of the target string
while (and pos
(<= (the fixnum pos) max-end-pos))
do (let ((next-pos (funcall match-fn pos)))
(when next-pos
(return-from scan (values pos
next-pos
*reg-starts*
*reg-ends*)))
;; not yet found, increment POS
#-cormanlisp (incf (the fixnum pos))
#+cormanlisp (incf pos)))))))))
:test #'equalp))
(defun create-scanner-aux (match-fn
min-len
start-anchored-p
starts-with
start-string-test
end-anchored-p
end-string-test
end-string-len
end-string-offset
rep-num
zero-length-num
reg-num)
(declare #.*standard-optimize-settings*)
(declare (type fixnum min-len zero-length-num rep-num reg-num))
"Auxiliary function to create and return a scanner \(which is
actually a closure). Used by CREATE-SCANNER."
(let ((starts-with-len (if (typep starts-with 'str)
(len starts-with)))
(starts-with-everything (typep starts-with 'everything)))
(cond
;; this COND statement dispatches on the different versions we
;; have for ADVANCE-FN and creates different closures for each;
;; note that you see only the bodies of ADVANCE-FN below - the
;; actual scanner is defined in INSERT-ADVANCE-FN above; (we
;; could have done this with closures instead of macrology but
;; would have consed a lot more)
((and start-string-test end-string-test end-string-offset)
;; we know that the regular expression has constant start and
;; end strings and we know the end string's offset (from the
;; left)
(insert-advance-fn
(advance-fn (pos)
(declare (type fixnum end-string-offset starts-with-len)
(type function start-string-test end-string-test))
(loop
(unless (setq pos (funcall start-string-test pos))
;; give up completely if we can't find a start string
;; candidate
(return-from scan nil))
(locally
;; from here we know that POS is a FIXNUM
(declare (type fixnum pos))
(when (= pos (- (the fixnum *end-string-pos*) end-string-offset))
;; if we already found an end string candidate the
;; position of which matches the start string
;; candidate we're done
(return-from advance-fn pos))
(let ((try-pos (+ pos starts-with-len)))
;; otherwise try (again) to find an end string
;; candidate which starts behind the start string
;; candidate
(loop
(unless (setq *end-string-pos*
(funcall end-string-test try-pos))
;; no end string candidate found, so give up
(return-from scan nil))
;; NEW-POS is where we should start scanning
;; according to the end string candidate
(let ((new-pos (- (the fixnum *end-string-pos*)
end-string-offset)))
(declare (type fixnum new-pos *end-string-pos*))
(cond ((= new-pos pos)
;; if POS and NEW-POS are equal then the
;; two candidates agree so we're fine
(return-from advance-fn pos))
((> new-pos pos)
;; if NEW-POS is further to the right we
;; advance POS and try again, i.e. we go
;; back to the start of the outer LOOP
(setq pos new-pos)
;; this means "return from inner LOOP"
(return))
(t
;; otherwise NEW-POS is smaller than POS,
;; so we have to redo the inner LOOP to
;; find another end string candidate
;; further to the right
(setq try-pos (1+ *end-string-pos*))))))))))))
((and starts-with-everything end-string-test end-string-offset)
;; we know that the regular expression starts with ".*" (which
;; is not in single-line-mode, see CREATE-SCANNER-AUX) and ends
;; with a constant end string and we know the end string's
;; offset (from the left)
(insert-advance-fn
(advance-fn (pos)
(declare (type fixnum end-string-offset)
(type function end-string-test))
(loop
(unless (setq pos (newline-skipper pos))
;; if we can't find a #\Newline we give up immediately
(return-from scan nil))
(locally
;; from here we know that POS is a FIXNUM
(declare (type fixnum pos))
(when (= pos (- (the fixnum *end-string-pos*) end-string-offset))
;; if we already found an end string candidate the
;; position of which matches the place behind the
;; #\Newline we're done
(return-from advance-fn pos))
(let ((try-pos pos))
;; otherwise try (again) to find an end string
;; candidate which starts behind the #\Newline
(loop
(unless (setq *end-string-pos*
(funcall end-string-test try-pos))
;; no end string candidate found, so we give up
(return-from scan nil))
;; NEW-POS is where we should start scanning
;; according to the end string candidate
(let ((new-pos (- (the fixnum *end-string-pos*)
end-string-offset)))
(declare (type fixnum new-pos *end-string-pos*))
(cond ((= new-pos pos)
;; if POS and NEW-POS are equal then the
;; the end string candidate agrees with
;; the #\Newline so we're fine
(return-from advance-fn pos))
((> new-pos pos)
;; if NEW-POS is further to the right we
;; advance POS and try again, i.e. we go
;; back to the start of the outer LOOP
(setq pos new-pos)
;; this means "return from inner LOOP"
(return))
(t
;; otherwise NEW-POS is smaller than POS,
;; so we have to redo the inner LOOP to
;; find another end string candidate
;; further to the right
(setq try-pos (1+ *end-string-pos*))))))))))))
((and start-string-test end-string-test)
;; we know that the regular expression has constant start and
;; end strings; similar to the first case but we only need to
;; check for the end string, it doesn't provide enough
;; information to advance POS
(insert-advance-fn
(advance-fn (pos)
(declare (type function start-string-test end-string-test))
(unless (setq pos (funcall start-string-test pos))
(return-from scan nil))
(if (<= (the fixnum pos)
(the fixnum *end-string-pos*))
(return-from advance-fn pos))
(unless (setq *end-string-pos* (funcall end-string-test pos))
(return-from scan nil))
pos)))
((and starts-with-everything end-string-test)
;; we know that the regular expression starts with ".*" (which
;; is not in single-line-mode, see CREATE-SCANNER-AUX) and ends
;; with a constant end string; similar to the second case but we
;; only need to check for the end string, it doesn't provide
;; enough information to advance POS
(insert-advance-fn
(advance-fn (pos)
(declare (type function end-string-test))
(unless (setq pos (newline-skipper pos))
(return-from scan nil))
(if (<= (the fixnum pos)
(the fixnum *end-string-pos*))
(return-from advance-fn pos))
(unless (setq *end-string-pos* (funcall end-string-test pos))
(return-from scan nil))
pos)))
(start-string-test
;; just check for constant start string candidate
(insert-advance-fn
(advance-fn (pos)
(declare (type function start-string-test))
(unless (setq pos (funcall start-string-test pos))
(return-from scan nil))
pos)))
(starts-with-everything
;; just advance POS with NEWLINE-SKIPPER
(insert-advance-fn
(advance-fn (pos)
(unless (setq pos (newline-skipper pos))
(return-from scan nil))
pos)))
(end-string-test
;; just check for the next end string candidate if POS has
;; advanced beyond the last one
(insert-advance-fn
(advance-fn (pos)
(declare (type function end-string-test))
(if (<= (the fixnum pos)
(the fixnum *end-string-pos*))
(return-from advance-fn pos))
(unless (setq *end-string-pos* (funcall end-string-test pos))
(return-from scan nil))
pos)))
(t
;; not enough optimization information about the regular
;; expression to optimize so we just return POS
(insert-advance-fn
(advance-fn (pos)
pos))))))
| 26,199 | Common Lisp | .lisp | 492 | 35.628049 | 101 | 0.506773 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 5811f4aa04cf4ebef9bc1632c7f0b0ddc9efa1ccf7ce298092b090fde3bc5ffa | 2,442 | [
-1
] |
2,443 | repetition-closures.lisp | hoytech_antiweb/bundled/cl-ppcre/repetition-closures.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/repetition-closures.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; This is actually a part of closures.lisp which we put into a
;;; separate file because it is rather complex. We only deal with
;;; REPETITIONs here. Note that this part of the code contains some
;;; rather crazy micro-optimizations which were introduced to be as
;;; competitive with Perl as possible in tight loops.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(defmacro incf-after (place &optional (delta 1) &environment env)
"Utility macro inspired by C's \"place++\", i.e. first return the
value of PLACE and afterwards increment it by DELTA."
(with-unique-names (%temp)
(multiple-value-bind (vars vals store-vars writer-form reader-form)
(get-setf-expansion place env)
`(let* (,@(mapcar #'list vars vals)
(,%temp ,reader-form)
(,(car store-vars) (+ ,%temp ,delta)))
,writer-form
,%temp))))
;; code for greedy repetitions with minimum zero
(defmacro greedy-constant-length-closure (check-curr-pos)
"This is the template for simple greedy repetitions (where simple
means that the minimum number of repetitions is zero, that the inner
regex to be checked is of fixed length LEN, and that it doesn't
contain registers, i.e. there's no need for backtracking).
CHECK-CURR-POS is a form which checks whether the inner regex of the
repetition matches at CURR-POS."
`(if maximum
(lambda (start-pos)
(declare (type fixnum start-pos maximum))
;; because we know LEN we know in advance where to stop at the
;; latest; we also take into consideration MIN-REST, i.e. the
;; minimal length of the part behind the repetition
(let ((target-end-pos (min (1+ (- *end-pos* len min-rest))
;; don't go further than MAXIMUM
;; repetitions, of course
(+ start-pos
(the fixnum (* len maximum)))))
(curr-pos start-pos))
(declare (type fixnum target-end-pos curr-pos))
(block greedy-constant-length-matcher
;; we use an ugly TAGBODY construct because this might be a
;; tight loop and this version is a bit faster than our LOOP
;; version (at least in CMUCL)
(tagbody
forward-loop
;; first go forward as far as possible, i.e. while
;; the inner regex matches
(when (>= curr-pos target-end-pos)
(go backward-loop))
(when ,check-curr-pos
(incf curr-pos len)
(go forward-loop))
backward-loop
;; now go back LEN steps each until we're able to match
;; the rest of the regex
(when (< curr-pos start-pos)
(return-from greedy-constant-length-matcher nil))
(let ((result (funcall next-fn curr-pos)))
(when result
(return-from greedy-constant-length-matcher result)))
(decf curr-pos len)
(go backward-loop)))))
;; basically the same code; it's just a bit easier because we're
;; not bounded by MAXIMUM
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((target-end-pos (1+ (- *end-pos* len min-rest)))
(curr-pos start-pos))
(declare (type fixnum target-end-pos curr-pos))
(block greedy-constant-length-matcher
(tagbody
forward-loop
(when (>= curr-pos target-end-pos)
(go backward-loop))
(when ,check-curr-pos
(incf curr-pos len)
(go forward-loop))
backward-loop
(when (< curr-pos start-pos)
(return-from greedy-constant-length-matcher nil))
(let ((result (funcall next-fn curr-pos)))
(when result
(return-from greedy-constant-length-matcher result)))
(decf curr-pos len)
(go backward-loop)))))))
(defun create-greedy-everything-matcher (maximum min-rest next-fn)
(declare #.*standard-optimize-settings*)
(declare (type fixnum min-rest)
(type function next-fn))
"Creates a closure which just matches as far ahead as possible,
i.e. a closure for a dot in single-line mode."
(if maximum
(lambda (start-pos)
(declare (type fixnum start-pos maximum))
;; because we know LEN we know in advance where to stop at the
;; latest; we also take into consideration MIN-REST, i.e. the
;; minimal length of the part behind the repetition
(let ((target-end-pos (min (+ start-pos maximum)
(- *end-pos* min-rest))))
(declare (type fixnum target-end-pos))
;; start from the highest possible position and go backward
;; until we're able to match the rest of the regex
(loop for curr-pos of-type fixnum from target-end-pos downto start-pos
thereis (funcall next-fn curr-pos))))
;; basically the same code; it's just a bit easier because we're
;; not bounded by MAXIMUM
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((target-end-pos (- *end-pos* min-rest)))
(declare (type fixnum target-end-pos))
(loop for curr-pos of-type fixnum from target-end-pos downto start-pos
thereis (funcall next-fn curr-pos))))))
(defgeneric create-greedy-constant-length-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION is greedy and the minimal number of repetitions is
zero. It is furthermore assumed that the inner regex of REPETITION is
of fixed length and doesn't contain registers."))
(defmethod create-greedy-constant-length-matcher ((repetition repetition)
next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len repetition))
(maximum (maximum repetition))
(regex (regex repetition))
(min-rest (min-rest repetition)))
(declare (type fixnum len min-rest)
(type function next-fn))
(cond ((zerop len)
;; inner regex has zero-length, so we can discard it
;; completely
next-fn)
(t
;; now first try to optimize for a couple of common cases
(typecase regex
(str
(let ((str (str regex)))
(if (= 1 len)
;; a single character
(let ((chr (schar str 0)))
(if (case-insensitive-p regex)
(greedy-constant-length-closure
(char-equal chr (schar *string* curr-pos)))
(greedy-constant-length-closure
(char= chr (schar *string* curr-pos)))))
;; a string
(if (case-insensitive-p regex)
(greedy-constant-length-closure
(*string*-equal str curr-pos (+ curr-pos len) 0 len))
(greedy-constant-length-closure
(*string*= str curr-pos (+ curr-pos len) 0 len))))))
(char-class
;; a character class
(insert-char-class-tester (regex (schar *string* curr-pos))
(if (invertedp regex)
(greedy-constant-length-closure
(not (char-class-test)))
(greedy-constant-length-closure
(char-class-test)))))
(everything
;; an EVERYTHING object, i.e. a dot
(if (single-line-p regex)
(create-greedy-everything-matcher maximum min-rest next-fn)
(greedy-constant-length-closure
(char/= #\Newline (schar *string* curr-pos)))))
(t
;; the general case - we build an inner matcher which
;; just checks for immediate success, i.e. NEXT-FN is
;; #'IDENTITY
(let ((inner-matcher (create-matcher-aux regex #'identity)))
(declare (type function inner-matcher))
(greedy-constant-length-closure
(funcall inner-matcher curr-pos)))))))))
(defgeneric create-greedy-no-zero-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION is greedy and the minimal number of repetitions is
zero. It is furthermore assumed that the inner regex of REPETITION can
never match a zero-length string (or instead the maximal number of
repetitions is 1)."))
(defmethod create-greedy-no-zero-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((maximum (maximum repetition))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after GREEDY-AUX is defined
repeat-matcher)
(declare (type function next-fn))
(cond
((eql maximum 1)
;; this is essentially like the next case but with a known
;; MAXIMUM of 1 we can get away without a counter; note that
;; we always arrive here if CONVERT optimizes <regex>* to
;; (?:<regex'>*<regex>)?
(setq repeat-matcher
(create-matcher-aux (regex repetition) next-fn))
(lambda (start-pos)
(declare (type function repeat-matcher))
(or (funcall repeat-matcher start-pos)
(funcall next-fn start-pos))))
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((greedy-aux (start-pos)
(declare (type fixnum start-pos maximum rep-num)
(type function repeat-matcher))
;; the actual matcher which first tries to match the
;; inner regex of REPETITION (if we haven't done so
;; too often) and on failure calls NEXT-FN
(or (and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))))
(funcall next-fn start-pos))))
;; create a closure to match the inner regex and to
;; implement backtracking via GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
;; the closure we return is just a thin wrapper around
;; GREEDY-AUX to initialize the repetition counter
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0)
(greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((greedy-aux (start-pos)
(declare (type fixnum start-pos)
(type function repeat-matcher))
(or (funcall repeat-matcher start-pos)
(funcall next-fn start-pos))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
#'greedy-aux)))))
(defgeneric create-greedy-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION is greedy and the minimal number of repetitions is
zero."))
(defmethod create-greedy-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((maximum (maximum repetition))
;; we make a reservation for our slot in *LAST-POS-STORES* because
;; we have to watch out for endless loops as the inner regex might
;; match zero-length strings
(zero-length-num (incf-after *zero-length-num*))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after GREEDY-AUX is defined
repeat-matcher)
(declare (type fixnum zero-length-num)
(type function next-fn))
(cond
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((greedy-aux (start-pos)
;; the actual matcher which first tries to match the
;; inner regex of REPETITION (if we haven't done so
;; too often) and on failure calls NEXT-FN
(declare (type fixnum start-pos maximum rep-num)
(type function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
;; stop immediately if we've been here before,
;; i.e. if the last attempt matched a zero-length
;; string
(return-from greedy-aux (funcall next-fn start-pos)))
;; otherwise remember this position for the next
;; repetition
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos)))
(funcall next-fn start-pos)))))
;; create a closure to match the inner regex and to
;; implement backtracking via GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
;; the closure we return is just a thin wrapper around
;; GREEDY-AUX to initialize the repetition counter and our
;; slot in *LAST-POS-STORES*
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0
(svref *last-pos-stores* zero-length-num) nil)
(greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((greedy-aux (start-pos)
(declare (type fixnum start-pos)
(type function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
(return-from greedy-aux (funcall next-fn start-pos)))
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (prog1
(funcall repeat-matcher start-pos)
(setf (svref *last-pos-stores* zero-length-num) old-last-pos))
(funcall next-fn start-pos)))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'greedy-aux))
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (svref *last-pos-stores* zero-length-num) nil)
(greedy-aux start-pos)))))))
;; code for non-greedy repetitions with minimum zero
(defmacro non-greedy-constant-length-closure (check-curr-pos)
"This is the template for simple non-greedy repetitions (where
simple means that the minimum number of repetitions is zero, that the
inner regex to be checked is of fixed length LEN, and that it doesn't
contain registers, i.e. there's no need for backtracking).
CHECK-CURR-POS is a form which checks whether the inner regex of the
repetition matches at CURR-POS."
`(if maximum
(lambda (start-pos)
(declare (type fixnum start-pos maximum))
;; because we know LEN we know in advance where to stop at the
;; latest; we also take into consideration MIN-REST, i.e. the
;; minimal length of the part behind the repetition
(let ((target-end-pos (min (1+ (- *end-pos* len min-rest))
(+ start-pos
(the fixnum (* len maximum))))))
;; move forward by LEN and always try NEXT-FN first, then
;; CHECK-CUR-POS
(loop for curr-pos of-type fixnum from start-pos
below target-end-pos
by len
thereis (funcall next-fn curr-pos)
while ,check-curr-pos
finally (return (funcall next-fn curr-pos)))))
;; basically the same code; it's just a bit easier because we're
;; not bounded by MAXIMUM
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((target-end-pos (1+ (- *end-pos* len min-rest))))
(loop for curr-pos of-type fixnum from start-pos
below target-end-pos
by len
thereis (funcall next-fn curr-pos)
while ,check-curr-pos
finally (return (funcall next-fn curr-pos)))))))
(defgeneric create-non-greedy-constant-length-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION is non-greedy and the minimal number of repetitions is
zero. It is furthermore assumed that the inner regex of REPETITION is
of fixed length and doesn't contain registers."))
(defmethod create-non-greedy-constant-length-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len repetition))
(maximum (maximum repetition))
(regex (regex repetition))
(min-rest (min-rest repetition)))
(declare (type fixnum len min-rest)
(type function next-fn))
(cond ((zerop len)
;; inner regex has zero-length, so we can discard it
;; completely
next-fn)
(t
;; now first try to optimize for a couple of common cases
(typecase regex
(str
(let ((str (str regex)))
(if (= 1 len)
;; a single character
(let ((chr (schar str 0)))
(if (case-insensitive-p regex)
(non-greedy-constant-length-closure
(char-equal chr (schar *string* curr-pos)))
(non-greedy-constant-length-closure
(char= chr (schar *string* curr-pos)))))
;; a string
(if (case-insensitive-p regex)
(non-greedy-constant-length-closure
(*string*-equal str curr-pos (+ curr-pos len) 0 len))
(non-greedy-constant-length-closure
(*string*= str curr-pos (+ curr-pos len) 0 len))))))
(char-class
;; a character class
(insert-char-class-tester (regex (schar *string* curr-pos))
(if (invertedp regex)
(non-greedy-constant-length-closure
(not (char-class-test)))
(non-greedy-constant-length-closure
(char-class-test)))))
(everything
(if (single-line-p regex)
;; a dot which really can match everything; we rely
;; on the compiler to optimize this away
(non-greedy-constant-length-closure
t)
;; a dot which has to watch out for #\Newline
(non-greedy-constant-length-closure
(char/= #\Newline (schar *string* curr-pos)))))
(t
;; the general case - we build an inner matcher which
;; just checks for immediate success, i.e. NEXT-FN is
;; #'IDENTITY
(let ((inner-matcher (create-matcher-aux regex #'identity)))
(declare (type function inner-matcher))
(non-greedy-constant-length-closure
(funcall inner-matcher curr-pos)))))))))
(defgeneric create-non-greedy-no-zero-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION is non-greedy and the minimal number of repetitions is
zero. It is furthermore assumed that the inner regex of REPETITION can
never match a zero-length string (or instead the maximal number of
repetitions is 1)."))
(defmethod create-non-greedy-no-zero-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((maximum (maximum repetition))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after NON-GREEDY-AUX is defined
repeat-matcher)
(declare (type function next-fn))
(cond
((eql maximum 1)
;; this is essentially like the next case but with a known
;; MAXIMUM of 1 we can get away without a counter
(setq repeat-matcher
(create-matcher-aux (regex repetition) next-fn))
(lambda (start-pos)
(declare (type function repeat-matcher))
(or (funcall next-fn start-pos)
(funcall repeat-matcher start-pos))))
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((non-greedy-aux (start-pos)
;; the actual matcher which first calls NEXT-FN and
;; on failure tries to match the inner regex of
;; REPETITION (if we haven't done so too often)
(declare (type fixnum start-pos maximum rep-num)
(type function repeat-matcher))
(or (funcall next-fn start-pos)
(and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; NON-GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num)))))))
;; create a closure to match the inner regex and to
;; implement backtracking via NON-GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
;; the closure we return is just a thin wrapper around
;; NON-GREEDY-AUX to initialize the repetition counter
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0)
(non-greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((non-greedy-aux (start-pos)
(declare (type fixnum start-pos)
(type function repeat-matcher))
(or (funcall next-fn start-pos)
(funcall repeat-matcher start-pos))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
#'non-greedy-aux)))))
(defgeneric create-non-greedy-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION is non-greedy and the minimal number of repetitions is
zero."))
(defmethod create-non-greedy-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
;; we make a reservation for our slot in *LAST-POS-STORES* because
;; we have to watch out for endless loops as the inner regex might
;; match zero-length strings
(let ((zero-length-num (incf-after *zero-length-num*))
(maximum (maximum repetition))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after NON-GREEDY-AUX is defined
repeat-matcher)
(declare (type fixnum zero-length-num)
(type function next-fn))
(cond
(maximum
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track whether we've reached MAXIMUM
;; repetitions
(let ((rep-num (incf-after *rep-num*)))
(flet ((non-greedy-aux (start-pos)
;; the actual matcher which first calls NEXT-FN and
;; on failure tries to match the inner regex of
;; REPETITION (if we haven't done so too often)
(declare (type fixnum start-pos maximum rep-num)
(type function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
;; stop immediately if we've been here before,
;; i.e. if the last attempt matched a zero-length
;; string
(return-from non-greedy-aux (funcall next-fn start-pos)))
;; otherwise remember this position for the next
;; repetition
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (funcall next-fn start-pos)
(and (< (aref *repeat-counters* rep-num) maximum)
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; NON-GREEDY-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos)))))))
;; create a closure to match the inner regex and to
;; implement backtracking via NON-GREEDY-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
;; the closure we return is just a thin wrapper around
;; NON-GREEDY-AUX to initialize the repetition counter and our
;; slot in *LAST-POS-STORES*
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0
(svref *last-pos-stores* zero-length-num) nil)
(non-greedy-aux start-pos)))))
(t
;; easier code because we're not bounded by MAXIMUM, but
;; basically the same
(flet ((non-greedy-aux (start-pos)
(declare (type fixnum start-pos)
(type function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
(return-from non-greedy-aux (funcall next-fn start-pos)))
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(or (funcall next-fn start-pos)
(prog1
(funcall repeat-matcher start-pos)
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos))))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'non-greedy-aux))
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (svref *last-pos-stores* zero-length-num) nil)
(non-greedy-aux start-pos)))))))
;; code for constant repetitions, i.e. those with a fixed number of repetitions
(defmacro constant-repetition-constant-length-closure (check-curr-pos)
"This is the template for simple constant repetitions (where simple
means that the inner regex to be checked is of fixed length LEN, and
that it doesn't contain registers, i.e. there's no need for
backtracking) and where constant means that MINIMUM is equal to
MAXIMUM. CHECK-CURR-POS is a form which checks whether the inner regex
of the repetition matches at CURR-POS."
`(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((target-end-pos (+ start-pos
(the fixnum (* len repetitions)))))
(declare (type fixnum target-end-pos))
;; first check if we won't go beyond the end of the string
(and (>= *end-pos* target-end-pos)
;; then loop through all repetitions step by step
(loop for curr-pos of-type fixnum from start-pos
below target-end-pos
by len
always ,check-curr-pos)
;; finally call NEXT-FN if we made it that far
(funcall next-fn target-end-pos)))))
(defgeneric create-constant-repetition-constant-length-matcher
(repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION has a constant number of repetitions. It is
furthermore assumed that the inner regex of REPETITION is of fixed
length and doesn't contain registers."))
(defmethod create-constant-repetition-constant-length-matcher
((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len repetition))
(repetitions (minimum repetition))
(regex (regex repetition)))
(declare (type fixnum len repetitions)
(type function next-fn))
(if (zerop len)
;; if the length is zero it suffices to try once
(create-matcher-aux regex next-fn)
;; otherwise try to optimize for a couple of common cases
(typecase regex
(str
(let ((str (str regex)))
(if (= 1 len)
;; a single character
(let ((chr (schar str 0)))
(if (case-insensitive-p regex)
(constant-repetition-constant-length-closure
(and (char-equal chr (schar *string* curr-pos))
(1+ curr-pos)))
(constant-repetition-constant-length-closure
(and (char= chr (schar *string* curr-pos))
(1+ curr-pos)))))
;; a string
(if (case-insensitive-p regex)
(constant-repetition-constant-length-closure
(let ((next-pos (+ curr-pos len)))
(declare (type fixnum next-pos))
(and (*string*-equal str curr-pos next-pos 0 len)
next-pos)))
(constant-repetition-constant-length-closure
(let ((next-pos (+ curr-pos len)))
(declare (type fixnum next-pos))
(and (*string*= str curr-pos next-pos 0 len)
next-pos)))))))
(char-class
;; a character class
(insert-char-class-tester (regex (schar *string* curr-pos))
(if (invertedp regex)
(constant-repetition-constant-length-closure
(and (not (char-class-test))
(1+ curr-pos)))
(constant-repetition-constant-length-closure
(and (char-class-test)
(1+ curr-pos))))))
(everything
(if (single-line-p regex)
;; a dot which really matches everything - we just have to
;; advance the index into *STRING* accordingly and check
;; if we didn't go past the end
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((next-pos (+ start-pos repetitions)))
(declare (type fixnum next-pos))
(and (<= next-pos *end-pos*)
(funcall next-fn next-pos))))
;; a dot which is not in single-line-mode - make sure we
;; don't match #\Newline
(constant-repetition-constant-length-closure
(and (char/= #\Newline (schar *string* curr-pos))
(1+ curr-pos)))))
(t
;; the general case - we build an inner matcher which just
;; checks for immediate success, i.e. NEXT-FN is #'IDENTITY
(let ((inner-matcher (create-matcher-aux regex #'identity)))
(declare (type function inner-matcher))
(constant-repetition-constant-length-closure
(funcall inner-matcher curr-pos))))))))
(defgeneric create-constant-repetition-matcher (repetition next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which tries to match REPETITION. It is assumed
that REPETITION has a constant number of repetitions."))
(defmethod create-constant-repetition-matcher ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(let ((repetitions (minimum repetition))
;; we make a reservation for our slot in *REPEAT-COUNTERS*
;; because we need to keep track of the number of repetitions
(rep-num (incf-after *rep-num*))
;; REPEAT-MATCHER is part of the closure's environment but it
;; can only be defined after NON-GREEDY-AUX is defined
repeat-matcher)
(declare (type fixnum repetitions rep-num)
(type function next-fn))
(if (zerop (min-len repetition))
;; we make a reservation for our slot in *LAST-POS-STORES*
;; because we have to watch out for needless loops as the inner
;; regex might match zero-length strings
(let ((zero-length-num (incf-after *zero-length-num*)))
(declare (type fixnum zero-length-num))
(flet ((constant-aux (start-pos)
;; the actual matcher which first calls NEXT-FN and
;; on failure tries to match the inner regex of
;; REPETITION (if we haven't done so too often)
(declare (type fixnum start-pos)
(type function repeat-matcher))
(let ((old-last-pos
(svref *last-pos-stores* zero-length-num)))
(when (and old-last-pos
(= (the fixnum old-last-pos) start-pos))
;; if we've been here before we matched a
;; zero-length string the last time, so we can
;; just carry on because we will definitely be
;; able to do this again often enough
(return-from constant-aux (funcall next-fn start-pos)))
;; otherwise remember this position for the next
;; repetition
(setf (svref *last-pos-stores* zero-length-num) start-pos)
(cond ((< (aref *repeat-counters* rep-num) repetitions)
;; not enough repetitions yet, try it again
(incf (aref *repeat-counters* rep-num))
;; note that REPEAT-MATCHER will call
;; CONSTANT-AUX again recursively
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))
(setf (svref *last-pos-stores* zero-length-num)
old-last-pos)))
(t
;; we're done - call NEXT-FN
(funcall next-fn start-pos))))))
;; create a closure to match the inner regex and to
;; implement backtracking via CONSTANT-AUX
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'constant-aux))
;; the closure we return is just a thin wrapper around
;; CONSTANT-AUX to initialize the repetition counter
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0
(aref *last-pos-stores* zero-length-num) nil)
(constant-aux start-pos))))
;; easier code because we don't have to care about zero-length
;; matches but basically the same
(flet ((constant-aux (start-pos)
(declare (type fixnum start-pos)
(type function repeat-matcher))
(cond ((< (aref *repeat-counters* rep-num) repetitions)
(incf (aref *repeat-counters* rep-num))
(prog1
(funcall repeat-matcher start-pos)
(decf (aref *repeat-counters* rep-num))))
(t (funcall next-fn start-pos)))))
(setq repeat-matcher
(create-matcher-aux (regex repetition) #'constant-aux))
(lambda (start-pos)
(declare (type fixnum start-pos))
(setf (aref *repeat-counters* rep-num) 0)
(constant-aux start-pos))))))
;; the actual CREATE-MATCHER-AUX method for REPETITION objects which
;; utilizes all the functions and macros defined above
(defmethod create-matcher-aux ((repetition repetition) next-fn)
(declare #.*standard-optimize-settings*)
(with-slots (minimum maximum len min-len greedyp contains-register-p)
repetition
(cond ((and maximum
(zerop maximum))
;; this should have been optimized away by CONVERT but just
;; in case...
(error "Got REPETITION with MAXIMUM 0 \(should not happen)"))
((and maximum
(= minimum maximum 1))
;; this should have been optimized away by CONVERT but just
;; in case...
(error "Got REPETITION with MAXIMUM 1 and MINIMUM 1 \(should not happen)"))
((and (eql minimum maximum)
len
(not contains-register-p))
(create-constant-repetition-constant-length-matcher repetition next-fn))
((eql minimum maximum)
(create-constant-repetition-matcher repetition next-fn))
((and greedyp
len
(not contains-register-p))
(create-greedy-constant-length-matcher repetition next-fn))
((and greedyp
(or (plusp min-len)
(eql maximum 1)))
(create-greedy-no-zero-matcher repetition next-fn))
(greedyp
(create-greedy-matcher repetition next-fn))
((and len
(plusp len)
(not contains-register-p))
(create-non-greedy-constant-length-matcher repetition next-fn))
((or (plusp min-len)
(eql maximum 1))
(create-non-greedy-no-zero-matcher repetition next-fn))
(t
(create-non-greedy-matcher repetition next-fn)))))
| 42,136 | Common Lisp | .lisp | 811 | 38.313194 | 113 | 0.572685 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | a01a4e0f29ee5ba68b19fe97f937d9ed1d2f500150b2a61841b499f8b45cd799 | 2,443 | [
-1
] |
2,444 | convert.lisp | hoytech_antiweb/bundled/cl-ppcre/convert.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/convert.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; Here the parse tree is converted into its internal representation
;;; using REGEX objects. At the same time some optimizations are
;;; already applied.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
;;; The flags that represent the "ism" modifiers are always kept
;;; together in a three-element list. We use the following macros to
;;; access individual elements.
(defmacro case-insensitive-mode-p (flags)
"Accessor macro to extract the first flag out of a three-element flag list."
`(first ,flags))
(defmacro multi-line-mode-p (flags)
"Accessor macro to extract the second flag out of a three-element flag list."
`(second ,flags))
(defmacro single-line-mode-p (flags)
"Accessor macro to extract the third flag out of a three-element flag list."
`(third ,flags))
(defun set-flag (token)
(declare #.*standard-optimize-settings*)
(declare (special flags))
"Reads a flag token and sets or unsets the corresponding entry in
the special FLAGS list."
(case token
((:case-insensitive-p)
(setf (case-insensitive-mode-p flags) t))
((:case-sensitive-p)
(setf (case-insensitive-mode-p flags) nil))
((:multi-line-mode-p)
(setf (multi-line-mode-p flags) t))
((:not-multi-line-mode-p)
(setf (multi-line-mode-p flags) nil))
((:single-line-mode-p)
(setf (single-line-mode-p flags) t))
((:not-single-line-mode-p)
(setf (single-line-mode-p flags) nil))
(otherwise
(signal-ppcre-syntax-error "Unknown flag token ~A" token))))
(defun add-range-to-hash (hash from to)
(declare #.*standard-optimize-settings*)
(declare (special flags))
"Adds all characters from character FROM to character TO (inclusive)
to the char class hash HASH. Does the right thing with respect to
case-(in)sensitivity as specified by the special variable FLAGS."
(let ((from-code (char-code from))
(to-code (char-code to)))
(when (> from-code to-code)
(signal-ppcre-syntax-error "Invalid range from ~A to ~A in char-class"
from to))
(cond ((case-insensitive-mode-p flags)
(loop for code from from-code to to-code
for chr = (code-char code)
do (setf (gethash (char-upcase chr) hash) t
(gethash (char-downcase chr) hash) t)))
(t
(loop for code from from-code to to-code
do (setf (gethash (code-char code) hash) t))))
hash))
(defun convert-char-class-to-hash (list)
(declare #.*standard-optimize-settings*)
"Combines all items in LIST into one char class hash and returns it.
Items can be single characters, character ranges like \(:RANGE #\\A
#\\E), or special character classes like :DIGIT-CLASS. Does the right
thing with respect to case-\(in)sensitivity as specified by the
special variable FLAGS."
(loop with hash = (make-hash-table :size (ceiling (expt *regex-char-code-limit* (/ 1 4)))
:rehash-size (float (expt *regex-char-code-limit* (/ 1 4)))
:rehash-threshold #-genera 1.0 #+genera 0.99)
for item in list
if (characterp item)
;; treat a single character C like a range (:RANGE C C)
do (add-range-to-hash hash item item)
else if (symbolp item)
;; special character classes
do (setq hash
(case item
((:digit-class)
(merge-hash hash +digit-hash+))
((:non-digit-class)
(merge-inverted-hash hash +digit-hash+))
((:whitespace-char-class)
(merge-hash hash +whitespace-char-hash+))
((:non-whitespace-char-class)
(merge-inverted-hash hash +whitespace-char-hash+))
((:word-char-class)
(merge-hash hash +word-char-hash+))
((:non-word-char-class)
(merge-inverted-hash hash +word-char-hash+))
(otherwise
(signal-ppcre-syntax-error
"Unknown symbol ~A in character class"
item))))
else if (and (consp item)
(eq (car item) :range))
;; proper ranges
do (add-range-to-hash hash
(second item)
(third item))
else do (signal-ppcre-syntax-error "Unknown item ~A in char-class list"
item)
finally (return hash)))
(defun maybe-split-repetition (regex
greedyp
minimum
maximum
min-len
length
reg-seen)
(declare #.*standard-optimize-settings*)
(declare (type fixnum minimum)
(type (or fixnum null) maximum))
"Splits a REPETITION object into a constant and a varying part if
applicable, i.e. something like
a{3,} -> a{3}a*
The arguments to this function correspond to the REPETITION slots of
the same name."
;; note the usage of COPY-REGEX here; we can't use the same REGEX
;; object in both REPETITIONS because they will have different
;; offsets
(when maximum
(when (zerop maximum)
;; trivial case: don't repeat at all
(return-from maybe-split-repetition
(make-instance 'void)))
(when (= 1 minimum maximum)
;; another trivial case: "repeat" exactly once
(return-from maybe-split-repetition
regex)))
;; first set up the constant part of the repetition
;; maybe that's all we need
(let ((constant-repetition (if (plusp minimum)
(make-instance 'repetition
:regex (copy-regex regex)
:greedyp greedyp
:minimum minimum
:maximum minimum
:min-len min-len
:len length
:contains-register-p reg-seen)
;; don't create garbage if minimum is 0
nil)))
(when (and maximum
(= maximum minimum))
(return-from maybe-split-repetition
;; no varying part needed because min = max
constant-repetition))
;; now construct the varying part
(let ((varying-repetition
(make-instance 'repetition
:regex regex
:greedyp greedyp
:minimum 0
:maximum (if maximum (- maximum minimum) nil)
:min-len min-len
:len length
:contains-register-p reg-seen)))
(cond ((zerop minimum)
;; min = 0, no constant part needed
varying-repetition)
((= 1 minimum)
;; min = 1, constant part needs no REPETITION wrapped around
(make-instance 'seq
:elements (list (copy-regex regex)
varying-repetition)))
(t
;; general case
(make-instance 'seq
:elements (list constant-repetition
varying-repetition)))))))
;; During the conversion of the parse tree we keep track of the start
;; of the parse tree in the special variable STARTS-WITH which'll
;; either hold a STR object or an EVERYTHING object. The latter is the
;; case if the regex starts with ".*" which implicitly anchors the
;; regex at the start (perhaps modulo #\Newline).
(defun maybe-accumulate (str)
(declare #.*standard-optimize-settings*)
(declare (special accumulate-start-p starts-with))
(declare (ftype (function (t) fixnum) len))
"Accumulate STR into the special variable STARTS-WITH if
ACCUMULATE-START-P (also special) is true and STARTS-WITH is either
NIL or a STR object of the same case mode. Always returns NIL."
(when accumulate-start-p
(etypecase starts-with
(str
;; STARTS-WITH already holds a STR, so we check if we can
;; concatenate
(cond ((eq (case-insensitive-p starts-with)
(case-insensitive-p str))
;; we modify STARTS-WITH in place
(setf (len starts-with)
(+ (len starts-with) (len str)))
;; note that we use SLOT-VALUE because the accessor
;; STR has a declared FTYPE which doesn't fit here
(adjust-array (slot-value starts-with 'str)
(len starts-with)
:fill-pointer t)
(setf (subseq (slot-value starts-with 'str)
(- (len starts-with) (len str)))
(str str)
;; STR objects that are parts of STARTS-WITH
;; always have their SKIP slot set to true
;; because the SCAN function will take care of
;; them, i.e. the matcher can ignore them
(skip str) t))
(t (setq accumulate-start-p nil))))
(null
;; STARTS-WITH is still empty, so we create a new STR object
(setf starts-with
(make-instance 'str
:str ""
:case-insensitive-p (case-insensitive-p str))
;; INITIALIZE-INSTANCE will coerce the STR to a simple
;; string, so we have to fill it afterwards
(slot-value starts-with 'str)
(make-array (len str)
:initial-contents (str str)
:element-type 'character
:fill-pointer t
:adjustable t)
(len starts-with)
(len str)
;; see remark about SKIP above
(skip str) t))
(everything
;; STARTS-WITH already holds an EVERYTHING object - we can't
;; concatenate
(setq accumulate-start-p nil))))
nil)
(defun convert-aux (parse-tree)
(declare #.*standard-optimize-settings*)
(declare (special flags reg-num reg-names accumulate-start-p starts-with max-back-ref))
"Converts the parse tree PARSE-TREE into a REGEX object and returns it.
Will also
- split and optimize repetitions,
- accumulate strings or EVERYTHING objects into the special variable
STARTS-WITH,
- keep track of all registers seen in the special variable REG-NUM,
- keep track of all named registers seen in the special variable REG-NAMES
- keep track of the highest backreference seen in the special
variable MAX-BACK-REF,
- maintain and adher to the currently applicable modifiers in the special
variable FLAGS, and
- maybe even wash your car..."
(cond ((consp parse-tree)
(case (first parse-tree)
;; (:SEQUENCE {<regex>}*)
((:sequence)
(cond ((cddr parse-tree)
;; this is essentially like
;; (MAPCAR 'CONVERT-AUX (REST PARSE-TREE))
;; but we don't cons a new list
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq
:elements (rest parse-tree)))
(t (convert-aux (second parse-tree)))))
;; (:GROUP {<regex>}*)
;; this is a syntactical construct equivalent to :SEQUENCE
;; intended to keep the effect of modifiers local
((:group)
;; make a local copy of FLAGS and shadow the global
;; value while we descend into the enclosed regexes
(let ((flags (copy-list flags)))
(declare (special flags))
(cond ((cddr parse-tree)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'seq
:elements (rest parse-tree)))
(t (convert-aux (second parse-tree))))))
;; (:ALTERNATION {<regex>}*)
((:alternation)
;; we must stop accumulating objects into STARTS-WITH
;; once we reach an alternation
(setq accumulate-start-p nil)
(loop for parse-tree-rest on (rest parse-tree)
while parse-tree-rest
do (setf (car parse-tree-rest)
(convert-aux (car parse-tree-rest))))
(make-instance 'alternation
:choices (rest parse-tree)))
;; (:BRANCH <test> <regex>)
;; <test> must be look-ahead, look-behind or number;
;; if <regex> is an alternation it must have one or two
;; choices
((:branch)
(setq accumulate-start-p nil)
(let* ((test-candidate (second parse-tree))
(test (cond ((numberp test-candidate)
(when (zerop (the fixnum test-candidate))
(signal-ppcre-syntax-error
"Register 0 doesn't exist: ~S"
parse-tree))
(1- (the fixnum test-candidate)))
(t (convert-aux test-candidate))))
(alternations (convert-aux (third parse-tree))))
(when (and (not (numberp test))
(not (typep test 'lookahead))
(not (typep test 'lookbehind)))
(signal-ppcre-syntax-error
"Branch test must be look-ahead, look-behind or number: ~S"
parse-tree))
(typecase alternations
(alternation
(case (length (choices alternations))
((0)
(signal-ppcre-syntax-error "No choices in branch: ~S"
parse-tree))
((1)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))))
((2)
(make-instance 'branch
:test test
:then-regex (first
(choices alternations))
:else-regex (second
(choices alternations))))
(otherwise
(signal-ppcre-syntax-error
"Too much choices in branch: ~S"
parse-tree))))
(t
(make-instance 'branch
:test test
:then-regex alternations)))))
;; (:POSITIVE-LOOKAHEAD|:NEGATIVE-LOOKAHEAD <regex>)
((:positive-lookahead :negative-lookahead)
;; keep the effect of modifiers local to the enclosed
;; regex and stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'lookahead
:regex (convert-aux (second parse-tree))
:positivep (eq (first parse-tree)
:positive-lookahead))))
;; (:POSITIVE-LOOKBEHIND|:NEGATIVE-LOOKBEHIND <regex>)
((:positive-lookbehind :negative-lookbehind)
;; keep the effect of modifiers local to the enclosed
;; regex and stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(let* ((flags (copy-list flags))
(regex (convert-aux (second parse-tree)))
(len (regex-length regex)))
(declare (special flags))
;; lookbehind assertions must be of fixed length
(unless len
(signal-ppcre-syntax-error
"Variable length look-behind not implemented (yet): ~S"
parse-tree))
(make-instance 'lookbehind
:regex regex
:positivep (eq (first parse-tree)
:positive-lookbehind)
:len len)))
;; (:GREEDY-REPETITION|:NON-GREEDY-REPETITION <min> <max> <regex>)
((:greedy-repetition :non-greedy-repetition)
;; remember the value of ACCUMULATE-START-P upon entering
(let ((local-accumulate-start-p accumulate-start-p))
(let ((minimum (second parse-tree))
(maximum (third parse-tree)))
(declare (type fixnum minimum))
(declare (type (or null fixnum) maximum))
(unless (and maximum
(= 1 minimum maximum))
;; set ACCUMULATE-START-P to NIL for the rest of
;; the conversion because we can't continue to
;; accumulate inside as well as after a proper
;; repetition
(setq accumulate-start-p nil))
(let* (reg-seen
(regex (convert-aux (fourth parse-tree)))
(min-len (regex-min-length regex))
(greedyp (eq (first parse-tree) :greedy-repetition))
(length (regex-length regex)))
;; note that this declaration already applies to
;; the call to CONVERT-AUX above
(declare (special reg-seen))
(when (and local-accumulate-start-p
(not starts-with)
(zerop minimum)
(not maximum))
;; if this repetition is (equivalent to) ".*"
;; and if we're at the start of the regex we
;; remember it for ADVANCE-FN (see the SCAN
;; function)
(setq starts-with (everythingp regex)))
(if (or (not reg-seen)
(not greedyp)
(not length)
(zerop length)
(and maximum (= minimum maximum)))
;; the repetition doesn't enclose a register, or
;; it's not greedy, or we can't determine it's
;; (inner) length, or the length is zero, or the
;; number of repetitions is fixed; in all of
;; these cases we don't bother to optimize
(maybe-split-repetition regex
greedyp
minimum
maximum
min-len
length
reg-seen)
;; otherwise we make a transformation that looks
;; roughly like one of
;; <regex>* -> (?:<regex'>*<regex>)?
;; <regex>+ -> <regex'>*<regex>
;; where the trick is that as much as possible
;; registers from <regex> are removed in
;; <regex'>
(let* (reg-seen ; new instance for REMOVE-REGISTERS
(remove-registers-p t)
(inner-regex (remove-registers regex))
(inner-repetition
;; this is the "<regex'>" part
(maybe-split-repetition inner-regex
;; always greedy
t
;; reduce minimum by 1
;; unless it's already 0
(if (zerop minimum)
0
(1- minimum))
;; reduce maximum by 1
;; unless it's NIL
(and maximum
(1- maximum))
min-len
length
reg-seen))
(inner-seq
;; this is the "<regex'>*<regex>" part
(make-instance 'seq
:elements (list inner-repetition
regex))))
;; note that this declaration already applies
;; to the call to REMOVE-REGISTERS above
(declare (special remove-registers-p reg-seen))
;; wrap INNER-SEQ with a greedy
;; {0,1}-repetition (i.e. "?") if necessary
(if (plusp minimum)
inner-seq
(maybe-split-repetition inner-seq
t
0
1
min-len
nil
t))))))))
;; (:REGISTER <regex>)
;; (:NAMED-REGISTER <name> <regex>)
((:register :named-register)
;; keep the effect of modifiers local to the enclosed
;; regex; also, assign the current value of REG-NUM to
;; the corresponding slot of the REGISTER object and
;; increase this counter afterwards; for named register
;; update REG-NAMES and set the corresponding name slot
;; of the REGISTER object too
(let ((flags (copy-list flags))
(stored-reg-num reg-num)
(reg-name (when (eq (first parse-tree) :named-register)
(copy-seq (second parse-tree)))))
(declare (special flags reg-seen named-reg-seen))
(setq reg-seen t)
(when reg-name
(setq named-reg-seen t))
(incf (the fixnum reg-num))
(push reg-name
reg-names)
(make-instance 'register
:regex (convert-aux (if (eq (first parse-tree) :named-register)
(third parse-tree)
(second parse-tree)))
:num stored-reg-num
:name reg-name)))
;; (:FILTER <function> &optional <length>)
((:filter)
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'filter
:fn (second parse-tree)
:len (third parse-tree)))
;; (:STANDALONE <regex>)
((:standalone)
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
;; keep the effect of modifiers local to the enclosed
;; regex
(let ((flags (copy-list flags)))
(declare (special flags))
(make-instance 'standalone
:regex (convert-aux (second parse-tree)))))
;; (:BACK-REFERENCE <number>)
;; (:BACK-REFERENCE <name>)
((:back-reference)
(locally (declare (special reg-names reg-num))
(let* ((backref-name (and (stringp (second parse-tree))
(second parse-tree)))
(referred-regs
(when backref-name
;; find which register corresponds to the given name
;; we have to deal with case where several registers share
;; the same name and collect their respective numbers
(loop
for name in reg-names
for reg-index from 0
when (string= name backref-name)
;; NOTE: REG-NAMES stores register names in reversed order
;; REG-NUM contains number of (any) registers seen so far
;; 1- will be done later
collect (- reg-num reg-index))))
;; store the register number for the simple case
(backref-number (or (first referred-regs)
(second parse-tree))))
(declare (type (or fixnum null) backref-number))
(when (or (not (typep backref-number 'fixnum))
(<= backref-number 0))
(signal-ppcre-syntax-error
"Illegal back-reference: ~S"
parse-tree))
;; stop accumulating into STARTS-WITH and increase
;; MAX-BACK-REF if necessary
(setq accumulate-start-p nil
max-back-ref (max (the fixnum max-back-ref)
backref-number))
(flet ((make-back-ref (backref-number)
(make-instance 'back-reference
;; we start counting from 0 internally
:num (1- backref-number)
:case-insensitive-p (case-insensitive-mode-p flags)
;; backref-name is NIL or string, safe to copy
:name (copy-seq backref-name))))
(cond
((cdr referred-regs)
;; several registers share the same name
;; we will try to match any of them, starting
;; with the most recent first
;; alternation is used to accomplish matching
(make-instance 'alternation
:choices (loop
for reg-index in referred-regs
collect (make-back-ref reg-index))))
;; simple case - backref corresponds to only one register
(t
(make-back-ref backref-number)))))))
;; (:REGEX <string>)
((:regex)
(let ((regex (second parse-tree)))
(convert-aux (parse-string regex))))
;; (:CHAR-CLASS|:INVERTED-CHAR-CLASS {<item>}*)
;; where item is one of
;; - a character
;; - a character range: (:RANGE <char1> <char2>)
;; - a special char class symbol like :DIGIT-CHAR-CLASS
((:char-class :inverted-char-class)
;; first create the hash-table and some auxiliary values
(let* (hash
hash-keys
(count most-positive-fixnum)
(item-list (rest parse-tree))
(invertedp (eq (first parse-tree) :inverted-char-class))
word-char-class-p)
(cond ((every (lambda (item) (eq item :word-char-class))
item-list)
;; treat "[\\w]" like "\\w"
(setq word-char-class-p t))
((every (lambda (item) (eq item :non-word-char-class))
item-list)
;; treat "[\\W]" like "\\W"
(setq word-char-class-p t)
(setq invertedp (not invertedp)))
(t
(setq hash (convert-char-class-to-hash item-list)
count (hash-table-count hash))
(when (<= count 2)
;; collect the hash-table keys into a list if
;; COUNT is smaller than 3
(setq hash-keys
(loop for chr being the hash-keys of hash
collect chr)))))
(cond ((and (not invertedp)
(= count 1))
;; convert one-element hash table into a STR
;; object and try to accumulate into
;; STARTS-WITH
(let ((str (make-instance 'str
:str (string
(first hash-keys))
:case-insensitive-p nil)))
(maybe-accumulate str)
str))
((and (not invertedp)
(= count 2)
(char-equal (first hash-keys) (second hash-keys)))
;; convert two-element hash table into a
;; case-insensitive STR object and try to
;; accumulate into STARTS-WITH if the two
;; characters are CHAR-EQUAL
(let ((str (make-instance 'str
:str (string
(first hash-keys))
:case-insensitive-p t)))
(maybe-accumulate str)
str))
(t
;; the general case; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'char-class
:hash hash
:case-insensitive-p
(case-insensitive-mode-p flags)
:invertedp invertedp
:word-char-class-p word-char-class-p)))))
;; (:FLAGS {<flag>}*)
;; where flag is a modifier symbol like :CASE-INSENSITIVE-P
((:flags)
;; set/unset the flags corresponding to the symbols
;; following :FLAGS
(mapc #'set-flag (rest parse-tree))
;; we're only interested in the side effect of
;; setting/unsetting the flags and turn this syntactical
;; construct into a VOID object which'll be optimized
;; away when creating the matcher
(make-instance 'void))
(otherwise
(signal-ppcre-syntax-error
"Unknown token ~A in parse-tree"
(first parse-tree)))))
((or (characterp parse-tree) (stringp parse-tree))
;; turn characters or strings into STR objects and try to
;; accumulate into STARTS-WITH
(let ((str (make-instance 'str
:str (string parse-tree)
:case-insensitive-p
(case-insensitive-mode-p flags))))
(maybe-accumulate str)
str))
(t
;; and now for the tokens which are symbols
(case parse-tree
((:void)
(make-instance 'void))
((:word-boundary)
(make-instance 'word-boundary :negatedp nil))
((:non-word-boundary)
(make-instance 'word-boundary :negatedp t))
;; the special character classes
((:digit-class
:non-digit-class
:word-char-class
:non-word-char-class
:whitespace-char-class
:non-whitespace-char-class)
;; stop accumulating into STARTS-WITH
(setq accumulate-start-p nil)
(make-instance 'char-class
;; use the constants defined in util.lisp
:hash (case parse-tree
((:digit-class
:non-digit-class)
+digit-hash+)
((:word-char-class
:non-word-char-class)
nil)
((:whitespace-char-class
:non-whitespace-char-class)
+whitespace-char-hash+))
;; this value doesn't really matter but
;; NIL should result in slightly faster
;; matchers
:case-insensitive-p nil
:invertedp (member parse-tree
'(:non-digit-class
:non-word-char-class
:non-whitespace-char-class)
:test #'eq)
:word-char-class-p (member parse-tree
'(:word-char-class
:non-word-char-class)
:test #'eq)))
((:start-anchor ; Perl's "^"
:end-anchor ; Perl's "$"
:modeless-end-anchor-no-newline
; Perl's "\z"
:modeless-start-anchor ; Perl's "\A"
:modeless-end-anchor) ; Perl's "\Z"
(make-instance 'anchor
:startp (member parse-tree
'(:start-anchor
:modeless-start-anchor)
:test #'eq)
;; set this value according to the
;; current settings of FLAGS (unless it's
;; a modeless anchor)
:multi-line-p
(and (multi-line-mode-p flags)
(not (member parse-tree
'(:modeless-start-anchor
:modeless-end-anchor
:modeless-end-anchor-no-newline)
:test #'eq)))
:no-newline-p
(eq parse-tree
:modeless-end-anchor-no-newline)))
((:everything)
;; stop accumulating into STARTS-WITHS
(setq accumulate-start-p nil)
(make-instance 'everything
:single-line-p (single-line-mode-p flags)))
;; special tokens corresponding to Perl's "ism" modifiers
((:case-insensitive-p
:case-sensitive-p
:multi-line-mode-p
:not-multi-line-mode-p
:single-line-mode-p
:not-single-line-mode-p)
;; we're only interested in the side effect of
;; setting/unsetting the flags and turn these tokens
;; into VOID objects which'll be optimized away when
;; creating the matcher
(set-flag parse-tree)
(make-instance 'void))
(otherwise
(let ((translation (and (symbolp parse-tree)
(parse-tree-synonym parse-tree))))
(if translation
(convert-aux (copy-tree translation))
(signal-ppcre-syntax-error "Unknown token ~A in parse-tree"
parse-tree))))))))
(defun convert (parse-tree)
(declare #.*standard-optimize-settings*)
"Converts the parse tree PARSE-TREE into an equivalent REGEX object
and returns three values: the REGEX object, the number of registers
seen and an object the regex starts with which is either a STR object
or an EVERYTHING object (if the regex starts with something like
\".*\") or NIL."
;; this function basically just initializes the special variables
;; and then calls CONVERT-AUX to do all the work
(let* ((flags (list nil nil nil))
(reg-num 0)
reg-names
named-reg-seen
(accumulate-start-p t)
starts-with
(max-back-ref 0)
(converted-parse-tree (convert-aux parse-tree)))
(declare (special flags reg-num reg-names named-reg-seen
accumulate-start-p starts-with max-back-ref))
;; make sure we don't reference registers which aren't there
(when (> (the fixnum max-back-ref)
(the fixnum reg-num))
(signal-ppcre-syntax-error
"Backreference to register ~A which has not been defined"
max-back-ref))
(when (typep starts-with 'str)
(setf (slot-value starts-with 'str)
(coerce (slot-value starts-with 'str) 'simple-string)))
(values converted-parse-tree reg-num starts-with
;; we can't simply use *ALLOW-NAMED-REGISTERS*
;; since parse-tree syntax ignores it
(when named-reg-seen
(nreverse reg-names)))))
| 40,264 | Common Lisp | .lisp | 791 | 31.361568 | 101 | 0.473906 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | cb0158e56a53b5ed0d744bd9986e5849364c011894ed8fff737a065ee4cf5f61 | 2,444 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.